From acc09d5c69690f2c46cb1bacf290da5dcc268b24 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 6 Jun 2023 15:53:46 +0200 Subject: Remove the sorries from Primitives.lean --- backends/lean/Primitives.lean | 184 +++++++++++++++++++++++++++--------------- backends/lean/lakefile.lean | 1 + 2 files changed, 120 insertions(+), 65 deletions(-) diff --git a/backends/lean/Primitives.lean b/backends/lean/Primitives.lean index 4a66a453..e7826fbf 100644 --- a/backends/lean/Primitives.lean +++ b/backends/lean/Primitives.lean @@ -2,9 +2,10 @@ import Lean import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith -------------------- --- ASSERT COMMAND -- +-- ASSERT COMMAND --Std. -------------------- open Lean Elab Command Term Meta @@ -249,27 +250,53 @@ def Scalar.cMax (ty : ScalarTy) : Int := | .Usize => U32.max | _ => Scalar.max ty -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry +theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] + +theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] + +theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * + -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + linarith + +theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * <;> + -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + linarith structure Scalar (ty : ScalarTy) where val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty + hmin : Scalar.min ty ≤ val + hmax : val ≤ Scalar.max ty theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry + Scalar.cMin ty ≤ x ∧ x ≤ Scalar.cMax ty -> + Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty + := + λ h => by + apply And.intro <;> have hmin := Scalar.cMin_bound ty <;> have hmax := Scalar.cMax_bound ty <;> linarith def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := + (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := { val := x, hmin := hmin, hmax := hmax } def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry + (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : Scalar ty := + let ⟨ hmin, hmax ⟩ := h Scalar.ofIntCore x hmin hmax -- Further thoughts: look at what has been done here: @@ -279,12 +306,15 @@ def Scalar.ofInt {ty : ScalarTy} (x : Int) -- which both contain a fair amount of reasoning already! def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow + if h: (Scalar.cMin ty ≤ x || Scalar.min ty ≤ x) && (x ≤ Scalar.cMax ty || x ≤ Scalar.max ty) then + let h: Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by + simp at * + have ⟨ hmin, hmax ⟩ := h + have hbmin := Scalar.cMin_bound ty + have hbmax := Scalar.cMax_bound ty + cases hmin <;> cases hmax <;> apply And.intro <;> linarith + let ⟨ hmin, hmax ⟩ := h + return Scalar.ofIntCore x hmin hmax else fail integerOverflow def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) @@ -292,11 +322,39 @@ def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tr def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 +-- Our custom remainder operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_rem (x y : Int) : Int := + if 0 ≤ x then |x| % |y| + else - (|x| % |y|) + +-- Our custom division operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_div (x y : Int) : Int := + if 0 ≤ x && 0 ≤ y then |x| / |y| + else if 0 ≤ x && y < 0 then - (|x| / |y|) + else if x < 0 && 0 ≤ y then - (|x| / |y|) + else |x| / |y| + +-- Checking that the remainder operation is correct +#assert scalar_rem 1 2 = 1 +#assert scalar_rem (-1) 2 = -1 +#assert scalar_rem 1 (-2) = 1 +#assert scalar_rem (-1) (-2) = -1 +#assert scalar_rem 7 3 = (1:Int) +#assert scalar_rem (-7) 3 = -1 +#assert scalar_rem 7 (-3) = 1 +#assert scalar_rem (-7) (-3) = -1 + +-- Checking that the division operation is correct +#assert scalar_div 3 2 = 1 +#assert scalar_div (-3) 2 = -1 +#assert scalar_div 3 (-2) = -1 +#assert scalar_div (-3) (-2) = 1 +#assert scalar_div 7 3 = 2 +#assert scalar_div (-7) 3 = -2 +#assert scalar_div 7 (-3) = -2 +#assert scalar_div (-7) (-3) = 2 def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero @@ -479,20 +537,29 @@ macro_rules -- VECTORS -- ------------- -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } +def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ +def vec_new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ def vec_len (α : Type u) (v : Vec α) : Usize := let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l + Usize.ofIntCore (List.length v) (by simp [Scalar.min]) l def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ + let nlen := List.length v.val + 1 + if h : nlen ≤ U32.max || nlen ≤ Usize.max then + have h : nlen ≤ Usize.max := by + simp at * + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * <;> + try assumption + cases h <;> + linarith + return ⟨ List.concat v.val x, by simp at *; assumption ⟩ else fail maximumSizeExceeded @@ -506,30 +573,28 @@ def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α if i.val < List.length v.val then -- TODO: maybe we should redefine a list library which uses integers -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] + let i := i.val.toNat + .ret ⟨ List.set v.val i x, by + have h: List.length v.val ≤ Usize.max := v.property + simp [*] at * assumption ⟩ else .fail arrayOutOfBounds +def vec_index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : + Fin (List.length v.val) := + let j := i.val.toNat + let h: j < List.length v.val := by + have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin + apply heq.mpr + assumption + ⟨j, h⟩ + def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret (List.get v.val i) else .fail arrayOutOfBounds @@ -540,29 +605,18 @@ def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := .fail arrayOutOfBounds def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret (List.get v.val i) else .fail arrayOutOfBounds def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret ⟨ List.set v.val i x, by + have h: List.length v.val ≤ Usize.max := v.property + simp [*] at * assumption ⟩ else diff --git a/backends/lean/lakefile.lean b/backends/lean/lakefile.lean index 9633e1e8..c5e27d1c 100644 --- a/backends/lean/lakefile.lean +++ b/backends/lean/lakefile.lean @@ -1,6 +1,7 @@ import Lake open Lake DSL +-- Important: mathlib imports std4 and quote4: we mustn't add a `require std4` line require mathlib from git "https://github.com/leanprover-community/mathlib4.git" -- cgit v1.2.3 From e2fef1a5c986aff4c9975b1376bcc0fc0bb87940 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Fri, 9 Jun 2023 10:06:43 +0200 Subject: Reorganize a bit the Lean library --- backends/lean/Base.lean | 1 + backends/lean/Base/Primitives.lean | 650 +++++++++++++++++++++++++++++++++++++ backends/lean/Primitives.lean | 637 ------------------------------------ backends/lean/lake-manifest.json | 8 +- backends/lean/lakefile.lean | 2 +- 5 files changed, 656 insertions(+), 642 deletions(-) create mode 100644 backends/lean/Base.lean create mode 100644 backends/lean/Base/Primitives.lean delete mode 100644 backends/lean/Primitives.lean diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean new file mode 100644 index 00000000..960b2bb5 --- /dev/null +++ b/backends/lean/Base.lean @@ -0,0 +1 @@ +import Base.Primitives diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean new file mode 100644 index 00000000..d3de1d10 --- /dev/null +++ b/backends/lean/Base/Primitives.lean @@ -0,0 +1,650 @@ +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith + +-------------------- +-- ASSERT COMMAND --Std. +-------------------- + +open Lean Elab Command Term Meta + +syntax (name := assert) "#assert" term: command + +@[command_elab assert] +unsafe +def assertImpl : CommandElab := fun (_stx: Syntax) => do + runTermElabM (fun _ => do + let r ← evalTerm Bool (mkConst ``Bool) _stx[1] + if not r then + logInfo "Assertion failed for: " + logInfo _stx[1] + logError "Expression reduced to false" + pure ()) + +#eval 2 == 2 +#assert (2 == 2) + +------------- +-- PRELUDE -- +------------- + +-- Results & monadic combinators + +inductive Error where + | assertionFailure: Error + | integerOverflow: Error + | divisionByZero: Error + | arrayOutOfBounds: Error + | maximumSizeExceeded: Error + | panic: Error +deriving Repr, BEq + +open Error + +inductive Result (α : Type u) where + | ret (v: α): Result α + | fail (e: Error): Result α +deriving Repr, BEq + +open Result + +instance Result_Inhabited (α : Type u) : Inhabited (Result α) := + Inhabited.mk (fail panic) + +/- HELPERS -/ + +def ret? {α: Type} (r: Result α): Bool := + match r with + | Result.ret _ => true + | Result.fail _ => false + +def massert (b:Bool) : Result Unit := + if b then .ret () else fail assertionFailure + +def eval_global {α: Type} (x: Result α) (_: ret? x): α := + match x with + | Result.fail _ => by contradiction + | Result.ret x => x + +/- DO-DSL SUPPORT -/ + +def bind (x: Result α) (f: α -> Result β) : Result β := + match x with + | ret v => f v + | fail v => fail v + +-- Allows using Result in do-blocks +instance : Bind Result where + bind := bind + +-- Allows using return x in do-blocks +instance : Pure Result where + pure := fun x => ret x + +/- CUSTOM-DSL SUPPORT -/ + +-- Let-binding the Result of a monadic operation is oftentimes not sufficient, +-- because we may need a hypothesis for equational reasoning in the scope. We +-- rely on subtype, and a custom let-binding operator, in effect recreating our +-- own variant of the do-dsl + +def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := + match o with + | .ret x => .ret ⟨x, rfl⟩ + | .fail e => .fail e + +macro "let" e:term " ⟵ " f:term : doElem => + `(doElem| let ⟨$e, h⟩ ← Result.attach $f) + +-- TODO: any way to factorize both definitions? +macro "let" e:term " <-- " f:term : doElem => + `(doElem| let ⟨$e, h⟩ ← Result.attach $f) + +-- We call the hypothesis `h`, in effect making it unavailable to the user +-- (because too much shadowing). But in practice, once can use the French single +-- quote notation (input with f< and f>), where `‹ h ›` finds a suitable +-- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` +#eval do + let y <-- .ret (0: Nat) + let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide + let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ + .ret r + +---------------------- +-- MACHINE INTEGERS -- +---------------------- + +-- We redefine our machine integers types. + +-- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` +-- using the simplifier, meaning that proofs do not depend on the compile-time value of +-- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at +-- least officially, 16-bit microcontrollers, so this seems like a fine design decision +-- for now.) + +-- Note from Chris Bailey: "If there's more than one salient property of your +-- definition then the subtyping strategy might get messy, and the property part +-- of a subtype is less discoverable by the simplifier or tactics like +-- library_search." So, we will not add refinements on the return values of the +-- operations defined on Primitives, but will rather rely on custom lemmas to +-- invert on possible return values of the primitive operations. + +-- Machine integer constants, done via `ofNatCore`, which requires a proof that +-- the `Nat` fits within the desired integer type. We provide a custom tactic. + +open System.Platform.getNumBits + +-- TODO: is there a way of only importing System.Platform.getNumBits? +-- +@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val + +-- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. +-- We keep the F* convention for now. +@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) +@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 +@[simp] def I8.min : Int := - (HPow.hPow 2 7) +@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 +@[simp] def I16.min : Int := - (HPow.hPow 2 15) +@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 +@[simp] def I32.min : Int := -(HPow.hPow 2 31) +@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 +@[simp] def I64.min : Int := -(HPow.hPow 2 63) +@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 +@[simp] def I128.min : Int := -(HPow.hPow 2 127) +@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 +@[simp] def Usize.min : Int := 0 +@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 +@[simp] def U8.min : Int := 0 +@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 +@[simp] def U16.min : Int := 0 +@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 +@[simp] def U32.min : Int := 0 +@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 +@[simp] def U64.min : Int := 0 +@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 +@[simp] def U128.min : Int := 0 +@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 + +#assert (I8.min == -128) +#assert (I8.max == 127) +#assert (I16.min == -32768) +#assert (I16.max == 32767) +#assert (I32.min == -2147483648) +#assert (I32.max == 2147483647) +#assert (I64.min == -9223372036854775808) +#assert (I64.max == 9223372036854775807) +#assert (I128.min == -170141183460469231731687303715884105728) +#assert (I128.max == 170141183460469231731687303715884105727) +#assert (U8.min == 0) +#assert (U8.max == 255) +#assert (U16.min == 0) +#assert (U16.max == 65535) +#assert (U32.min == 0) +#assert (U32.max == 4294967295) +#assert (U64.min == 0) +#assert (U64.max == 18446744073709551615) +#assert (U128.min == 0) +#assert (U128.max == 340282366920938463463374607431768211455) + +inductive ScalarTy := +| Isize +| I8 +| I16 +| I32 +| I64 +| I128 +| Usize +| U8 +| U16 +| U32 +| U64 +| U128 + +def Scalar.min (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.min + | .I8 => I8.min + | .I16 => I16.min + | .I32 => I32.min + | .I64 => I64.min + | .I128 => I128.min + | .Usize => Usize.min + | .U8 => U8.min + | .U16 => U16.min + | .U32 => U32.min + | .U64 => U64.min + | .U128 => U128.min + +def Scalar.max (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.max + | .I8 => I8.max + | .I16 => I16.max + | .I32 => I32.max + | .I64 => I64.max + | .I128 => I128.max + | .Usize => Usize.max + | .U8 => U8.max + | .U16 => U16.max + | .U32 => U32.max + | .U64 => U64.max + | .U128 => U128.max + +-- "Conservative" bounds +-- We use those because we can't compare to the isize bounds (which can't +-- reduce at compile-time). Whenever we perform an arithmetic operation like +-- addition we need to check that the result is in bounds: we first compare +-- to the conservative bounds, which reduce, then compare to the real bounds. +-- This is useful for the various #asserts that we want to reduce at +-- type-checking time. +def Scalar.cMin (ty : ScalarTy) : Int := + match ty with + | .Isize => I32.min + | _ => Scalar.min ty + +def Scalar.cMax (ty : ScalarTy) : Int := + match ty with + | .Isize => I32.max + | .Usize => U32.max + | _ => Scalar.max ty + +theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] + +theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] + +theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * + -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + linarith + +theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * <;> + -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + linarith + +structure Scalar (ty : ScalarTy) where + val : Int + hmin : Scalar.min ty ≤ val + hmax : val ≤ Scalar.max ty +deriving Repr + +theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : + Scalar.cMin ty ≤ x ∧ x ≤ Scalar.cMax ty -> + Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty + := + λ h => by + apply And.intro <;> have hmin := Scalar.cMin_bound ty <;> have hmax := Scalar.cMax_bound ty <;> linarith + +def Scalar.ofIntCore {ty : ScalarTy} (x : Int) + (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := + { val := x, hmin := hmin, hmax := hmax } + +def Scalar.ofInt {ty : ScalarTy} (x : Int) + (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : Scalar ty := + -- Remark: we initially wrote: + -- let ⟨ hmin, hmax ⟩ := h + -- Scalar.ofIntCore x hmin hmax + -- We updated to the line below because a similar pattern in `Scalar.tryMk` + -- made reduction block. Both versions seem to work for `Scalar.ofInt`, though. + -- TODO: investigate + Scalar.ofIntCore x h.left h.right + +@[simp] def Scalar.check_bounds (ty : ScalarTy) (x : Int) : Bool := + (Scalar.cMin ty ≤ x || Scalar.min ty ≤ x) ∧ (x ≤ Scalar.cMax ty || x ≤ Scalar.max ty) + +theorem Scalar.check_bounds_prop {ty : ScalarTy} {x : Int} (h: Scalar.check_bounds ty x) : + Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by + simp at * + have ⟨ hmin, hmax ⟩ := h + have hbmin := Scalar.cMin_bound ty + have hbmax := Scalar.cMax_bound ty + cases hmin <;> cases hmax <;> apply And.intro <;> linarith + +-- Further thoughts: look at what has been done here: +-- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean +-- and +-- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean +-- which both contain a fair amount of reasoning already! +def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := + if h:Scalar.check_bounds ty x then + -- If we do: + -- ``` + -- let ⟨ hmin, hmax ⟩ := (Scalar.check_bounds_prop h) + -- Scalar.ofIntCore x hmin hmax + -- ``` + -- then normalization blocks (for instance, some proofs which use reflexivity fail). + -- However, the version below doesn't block reduction (TODO: investigate): + return Scalar.ofInt x (Scalar.check_bounds_prop h) + else fail integerOverflow + +def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) + +def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero + +-- Our custom remainder operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_rem (x y : Int) : Int := + if 0 ≤ x then |x| % |y| + else - (|x| % |y|) + +-- Our custom division operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_div (x y : Int) : Int := + if 0 ≤ x && 0 ≤ y then |x| / |y| + else if 0 ≤ x && y < 0 then - (|x| / |y|) + else if x < 0 && 0 ≤ y then - (|x| / |y|) + else |x| / |y| + +-- Checking that the remainder operation is correct +#assert scalar_rem 1 2 = 1 +#assert scalar_rem (-1) 2 = -1 +#assert scalar_rem 1 (-2) = 1 +#assert scalar_rem (-1) (-2) = -1 +#assert scalar_rem 7 3 = (1:Int) +#assert scalar_rem (-7) 3 = -1 +#assert scalar_rem 7 (-3) = 1 +#assert scalar_rem (-7) (-3) = -1 + +-- Checking that the division operation is correct +#assert scalar_div 3 2 = 1 +#assert scalar_div (-3) 2 = -1 +#assert scalar_div 3 (-2) = -1 +#assert scalar_div (-3) (-2) = 1 +#assert scalar_div 7 3 = 2 +#assert scalar_div (-7) 3 = -2 +#assert scalar_div 7 (-3) = -2 +#assert scalar_div (-7) (-3) = 2 + +def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero + +def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val + y.val) + +def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val - y.val) + +def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val * y.val) + +-- TODO: instances of +, -, * etc. for scalars + +-- Cast an integer from a [src_ty] to a [tgt_ty] +-- TODO: check the semantics of casts in Rust +def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := + Scalar.tryMk tgt_ty x.val + +-- The scalar types +-- We declare the definitions as reducible so that Lean can unfold them (useful +-- for type class resolution for instance). +@[reducible] def Isize := Scalar .Isize +@[reducible] def I8 := Scalar .I8 +@[reducible] def I16 := Scalar .I16 +@[reducible] def I32 := Scalar .I32 +@[reducible] def I64 := Scalar .I64 +@[reducible] def I128 := Scalar .I128 +@[reducible] def Usize := Scalar .Usize +@[reducible] def U8 := Scalar .U8 +@[reducible] def U16 := Scalar .U16 +@[reducible] def U32 := Scalar .U32 +@[reducible] def U64 := Scalar .U64 +@[reducible] def U128 := Scalar .U128 + +-- TODO: below: not sure this is the best way. +-- Should we rather overload operations like +, -, etc.? +-- Also, it is possible to automate the generation of those definitions +-- with macros (but would it be a good idea? It would be less easy to +-- read the file, which is not supposed to change a lot) + +-- Negation + +/-- +Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce +one here. + +The notation typeclass for heterogeneous addition. +This enables the notation `- a : β` where `a : α`. +-/ +class HNeg (α : Type u) (β : outParam (Type v)) where + /-- `- a` computes the negation of `a`. + The meaning of this notation is type-dependent. -/ + hNeg : α → β + +prefix:75 "-" => HNeg.hNeg + +instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x +instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x +instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x +instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x +instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x +instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x + +-- Addition +instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hAdd x y := Scalar.add x y + +-- Substraction +instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hSub x y := Scalar.sub x y + +-- Multiplication +instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hMul x y := Scalar.mul x y + +-- Division +instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hDiv x y := Scalar.div x y + +-- Remainder +instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hMod x y := Scalar.rem x y + +-- ofIntCore +-- TODO: typeclass? +def Isize.ofIntCore := @Scalar.ofIntCore .Isize +def I8.ofIntCore := @Scalar.ofIntCore .I8 +def I16.ofIntCore := @Scalar.ofIntCore .I16 +def I32.ofIntCore := @Scalar.ofIntCore .I32 +def I64.ofIntCore := @Scalar.ofIntCore .I64 +def I128.ofIntCore := @Scalar.ofIntCore .I128 +def Usize.ofIntCore := @Scalar.ofIntCore .Usize +def U8.ofIntCore := @Scalar.ofIntCore .U8 +def U16.ofIntCore := @Scalar.ofIntCore .U16 +def U32.ofIntCore := @Scalar.ofIntCore .U32 +def U64.ofIntCore := @Scalar.ofIntCore .U64 +def U128.ofIntCore := @Scalar.ofIntCore .U128 + +-- ofInt +-- TODO: typeclass? +def Isize.ofInt := @Scalar.ofInt .Isize +def I8.ofInt := @Scalar.ofInt .I8 +def I16.ofInt := @Scalar.ofInt .I16 +def I32.ofInt := @Scalar.ofInt .I32 +def I64.ofInt := @Scalar.ofInt .I64 +def I128.ofInt := @Scalar.ofInt .I128 +def Usize.ofInt := @Scalar.ofInt .Usize +def U8.ofInt := @Scalar.ofInt .U8 +def U16.ofInt := @Scalar.ofInt .U16 +def U32.ofInt := @Scalar.ofInt .U32 +def U64.ofInt := @Scalar.ofInt .U64 +def U128.ofInt := @Scalar.ofInt .U128 + +-- Comparisons +instance {ty} : LT (Scalar ty) where + lt a b := LT.lt a.val b.val + +instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val + +instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. +instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. + +theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j + | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl + +theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := + h ▸ rfl + +theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := + fun h' => absurd (val_eq_of_eq h') h + +instance (ty : ScalarTy) : DecidableEq (Scalar ty) := + fun i j => + match decEq i.val j.val with + | isTrue h => isTrue (Scalar.eq_of_val_eq h) + | isFalse h => isFalse (Scalar.ne_of_val_ne h) + +def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val + +-- Tactic to prove that integers are in bounds +syntax "intlit" : tactic + +macro_rules + | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) + +-- -- We now define a type class that subsumes the various machine integer types, so +-- -- as to write a concise definition for scalar_cast, rather than exhaustively +-- -- enumerating all of the possible pairs. We remark that Rust has sane semantics +-- -- and fails if a cast operation would involve a truncation or modulo. + +-- class MachineInteger (t: Type) where +-- size: Nat +-- val: t -> Fin size +-- ofNatCore: (n:Nat) -> LT.lt n size -> t + +-- set_option hygiene false in +-- run_cmd +-- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do +-- Lean.Elab.Command.elabCommand (← `( +-- namespace $typeName +-- instance: MachineInteger $typeName where +-- size := size +-- val := val +-- ofNatCore := ofNatCore +-- end $typeName +-- )) + +-- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on +-- -- Lean to infer `src`. + +-- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := +-- if h: MachineInteger.val x < MachineInteger.size dst then +-- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) +-- else +-- .fail integerOverflow + +------------- +-- VECTORS -- +------------- + +def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } + +def vec_new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ + +def vec_len (α : Type u) (v : Vec α) : Usize := + let ⟨ v, l ⟩ := v + Usize.ofIntCore (List.length v) (by simp [Scalar.min]) l + +def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () + +def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) + := + let nlen := List.length v.val + 1 + if h : nlen ≤ U32.max || nlen ≤ Usize.max then + have h : nlen ≤ Usize.max := by + simp at * + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> + simp [*] at * <;> + try assumption + cases h <;> + linarith + return ⟨ List.concat v.val x, by simp at *; assumption ⟩ + else + fail maximumSizeExceeded + +def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := + if i.val < List.length v.val then + .ret () + else + .fail arrayOutOfBounds + +def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := + if i.val < List.length v.val then + -- TODO: maybe we should redefine a list library which uses integers + -- (instead of natural numbers) + let i := i.val.toNat + .ret ⟨ List.set v.val i x, by + have h: List.length v.val ≤ Usize.max := v.property + simp [*] at * + assumption + ⟩ + else + .fail arrayOutOfBounds + +def vec_index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : + Fin (List.length v.val) := + let j := i.val.toNat + let h: j < List.length v.val := by + have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin + apply heq.mpr + assumption + ⟨j, h⟩ + +def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret (List.get v.val i) + else + .fail arrayOutOfBounds + +def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := + if i.val < List.length v.val then + .ret () + else + .fail arrayOutOfBounds + +def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret (List.get v.val i) + else + .fail arrayOutOfBounds + +def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := + if h: i.val < List.length v.val then + let i := vec_index_to_fin h + .ret ⟨ List.set v.val i x, by + have h: List.length v.val ≤ Usize.max := v.property + simp [*] at * + assumption + ⟩ + else + .fail arrayOutOfBounds + +---------- +-- MISC -- +---------- + +@[simp] def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := x +@[simp] def mem_replace_back (a : Type) (_ : a) (y : a) : a := y + +/-- Aeneas-translated function -- useful to reduce non-recursive definitions. + Use with `simp [ aeneas ]` -/ +register_simp_attr aeneas diff --git a/backends/lean/Primitives.lean b/backends/lean/Primitives.lean deleted file mode 100644 index e7826fbf..00000000 --- a/backends/lean/Primitives.lean +++ /dev/null @@ -1,637 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd -import Mathlib.Tactic.Linarith - --------------------- --- ASSERT COMMAND --Std. --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] - -theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] - -theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * - -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified - linarith - -theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * <;> - -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified - linarith - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty ≤ val - hmax : val ≤ Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty ≤ x ∧ x ≤ Scalar.cMax ty -> - Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty - := - λ h => by - apply And.intro <;> have hmin := Scalar.cMin_bound ty <;> have hmax := Scalar.cMax_bound ty <;> linarith - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : Scalar ty := - let ⟨ hmin, hmax ⟩ := h - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if h: (Scalar.cMin ty ≤ x || Scalar.min ty ≤ x) && (x ≤ Scalar.cMax ty || x ≤ Scalar.max ty) then - let h: Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by - simp at * - have ⟨ hmin, hmax ⟩ := h - have hbmin := Scalar.cMin_bound ty - have hbmax := Scalar.cMax_bound ty - cases hmin <;> cases hmax <;> apply And.intro <;> linarith - let ⟨ hmin, hmax ⟩ := h - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Our custom remainder operation, which satisfies the semantics of Rust --- TODO: is there a better way? -def scalar_rem (x y : Int) : Int := - if 0 ≤ x then |x| % |y| - else - (|x| % |y|) - --- Our custom division operation, which satisfies the semantics of Rust --- TODO: is there a better way? -def scalar_div (x y : Int) : Int := - if 0 ≤ x && 0 ≤ y then |x| / |y| - else if 0 ≤ x && y < 0 then - (|x| / |y|) - else if x < 0 && 0 ≤ y then - (|x| / |y|) - else |x| / |y| - --- Checking that the remainder operation is correct -#assert scalar_rem 1 2 = 1 -#assert scalar_rem (-1) 2 = -1 -#assert scalar_rem 1 (-2) = 1 -#assert scalar_rem (-1) (-2) = -1 -#assert scalar_rem 7 3 = (1:Int) -#assert scalar_rem (-7) 3 = -1 -#assert scalar_rem 7 (-3) = 1 -#assert scalar_rem (-7) (-3) = -1 - --- Checking that the division operation is correct -#assert scalar_div 3 2 = 1 -#assert scalar_div (-3) 2 = -1 -#assert scalar_div 3 (-2) = -1 -#assert scalar_div (-3) (-2) = 1 -#assert scalar_div 7 3 = 2 -#assert scalar_div (-7) 3 = -2 -#assert scalar_div 7 (-3) = -2 -#assert scalar_div (-7) (-3) = 2 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by simp [Scalar.min]) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - let nlen := List.length v.val + 1 - if h : nlen ≤ U32.max || nlen ≤ Usize.max then - have h : nlen ≤ Usize.max := by - simp at * - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * <;> - try assumption - cases h <;> - linarith - return ⟨ List.concat v.val x, by simp at *; assumption ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i := i.val.toNat - .ret ⟨ List.set v.val i x, by - have h: List.length v.val ≤ Usize.max := v.property - simp [*] at * - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : - Fin (List.length v.val) := - let j := i.val.toNat - let h: j < List.length v.val := by - have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin - apply heq.mpr - assumption - ⟨j, h⟩ - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if h: i.val < List.length v.val then - let i := vec_index_to_fin h - .ret (List.get v.val i) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if h: i.val < List.length v.val then - let i := vec_index_to_fin h - .ret (List.get v.val i) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if h: i.val < List.length v.val then - let i := vec_index_to_fin h - .ret ⟨ List.set v.val i x, by - have h: List.length v.val ≤ Usize.max := v.property - simp [*] at * - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/backends/lean/lake-manifest.json b/backends/lean/lake-manifest.json index 7b23fc19..e5d362fc 100644 --- a/backends/lean/lake-manifest.json +++ b/backends/lean/lake-manifest.json @@ -4,24 +4,24 @@ [{"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "f89ee53085b8aad0bacd3bc94d7ef4b8d9aba643", + "rev": "cdb1b898e4317567699181f27533182046ebc544", "name": "mathlib", "inputRev?": null}}, {"git": {"url": "https://github.com/gebner/quote4", "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", + "rev": "c71f94e34c1cda52eef5c93dc9da409ab2727420", "name": "Qq", "inputRev?": "master"}}, {"git": {"url": "https://github.com/JLimperg/aesop", "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", + "rev": "ca73109cc40837bc61df8024c9016da4b4f99d4c", "name": "aesop", "inputRev?": "master"}}, {"git": {"url": "https://github.com/leanprover/std4", "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", + "rev": "6932c4ea52914dc6b0488944e367459ddc4d01a6", "name": "std", "inputRev?": "main"}}]} diff --git a/backends/lean/lakefile.lean b/backends/lean/lakefile.lean index c5e27d1c..21a4a332 100644 --- a/backends/lean/lakefile.lean +++ b/backends/lean/lakefile.lean @@ -8,4 +8,4 @@ require mathlib from git package «base» {} @[default_target] -lean_lib «Primitives» {} +lean_lib «Base» {} -- cgit v1.2.3 From c034a7ea1335705ca1e1a7461fac257df6757d57 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Fri, 9 Jun 2023 16:07:39 +0200 Subject: Start working on extrinsic proofs of termination --- backends/lean/Base.lean | 1 + backends/lean/Base/Diverge.lean | 208 +++++++++++++++++++++++++++++++++++++ backends/lean/Base/Primitives.lean | 29 ++++-- backends/lean/lean-toolchain | 1 + 4 files changed, 232 insertions(+), 7 deletions(-) create mode 100644 backends/lean/Base/Diverge.lean create mode 100644 backends/lean/lean-toolchain diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index 960b2bb5..92e87e6c 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -1 +1,2 @@ import Base.Primitives +import Base.Diverge diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean new file mode 100644 index 00000000..bd500c25 --- /dev/null +++ b/backends/lean/Base/Diverge.lean @@ -0,0 +1,208 @@ +import Lean +import Base.Primitives + +namespace Diverge + +open Primitives + +section Fix + +open Result + +variable {a b : Type} + +/-! # The least fixed point definition and its properties -/ + +def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) +noncomputable def least (p : Nat → Prop) : Nat := + Classical.epsilon (least_p p) + +-- Auxiliary theorem for [least_spec]: if there exists an `n` satisfying `p`, +-- there there exists a least `m` satisfying `p`. +theorem least_spec_aux (p : Nat → Prop) : ∀ (n : Nat), (hn : p n) → ∃ m, least_p p m := by + apply Nat.strongRec' + intros n hi hn + -- Case disjunction on: is n the smallest n satisfying p? + match Classical.em (∀ m, m < n → ¬ p m) with + | .inl hlt => + -- Yes: trivial + exists n + | .inr hlt => + simp at * + let ⟨ m, ⟨ hmlt, hm ⟩ ⟩ := hlt + have hi := hi m hmlt hm + apply hi + +-- The specification of [least]: either `p` is never satisfied, or it is satisfied +-- by `least p` and no `n < least p` satisfies `p`. +theorem least_spec (p : Nat → Prop) : (∀ n, ¬ p n) ∨ (p (least p) ∧ ∀ n, n < least p → ¬ p n) := by + -- Case disjunction on the existence of an `n` which satisfies `p` + match Classical.em (∀ n, ¬ p n) with + | .inl h => + -- There doesn't exist: trivial + apply (Or.inl h) + | .inr h => + -- There exists: we simply use `least_spec_aux` in combination with the property + -- of the epsilon operator + simp at * + let ⟨ n, hn ⟩ := h + apply Or.inr + have hl := least_spec_aux p n hn + have he := Classical.epsilon_spec hl + apply he + +/-! # The fixed point definitions -/ + +def fix_fuel (n : Nat) (f : (a → Result b) → a → Result b) (x : a) : Result b := + match n with + | 0 => .div + | n + 1 => + f (fix_fuel n f) x + +@[simp] def fix_fuel_pred (f : (a → Result b) → a → Result b) (x : a) (n : Nat) := + not (div? (fix_fuel n f x)) + +def fix_fuel_P (f : (a → Result b) → a → Result b) (x : a) (n : Nat) : Prop := + fix_fuel_pred f x n + +noncomputable def fix (f : (a → Result b) → a → Result b) (x : a) : Result b := + fix_fuel (least (fix_fuel_P f x)) f x + +/-! # The proof of the fixed point equation -/ + +-- Monotonicity relation over results +-- TODO: generalize +def result_rel {a : Type u} (x1 x2 : Result a) : Prop := + match x1 with + | div => True + | fail _ => x2 = x1 + | ret _ => x2 = x1 -- TODO: generalize + +-- Monotonicity relation over monadic arrows +-- TODO: generalize +def marrow_rel (f g : a → Result b) : Prop := + ∀ x, result_rel (f x) (g x) + +-- Validity property for a body +def is_valid (f : (a → Result b) → a → Result b) : Prop := + ∀ {{g h}}, marrow_rel g h → marrow_rel (f g) (f h) + +/- + + -/ + +theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : + ∀ {{n m}}, n ≤ m → marrow_rel (fix_fuel n f) (fix_fuel m f) := by + intros n + induction n + case zero => simp [marrow_rel, fix_fuel, result_rel] + case succ n1 Hi => + intros m Hle x + simp [result_rel] + match m with + | 0 => + exfalso + -- TODO: annoying to do those conversions by hand - try zify? + have : n1 + 1 ≤ (0 : Int) := by simp [*] at * + have : 0 ≤ n1 := by simp [*] at * + linarith + | Nat.succ m1 => + simp_arith at Hle + simp [fix_fuel] + have Hi := Hi Hle + simp [is_valid] at Hvalid + have Hvalid := Hvalid Hi x + simp [result_rel] at Hvalid + apply Hvalid + +@[simp] theorem neg_fix_fuel_P {f : (a → Result b) → a → Result b} {x : a} {n : Nat} : + ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by + simp [fix_fuel_P, div?] + cases fix_fuel n f x <;> simp + +theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : + ∀ n, marrow_rel (fix_fuel n f) (fix f) := by + intros n x + simp [result_rel] + have Hl := least_spec (fix_fuel_P f x) + simp at Hl + match Hl with + | .inl Hl => simp [*] + | .inr ⟨ Hl, Hn ⟩ => + match Classical.em (fix_fuel n f x = div) with + | .inl Hd => + simp [*] + | .inr Hd => + have Hineq : least (fix_fuel_P f x) ≤ n := by + -- Proof by contradiction + cases Classical.em (least (fix_fuel_P f x) ≤ n) <;> simp [*] + simp at * + rename_i Hineq + have Hn := Hn n Hineq + contradiction + have Hfix : ¬ (fix f x = div) := by + simp [fix] + -- By property of the least upper bound + revert Hd Hl + -- TODO: there is no conversion to select the head of a function! + have : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := + by simp[fix_fuel_P] + simp [this, div?] + clear this + cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp + have Hmono := fix_fuel_mono Hvalid Hineq x + simp [result_rel] at Hmono + -- TODO: there is no conversion to select the head of a function! + revert Hmono Hfix Hd + simp [fix] + -- TODO: it would be good if cases actually introduces an equation: this + -- way we wouldn't have to do all the book-keeping + cases fix_fuel (least (fix_fuel_P f x)) f x <;> cases fix_fuel n f x <;> + intros <;> simp [*] at * + +theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : + ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by sorry + +theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_valid f) : + ∀ x, fix f x = f (fix f) x := by + intros x + -- conv => lhs; simp [fix] + -- Case disjunction: is there a fuel such that the execution successfully execute? + match Classical.em (∃ n, fix_fuel_P f x n) with + | .inr He => + -- No fuel: the fixed point evaluates to `div` + --simp [fix] at * + simp at * + simp [fix] + have He := He (Nat.succ (least (fix_fuel_P f x))) + simp [*, fix_fuel] at * + -- Use the monotonicity of `f` + have Hmono := fix_fuel_fix_mono Hvalid (least (fix_fuel_P f x)) x + simp [result_rel] at Hmono + simp [*] at * + -- TODO: we need a stronger validity predicate + sorry + | .inl ⟨ n, He ⟩ => + have Hl := fix_fuel_P_least Hvalid He + -- TODO: better control of simplification + have Heq : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := + by simp [fix_fuel_P] + simp [Heq] at Hl; clear Heq + -- The least upper bound is > 0 + have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by sorry + simp [Hsucc] at Hl + revert Hl + simp [*, div?, fix, fix_fuel] + -- Use the monotonicity + have Hineq : n ≤ Nat.succ n := by sorry + have Hmono := fix_fuel_fix_mono Hvalid n + have Hv := Hvalid Hmono x + -- Use functional extensionality + simp [result_rel, fix] at Hv + revert Hv + split <;> simp [*] <;> intros <;> simp [*] + + +end Fix + +end Diverge diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index d3de1d10..85e088fc 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -4,6 +4,8 @@ import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith +namespace Primitives + -------------------- -- ASSERT COMMAND --Std. -------------------- @@ -46,6 +48,7 @@ open Error inductive Result (α : Type u) where | ret (v: α): Result α | fail (e: Error): Result α + | div deriving Repr, BEq open Result @@ -53,20 +56,28 @@ open Result instance Result_Inhabited (α : Type u) : Inhabited (Result α) := Inhabited.mk (fail panic) +instance Result_Nonempty (α : Type u) : Nonempty (Result α) := + Nonempty.intro div + /- HELPERS -/ def ret? {α: Type} (r: Result α): Bool := match r with - | Result.ret _ => true - | Result.fail _ => false + | ret _ => true + | fail _ | div => false + +def div? {α: Type} (r: Result α): Bool := + match r with + | div => true + | ret _ | fail _ => false def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure + if b then ret () else fail assertionFailure def eval_global {α: Type} (x: Result α) (_: ret? x): α := match x with - | Result.fail _ => by contradiction - | Result.ret x => x + | fail _ | div => by contradiction + | ret x => x /- DO-DSL SUPPORT -/ @@ -74,6 +85,7 @@ def bind (x: Result α) (f: α -> Result β) : Result β := match x with | ret v => f v | fail v => fail v + | div => div -- Allows using Result in do-blocks instance : Bind Result where @@ -92,8 +104,9 @@ instance : Pure Result where def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e + | ret x => ret ⟨x, rfl⟩ + | fail e => fail e + | div => div macro "let" e:term " ⟵ " f:term : doElem => `(doElem| let ⟨$e, h⟩ ← Result.attach $f) @@ -648,3 +661,5 @@ def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec /-- Aeneas-translated function -- useful to reduce non-recursive definitions. Use with `simp [ aeneas ]` -/ register_simp_attr aeneas + +end Primitives diff --git a/backends/lean/lean-toolchain b/backends/lean/lean-toolchain new file mode 100644 index 00000000..1211e372 --- /dev/null +++ b/backends/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:nightly-2023-05-31 \ No newline at end of file -- cgit v1.2.3 From ef6204e1e1b0a21975fcd9e3d0e5aa7ec3d9125f Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 13 Jun 2023 16:22:08 +0200 Subject: Find sufficient validity criteria for Diverge.lean --- backends/lean/Base/Diverge.lean | 350 +++++++++++++++++++++++++++++++++++----- 1 file changed, 309 insertions(+), 41 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index bd500c25..b5264d0d 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -5,7 +5,7 @@ namespace Diverge open Primitives -section Fix +namespace Fix open Result @@ -79,19 +79,32 @@ def result_rel {a : Type u} (x1 x2 : Result a) : Prop := | ret _ => x2 = x1 -- TODO: generalize -- Monotonicity relation over monadic arrows +-- TODO: Kleisli arrow -- TODO: generalize def marrow_rel (f g : a → Result b) : Prop := ∀ x, result_rel (f x) (g x) --- Validity property for a body -def is_valid (f : (a → Result b) → a → Result b) : Prop := +-- Monotonicity property +def is_mono (f : (a → Result b) → a → Result b) : Prop := ∀ {{g h}}, marrow_rel g h → marrow_rel (f g) (f h) +-- "Continuity" property. +-- We need this, and this looks a lot like continuity. Also see this paper: +-- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf +def is_cont (f : (a → Result b) → a → Result b) : Prop := + ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div + +-- Validity property for a body +structure is_valid (f : (a → Result b) → a → Result b) := + intro:: + hmono : is_mono f + hcont : is_cont f + /- -/ -theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : +theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : ∀ {{n m}}, n ≤ m → marrow_rel (fix_fuel n f) (fix_fuel m f) := by intros n induction n @@ -110,17 +123,16 @@ theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hvalid : is_val simp_arith at Hle simp [fix_fuel] have Hi := Hi Hle - simp [is_valid] at Hvalid - have Hvalid := Hvalid Hi x - simp [result_rel] at Hvalid - apply Hvalid + have Hmono := Hmono Hi x + simp [result_rel] at Hmono + apply Hmono @[simp] theorem neg_fix_fuel_P {f : (a → Result b) → a → Result b} {x : a} {n : Nat} : ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by simp [fix_fuel_P, div?] cases fix_fuel n f x <;> simp -theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : +theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : ∀ n, marrow_rel (fix_fuel n f) (fix f) := by intros n x simp [result_rel] @@ -150,7 +162,7 @@ theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hvalid : is simp [this, div?] clear this cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp - have Hmono := fix_fuel_mono Hvalid Hineq x + have Hmono := fix_fuel_mono Hmono Hineq x simp [result_rel] at Hmono -- TODO: there is no conversion to select the head of a function! revert Hmono Hfix Hd @@ -160,9 +172,42 @@ theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hvalid : is cases fix_fuel (least (fix_fuel_P f x)) f x <;> cases fix_fuel n f x <;> intros <;> simp [*] at * -theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hvalid : is_valid f) : - ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by sorry +theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by + intros x n Hf + have Hfmono := fix_fuel_fix_mono Hmono n x + revert Hf Hfmono + -- TODO: would be good to be able to unfold fix_fuel_P only on the left + simp [fix_fuel_P, div?, result_rel, fix] + cases fix_fuel n f x <;> simp_all +-- Prove the fixed point equation in the case there exists some fuel for which +-- the execution terminates +theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono : is_mono f) + (x : a) (n : Nat) (He : fix_fuel_P f x n) : + fix f x = f (fix f) x := by + have Hl := fix_fuel_P_least Hmono He + -- TODO: better control of simplification + have Heq : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := + by simp [fix_fuel_P] + simp [Heq] at Hl; clear Heq + -- The least upper bound is > 0 + have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by + revert Hl + simp [div?] + cases least (fix_fuel_P f x) <;> simp [fix_fuel] + simp [Hsucc] at Hl + revert Hl + simp [*, div?, fix, fix_fuel] + -- Use the monotonicity + have Hfixmono := fix_fuel_fix_mono Hmono n + have Hvm := Hmono Hfixmono x + -- Use functional extensionality + simp [result_rel, fix] at Hvm + revert Hvm + split <;> simp [*] <;> intros <;> simp [*] + +-- The final fixed point equation theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_valid f) : ∀ x, fix f x = f (fix f) x := by intros x @@ -173,36 +218,259 @@ theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_vali -- No fuel: the fixed point evaluates to `div` --simp [fix] at * simp at * - simp [fix] - have He := He (Nat.succ (least (fix_fuel_P f x))) - simp [*, fix_fuel] at * - -- Use the monotonicity of `f` - have Hmono := fix_fuel_fix_mono Hvalid (least (fix_fuel_P f x)) x - simp [result_rel] at Hmono - simp [*] at * - -- TODO: we need a stronger validity predicate - sorry - | .inl ⟨ n, He ⟩ => - have Hl := fix_fuel_P_least Hvalid He - -- TODO: better control of simplification - have Heq : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := - by simp [fix_fuel_P] - simp [Heq] at Hl; clear Heq - -- The least upper bound is > 0 - have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by sorry - simp [Hsucc] at Hl - revert Hl - simp [*, div?, fix, fix_fuel] - -- Use the monotonicity - have Hineq : n ≤ Nat.succ n := by sorry - have Hmono := fix_fuel_fix_mono Hvalid n - have Hv := Hvalid Hmono x - -- Use functional extensionality - simp [result_rel, fix] at Hv - revert Hv - split <;> simp [*] <;> intros <;> simp [*] - + conv => lhs; simp [fix] + have Hel := He (Nat.succ (least (fix_fuel_P f x))); simp [*, fix_fuel] at *; clear Hel + -- Use the "continuity" of `f` + have He : ∀ n, fix_fuel (.succ n) f x = div := by intros; simp [*] + have Hcont := Hvalid.hcont x He + simp [Hcont] + | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hvalid.hmono x n He +/- +(∀ n, fix_fuel n f x = div) + +⊢ f (fun y => fix_fuel (least (fix_fuel_P f y)) f y) x = div + +(? x. p x) ==> p (epsilon p) + + +P (nf : a -> option Nat) := + match nf x with + | None => forall n, fix_fuel n f x = div + | Some n => fix_fuel n f x <> div + +TODO: theorem de Tarsky, +Gilles Dowek (Introduction à la théorie des langages de programmation) + +fix_f is f s.t.: f x = f (fix f) x ∧ ! g. g x = g (fix g) x ==> f <= g + +-/ + end Fix +namespace Ex1 + /- An example of use of the fixed-point -/ + open Fix + + variable {a : Type} (f : (List a × Int) → Result a) + + def list_nth_body (x : (List a × Int)) : Result a := + let (ls, i) := x + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else f (tl, i - 1) + + theorem list_nth_body_mono : is_mono (@list_nth_body a) := by + simp [is_mono]; intro g h Hr (ls, i); simp [result_rel, list_nth_body] + cases ls <;> simp + rename_i hd tl + -- TODO: making a case disjunction over `i = 0` is annoying, we need a more + -- general tactic for this + cases (Classical.em (Eq i 0)) <;> simp [*] at * + apply Hr + + theorem list_nth_body_cont : is_cont (@list_nth_body a) := by + rw [is_cont]; intro (ls, i) Hdiv; simp [list_nth_body, fix_fuel] at * + cases ls <;> simp at * + -- TODO: automate this + cases (Classical.em (Eq i 0)) <;> simp [*] at * + -- Recursive call + apply Hdiv + + noncomputable + def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + + theorem list_nth_eq (ls : List a) (i : Int) : + list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else list_nth tl (i - 1) + := by + have Hvalid : is_valid (@list_nth_body a) := + is_valid.intro list_nth_body_mono list_nth_body_cont + have Heq := fix_fixed_eq (@list_nth_body a) Hvalid + simp [Heq, list_nth] + conv => lhs; rw [list_nth_body] + simp [Heq] + +end Ex1 + +namespace Ex2 + /- Higher-order example -/ + open Fix + + variable {a b : Type} + + /- An auxiliary function, which doesn't require the fixed-point -/ + def map (f : a → Result b) (ls : List a) : Result (List b) := + match ls with + | [] => .ret [] + | hd :: tl => + do + match f hd with + | .ret hd => + match map f tl with + | .ret tl => + .ret (hd :: tl) + | r => r + | .fail e => .fail e + | .div => .div + + theorem map_is_mono {{f g : a → Result b}} (Hr : marrow_rel f g) : + ∀ ls, result_rel (map f ls) (map g ls) := by + intro ls; induction ls <;> simp [result_rel, map] + case cons hd tl Hi => + have Hr1 := Hr hd; simp [result_rel] at Hr1 + -- TODO: reverting is annoying + revert Hr1 + cases f hd <;> intro Hr1 <;> simp [*] + -- ret case + simp [result_rel] at Hi + -- TODO: annoying + revert Hi + cases map f tl <;> intro Hi <;> simp [*] + + -- Auxiliary definition + def map_fix_fuel (n0 n1 : Nat) (f : (a → Result b) → a → Result b) (ls : List a) : Result (List b) := + match ls with + | [] => .ret [] + | hd :: tl => + do + match fix_fuel n0 f hd with + | .ret hd => + match map (fix_fuel n1 f) tl with + | .ret tl => + .ret (hd :: tl) + | r => r + | .fail e => .fail e + | .div => .div + + def exists_map_fix_fuel_not_div_imp {{f : (a → Result b) → a → Result b}} {{ls : List a}} + (Hmono : is_mono f) : + (∃ n0 n1, map_fix_fuel n0 n1 f ls ≠ .div) → + ∃ n2, map (fix_fuel n2 f) ls ≠ .div := by + intro ⟨ n0, n1, Hnd ⟩ + exists n0 + n1 + have Hineq0 : n0 ≤ n0 + n1 := by linarith + have Hineq1 : n1 ≤ n0 + n1 := by linarith + simp [map_fix_fuel] at Hnd + -- TODO: I would like a rewrite_once tactic + unfold map; simp + -- + revert Hnd + cases ls <;> simp + rename_i hd tl + -- Use the monotonicity of fix_fuel + have Hfmono := fix_fuel_mono Hmono Hineq0 hd + simp [result_rel] at Hfmono; revert Hfmono + cases fix_fuel n0 f hd <;> intro <;> simp [*] + -- Use the monotonicity of map + have Hfmono := fix_fuel_mono Hmono Hineq1 + have Hmmono := map_is_mono Hfmono tl + simp [result_rel] at Hmmono; revert Hmmono + cases map (fix_fuel n1 f) tl <;> intro <;> simp [*] + + -- TODO: it is simpler to prove the contrapositive of is_cont than is_cont itself. + -- The proof is still quite technical: think of a criteria whose proof is simpler + -- to automate. + theorem map_is_cont_contra_aux {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : + ∀ ls, map (fix f) ls ≠ .div → + ∃ n0 n1, map_fix_fuel n0 n1 f ls ≠ .div + := by + intro ls; induction ls <;> simp [result_rel, map_fix_fuel, map] + simp [fix] + case cons hd tl Hi => + -- Instantiate the first n and do a case disjunction + intro Hf; exists (least (fix_fuel_P f hd)); revert Hf + cases fix_fuel (least (fix_fuel_P f hd)) f hd <;> simp + -- Use the induction hyp + have Hr := Classical.em (map (fix f) tl = .div) + simp [fix] at * + cases Hr <;> simp_all + have Hj : ∃ n2, map (fix_fuel n2 f) tl ≠ .div := exists_map_fix_fuel_not_div_imp Hmono Hi + revert Hj; intro ⟨ n2, Hj ⟩ + intro Hf; exists n2; revert Hf + revert Hj; cases map (fix_fuel n2 f) tl <;> simp_all + + theorem map_is_cont_contra {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : + ∀ ls, map (fix f) ls ≠ .div → + ∃ n, map (fix_fuel n f) ls ≠ .div + := by + intro ls Hf + have Hc := map_is_cont_contra_aux Hmono ls Hf + apply exists_map_fix_fuel_not_div_imp <;> assumption + + theorem map_is_cont {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : + ∀ ls, (Hc : ∀ n, map (fix_fuel n f) ls = .div) → + map (fix f) ls = .div + := by + intro ls Hc + -- TODO: is there a tactic for proofs by contraposition? + apply Classical.byContradiction; intro Hndiv + let ⟨ n, Hcc ⟩ := map_is_cont_contra Hmono ls Hndiv + simp_all + + /- An example which uses map -/ + inductive Tree (a : Type) := + | leaf (x : a) + | node (tl : List (Tree a)) + + def id_body (f : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + match map f tl with + | .div => .div + | .fail e => .fail e + | .ret tl => .ret (.node tl) + + theorem id_body_mono : is_mono (@id_body a) := by + simp [is_mono]; intro g h Hr t; simp [result_rel, id_body] + cases t <;> simp + rename_i tl + have Hmmono := map_is_mono Hr tl + revert Hmmono; simp [result_rel] + cases map g tl <;> simp_all + + theorem id_body_cont : is_cont (@id_body a) := by + rw [is_cont]; intro t Hdiv + simp [fix_fuel] at * + -- TODO: weird things are happening with the rewriter and the simplifier here + rw [id_body] + simp [id_body] at Hdiv + -- + cases t <;> simp at * + rename_i tl + -- TODO: automate this + have Hmc := map_is_cont id_body_mono tl + have Hdiv : ∀ (n : ℕ), map (fix_fuel n id_body) tl = Result.div := by + intro n + have Hdiv := Hdiv n; revert Hdiv + cases map (fix_fuel n id_body) tl <;> simp_all + have Hmc := Hmc Hdiv; revert Hmc + cases map (fix id_body) tl <;> simp_all + + noncomputable def id (t : Tree a) := fix id_body t + + theorem id_eq (t : Tree a) : + id t = + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + match map id tl with + | .div => .div + | .fail e => .fail e + | .ret tl => .ret (.node tl) + := by + have Hvalid : is_valid (@id_body a) := + is_valid.intro id_body_mono id_body_cont + have Heq := fix_fixed_eq (@id_body a) Hvalid + conv => lhs; rw [id, Heq, id_body] + +end Ex2 + end Diverge -- cgit v1.2.3 From ccc97b46c166a45255096d3fec2444c90f7c5aaa Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 14 Jun 2023 11:24:58 +0200 Subject: Make minor modifications --- backends/lean/Base/Diverge.lean | 31 +++++++++++++++++++++++++------ backends/lean/Base/Primitives.lean | 1 + 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index b5264d0d..37d8eb27 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -11,6 +11,27 @@ open Result variable {a b : Type} +/- +TODO: +- we want an easier to use cases: + - keeps in the goal an equation of the shape: `t = case` + - if called on Prop terms, uses Classical.em + Actually, the cases from mathlib seems already quite powerful + (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) + For instance: cases h : e + Also: cases_matching +- better split tactic +- we need conversions to operate on the head of applications. + Actually, something like this works: + ``` + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + ``` + Maybe we need a rpt ... ; focus? +- simplifier/rewriter have a strange behavior sometimes +-/ + /-! # The least fixed point definition and its properties -/ def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) @@ -115,9 +136,7 @@ theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono match m with | 0 => exfalso - -- TODO: annoying to do those conversions by hand - try zify? - have : n1 + 1 ≤ (0 : Int) := by simp [*] at * - have : 0 ≤ n1 := by simp [*] at * + zify at * linarith | Nat.succ m1 => simp_arith at Hle @@ -188,9 +207,9 @@ theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono fix f x = f (fix f) x := by have Hl := fix_fuel_P_least Hmono He -- TODO: better control of simplification - have Heq : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := - by simp [fix_fuel_P] - simp [Heq] at Hl; clear Heq + conv at Hl => + apply congr_fun + simp [fix_fuel_P] -- The least upper bound is > 0 have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by revert Hl diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 85e088fc..6b922143 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -526,6 +526,7 @@ instance (ty : ScalarTy) : DecidableEq (Scalar ty) := def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val -- Tactic to prove that integers are in bounds +-- TODO: use this: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/instance.20with.20tactic.20autoparam syntax "intlit" : tactic macro_rules -- cgit v1.2.3 From 04cefd3b4f3d2c11cfc3542a5ad6fae31dae4796 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Sun, 18 Jun 2023 19:09:19 +0200 Subject: Make minor modifications --- backends/lean/Base.lean | 1 + backends/lean/Base/Primitives.lean | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index 92e87e6c..f6a78bba 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -1,2 +1,3 @@ import Base.Primitives import Base.Diverge +import Base.TestTactics diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 6b922143..d6cc0bad 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -20,9 +20,8 @@ def assertImpl : CommandElab := fun (_stx: Syntax) => do runTermElabM (fun _ => do let r ← evalTerm Bool (mkConst ``Bool) _stx[1] if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" + logInfo ("Assertion failed for:\n" ++ _stx[1]) + throwError ("Expression reduced to false:\n" ++ _stx[1]) pure ()) #eval 2 == 2 -- cgit v1.2.3 From 75f5f8a68b0ce028689c1d880ec99448e6d8dc3a Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 15:03:00 +0200 Subject: Make progress on making the proofs in Diverge more systematic --- backends/lean/Base/Diverge.lean | 260 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 252 insertions(+), 8 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 37d8eb27..0eff17e3 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -1,12 +1,76 @@ import Lean -import Base.Primitives +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Tauto namespace Diverge -open Primitives +namespace Primitives + +inductive Error where + | assertionFailure: Error + | integerOverflow: Error + | divisionByZero: Error + | arrayOutOfBounds: Error + | maximumSizeExceeded: Error + | panic: Error +deriving Repr, BEq + +open Error + +inductive Result (α : Type u) where + | ret (v: α): Result α + | fail (e: Error): Result α + | div +deriving Repr, BEq + +open Result + +-- instance Result_Inhabited (α : Type u) : Inhabited (Result α) := +-- Inhabited.mk (fail panic) + +-- instance Result_Nonempty (α : Type u) : Nonempty (Result α) := +-- Nonempty.intro div + +def bind (x: Result α) (f: α -> Result β) : Result β := + match x with + | ret v => f v + | fail v => fail v + | div => div + +@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] +@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] +@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] + +-- Allows using Result in do-blocks +instance : Bind Result where + bind := bind + +-- Allows using return x in do-blocks +instance : Pure Result where + pure := fun x => ret x + +@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : + (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : + (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_div (f : α → Result β) : + (do let y ← div; f y) = div := by simp [Bind.bind, bind] + +def div? {α: Type} (r: Result α): Bool := + match r with + | div => true + | ret _ | fail _ => false + +end Primitives namespace Fix +open Primitives open Result variable {a b : Type} @@ -123,7 +187,7 @@ structure is_valid (f : (a → Result b) → a → Result b) := /- - -/ + -/ theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : ∀ {{n m}}, n ≤ m → marrow_rel (fix_fuel n f) (fix_fuel m f) := by @@ -244,7 +308,38 @@ theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_vali have Hcont := Hvalid.hcont x He simp [Hcont] | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hvalid.hmono x n He + + /- Making the proofs more systematic -/ + -- TODO: rewrite is_mono in terms of is_mono_p + def is_mono_p (body : (a → Result b) → Result b) : Prop := + ∀ {{g h}}, marrow_rel g h → result_rel (body g) (body h) + + @[simp] theorem is_mono_p_same (x : Result b) : + @is_mono_p a b (λ _ => x) := by + simp [is_mono_p, marrow_rel, result_rel] + split <;> simp + + -- TODO: generalize + @[simp] theorem is_mono_p_tail_rec (x : a) : + @is_mono_p a b (λ f => f x) := by + simp_all [is_mono_p, marrow_rel, result_rel] + + -- TODO: rewrite is_cont in terms of is_cont_p + def is_cont_p (f : (a → Result b) → a → Result b) + (body : (a → Result b) → Result b) : Prop := + (Hc : ∀ n, body (fix_fuel n f) = .div) → + body (fix f) = .div + + @[simp] theorem is_cont_p_same (f : (a → Result b) → a → Result b) (x : Result b) : + is_cont_p f (λ _ => x) := by + simp [is_cont_p] + + -- TODO: generalize + @[simp] theorem is_cont_p_tail_rec (f : (a → Result b) → a → Result b) (x : a) : + is_cont_p f (λ f => f x) := by + simp_all [is_cont_p, fix] + /- (∀ n, fix_fuel n f x = div) @@ -269,7 +364,7 @@ end Fix namespace Ex1 /- An example of use of the fixed-point -/ - open Fix + open Primitives Fix variable {a : Type} (f : (List a × Int) → Result a) @@ -298,6 +393,20 @@ namespace Ex1 -- Recursive call apply Hdiv + /- Making the monotonicity/continuity proofs more systematic -/ + + theorem list_nth_body_mono2 : ∀ x, is_mono_p (λ f => @list_nth_body a f x) := by + intro x + simp [list_nth_body] + split <;> simp + split <;> simp + + theorem list_nth_body_cont2: ∀ f x, is_cont_p f (λ f => @list_nth_body a f x) := by + intro f x + simp [list_nth_body] + split <;> simp + split <;> simp + noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) @@ -319,8 +428,142 @@ namespace Ex1 end Ex1 namespace Ex2 + /- Same as Ex1, but we make the body of nth non tail-rec -/ + open Primitives Fix + + variable {a : Type} (f : (List a × Int) → Result a) + + def list_nth_body (x : (List a × Int)) : Result a := + let (ls, i) := x + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else + do + let y ← f (tl, i - 1) + .ret y + + -- Lean is good at applying lemmas: we can write a very general version + theorem is_mono_p_bind + (g : (a → Result b) → Result b) + (h : b → (a → Result b) → Result b) : + is_mono_p g → + (∀ y, is_mono_p (h y)) → + is_mono_p (λ f => do let y ← g f; h y f) := by + intro hg hh + simp [is_mono_p] + intro fg fh Hrgh + simp [marrow_rel, result_rel] + have hg := hg Hrgh; simp [result_rel] at hg + cases heq0: g fg <;> simp_all + rename_i y _ + have hh := hh y Hrgh; simp [result_rel] at hh + simp_all + + -- Lean is good at applying lemmas: we can write a very general version + theorem is_cont_p_bind + (f : (a → Result b) → a → Result b) + (g : (a → Result b) → Result b) + (h : b → (a → Result b) → Result b) : + is_cont_p f (λ f => g f) → + (∀ y, is_cont_p f (h y)) → + is_cont_p f (λ f => do let y ← g f; h y f) := by + intro Hg Hh + simp [is_cont_p] + intro Hdiv + -- Case on `g (fix... f)`: is there an n s.t. it terminates? + cases Classical.em (∀ n, g (fix_fuel n f) = .div) <;> rename_i Hn + . -- Case 1: g diverges + have Hg := Hg Hn + simp_all + . -- Case 2: g doesn't diverge + simp at Hn + let ⟨ n, Hn ⟩ := Hn + have Hdivn := Hdiv n + -- TODO: we need monotonicity of g and f + have Hgmono : is_mono_p g := by sorry + have Hfmono : is_mono f := by sorry + have Hffmono := fix_fuel_fix_mono Hfmono n + have Hgeq := Hgmono Hffmono + simp [result_rel] at Hgeq + cases Heq: g (fix_fuel n f) <;> rename_i y <;> simp_all + -- Remains the .ret case + -- TODO: we need monotonicity of h? + have Hhmono : is_mono_p (h y) := by sorry + -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div + -- We do this in two steps: first we prove it for m ≥ n + have Hhdiv: ∀ m, h y (fix_fuel m f) = .div := by + have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m f) = .div := by + -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv + intro m Hle + have Hdivm := Hdiv m + -- Monotonicity of g + have Hffmono := fix_fuel_mono Hfmono Hle + have Hgmono := Hgmono Hffmono + -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv + clear Hdiv + simp_all [result_rel] + intro m + -- TODO: we shouldn't need the excluded middle here because it is decidable + cases Classical.em (n ≤ m) <;> rename_i Hl + . apply Hhdiv; assumption + . simp at Hl + -- Make a case disjunction on `h y (fix_fuel m f)`: if it is not equal + -- to div, use the monotonicity of `h y` + have Hle : m ≤ n := by linarith + have Hffmono := fix_fuel_mono Hfmono Hle + have Hmono := Hhmono Hffmono + simp [result_rel] at Hmono + cases Heq: h y (fix_fuel m f) <;> simp_all + -- We can now use the continuity hypothesis for h + apply Hh; assumption + + + -- TODO: what is the name of this theorem? + -- theorem eta_app_eq (x : a) (f : a → b) : f x = (λ x => f x) x := by simp + -- theorem eta_eq (x : a) (f : a → b) : (λ x => f x) = f := by simp + + --set_option pp.funBinderTypes true + --set_option pp.explicit true + --set_option pp.notation false + + theorem list_nth_body_mono : ∀ x, is_mono_p (λ f => @list_nth_body a f x) := by + intro x + simp [list_nth_body] + split <;> simp + split <;> simp + apply is_mono_p_bind <;> intros <;> simp + + theorem list_nth_body_cont2: ∀ f x, is_cont_p f (λ f => @list_nth_body a f x) := by + intro f x + simp [list_nth_body] + split <;> simp + split <;> simp + + noncomputable + def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + + theorem list_nth_eq (ls : List a) (i : Int) : + list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else list_nth tl (i - 1) + := by + have Hvalid : is_valid (@list_nth_body a) := + is_valid.intro list_nth_body_mono list_nth_body_cont + have Heq := fix_fixed_eq (@list_nth_body a) Hvalid + simp [Heq, list_nth] + conv => lhs; rw [list_nth_body] + simp [Heq] + +end Ex2 + +namespace Ex3 /- Higher-order example -/ - open Fix + open Primitives Fix variable {a b : Type} @@ -330,6 +573,7 @@ namespace Ex2 | [] => .ret [] | hd :: tl => do + -- TODO: monadic syntax match f hd with | .ret hd => match map f tl with @@ -423,7 +667,7 @@ namespace Ex2 have Hc := map_is_cont_contra_aux Hmono ls Hf apply exists_map_fix_fuel_not_div_imp <;> assumption - theorem map_is_cont {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : + theorem map_is_cont {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : ∀ ls, (Hc : ∀ n, map (fix_fuel n f) ls = .div) → map (fix f) ls = .div := by @@ -431,7 +675,7 @@ namespace Ex2 -- TODO: is there a tactic for proofs by contraposition? apply Classical.byContradiction; intro Hndiv let ⟨ n, Hcc ⟩ := map_is_cont_contra Hmono ls Hndiv - simp_all + simp_all /- An example which uses map -/ inductive Tree (a : Type) := @@ -490,6 +734,6 @@ namespace Ex2 have Heq := fix_fixed_eq (@id_body a) Hvalid conv => lhs; rw [id, Heq, id_body] -end Ex2 +end Ex3 end Diverge -- cgit v1.2.3 From 6297cdd89299452f8043f7aed75cf2eb01d31e24 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 16:20:35 +0200 Subject: Further simplify the proofs in Diverge.lean --- backends/lean/Base/Diverge.lean | 273 ++++++++++++++++++++++------------------ 1 file changed, 151 insertions(+), 122 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 0eff17e3..759773c9 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -4,6 +4,7 @@ import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith import Mathlib.Tactic.Tauto +--import Mathlib.Logic namespace Diverge @@ -291,7 +292,7 @@ theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono split <;> simp [*] <;> intros <;> simp [*] -- The final fixed point equation -theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_valid f) : +theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_valid f) : ∀ x, fix f x = f (fix f) x := by intros x -- conv => lhs; simp [fix] @@ -320,7 +321,7 @@ theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_vali simp [is_mono_p, marrow_rel, result_rel] split <;> simp - -- TODO: generalize + -- TODO: remove @[simp] theorem is_mono_p_tail_rec (x : a) : @is_mono_p a b (λ f => f x) := by simp_all [is_mono_p, marrow_rel, result_rel] @@ -335,30 +336,147 @@ theorem fix_fixed_eq (f : (a → Result b) → a → Result b) (Hvalid : is_vali is_cont_p f (λ _ => x) := by simp [is_cont_p] - -- TODO: generalize + -- TODO: remove @[simp] theorem is_cont_p_tail_rec (f : (a → Result b) → a → Result b) (x : a) : is_cont_p f (λ f => f x) := by simp_all [is_cont_p, fix] -/- -(∀ n, fix_fuel n f x = div) - -⊢ f (fun y => fix_fuel (least (fix_fuel_P f y)) f y) x = div - -(? x. p x) ==> p (epsilon p) - - -P (nf : a -> option Nat) := - match nf x with - | None => forall n, fix_fuel n f x = div - | Some n => fix_fuel n f x <> div + -- Lean is good at unification: we can write a very general version + theorem is_mono_p_bind + (g : (a → Result b) → Result b) + (h : b → (a → Result b) → Result b) : + is_mono_p g → + (∀ y, is_mono_p (h y)) → + is_mono_p (λ f => do let y ← g f; h y f) := by + intro hg hh + simp [is_mono_p] + intro fg fh Hrgh + simp [marrow_rel, result_rel] + have hg := hg Hrgh; simp [result_rel] at hg + cases heq0: g fg <;> simp_all + rename_i y _ + have hh := hh y Hrgh; simp [result_rel] at hh + simp_all -TODO: theorem de Tarsky, -Gilles Dowek (Introduction à la théorie des langages de programmation) + -- Lean is good at unification: we can write a very general version + -- (in particular, it will manage to figure out `g` and `h` when we + -- apply the lemma) + theorem is_cont_p_bind + (f : (a → Result b) → a → Result b) + (Hfmono : is_mono f) + (g : (a → Result b) → Result b) + (h : b → (a → Result b) → Result b) : + is_mono_p g → + is_cont_p f g → + (∀ y, is_mono_p (h y)) → + (∀ y, is_cont_p f (h y)) → + is_cont_p f (λ f => do let y ← g f; h y f) := by + intro Hgmono Hgcont Hhmono Hhcont + simp [is_cont_p] + intro Hdiv + -- Case on `g (fix... f)`: is there an n s.t. it terminates? + cases Classical.em (∀ n, g (fix_fuel n f) = .div) <;> rename_i Hn + . -- Case 1: g diverges + have Hgcont := Hgcont Hn + simp_all + . -- Case 2: g doesn't diverge + simp at Hn + let ⟨ n, Hn ⟩ := Hn + have Hdivn := Hdiv n + have Hffmono := fix_fuel_fix_mono Hfmono n + have Hgeq := Hgmono Hffmono + simp [result_rel] at Hgeq + cases Heq: g (fix_fuel n f) <;> rename_i y <;> simp_all + -- Remains the .ret case + -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div + -- We do this in two steps: first we prove it for m ≥ n + have Hhdiv: ∀ m, h y (fix_fuel m f) = .div := by + have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m f) = .div := by + -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv + intro m Hle + have Hdivm := Hdiv m + -- Monotonicity of g + have Hffmono := fix_fuel_mono Hfmono Hle + have Hgmono := Hgmono Hffmono + -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv + clear Hdiv + simp_all [result_rel] + intro m + -- TODO: we shouldn't need the excluded middle here because it is decidable + cases Classical.em (n ≤ m) <;> rename_i Hl + . apply Hhdiv; assumption + . simp at Hl + -- Make a case disjunction on `h y (fix_fuel m f)`: if it is not equal + -- to div, use the monotonicity of `h y` + have Hle : m ≤ n := by linarith + have Hffmono := fix_fuel_mono Hfmono Hle + have Hmono := Hhmono y Hffmono + simp [result_rel] at Hmono + cases Heq: h y (fix_fuel m f) <;> simp_all + -- We can now use the continuity hypothesis for h + apply Hhcont; assumption -fix_f is f s.t.: f x = f (fix f) x ∧ ! g. g x = g (fix g) x ==> f <= g + -- TODO: move + def is_valid_p (f : (a → Result b) → a → Result b) + (body : (a → Result b) → Result b) : Prop := + is_mono_p body ∧ + (is_mono f → is_cont_p f body) + + @[simp] theorem is_valid_p_same (f : (a → Result b) → a → Result b) (x : Result b) : + is_valid_p f (λ _ => x) := by + simp [is_valid_p] + + @[simp] theorem is_valid_p_rec (f : (a → Result b) → a → Result b) (x : a) : + is_valid_p f (λ f => f x) := by + simp [is_valid_p] + + -- Lean is good at unification: we can write a very general version + -- (in particular, it will manage to figure out `g` and `h` when we + -- apply the lemma) + theorem is_valid_p_bind + {{f : (a → Result b) → a → Result b}} + {{g : (a → Result b) → Result b}} + {{h : b → (a → Result b) → Result b}} + (Hgvalid : is_valid_p f g) + (Hhvalid : ∀ y, is_valid_p f (h y)) : + is_valid_p f (λ f => do let y ← g f; h y f) := by + let ⟨ Hgmono, Hgcont ⟩ := Hgvalid + -- TODO: conversion to move forall below and conjunction? + simp [is_valid_p, forall_and] at Hhvalid + have ⟨ Hhmono, Hhcont ⟩ := Hhvalid + simp [← imp_forall_iff] at Hhcont + simp [is_valid_p]; constructor + . -- Monotonicity + apply is_mono_p_bind <;> assumption + . -- Continuity + intro Hfmono + have Hgcont := Hgcont Hfmono + have Hhcont := Hhcont Hfmono + apply is_cont_p_bind <;> assumption + + theorem is_valid_p_imp_is_valid {{body : (a → Result b) → a → Result b}} + (Hvalid : ∀ f x, is_valid_p f (λ f => body f x)) : + is_valid body := by + have Hmono : is_mono body := by + intro f h Hr x + have Hmono := Hvalid (λ _ _ => .div) x + have Hmono := Hmono.left + apply Hmono; assumption + have Hcont : is_cont body := by + intro x Hdiv + have Hcont := (Hvalid body x).right Hmono + simp [is_cont_p] at Hcont + apply Hcont + intro n + have Hdiv := Hdiv n + simp [fix_fuel] at Hdiv + simp [*] + apply is_valid.intro Hmono Hcont --/ + theorem is_valid_p_fix_fixed_eq {{body : (a → Result b) → a → Result b}} + (Hvalid : ∀ f x, is_valid_p f (λ f => body f x)) : + ∀ x, fix body x = body (fix body) x := + fix_fixed_eq (is_valid_p_imp_is_valid Hvalid) end Fix @@ -420,7 +538,7 @@ namespace Ex1 := by have Hvalid : is_valid (@list_nth_body a) := is_valid.intro list_nth_body_mono list_nth_body_cont - have Heq := fix_fixed_eq (@list_nth_body a) Hvalid + have Heq := fix_fixed_eq Hvalid simp [Heq, list_nth] conv => lhs; rw [list_nth_body] simp [Heq] @@ -444,117 +562,28 @@ namespace Ex2 let y ← f (tl, i - 1) .ret y - -- Lean is good at applying lemmas: we can write a very general version - theorem is_mono_p_bind - (g : (a → Result b) → Result b) - (h : b → (a → Result b) → Result b) : - is_mono_p g → - (∀ y, is_mono_p (h y)) → - is_mono_p (λ f => do let y ← g f; h y f) := by - intro hg hh - simp [is_mono_p] - intro fg fh Hrgh - simp [marrow_rel, result_rel] - have hg := hg Hrgh; simp [result_rel] at hg - cases heq0: g fg <;> simp_all - rename_i y _ - have hh := hh y Hrgh; simp [result_rel] at hh - simp_all - - -- Lean is good at applying lemmas: we can write a very general version - theorem is_cont_p_bind - (f : (a → Result b) → a → Result b) - (g : (a → Result b) → Result b) - (h : b → (a → Result b) → Result b) : - is_cont_p f (λ f => g f) → - (∀ y, is_cont_p f (h y)) → - is_cont_p f (λ f => do let y ← g f; h y f) := by - intro Hg Hh - simp [is_cont_p] - intro Hdiv - -- Case on `g (fix... f)`: is there an n s.t. it terminates? - cases Classical.em (∀ n, g (fix_fuel n f) = .div) <;> rename_i Hn - . -- Case 1: g diverges - have Hg := Hg Hn - simp_all - . -- Case 2: g doesn't diverge - simp at Hn - let ⟨ n, Hn ⟩ := Hn - have Hdivn := Hdiv n - -- TODO: we need monotonicity of g and f - have Hgmono : is_mono_p g := by sorry - have Hfmono : is_mono f := by sorry - have Hffmono := fix_fuel_fix_mono Hfmono n - have Hgeq := Hgmono Hffmono - simp [result_rel] at Hgeq - cases Heq: g (fix_fuel n f) <;> rename_i y <;> simp_all - -- Remains the .ret case - -- TODO: we need monotonicity of h? - have Hhmono : is_mono_p (h y) := by sorry - -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div - -- We do this in two steps: first we prove it for m ≥ n - have Hhdiv: ∀ m, h y (fix_fuel m f) = .div := by - have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m f) = .div := by - -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv - intro m Hle - have Hdivm := Hdiv m - -- Monotonicity of g - have Hffmono := fix_fuel_mono Hfmono Hle - have Hgmono := Hgmono Hffmono - -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv - clear Hdiv - simp_all [result_rel] - intro m - -- TODO: we shouldn't need the excluded middle here because it is decidable - cases Classical.em (n ≤ m) <;> rename_i Hl - . apply Hhdiv; assumption - . simp at Hl - -- Make a case disjunction on `h y (fix_fuel m f)`: if it is not equal - -- to div, use the monotonicity of `h y` - have Hle : m ≤ n := by linarith - have Hffmono := fix_fuel_mono Hfmono Hle - have Hmono := Hhmono Hffmono - simp [result_rel] at Hmono - cases Heq: h y (fix_fuel m f) <;> simp_all - -- We can now use the continuity hypothesis for h - apply Hh; assumption - - - -- TODO: what is the name of this theorem? - -- theorem eta_app_eq (x : a) (f : a → b) : f x = (λ x => f x) x := by simp - -- theorem eta_eq (x : a) (f : a → b) : (λ x => f x) = f := by simp - - --set_option pp.funBinderTypes true - --set_option pp.explicit true - --set_option pp.notation false - - theorem list_nth_body_mono : ∀ x, is_mono_p (λ f => @list_nth_body a f x) := by - intro x - simp [list_nth_body] - split <;> simp - split <;> simp - apply is_mono_p_bind <;> intros <;> simp - - theorem list_nth_body_cont2: ∀ f x, is_cont_p f (λ f => @list_nth_body a f x) := by + theorem list_nth_body_valid: ∀ f x, is_valid_p f (λ f => @list_nth_body a f x) := by intro f x simp [list_nth_body] split <;> simp split <;> simp + apply is_valid_p_bind <;> intros <;> simp_all noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) theorem list_nth_eq (ls : List a) (i : Int) : - list_nth ls i = - match ls with - | [] => .fail .panic - | hd :: tl => - if i = 0 then .ret hd - else list_nth tl (i - 1) + (list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else + do + let y ← list_nth tl (i - 1) + .ret y) := by - have Hvalid : is_valid (@list_nth_body a) := - is_valid.intro list_nth_body_mono list_nth_body_cont - have Heq := fix_fixed_eq (@list_nth_body a) Hvalid + have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_valid a) simp [Heq, list_nth] conv => lhs; rw [list_nth_body] simp [Heq] @@ -731,7 +760,7 @@ namespace Ex3 := by have Hvalid : is_valid (@id_body a) := is_valid.intro id_body_mono id_body_cont - have Heq := fix_fixed_eq (@id_body a) Hvalid + have Heq := fix_fixed_eq Hvalid conv => lhs; rw [id, Heq, id_body] end Ex3 -- cgit v1.2.3 From 34a471c02d6c49aa34b7f353b28b90b09a69864a Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 17:10:24 +0200 Subject: Simplify the id example in Diverge.lean --- backends/lean/Base/Diverge.lean | 119 ++++++++++++++++++++++++++++++++-------- 1 file changed, 95 insertions(+), 24 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 759773c9..2c764c5e 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -74,7 +74,7 @@ namespace Fix open Primitives open Result -variable {a b : Type} +variable {a b c d : Type} /- TODO: @@ -292,6 +292,7 @@ theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono split <;> simp [*] <;> intros <;> simp [*] -- The final fixed point equation +-- TODO: remove the `forall x` theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_valid f) : ∀ x, fix f x = f (fix f) x := by intros x @@ -313,26 +314,26 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va /- Making the proofs more systematic -/ -- TODO: rewrite is_mono in terms of is_mono_p - def is_mono_p (body : (a → Result b) → Result b) : Prop := + def is_mono_p (body : (a → Result b) → Result c) : Prop := ∀ {{g h}}, marrow_rel g h → result_rel (body g) (body h) - @[simp] theorem is_mono_p_same (x : Result b) : - @is_mono_p a b (λ _ => x) := by + @[simp] theorem is_mono_p_same (x : Result c) : + @is_mono_p a b c (λ _ => x) := by simp [is_mono_p, marrow_rel, result_rel] split <;> simp -- TODO: remove @[simp] theorem is_mono_p_tail_rec (x : a) : - @is_mono_p a b (λ f => f x) := by + @is_mono_p a b b (λ f => f x) := by simp_all [is_mono_p, marrow_rel, result_rel] -- TODO: rewrite is_cont in terms of is_cont_p def is_cont_p (f : (a → Result b) → a → Result b) - (body : (a → Result b) → Result b) : Prop := + (body : (a → Result b) → Result c) : Prop := (Hc : ∀ n, body (fix_fuel n f) = .div) → body (fix f) = .div - @[simp] theorem is_cont_p_same (f : (a → Result b) → a → Result b) (x : Result b) : + @[simp] theorem is_cont_p_same (f : (a → Result b) → a → Result b) (x : Result c) : is_cont_p f (λ _ => x) := by simp [is_cont_p] @@ -343,8 +344,8 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va -- Lean is good at unification: we can write a very general version theorem is_mono_p_bind - (g : (a → Result b) → Result b) - (h : b → (a → Result b) → Result b) : + (g : (a → Result b) → Result c) + (h : c → (a → Result b) → Result d) : is_mono_p g → (∀ y, is_mono_p (h y)) → is_mono_p (λ f => do let y ← g f; h y f) := by @@ -364,8 +365,8 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va theorem is_cont_p_bind (f : (a → Result b) → a → Result b) (Hfmono : is_mono f) - (g : (a → Result b) → Result b) - (h : b → (a → Result b) → Result b) : + (g : (a → Result b) → Result c) + (h : c → (a → Result b) → Result d) : is_mono_p g → is_cont_p f g → (∀ y, is_mono_p (h y)) → @@ -417,12 +418,12 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va apply Hhcont; assumption -- TODO: move - def is_valid_p (f : (a → Result b) → a → Result b) - (body : (a → Result b) → Result b) : Prop := + def is_valid_p (k : (a → Result b) → a → Result b) + (body : (a → Result b) → Result c) : Prop := is_mono_p body ∧ - (is_mono f → is_cont_p f body) + (is_mono k → is_cont_p k body) - @[simp] theorem is_valid_p_same (f : (a → Result b) → a → Result b) (x : Result b) : + @[simp] theorem is_valid_p_same (f : (a → Result b) → a → Result b) (x : Result c) : is_valid_p f (λ _ => x) := by simp [is_valid_p] @@ -435,8 +436,8 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va -- apply the lemma) theorem is_valid_p_bind {{f : (a → Result b) → a → Result b}} - {{g : (a → Result b) → Result b}} - {{h : b → (a → Result b) → Result b}} + {{g : (a → Result b) → Result c}} + {{h : c → (a → Result b) → Result d}} (Hgvalid : is_valid_p f g) (Hhvalid : ∀ y, is_valid_p f (h y)) : is_valid_p f (λ f => do let y ← g f; h y f) := by @@ -473,10 +474,12 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va simp [*] apply is_valid.intro Hmono Hcont + -- TODO: functional extensionality theorem is_valid_p_fix_fixed_eq {{body : (a → Result b) → a → Result b}} (Hvalid : ∀ f x, is_valid_p f (λ f => body f x)) : - ∀ x, fix body x = body (fix body) x := - fix_fixed_eq (is_valid_p_imp_is_valid Hvalid) + fix body = body (fix body) := by + apply funext + exact fix_fixed_eq (is_valid_p_imp_is_valid Hvalid) end Fix @@ -562,8 +565,8 @@ namespace Ex2 let y ← f (tl, i - 1) .ret y - theorem list_nth_body_valid: ∀ f x, is_valid_p f (λ f => @list_nth_body a f x) := by - intro f x + theorem list_nth_body_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + intro k x simp [list_nth_body] split <;> simp split <;> simp @@ -584,9 +587,8 @@ namespace Ex2 .ret y) := by have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_valid a) - simp [Heq, list_nth] - conv => lhs; rw [list_nth_body] - simp [Heq] + simp [list_nth] + conv => lhs; rw [Heq] end Ex2 @@ -765,4 +767,73 @@ namespace Ex3 end Ex3 +namespace Ex4 + /- Higher-order example -/ + open Primitives Fix + + variable {a b : Type} + + /- An auxiliary function, which doesn't require the fixed-point -/ + def map (f : a → Result b) (ls : List a) : Result (List b) := + match ls with + | [] => .ret [] + | hd :: tl => + do + let hd ← f hd + let tl ← map f tl + .ret (hd :: tl) + + /- The validity theorem for `map`, generic in `f` -/ + /- TODO: rename the condition to k in all the lemma statements -/ + theorem map_is_valid + {{f : (a → Result b) → a → Result c}} + (Hfvalid : ∀ k x, is_valid_p k (λ k => f k x)) + (k : (a → Result b) → a → Result b) + (ls : List a) : + is_valid_p k (λ k => map (f k) ls) := by + induction ls <;> simp [map] + apply is_valid_p_bind <;> simp_all + intros + apply is_valid_p_bind <;> simp_all + + /- An example which uses map -/ + inductive Tree (a : Type) := + | leaf (x : a) + | node (tl : List (Tree a)) + + def id_body (f : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + do + let tl ← map f tl + .ret (.node tl) + + /- TODO: make the naming consistent (suffix with "_is") -/ + theorem id_body_is_valid : + ∀ k x, is_valid_p k (λ k => @id_body a k x) := by + intro k x + simp [id_body] + split <;> simp + apply is_valid_p_bind <;> simp_all + -- We have to show that `map k tl` is valid + apply map_is_valid; simp + + noncomputable def id (t : Tree a) := fix id_body t + + theorem id_eq (t : Tree a) : + (id t = + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + do + let tl ← map id tl + .ret (.node tl)) + := by + have Heq := is_valid_p_fix_fixed_eq (@id_body_is_valid a) + simp [id] + conv => lhs; rw [Heq]; simp; rw [id_body] + +end Ex4 + end Diverge -- cgit v1.2.3 From 5d8eea6504d9dcfa43844d5ba51c7abf6c589701 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 17:26:51 +0200 Subject: Remove the obsolete examples from Diverge --- backends/lean/Base/Diverge.lean | 213 +--------------------------------------- 1 file changed, 5 insertions(+), 208 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 2c764c5e..0e3e96c3 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -497,33 +497,8 @@ namespace Ex1 if i = 0 then .ret hd else f (tl, i - 1) - theorem list_nth_body_mono : is_mono (@list_nth_body a) := by - simp [is_mono]; intro g h Hr (ls, i); simp [result_rel, list_nth_body] - cases ls <;> simp - rename_i hd tl - -- TODO: making a case disjunction over `i = 0` is annoying, we need a more - -- general tactic for this - cases (Classical.em (Eq i 0)) <;> simp [*] at * - apply Hr - - theorem list_nth_body_cont : is_cont (@list_nth_body a) := by - rw [is_cont]; intro (ls, i) Hdiv; simp [list_nth_body, fix_fuel] at * - cases ls <;> simp at * - -- TODO: automate this - cases (Classical.em (Eq i 0)) <;> simp [*] at * - -- Recursive call - apply Hdiv - - /- Making the monotonicity/continuity proofs more systematic -/ - - theorem list_nth_body_mono2 : ∀ x, is_mono_p (λ f => @list_nth_body a f x) := by - intro x - simp [list_nth_body] - split <;> simp - split <;> simp - - theorem list_nth_body_cont2: ∀ f x, is_cont_p f (λ f => @list_nth_body a f x) := by - intro f x + theorem list_nth_body_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + intro k x simp [list_nth_body] split <;> simp split <;> simp @@ -539,12 +514,9 @@ namespace Ex1 if i = 0 then .ret hd else list_nth tl (i - 1) := by - have Hvalid : is_valid (@list_nth_body a) := - is_valid.intro list_nth_body_mono list_nth_body_cont - have Heq := fix_fixed_eq Hvalid - simp [Heq, list_nth] - conv => lhs; rw [list_nth_body] - simp [Heq] + have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_valid a) + simp [list_nth] + conv => lhs; rw [Heq] end Ex1 @@ -592,181 +564,6 @@ namespace Ex2 end Ex2 -namespace Ex3 - /- Higher-order example -/ - open Primitives Fix - - variable {a b : Type} - - /- An auxiliary function, which doesn't require the fixed-point -/ - def map (f : a → Result b) (ls : List a) : Result (List b) := - match ls with - | [] => .ret [] - | hd :: tl => - do - -- TODO: monadic syntax - match f hd with - | .ret hd => - match map f tl with - | .ret tl => - .ret (hd :: tl) - | r => r - | .fail e => .fail e - | .div => .div - - theorem map_is_mono {{f g : a → Result b}} (Hr : marrow_rel f g) : - ∀ ls, result_rel (map f ls) (map g ls) := by - intro ls; induction ls <;> simp [result_rel, map] - case cons hd tl Hi => - have Hr1 := Hr hd; simp [result_rel] at Hr1 - -- TODO: reverting is annoying - revert Hr1 - cases f hd <;> intro Hr1 <;> simp [*] - -- ret case - simp [result_rel] at Hi - -- TODO: annoying - revert Hi - cases map f tl <;> intro Hi <;> simp [*] - - -- Auxiliary definition - def map_fix_fuel (n0 n1 : Nat) (f : (a → Result b) → a → Result b) (ls : List a) : Result (List b) := - match ls with - | [] => .ret [] - | hd :: tl => - do - match fix_fuel n0 f hd with - | .ret hd => - match map (fix_fuel n1 f) tl with - | .ret tl => - .ret (hd :: tl) - | r => r - | .fail e => .fail e - | .div => .div - - def exists_map_fix_fuel_not_div_imp {{f : (a → Result b) → a → Result b}} {{ls : List a}} - (Hmono : is_mono f) : - (∃ n0 n1, map_fix_fuel n0 n1 f ls ≠ .div) → - ∃ n2, map (fix_fuel n2 f) ls ≠ .div := by - intro ⟨ n0, n1, Hnd ⟩ - exists n0 + n1 - have Hineq0 : n0 ≤ n0 + n1 := by linarith - have Hineq1 : n1 ≤ n0 + n1 := by linarith - simp [map_fix_fuel] at Hnd - -- TODO: I would like a rewrite_once tactic - unfold map; simp - -- - revert Hnd - cases ls <;> simp - rename_i hd tl - -- Use the monotonicity of fix_fuel - have Hfmono := fix_fuel_mono Hmono Hineq0 hd - simp [result_rel] at Hfmono; revert Hfmono - cases fix_fuel n0 f hd <;> intro <;> simp [*] - -- Use the monotonicity of map - have Hfmono := fix_fuel_mono Hmono Hineq1 - have Hmmono := map_is_mono Hfmono tl - simp [result_rel] at Hmmono; revert Hmmono - cases map (fix_fuel n1 f) tl <;> intro <;> simp [*] - - -- TODO: it is simpler to prove the contrapositive of is_cont than is_cont itself. - -- The proof is still quite technical: think of a criteria whose proof is simpler - -- to automate. - theorem map_is_cont_contra_aux {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : - ∀ ls, map (fix f) ls ≠ .div → - ∃ n0 n1, map_fix_fuel n0 n1 f ls ≠ .div - := by - intro ls; induction ls <;> simp [result_rel, map_fix_fuel, map] - simp [fix] - case cons hd tl Hi => - -- Instantiate the first n and do a case disjunction - intro Hf; exists (least (fix_fuel_P f hd)); revert Hf - cases fix_fuel (least (fix_fuel_P f hd)) f hd <;> simp - -- Use the induction hyp - have Hr := Classical.em (map (fix f) tl = .div) - simp [fix] at * - cases Hr <;> simp_all - have Hj : ∃ n2, map (fix_fuel n2 f) tl ≠ .div := exists_map_fix_fuel_not_div_imp Hmono Hi - revert Hj; intro ⟨ n2, Hj ⟩ - intro Hf; exists n2; revert Hf - revert Hj; cases map (fix_fuel n2 f) tl <;> simp_all - - theorem map_is_cont_contra {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : - ∀ ls, map (fix f) ls ≠ .div → - ∃ n, map (fix_fuel n f) ls ≠ .div - := by - intro ls Hf - have Hc := map_is_cont_contra_aux Hmono ls Hf - apply exists_map_fix_fuel_not_div_imp <;> assumption - - theorem map_is_cont {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) : - ∀ ls, (Hc : ∀ n, map (fix_fuel n f) ls = .div) → - map (fix f) ls = .div - := by - intro ls Hc - -- TODO: is there a tactic for proofs by contraposition? - apply Classical.byContradiction; intro Hndiv - let ⟨ n, Hcc ⟩ := map_is_cont_contra Hmono ls Hndiv - simp_all - - /- An example which uses map -/ - inductive Tree (a : Type) := - | leaf (x : a) - | node (tl : List (Tree a)) - - def id_body (f : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := - match t with - | .leaf x => .ret (.leaf x) - | .node tl => - match map f tl with - | .div => .div - | .fail e => .fail e - | .ret tl => .ret (.node tl) - - theorem id_body_mono : is_mono (@id_body a) := by - simp [is_mono]; intro g h Hr t; simp [result_rel, id_body] - cases t <;> simp - rename_i tl - have Hmmono := map_is_mono Hr tl - revert Hmmono; simp [result_rel] - cases map g tl <;> simp_all - - theorem id_body_cont : is_cont (@id_body a) := by - rw [is_cont]; intro t Hdiv - simp [fix_fuel] at * - -- TODO: weird things are happening with the rewriter and the simplifier here - rw [id_body] - simp [id_body] at Hdiv - -- - cases t <;> simp at * - rename_i tl - -- TODO: automate this - have Hmc := map_is_cont id_body_mono tl - have Hdiv : ∀ (n : ℕ), map (fix_fuel n id_body) tl = Result.div := by - intro n - have Hdiv := Hdiv n; revert Hdiv - cases map (fix_fuel n id_body) tl <;> simp_all - have Hmc := Hmc Hdiv; revert Hmc - cases map (fix id_body) tl <;> simp_all - - noncomputable def id (t : Tree a) := fix id_body t - - theorem id_eq (t : Tree a) : - id t = - match t with - | .leaf x => .ret (.leaf x) - | .node tl => - match map id tl with - | .div => .div - | .fail e => .fail e - | .ret tl => .ret (.node tl) - := by - have Hvalid : is_valid (@id_body a) := - is_valid.intro id_body_mono id_body_cont - have Heq := fix_fixed_eq Hvalid - conv => lhs; rw [id, Heq, id_body] - -end Ex3 - namespace Ex4 /- Higher-order example -/ open Primitives Fix -- cgit v1.2.3 From 8db6718d06023ffa77035b29ec92cec03ee838bc Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 18:13:29 +0200 Subject: Add an example with even/odd in Diverge.lean --- backends/lean/Base/Diverge.lean | 120 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 0e3e96c3..2e77c5e0 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -564,6 +564,124 @@ namespace Ex2 end Ex2 +namespace Ex3 + /- Mutually recursive functions -/ + open Primitives Fix + + /- Because we have mutually recursive functions, we use a sum for the inputs + and the output types: + - inputs: the sum allows to select the function to call in the recursive + calls (and the functions may not have the same input types) + - outpus: this case is degenerate because `even` and `odd` both have the + return type `Bool`, but generally speaking we need a sum type because + the functions in the mutually recursive group may not have the same + return type. + -/ + variable (f : (Int ⊕ Int) → Result (Bool ⊕ Bool)) + + def is_even_is_odd_body (x : (Int ⊕ Int)) : Result (Bool ⊕ Bool) := + match x with + | .inl i => + -- Body of `is_even` + if i = 0 + then .ret (.inl true) -- We return .inl because this is `is_even` + else + do + let b ← + do + -- Call `odd`: we need to wrap the input value in `.inr`, then + -- extract the output value + let r ← f (.inr (i- 1)) + match r with + | .inl _ => .fail .panic -- Invalid output + | .inr b => .ret b + -- Wrap the return value + .ret (.inl b) + | .inr i => + -- Body of `is_odd` + if i = 0 + then .ret (.inr false) -- We return .inr because this is `is_odd` + else + do + let b ← + do + -- Call `is_even`: we need to wrap the input value in .inr, then + -- extract the output value + let r ← f (.inl (i- 1)) + match r with + | .inl b => .ret b + | .inr _ => .fail .panic -- Invalid output + -- Wrap the return value + .ret (.inr b) + + theorem is_even_is_odd_body_is_valid: + ∀ k x, is_valid_p k (λ k => is_even_is_odd_body k x) := by + intro k x + simp [is_even_is_odd_body] + split <;> simp <;> split <;> simp + apply is_valid_p_bind; simp + intros; split <;> simp + apply is_valid_p_bind; simp + intros; split <;> simp + + noncomputable + def is_even (i : Int): Result Bool := + do + let r ← fix is_even_is_odd_body (.inl i) + match r with + | .inl b => .ret b + | .inr _ => .fail .panic + + noncomputable + def is_odd (i : Int): Result Bool := + do + let r ← fix is_even_is_odd_body (.inr i) + match r with + | .inl _ => .fail .panic + | .inr b => .ret b + + -- TODO: move + -- TODO: this is not enough + theorem swap_if_bind {a b : Type} (e : Prop) [Decidable e] (x y : Result a) (f : a → Result b) : + (do + let z ← (if e then x else y) + f z) + = + (if e then do let z ← x; f z + else do let z ← y; f z) := by + split <;> simp + + theorem is_even_eq (i : Int) : + is_even i = (if i = 0 then .ret true else is_odd (i - 1)) + := by + have Heq := is_valid_p_fix_fixed_eq is_even_is_odd_body_is_valid + simp [is_even, is_odd] + conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp + -- Very annoying: we need to swap the matches + -- Doing this with rewriting lemmas is hard generally speaking + -- (especially as we may have to generate lemmas for user-defined + -- inductives on the fly). + -- The simplest is to repeatedly split then simplify (we identify + -- the outer match or monadic let-binding, and split on its scrutinee) + split <;> simp + cases H0 : fix is_even_is_odd_body (Sum.inr (i - 1)) <;> simp + rename_i v + split <;> simp + + theorem is_odd_eq (i : Int) : + is_odd i = (if i = 0 then .ret false else is_even (i - 1)) + := by + have Heq := is_valid_p_fix_fixed_eq is_even_is_odd_body_is_valid + simp [is_even, is_odd] + conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp + -- Same remark as for `even` + split <;> simp + cases H0 : fix is_even_is_odd_body (Sum.inl (i - 1)) <;> simp + rename_i v + split <;> simp + +end Ex3 + namespace Ex4 /- Higher-order example -/ open Primitives Fix @@ -581,7 +699,7 @@ namespace Ex4 .ret (hd :: tl) /- The validity theorem for `map`, generic in `f` -/ - /- TODO: rename the condition to k in all the lemma statements -/ + /- TODO: rename the continuation to k in all the lemma statements -/ theorem map_is_valid {{f : (a → Result b) → a → Result c}} (Hfvalid : ∀ k x, is_valid_p k (λ k => f k x)) -- cgit v1.2.3 From a2670f4d097075c23b9affceb8ed8498b73c4b8c Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 19 Jun 2023 18:52:29 +0200 Subject: Cleanup Diverge.lean --- backends/lean/Base/Diverge.lean | 657 ++++++++++++++++++------------------- backends/lean/Base/Primitives.lean | 13 + 2 files changed, 333 insertions(+), 337 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 2e77c5e0..65c061bd 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -3,12 +3,32 @@ import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith -import Mathlib.Tactic.Tauto ---import Mathlib.Logic + +/- +TODO: +- we want an easier to use cases: + - keeps in the goal an equation of the shape: `t = case` + - if called on Prop terms, uses Classical.em + Actually, the cases from mathlib seems already quite powerful + (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) + For instance: cases h : e + Also: cases_matching +- better split tactic +- we need conversions to operate on the head of applications. + Actually, something like this works: + ``` + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + ``` + Maybe we need a rpt ... ; focus? +- simplifier/rewriter have a strange behavior sometimes +-/ namespace Diverge namespace Primitives +/-! # Copy-pasting from Primitives to make the file self-contained -/ inductive Error where | assertionFailure: Error @@ -29,12 +49,6 @@ deriving Repr, BEq open Result --- instance Result_Inhabited (α : Type u) : Inhabited (Result α) := --- Inhabited.mk (fail panic) - --- instance Result_Nonempty (α : Type u) : Nonempty (Result α) := --- Nonempty.intro div - def bind (x: Result α) (f: α -> Result β) : Result β := match x with | ret v => f v @@ -71,312 +85,276 @@ end Primitives namespace Fix -open Primitives -open Result - -variable {a b c d : Type} - -/- -TODO: -- we want an easier to use cases: - - keeps in the goal an equation of the shape: `t = case` - - if called on Prop terms, uses Classical.em - Actually, the cases from mathlib seems already quite powerful - (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) - For instance: cases h : e - Also: cases_matching -- better split tactic -- we need conversions to operate on the head of applications. - Actually, something like this works: - ``` - conv at Hl => - apply congr_fun - simp [fix_fuel_P] - ``` - Maybe we need a rpt ... ; focus? -- simplifier/rewriter have a strange behavior sometimes --/ - -/-! # The least fixed point definition and its properties -/ - -def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) -noncomputable def least (p : Nat → Prop) : Nat := - Classical.epsilon (least_p p) - --- Auxiliary theorem for [least_spec]: if there exists an `n` satisfying `p`, --- there there exists a least `m` satisfying `p`. -theorem least_spec_aux (p : Nat → Prop) : ∀ (n : Nat), (hn : p n) → ∃ m, least_p p m := by - apply Nat.strongRec' - intros n hi hn - -- Case disjunction on: is n the smallest n satisfying p? - match Classical.em (∀ m, m < n → ¬ p m) with - | .inl hlt => - -- Yes: trivial - exists n - | .inr hlt => - simp at * - let ⟨ m, ⟨ hmlt, hm ⟩ ⟩ := hlt - have hi := hi m hmlt hm - apply hi - --- The specification of [least]: either `p` is never satisfied, or it is satisfied --- by `least p` and no `n < least p` satisfies `p`. -theorem least_spec (p : Nat → Prop) : (∀ n, ¬ p n) ∨ (p (least p) ∧ ∀ n, n < least p → ¬ p n) := by - -- Case disjunction on the existence of an `n` which satisfies `p` - match Classical.em (∀ n, ¬ p n) with - | .inl h => - -- There doesn't exist: trivial - apply (Or.inl h) - | .inr h => - -- There exists: we simply use `least_spec_aux` in combination with the property - -- of the epsilon operator - simp at * - let ⟨ n, hn ⟩ := h - apply Or.inr - have hl := least_spec_aux p n hn - have he := Classical.epsilon_spec hl - apply he - -/-! # The fixed point definitions -/ - -def fix_fuel (n : Nat) (f : (a → Result b) → a → Result b) (x : a) : Result b := - match n with - | 0 => .div - | n + 1 => - f (fix_fuel n f) x - -@[simp] def fix_fuel_pred (f : (a → Result b) → a → Result b) (x : a) (n : Nat) := - not (div? (fix_fuel n f x)) - -def fix_fuel_P (f : (a → Result b) → a → Result b) (x : a) (n : Nat) : Prop := - fix_fuel_pred f x n - -noncomputable def fix (f : (a → Result b) → a → Result b) (x : a) : Result b := - fix_fuel (least (fix_fuel_P f x)) f x - -/-! # The proof of the fixed point equation -/ - --- Monotonicity relation over results --- TODO: generalize -def result_rel {a : Type u} (x1 x2 : Result a) : Prop := - match x1 with - | div => True - | fail _ => x2 = x1 - | ret _ => x2 = x1 -- TODO: generalize - --- Monotonicity relation over monadic arrows --- TODO: Kleisli arrow --- TODO: generalize -def marrow_rel (f g : a → Result b) : Prop := - ∀ x, result_rel (f x) (g x) - --- Monotonicity property -def is_mono (f : (a → Result b) → a → Result b) : Prop := - ∀ {{g h}}, marrow_rel g h → marrow_rel (f g) (f h) - --- "Continuity" property. --- We need this, and this looks a lot like continuity. Also see this paper: --- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf -def is_cont (f : (a → Result b) → a → Result b) : Prop := - ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div - --- Validity property for a body -structure is_valid (f : (a → Result b) → a → Result b) := - intro:: - hmono : is_mono f - hcont : is_cont f - -/- - - -/ - -theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : - ∀ {{n m}}, n ≤ m → marrow_rel (fix_fuel n f) (fix_fuel m f) := by - intros n - induction n - case zero => simp [marrow_rel, fix_fuel, result_rel] - case succ n1 Hi => - intros m Hle x + open Primitives + open Result + + variable {a b c d : Type} + + /-! # The least fixed point definition and its properties -/ + + def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) + noncomputable def least (p : Nat → Prop) : Nat := + Classical.epsilon (least_p p) + + -- Auxiliary theorem for [least_spec]: if there exists an `n` satisfying `p`, + -- there there exists a least `m` satisfying `p`. + theorem least_spec_aux (p : Nat → Prop) : ∀ (n : Nat), (hn : p n) → ∃ m, least_p p m := by + apply Nat.strongRec' + intros n hi hn + -- Case disjunction on: is n the smallest n satisfying p? + match Classical.em (∀ m, m < n → ¬ p m) with + | .inl hlt => + -- Yes: trivial + exists n + | .inr hlt => + simp at * + let ⟨ m, ⟨ hmlt, hm ⟩ ⟩ := hlt + have hi := hi m hmlt hm + apply hi + + -- The specification of [least]: either `p` is never satisfied, or it is satisfied + -- by `least p` and no `n < least p` satisfies `p`. + theorem least_spec (p : Nat → Prop) : (∀ n, ¬ p n) ∨ (p (least p) ∧ ∀ n, n < least p → ¬ p n) := by + -- Case disjunction on the existence of an `n` which satisfies `p` + match Classical.em (∀ n, ¬ p n) with + | .inl h => + -- There doesn't exist: trivial + apply (Or.inl h) + | .inr h => + -- There exists: we simply use `least_spec_aux` in combination with the property + -- of the epsilon operator + simp at * + let ⟨ n, hn ⟩ := h + apply Or.inr + have hl := least_spec_aux p n hn + have he := Classical.epsilon_spec hl + apply he + + /-! # The fixed point definitions -/ + + def fix_fuel (n : Nat) (f : (a → Result b) → a → Result b) (x : a) : Result b := + match n with + | 0 => .div + | n + 1 => + f (fix_fuel n f) x + + @[simp] def fix_fuel_pred (f : (a → Result b) → a → Result b) (x : a) (n : Nat) := + not (div? (fix_fuel n f x)) + + def fix_fuel_P (f : (a → Result b) → a → Result b) (x : a) (n : Nat) : Prop := + fix_fuel_pred f x n + + noncomputable def fix (f : (a → Result b) → a → Result b) (x : a) : Result b := + fix_fuel (least (fix_fuel_P f x)) f x + + /-! # The validity property -/ + + -- Monotonicity relation over results + -- TODO: generalize (we should parameterize the definition by a relation over `a`) + def result_rel {a : Type u} (x1 x2 : Result a) : Prop := + match x1 with + | div => True + | fail _ => x2 = x1 + | ret _ => x2 = x1 -- TODO: generalize + + -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) + def karrow_rel (k1 k2 : a → Result b) : Prop := + ∀ x, result_rel (k1 x) (k2 x) + + -- Monotonicity property for function bodies + def is_mono (f : (a → Result b) → a → Result b) : Prop := + ∀ {{k1 k2}}, karrow_rel k1 k2 → karrow_rel (f k1) (f k2) + + -- "Continuity" property. + -- We need this, and this looks a lot like continuity. Also see this paper: + -- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf + -- We define our "continuity" criteria so that it gives us what we need to + -- prove the fixed-point equation, and we can also easily manipulate it. + def is_cont (f : (a → Result b) → a → Result b) : Prop := + ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div + + /-! # The proof of the fixed-point equation -/ + theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + ∀ {{n m}}, n ≤ m → karrow_rel (fix_fuel n f) (fix_fuel m f) := by + intros n + induction n + case zero => simp [karrow_rel, fix_fuel, result_rel] + case succ n1 Hi => + intros m Hle x + simp [result_rel] + match m with + | 0 => + exfalso + zify at * + linarith + | Nat.succ m1 => + simp_arith at Hle + simp [fix_fuel] + have Hi := Hi Hle + have Hmono := Hmono Hi x + simp [result_rel] at Hmono + apply Hmono + + @[simp] theorem neg_fix_fuel_P {f : (a → Result b) → a → Result b} {x : a} {n : Nat} : + ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by + simp [fix_fuel_P, div?] + cases fix_fuel n f x <;> simp + + theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + ∀ n, karrow_rel (fix_fuel n f) (fix f) := by + intros n x simp [result_rel] - match m with - | 0 => - exfalso - zify at * - linarith - | Nat.succ m1 => - simp_arith at Hle - simp [fix_fuel] - have Hi := Hi Hle - have Hmono := Hmono Hi x - simp [result_rel] at Hmono - apply Hmono - -@[simp] theorem neg_fix_fuel_P {f : (a → Result b) → a → Result b} {x : a} {n : Nat} : - ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by - simp [fix_fuel_P, div?] - cases fix_fuel n f x <;> simp - -theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : - ∀ n, marrow_rel (fix_fuel n f) (fix f) := by - intros n x - simp [result_rel] - have Hl := least_spec (fix_fuel_P f x) - simp at Hl - match Hl with - | .inl Hl => simp [*] - | .inr ⟨ Hl, Hn ⟩ => - match Classical.em (fix_fuel n f x = div) with - | .inl Hd => - simp [*] - | .inr Hd => - have Hineq : least (fix_fuel_P f x) ≤ n := by - -- Proof by contradiction - cases Classical.em (least (fix_fuel_P f x) ≤ n) <;> simp [*] - simp at * - rename_i Hineq - have Hn := Hn n Hineq - contradiction - have Hfix : ¬ (fix f x = div) := by - simp [fix] - -- By property of the least upper bound - revert Hd Hl - -- TODO: there is no conversion to select the head of a function! - have : fix_fuel_P f x (least (fix_fuel_P f x)) = fix_fuel_pred f x (least (fix_fuel_P f x)) := - by simp[fix_fuel_P] - simp [this, div?] - clear this - cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp - have Hmono := fix_fuel_mono Hmono Hineq x - simp [result_rel] at Hmono - -- TODO: there is no conversion to select the head of a function! - revert Hmono Hfix Hd - simp [fix] - -- TODO: it would be good if cases actually introduces an equation: this - -- way we wouldn't have to do all the book-keeping - cases fix_fuel (least (fix_fuel_P f x)) f x <;> cases fix_fuel n f x <;> - intros <;> simp [*] at * - -theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : - ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by - intros x n Hf - have Hfmono := fix_fuel_fix_mono Hmono n x - revert Hf Hfmono - -- TODO: would be good to be able to unfold fix_fuel_P only on the left - simp [fix_fuel_P, div?, result_rel, fix] - cases fix_fuel n f x <;> simp_all - --- Prove the fixed point equation in the case there exists some fuel for which --- the execution terminates -theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono : is_mono f) - (x : a) (n : Nat) (He : fix_fuel_P f x n) : - fix f x = f (fix f) x := by - have Hl := fix_fuel_P_least Hmono He - -- TODO: better control of simplification - conv at Hl => - apply congr_fun - simp [fix_fuel_P] - -- The least upper bound is > 0 - have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by + have Hl := least_spec (fix_fuel_P f x) + simp at Hl + match Hl with + | .inl Hl => simp [*] + | .inr ⟨ Hl, Hn ⟩ => + match Classical.em (fix_fuel n f x = div) with + | .inl Hd => + simp [*] + | .inr Hd => + have Hineq : least (fix_fuel_P f x) ≤ n := by + -- Proof by contradiction + cases Classical.em (least (fix_fuel_P f x) ≤ n) <;> simp [*] + simp at * + rename_i Hineq + have Hn := Hn n Hineq + contradiction + have Hfix : ¬ (fix f x = div) := by + simp [fix] + -- By property of the least upper bound + revert Hd Hl + -- TODO: there is no conversion to select the head of a function! + conv => lhs; apply congr_fun; apply congr_fun; apply congr_fun; simp [fix_fuel_P, div?] + cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp + have Hmono := fix_fuel_mono Hmono Hineq x + simp [result_rel] at Hmono + simp [fix] at * + cases Heq: fix_fuel (least (fix_fuel_P f x)) f x <;> + cases Heq':fix_fuel n f x <;> + simp_all + + theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by + intros x n Hf + have Hfmono := fix_fuel_fix_mono Hmono n x + -- TODO: there is no conversion to select the head of a function! + conv => apply congr_fun; simp [fix_fuel_P] + simp [fix_fuel_P] at Hf + revert Hf Hfmono + simp [div?, result_rel, fix] + cases fix_fuel n f x <;> simp_all + + -- Prove the fixed point equation in the case there exists some fuel for which + -- the execution terminates + theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono : is_mono f) + (x : a) (n : Nat) (He : fix_fuel_P f x n) : + fix f x = f (fix f) x := by + have Hl := fix_fuel_P_least Hmono He + -- TODO: better control of simplification + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + -- The least upper bound is > 0 + have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by + revert Hl + simp [div?] + cases least (fix_fuel_P f x) <;> simp [fix_fuel] + simp [Hsucc] at Hl revert Hl - simp [div?] - cases least (fix_fuel_P f x) <;> simp [fix_fuel] - simp [Hsucc] at Hl - revert Hl - simp [*, div?, fix, fix_fuel] - -- Use the monotonicity - have Hfixmono := fix_fuel_fix_mono Hmono n - have Hvm := Hmono Hfixmono x - -- Use functional extensionality - simp [result_rel, fix] at Hvm - revert Hvm - split <;> simp [*] <;> intros <;> simp [*] - --- The final fixed point equation --- TODO: remove the `forall x` -theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_valid f) : - ∀ x, fix f x = f (fix f) x := by - intros x - -- conv => lhs; simp [fix] - -- Case disjunction: is there a fuel such that the execution successfully execute? - match Classical.em (∃ n, fix_fuel_P f x n) with - | .inr He => - -- No fuel: the fixed point evaluates to `div` - --simp [fix] at * - simp at * - conv => lhs; simp [fix] - have Hel := He (Nat.succ (least (fix_fuel_P f x))); simp [*, fix_fuel] at *; clear Hel - -- Use the "continuity" of `f` - have He : ∀ n, fix_fuel (.succ n) f x = div := by intros; simp [*] - have Hcont := Hvalid.hcont x He - simp [Hcont] - | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hvalid.hmono x n He - - /- Making the proofs more systematic -/ - - -- TODO: rewrite is_mono in terms of is_mono_p - def is_mono_p (body : (a → Result b) → Result c) : Prop := - ∀ {{g h}}, marrow_rel g h → result_rel (body g) (body h) - - @[simp] theorem is_mono_p_same (x : Result c) : + simp [*, div?, fix, fix_fuel] + -- Use the monotonicity + have Hfixmono := fix_fuel_fix_mono Hmono n + have Hvm := Hmono Hfixmono x + -- Use functional extensionality + simp [result_rel, fix] at Hvm + revert Hvm + split <;> simp [*] <;> intros <;> simp [*] + + -- The final fixed point equation + -- TODO: remove the `forall x` + theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} + (Hmono : is_mono f) (Hcont : is_cont f) : + ∀ x, fix f x = f (fix f) x := by + intros x + -- Case disjunction: is there a fuel such that the execution successfully execute? + match Classical.em (∃ n, fix_fuel_P f x n) with + | .inr He => + -- No fuel: the fixed point evaluates to `div` + --simp [fix] at * + simp at * + conv => lhs; simp [fix] + have Hel := He (Nat.succ (least (fix_fuel_P f x))); simp [*, fix_fuel] at *; clear Hel + -- Use the "continuity" of `f` + have He : ∀ n, fix_fuel (.succ n) f x = div := by intros; simp [*] + have Hcont := Hcont x He + simp [Hcont] + | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hmono x n He + + + /-! # Making the proofs of validity manageable (and automatable) -/ + + -- Monotonicity property for expressions + def is_mono_p (e : (a → Result b) → Result c) : Prop := + ∀ {{k1 k2}}, karrow_rel k1 k2 → result_rel (e k1) (e k2) + + theorem is_mono_p_same (x : Result c) : @is_mono_p a b c (λ _ => x) := by - simp [is_mono_p, marrow_rel, result_rel] + simp [is_mono_p, karrow_rel, result_rel] split <;> simp - -- TODO: remove - @[simp] theorem is_mono_p_tail_rec (x : a) : + theorem is_mono_p_rec (x : a) : @is_mono_p a b b (λ f => f x) := by - simp_all [is_mono_p, marrow_rel, result_rel] + simp_all [is_mono_p, karrow_rel, result_rel] - -- TODO: rewrite is_cont in terms of is_cont_p - def is_cont_p (f : (a → Result b) → a → Result b) - (body : (a → Result b) → Result c) : Prop := - (Hc : ∀ n, body (fix_fuel n f) = .div) → - body (fix f) = .div - - @[simp] theorem is_cont_p_same (f : (a → Result b) → a → Result b) (x : Result c) : - is_cont_p f (λ _ => x) := by - simp [is_cont_p] - - -- TODO: remove - @[simp] theorem is_cont_p_tail_rec (f : (a → Result b) → a → Result b) (x : a) : - is_cont_p f (λ f => f x) := by - simp_all [is_cont_p, fix] - - -- Lean is good at unification: we can write a very general version + -- The important lemma about `is_mono_p` theorem is_mono_p_bind (g : (a → Result b) → Result c) (h : c → (a → Result b) → Result d) : is_mono_p g → (∀ y, is_mono_p (h y)) → - is_mono_p (λ f => do let y ← g f; h y f) := by + is_mono_p (λ k => do let y ← g k; h y k) := by intro hg hh simp [is_mono_p] intro fg fh Hrgh - simp [marrow_rel, result_rel] + simp [karrow_rel, result_rel] have hg := hg Hrgh; simp [result_rel] at hg cases heq0: g fg <;> simp_all rename_i y _ have hh := hh y Hrgh; simp [result_rel] at hh simp_all - -- Lean is good at unification: we can write a very general version - -- (in particular, it will manage to figure out `g` and `h` when we - -- apply the lemma) + -- Continuity property for expressions - note that we take the continuation + -- as parameter + def is_cont_p (k : (a → Result b) → a → Result b) + (e : (a → Result b) → Result c) : Prop := + (Hc : ∀ n, e (fix_fuel n k) = .div) → + e (fix k) = .div + + theorem is_cont_p_same (k : (a → Result b) → a → Result b) (x : Result c) : + is_cont_p k (λ _ => x) := by + simp [is_cont_p] + + theorem is_cont_p_rec (f : (a → Result b) → a → Result b) (x : a) : + is_cont_p f (λ f => f x) := by + simp_all [is_cont_p, fix] + + -- The important lemma about `is_cont_p` theorem is_cont_p_bind - (f : (a → Result b) → a → Result b) - (Hfmono : is_mono f) + (k : (a → Result b) → a → Result b) + (Hkmono : is_mono k) (g : (a → Result b) → Result c) (h : c → (a → Result b) → Result d) : is_mono_p g → - is_cont_p f g → + is_cont_p k g → (∀ y, is_mono_p (h y)) → - (∀ y, is_cont_p f (h y)) → - is_cont_p f (λ f => do let y ← g f; h y f) := by + (∀ y, is_cont_p k (h y)) → + is_cont_p k (λ k => do let y ← g k; h y k) := by intro Hgmono Hgcont Hhmono Hhcont simp [is_cont_p] intro Hdiv - -- Case on `g (fix... f)`: is there an n s.t. it terminates? - cases Classical.em (∀ n, g (fix_fuel n f) = .div) <;> rename_i Hn + -- Case on `g (fix... k)`: is there an n s.t. it terminates? + cases Classical.em (∀ n, g (fix_fuel n k) = .div) <;> rename_i Hn . -- Case 1: g diverges have Hgcont := Hgcont Hn simp_all @@ -384,20 +362,20 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va simp at Hn let ⟨ n, Hn ⟩ := Hn have Hdivn := Hdiv n - have Hffmono := fix_fuel_fix_mono Hfmono n + have Hffmono := fix_fuel_fix_mono Hkmono n have Hgeq := Hgmono Hffmono simp [result_rel] at Hgeq - cases Heq: g (fix_fuel n f) <;> rename_i y <;> simp_all + cases Heq: g (fix_fuel n k) <;> rename_i y <;> simp_all -- Remains the .ret case -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div -- We do this in two steps: first we prove it for m ≥ n - have Hhdiv: ∀ m, h y (fix_fuel m f) = .div := by - have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m f) = .div := by + have Hhdiv: ∀ m, h y (fix_fuel m k) = .div := by + have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m k) = .div := by -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv intro m Hle have Hdivm := Hdiv m -- Monotonicity of g - have Hffmono := fix_fuel_mono Hfmono Hle + have Hffmono := fix_fuel_mono Hkmono Hle have Hgmono := Hgmono Hffmono -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv clear Hdiv @@ -407,42 +385,41 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va cases Classical.em (n ≤ m) <;> rename_i Hl . apply Hhdiv; assumption . simp at Hl - -- Make a case disjunction on `h y (fix_fuel m f)`: if it is not equal + -- Make a case disjunction on `h y (fix_fuel m k)`: if it is not equal -- to div, use the monotonicity of `h y` have Hle : m ≤ n := by linarith - have Hffmono := fix_fuel_mono Hfmono Hle + have Hffmono := fix_fuel_mono Hkmono Hle have Hmono := Hhmono y Hffmono simp [result_rel] at Hmono - cases Heq: h y (fix_fuel m f) <;> simp_all + cases Heq: h y (fix_fuel m k) <;> simp_all -- We can now use the continuity hypothesis for h apply Hhcont; assumption - -- TODO: move + -- The validity property for an expression def is_valid_p (k : (a → Result b) → a → Result b) - (body : (a → Result b) → Result c) : Prop := - is_mono_p body ∧ - (is_mono k → is_cont_p k body) + (e : (a → Result b) → Result c) : Prop := + is_mono_p e ∧ + (is_mono k → is_cont_p k e) - @[simp] theorem is_valid_p_same (f : (a → Result b) → a → Result b) (x : Result c) : - is_valid_p f (λ _ => x) := by - simp [is_valid_p] + @[simp] theorem is_valid_p_same (k : (a → Result b) → a → Result b) (x : Result c) : + is_valid_p k (λ _ => x) := by + simp [is_valid_p, is_mono_p_same, is_cont_p_same] - @[simp] theorem is_valid_p_rec (f : (a → Result b) → a → Result b) (x : a) : - is_valid_p f (λ f => f x) := by - simp [is_valid_p] + @[simp] theorem is_valid_p_rec (k : (a → Result b) → a → Result b) (x : a) : + is_valid_p k (λ k => k x) := by + simp_all [is_valid_p, is_mono_p_rec, is_cont_p_rec] -- Lean is good at unification: we can write a very general version -- (in particular, it will manage to figure out `g` and `h` when we -- apply the lemma) theorem is_valid_p_bind - {{f : (a → Result b) → a → Result b}} + {{k : (a → Result b) → a → Result b}} {{g : (a → Result b) → Result c}} {{h : c → (a → Result b) → Result d}} - (Hgvalid : is_valid_p f g) - (Hhvalid : ∀ y, is_valid_p f (h y)) : - is_valid_p f (λ f => do let y ← g f; h y f) := by + (Hgvalid : is_valid_p k g) + (Hhvalid : ∀ y, is_valid_p k (h y)) : + is_valid_p k (λ k => do let y ← g k; h y k) := by let ⟨ Hgmono, Hgcont ⟩ := Hgvalid - -- TODO: conversion to move forall below and conjunction? simp [is_valid_p, forall_and] at Hhvalid have ⟨ Hhmono, Hhcont ⟩ := Hhvalid simp [← imp_forall_iff] at Hhcont @@ -450,36 +427,37 @@ theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} (Hvalid : is_va . -- Monotonicity apply is_mono_p_bind <;> assumption . -- Continuity - intro Hfmono - have Hgcont := Hgcont Hfmono - have Hhcont := Hhcont Hfmono + intro Hkmono + have Hgcont := Hgcont Hkmono + have Hhcont := Hhcont Hkmono apply is_cont_p_bind <;> assumption - theorem is_valid_p_imp_is_valid {{body : (a → Result b) → a → Result b}} - (Hvalid : ∀ f x, is_valid_p f (λ f => body f x)) : - is_valid body := by - have Hmono : is_mono body := by + theorem is_valid_p_imp_is_valid {{e : (a → Result b) → a → Result b}} + (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : + is_mono e ∧ is_cont e := by + have Hmono : is_mono e := by intro f h Hr x have Hmono := Hvalid (λ _ _ => .div) x have Hmono := Hmono.left apply Hmono; assumption - have Hcont : is_cont body := by + have Hcont : is_cont e := by intro x Hdiv - have Hcont := (Hvalid body x).right Hmono + have Hcont := (Hvalid e x).right Hmono simp [is_cont_p] at Hcont apply Hcont intro n have Hdiv := Hdiv n simp [fix_fuel] at Hdiv simp [*] - apply is_valid.intro Hmono Hcont + simp [*] -- TODO: functional extensionality - theorem is_valid_p_fix_fixed_eq {{body : (a → Result b) → a → Result b}} - (Hvalid : ∀ f x, is_valid_p f (λ f => body f x)) : - fix body = body (fix body) := by + theorem is_valid_p_fix_fixed_eq {{e : (a → Result b) → a → Result b}} + (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : + fix e = e (fix e) := by apply funext - exact fix_fixed_eq (is_valid_p_imp_is_valid Hvalid) + have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid + exact fix_fixed_eq Hmono Hcont end Fix @@ -487,7 +465,7 @@ namespace Ex1 /- An example of use of the fixed-point -/ open Primitives Fix - variable {a : Type} (f : (List a × Int) → Result a) + variable {a : Type} (k : (List a × Int) → Result a) def list_nth_body (x : (List a × Int)) : Result a := let (ls, i) := x @@ -495,9 +473,9 @@ namespace Ex1 | [] => .fail .panic | hd :: tl => if i = 0 then .ret hd - else f (tl, i - 1) + else k (tl, i - 1) - theorem list_nth_body_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by intro k x simp [list_nth_body] split <;> simp @@ -506,6 +484,7 @@ namespace Ex1 noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + -- The unfolding equation theorem list_nth_eq (ls : List a) (i : Int) : list_nth ls i = match ls with @@ -514,17 +493,18 @@ namespace Ex1 if i = 0 then .ret hd else list_nth tl (i - 1) := by - have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_valid a) + have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_is_valid a) simp [list_nth] conv => lhs; rw [Heq] end Ex1 namespace Ex2 - /- Same as Ex1, but we make the body of nth non tail-rec -/ + /- Same as Ex1, but we make the body of nth non tail-rec (this is mostly + to see what happens when there are let-bindings) -/ open Primitives Fix - variable {a : Type} (f : (List a × Int) → Result a) + variable {a : Type} (k : (List a × Int) → Result a) def list_nth_body (x : (List a × Int)) : Result a := let (ls, i) := x @@ -534,10 +514,10 @@ namespace Ex2 if i = 0 then .ret hd else do - let y ← f (tl, i - 1) + let y ← k (tl, i - 1) .ret y - theorem list_nth_body_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by intro k x simp [list_nth_body] split <;> simp @@ -547,6 +527,7 @@ namespace Ex2 noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + -- The unfolding equation theorem list_nth_eq (ls : List a) (i : Int) : (list_nth ls i = match ls with @@ -558,7 +539,7 @@ namespace Ex2 let y ← list_nth tl (i - 1) .ret y) := by - have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_valid a) + have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_is_valid a) simp [list_nth] conv => lhs; rw [Heq] @@ -577,7 +558,7 @@ namespace Ex3 the functions in the mutually recursive group may not have the same return type. -/ - variable (f : (Int ⊕ Int) → Result (Bool ⊕ Bool)) + variable (k : (Int ⊕ Int) → Result (Bool ⊕ Bool)) def is_even_is_odd_body (x : (Int ⊕ Int)) : Result (Bool ⊕ Bool) := match x with @@ -591,7 +572,7 @@ namespace Ex3 do -- Call `odd`: we need to wrap the input value in `.inr`, then -- extract the output value - let r ← f (.inr (i- 1)) + let r ← k (.inr (i- 1)) match r with | .inl _ => .fail .panic -- Invalid output | .inr b => .ret b @@ -607,7 +588,7 @@ namespace Ex3 do -- Call `is_even`: we need to wrap the input value in .inr, then -- extract the output value - let r ← f (.inl (i- 1)) + let r ← k (.inl (i- 1)) match r with | .inl b => .ret b | .inr _ => .fail .panic -- Invalid output @@ -642,7 +623,8 @@ namespace Ex3 -- TODO: move -- TODO: this is not enough - theorem swap_if_bind {a b : Type} (e : Prop) [Decidable e] (x y : Result a) (f : a → Result b) : + theorem swap_if_bind {a b : Type} (e : Prop) [Decidable e] + (x y : Result a) (f : a → Result b) : (do let z ← (if e then x else y) f z) @@ -651,6 +633,7 @@ namespace Ex3 else do let z ← y; f z) := by split <;> simp + -- The unfolding equation for `is_even` theorem is_even_eq (i : Int) : is_even i = (if i = 0 then .ret true else is_odd (i - 1)) := by @@ -668,6 +651,7 @@ namespace Ex3 rename_i v split <;> simp + -- The unfolding equation for `is_odd` theorem is_odd_eq (i : Int) : is_odd i = (if i = 0 then .ret false else is_even (i - 1)) := by @@ -699,7 +683,6 @@ namespace Ex4 .ret (hd :: tl) /- The validity theorem for `map`, generic in `f` -/ - /- TODO: rename the continuation to k in all the lemma statements -/ theorem map_is_valid {{f : (a → Result b) → a → Result c}} (Hfvalid : ∀ k x, is_valid_p k (λ k => f k x)) @@ -724,7 +707,6 @@ namespace Ex4 let tl ← map f tl .ret (.node tl) - /- TODO: make the naming consistent (suffix with "_is") -/ theorem id_body_is_valid : ∀ k x, is_valid_p k (λ k => @id_body a k x) := by intro k x @@ -736,6 +718,7 @@ namespace Ex4 noncomputable def id (t : Tree a) := fix id_body t + -- The unfolding equation theorem id_eq (t : Tree a) : (id t = match t with diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index d6cc0bad..1185a07d 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -94,6 +94,10 @@ instance : Bind Result where instance : Pure Result where pure := fun x => ret x +@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] +@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] +@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] + /- CUSTOM-DSL SUPPORT -/ -- Let-binding the Result of a monadic operation is oftentimes not sufficient, @@ -124,6 +128,15 @@ macro "let" e:term " <-- " f:term : doElem => let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ .ret r +@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : + (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : + (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_div (f : α → Result β) : + (do let y ← div; f y) = div := by simp [Bind.bind, bind] + ---------------------- -- MACHINE INTEGERS -- ---------------------- -- cgit v1.2.3 From 393748cc3dd0f43a79d2342379008bbf445f116d Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 20 Jun 2023 12:30:39 +0200 Subject: Remove the use of fun. ext. in Diverge.lean --- backends/lean/Base/Diverge.lean | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 65c061bd..97ffa214 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -271,9 +271,7 @@ namespace Fix revert Hvm split <;> simp [*] <;> intros <;> simp [*] - -- The final fixed point equation - -- TODO: remove the `forall x` - theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} + theorem fix_fixed_eq_forall {{f : (a → Result b) → a → Result b}} (Hmono : is_mono f) (Hcont : is_cont f) : ∀ x, fix f x = f (fix f) x := by intros x @@ -291,6 +289,14 @@ namespace Fix simp [Hcont] | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hmono x n He + -- The final fixed point equation + theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} + (Hmono : is_mono f) (Hcont : is_cont f) : + fix f = f (fix f) := by + have Heq := fix_fixed_eq_forall Hmono Hcont + have Heq1 : fix f = (λ x => fix f x) := by simp + rw [Heq1] + conv => lhs; ext; simp [Heq] /-! # Making the proofs of validity manageable (and automatable) -/ @@ -451,11 +457,9 @@ namespace Fix simp [*] simp [*] - -- TODO: functional extensionality theorem is_valid_p_fix_fixed_eq {{e : (a → Result b) → a → Result b}} (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : fix e = e (fix e) := by - apply funext have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid exact fix_fixed_eq Hmono Hcont @@ -484,7 +488,7 @@ namespace Ex1 noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) - -- The unfolding equation + -- The unfolding equation - diverges if `i < 0` theorem list_nth_eq (ls : List a) (i : Int) : list_nth ls i = match ls with @@ -527,7 +531,7 @@ namespace Ex2 noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) - -- The unfolding equation + -- The unfolding equation - diverges if `i < 0` theorem list_nth_eq (ls : List a) (i : Int) : (list_nth ls i = match ls with @@ -553,10 +557,10 @@ namespace Ex3 and the output types: - inputs: the sum allows to select the function to call in the recursive calls (and the functions may not have the same input types) - - outpus: this case is degenerate because `even` and `odd` both have the + - outputs: this case is degenerate because `even` and `odd` have the same return type `Bool`, but generally speaking we need a sum type because - the functions in the mutually recursive group may not have the same - return type. + the functions in the mutually recursive group may have different + return types. -/ variable (k : (Int ⊕ Int) → Result (Bool ⊕ Bool)) @@ -565,7 +569,7 @@ namespace Ex3 | .inl i => -- Body of `is_even` if i = 0 - then .ret (.inl true) -- We return .inl because this is `is_even` + then .ret (.inl true) -- We use .inl because this is `is_even` else do let b ← @@ -581,7 +585,7 @@ namespace Ex3 | .inr i => -- Body of `is_odd` if i = 0 - then .ret (.inr false) -- We return .inr because this is `is_odd` + then .ret (.inr false) -- We use .inr because this is `is_odd` else do let b ← @@ -633,7 +637,7 @@ namespace Ex3 else do let z ← y; f z) := by split <;> simp - -- The unfolding equation for `is_even` + -- The unfolding equation for `is_even` - diverges if `i < 0` theorem is_even_eq (i : Int) : is_even i = (if i = 0 then .ret true else is_odd (i - 1)) := by @@ -651,9 +655,9 @@ namespace Ex3 rename_i v split <;> simp - -- The unfolding equation for `is_odd` + -- The unfolding equation for `is_odd` - diverges if `i < 0` theorem is_odd_eq (i : Int) : - is_odd i = (if i = 0 then .ret false else is_even (i - 1)) + is_odd i = (if i = 0 then .ret false else is_even (i - 1)) := by have Heq := is_valid_p_fix_fixed_eq is_even_is_odd_body_is_valid simp [is_even, is_odd] -- cgit v1.2.3 From 3971da603ee54d373b4c73d6a20b3d83dea7b5b9 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 21 Jun 2023 16:20:25 +0200 Subject: Start working on Arith.lean --- backends/lean/Base.lean | 1 + backends/lean/Base/Arith.lean | 221 ++++++++++++++++++++++++++++++++++++++++ backends/lean/Base/Diverge.lean | 4 +- 3 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 backends/lean/Base/Arith.lean diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index f6a78bba..6e9ff873 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -1,3 +1,4 @@ import Base.Primitives import Base.Diverge import Base.TestTactics +import Base.Arith diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean new file mode 100644 index 00000000..6339f218 --- /dev/null +++ b/backends/lean/Base/Arith.lean @@ -0,0 +1,221 @@ +/- This file contains tactics to solve arithmetic goals -/ + +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith +import Base.Primitives + +/- +Mathlib tactics: +- rcases: https://leanprover-community.github.io/mathlib_docs/tactics.html#rcases +- split_ifs: https://leanprover-community.github.io/mathlib_docs/tactics.html#split_ifs +- norm_num: https://leanprover-community.github.io/mathlib_docs/tactics.html#norm_num +- should we use linarith or omega? +- hint: https://leanprover-community.github.io/mathlib_docs/tactics.html#hint +- classical: https://leanprover-community.github.io/mathlib_docs/tactics.html#classical +-/ + +namespace List + + -- TODO: I could not find this function?? + @[simp] def flatten {a : Type u} : List (List a) → List a + | [] => [] + | x :: ls => x ++ flatten ls + +end List + +namespace Lean + +namespace LocalContext + + open Lean Lean.Elab Command Term Lean.Meta + + -- Small utility: return the list of declarations in the context, from + -- the last to the first. + def getAllDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := + lctx.foldrM (fun d ls => do let d ← instantiateLocalDeclMVars d; pure (d :: ls)) [] + + -- Return the list of declarations in the context, but filter the + -- declarations which are considered as implementation details + def getDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := do + let ls ← lctx.getAllDecls + pure (ls.filter (fun d => not d.isImplementationDetail)) + +end LocalContext + +end Lean + +namespace Arith + +open Primitives + +--set_option pp.explicit true +--set_option pp.notation false +--set_option pp.coercions false + +-- TODO: move +instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val + +-- TODO: move +/- Remark: we can't write the following instance because of restrictions about + the type class parameters (`ty` doesn't appear in the return type, which is + forbidden): + + ``` + instance Scalar.cast (ty : ScalarTy) : Coe (Scalar ty) Int where coe := λ v => v.val + ``` + -/ +def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val + +-- We use this type-class to test if an expression is a scalar (if we manage +-- to lookup an instance of this type-class, then it is) +class IsScalar (a : Type) where + +instance (ty : ScalarTy) : IsScalar (Scalar ty) where + +--example (ty : ScalarTy) : IsScalar (Scalar ty) := _ + +open Lean Lean.Elab Command Term Lean.Meta + +-- Return true if the expression is a scalar expression +def isScalarExpr (e : Expr) : MetaM Bool := do + -- Try to convert the expression to a scalar + -- TODO: I tried to do it with Lean.Meta.mkAppM but it didn't work: how + -- do we allow Lean to perform (controlled) unfoldings for instantiation + -- purposes? + let r ← Lean.observing? do + let ty ← Lean.Meta.inferType e + let isScalar ← mkAppM `Arith.IsScalar #[ty] + let isScalar ← trySynthInstance isScalar + match isScalar with + | LOption.some x => some x + | _ => none + match r with + | .some _ => pure true + | _ => pure false + +-- Explore a term and return the set of scalar expressions found inside +partial def collectScalarExprsAux (hs : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do + -- We do it in a very simpler manner: we deconstruct applications, + -- and recursively explore the sub-expressions. Note that we do + -- not go inside foralls and abstractions (should we?). + e.withApp fun f args => do + let hs ← if ← isScalarExpr f then pure (hs.insert f) else pure hs + let hs ← args.foldlM collectScalarExprsAux hs + pure hs + +-- Explore a term and return the list of scalar expressions found inside +def collectScalarExprs (e : Expr) : MetaM (HashSet Expr) := + collectScalarExprsAux HashSet.empty e + +-- Collect the scalar expressions in the context +def getScalarExprsFromMainCtx : Tactic.TacticM (HashSet Expr) := do + Lean.Elab.Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + -- Just a matter of precaution + let ctx ← instantiateLCtxMVars ctx + -- Initialize the hashset + let hs := HashSet.empty + -- Explore the declarations + let decls ← ctx.getDecls + let hs ← decls.foldlM (fun hs d => collectScalarExprsAux hs d.toExpr) hs + -- Return + pure hs + + +#check TSyntax +#check mkIdent +-- TODO: addDecl? +-- Project the scalar expressions into the context, to retrieve the bound inequalities +-- def projectScalarExpr (e: Expr) : Tactic.TacticM Unit := do +-- let e ← `($e) +-- let e ← Lean.Elab.Term.elabTerm `($e) none +-- Lean.Elab.Tactic.evalCases `($e) + +elab "list_scalar_exprs" : tactic => do + let hs ← getScalarExprsFromMainCtx + hs.forM fun e => do + dbg_trace f!"+ Scalar expression: {e}" + +#check LocalContext + +elab "list_local_decls_1" : tactic => + Lean.Elab.Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + let ctx ← instantiateLCtxMVars ctx + let decls ← ctx.getDecls + -- Filter the scalar expressions + let decls ← decls.filterMapM fun decl: Lean.LocalDecl => do + let declExpr := decl.toExpr + let declName := decl.userName + let declType ← Lean.Meta.inferType declExpr + dbg_trace f!"+ local decl: name: {declName} | expr: {declExpr} | ty: {declType}" + -- Try to convert the expression to a scalar + -- TODO: I tried to do it with Lean.Meta.mkAppM but it didn't work: how + -- do we allow Lean to perform (controlled) unfoldings for instantiation + -- purposes? + let r ← Lean.observing? do + let isScalar ← mkAppM `Arith.IsScalar #[declType] + let isScalar ← trySynthInstance isScalar + match isScalar with + | LOption.some x => some x + | _ => none + match r with + | .some _ => dbg_trace f!" Scalar expression"; pure r + | _ => dbg_trace f!" Not a scalar"; pure .none + pure () + -- match ← Lean.observing? (Lean.Meta.mkAppM `Scalar.toInt #[decl.toExpr]) with + -- | .none => dbg_trace f!" Not a scalar" + -- | .some _ => dbg_trace f!" Scalar expression" + +#check Lean.Environment.addDecl +#check Expr +#check LocalContext +#check MVarId +#check Lean.Elab.Tactic.setGoals +#check Lean.Elab.Tactic.Context +#check withLocalDecl +#check Lean.MVarId.assert +#check LocalDecl + +-- Insert x = 3 in the context +elab "custom_let" : tactic => + -- I don't think we need that + Lean.Elab.Tactic.withMainContext do + -- + let type := (Expr.const `Nat []) + let val : Expr := .lit (.natVal 3) + let n := `x -- the name is "x" + withLetDecl n type val fun nval => do + -- For debugging + let lctx ← Lean.MonadLCtx.getLCtx + let fid := nval.fvarId! + let decl := lctx.get! fid + dbg_trace f!" nval: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" + -- + -- Tranform the main goal `m0?` to `let x = nval in m1?` + let mvarId ← Tactic.getMainGoal + let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) + let newVal ← mkLetFVars #[nval] newMVar + -- Focus on the current goal + Tactic.focus do + -- Assign the main goal. + -- We must do this *after* we focused on the current goal, because + -- after we assigned the meta variable the goal is considered as solved + mvarId.assign newVal + -- Replace the list of goals with the new goal - we can do this because + -- we focused on the current goal + Lean.Elab.Tactic.setGoals [newMVar.mvarId!] + +example : Nat := by + custom_let + apply x + +example (x : Bool) : Nat := by + cases x <;> custom_let <;> apply x + +end Arith diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 97ffa214..1ff34516 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -703,12 +703,12 @@ namespace Ex4 | leaf (x : a) | node (tl : List (Tree a)) - def id_body (f : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := + def id_body (k : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := match t with | .leaf x => .ret (.leaf x) | .node tl => do - let tl ← map f tl + let tl ← map k tl .ret (.node tl) theorem id_body_is_valid : -- cgit v1.2.3 From 34f1f4d877b32002cd292cb1fe27969184efcf94 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 22 Jun 2023 10:37:13 +0200 Subject: Finish the custom_let tactic --- backends/lean/Base/Arith.lean | 44 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index 6339f218..d4611deb 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -168,36 +168,27 @@ elab "list_local_decls_1" : tactic => | .some _ => dbg_trace f!" Scalar expression"; pure r | _ => dbg_trace f!" Not a scalar"; pure .none pure () - -- match ← Lean.observing? (Lean.Meta.mkAppM `Scalar.toInt #[decl.toExpr]) with - -- | .none => dbg_trace f!" Not a scalar" - -- | .some _ => dbg_trace f!" Scalar expression" -#check Lean.Environment.addDecl -#check Expr -#check LocalContext -#check MVarId -#check Lean.Elab.Tactic.setGoals -#check Lean.Elab.Tactic.Context -#check withLocalDecl -#check Lean.MVarId.assert -#check LocalDecl - --- Insert x = 3 in the context -elab "custom_let" : tactic => +def evalCustomLet (name : Name) (val : Syntax) : Tactic.TacticM Unit := -- I don't think we need that Lean.Elab.Tactic.withMainContext do -- - let type := (Expr.const `Nat []) - let val : Expr := .lit (.natVal 3) - let n := `x -- the name is "x" - withLetDecl n type val fun nval => do + let val ← elabTerm val .none + let type ← inferType val + -- In some situations, the type will be left as a metavariable (for instance, + -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will + -- not choose): we force the instantiation of the meta-variable + synthesizeSyntheticMVarsUsingDefault + -- Insert the new declaration + withLetDecl name type val fun nval => do -- For debugging let lctx ← Lean.MonadLCtx.getLCtx let fid := nval.fvarId! let decl := lctx.get! fid - dbg_trace f!" nval: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" + -- Remark: logInfo instantiates the mvars (contrary to dbg_trace): + logInfo m!" new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" -- - -- Tranform the main goal `m0?` to `let x = nval in m1?` + -- Tranform the main goal `?m0` to `let x = nval in ?m1` let mvarId ← Tactic.getMainGoal let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) let newVal ← mkLetFVars #[nval] newMVar @@ -211,11 +202,18 @@ elab "custom_let" : tactic => -- we focused on the current goal Lean.Elab.Tactic.setGoals [newMVar.mvarId!] +elab "custom_let " n:ident " := " v:term : tactic => + evalCustomLet n.getId v + +-- Insert x = 3 in the context +elab "custom_let " n:ident " := " v:term : tactic => + evalCustomLet n.getId v + example : Nat := by - custom_let + custom_let x := 4 apply x example (x : Bool) : Nat := by - cases x <;> custom_let <;> apply x + cases x <;> custom_let x := 3 <;> apply x end Arith -- cgit v1.2.3 From 9421b215a8911bc545eb524b8b07e7ca2eb717f3 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 22 Jun 2023 16:02:09 +0200 Subject: Make intro_has_prop_instances work --- backends/lean/Base/Arith.lean | 171 +++++++++++++++++++++++++++++++++++------- 1 file changed, 145 insertions(+), 26 deletions(-) diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index d4611deb..a792deb2 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -75,7 +75,28 @@ class IsScalar (a : Type) where instance (ty : ScalarTy) : IsScalar (Scalar ty) where ---example (ty : ScalarTy) : IsScalar (Scalar ty) := _ +example (ty : ScalarTy) : IsScalar (Scalar ty) := inferInstance + +-- TODO: lookup doesn't work +class HasProp {a : Type} (x : a) where + prop_ty : Prop + prop : prop_ty + +class HasProp' (a : Type) where + prop_ty : a → Prop + prop : ∀ x:a, prop_ty x + +instance {ty : ScalarTy} (x : Scalar x) : HasProp x where + -- prop_ty is inferred + prop := And.intro x.hmin x.hmax + +instance (ty : ScalarTy) : HasProp' (Scalar ty) where + -- prop_ty is inferred + prop := λ x => And.intro x.hmin x.hmax + +example {a : Type} (x : a) [HasProp x] : Prop := + let i : HasProp x := inferInstance + i.prop_ty open Lean Lean.Elab Command Term Lean.Meta @@ -96,6 +117,40 @@ def isScalarExpr (e : Expr) : MetaM Bool := do | .some _ => pure true | _ => pure false +#check @HasProp'.prop + +-- Return an instance of `HasProp` for `e` if it has some +def lookupHasProp (e : Expr) : MetaM (Option Expr) := do + logInfo f!"lookupHasProp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + logInfo f!"lookupHasProp: observing" + let ty ← Lean.Meta.inferType e + let hasProp ← mkAppM `Arith.HasProp' #[ty] + let hasPropInst ← trySynthInstance hasProp + match hasPropInst with + | LOption.some i => + logInfo m!"Found HasProp instance" + let i_prop ← mkProjection i `prop + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Auxiliary function for `collectHasPropInstances` +private partial def collectHasPropInstancesAux (hs : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do + -- We do it in a very simpler manner: we deconstruct applications, + -- and recursively explore the sub-expressions. Note that we do + -- not go inside foralls and abstractions (should we?). + e.withApp fun f args => do + let hasPropInst ← lookupHasProp f + let hs := Option.getD (hasPropInst.map hs.insert) hs + let hs ← args.foldlM collectHasPropInstancesAux hs + pure hs + +-- Explore a term and return the instances of `HasProp` found for the sub-expressions +def collectHasPropInstances (e : Expr) : MetaM (HashSet Expr) := + collectHasPropInstancesAux HashSet.empty e + -- Explore a term and return the set of scalar expressions found inside partial def collectScalarExprsAux (hs : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do -- We do it in a very simpler manner: we deconstruct applications, @@ -125,22 +180,43 @@ def getScalarExprsFromMainCtx : Tactic.TacticM (HashSet Expr) := do -- Return pure hs - -#check TSyntax -#check mkIdent --- TODO: addDecl? --- Project the scalar expressions into the context, to retrieve the bound inequalities --- def projectScalarExpr (e: Expr) : Tactic.TacticM Unit := do --- let e ← `($e) --- let e ← Lean.Elab.Term.elabTerm `($e) none --- Lean.Elab.Tactic.evalCases `($e) +-- Collect the instances of `HasProp` for the subexpressions in the context +def getHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + Lean.Elab.Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + -- Just a matter of precaution + let ctx ← instantiateLCtxMVars ctx + -- Initialize the hashset + let hs := HashSet.empty + -- Explore the declarations + let decls ← ctx.getDecls + let hs ← decls.foldlM (fun hs d => collectHasPropInstancesAux hs d.toExpr) hs + -- Return + pure hs elab "list_scalar_exprs" : tactic => do + logInfo m!"Listing scalar expressions" let hs ← getScalarExprsFromMainCtx hs.forM fun e => do - dbg_trace f!"+ Scalar expression: {e}" + logInfo m!"+ Scalar expression: {e}" + +example (x y : U32) (z : Usize) : True := by + list_scalar_exprs + simp + +elab "display_has_prop_instances" : tactic => do + logInfo m!"Displaying the HasProp instances" + let hs ← getHasPropInstancesFromMainCtx + hs.forM fun e => do + logInfo m!"+ HasProp instance: {e}" -#check LocalContext +example (x : U32) : True := by + let i : HasProp' U32 := inferInstance + have p := @HasProp'.prop _ i x + simp only [HasProp'.prop_ty] at p + display_has_prop_instances + simp elab "list_local_decls_1" : tactic => Lean.Elab.Tactic.withMainContext do @@ -169,18 +245,12 @@ elab "list_local_decls_1" : tactic => | _ => dbg_trace f!" Not a scalar"; pure .none pure () -def evalCustomLet (name : Name) (val : Syntax) : Tactic.TacticM Unit := +def evalAddDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool := false) : Tactic.TacticM Unit := -- I don't think we need that Lean.Elab.Tactic.withMainContext do - -- - let val ← elabTerm val .none - let type ← inferType val - -- In some situations, the type will be left as a metavariable (for instance, - -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will - -- not choose): we force the instantiation of the meta-variable - synthesizeSyntheticMVarsUsingDefault -- Insert the new declaration - withLetDecl name type val fun nval => do + let withDecl := if asLet then withLetDecl name type val else withLocalDeclD name type + withDecl fun nval => do -- For debugging let lctx ← Lean.MonadLCtx.getLCtx let fid := nval.fvarId! @@ -192,6 +262,11 @@ def evalCustomLet (name : Name) (val : Syntax) : Tactic.TacticM Unit := let mvarId ← Tactic.getMainGoal let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) let newVal ← mkLetFVars #[nval] newMVar + -- There are two cases: + -- - asLet is true: newVal is `let $name := $val in $newMVar` + -- - asLet is false: ewVal is `λ $name => $newMVar` + -- We need to apply it to `val` + let newVal := if asLet then newVal else mkAppN newVal #[val] -- Focus on the current goal Tactic.focus do -- Assign the main goal. @@ -202,18 +277,62 @@ def evalCustomLet (name : Name) (val : Syntax) : Tactic.TacticM Unit := -- we focused on the current goal Lean.Elab.Tactic.setGoals [newMVar.mvarId!] -elab "custom_let " n:ident " := " v:term : tactic => - evalCustomLet n.getId v +def evalAddDeclSyntax (name : Name) (val : Syntax) (asLet : Bool := false) : Tactic.TacticM Unit := + -- I don't think we need that + Lean.Elab.Tactic.withMainContext do + -- + let val ← elabTerm val .none + let type ← inferType val + -- In some situations, the type will be left as a metavariable (for instance, + -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will + -- not choose): we force the instantiation of the meta-variable + synthesizeSyntheticMVarsUsingDefault + -- + evalAddDecl name val type asLet --- Insert x = 3 in the context elab "custom_let " n:ident " := " v:term : tactic => - evalCustomLet n.getId v + evalAddDeclSyntax n.getId v (asLet := true) + +elab "custom_have " n:ident " := " v:term : tactic => + evalAddDeclSyntax n.getId v (asLet := false) example : Nat := by custom_let x := 4 - apply x + custom_have y := 4 + apply y example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x +#check mkIdent +#check Syntax + +-- Lookup the instances of `HasProp' for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_has_prop_instances" : tactic => do + logInfo m!"Introducing the HasProp instances" + let hs ← getHasPropInstancesFromMainCtx + hs.forM fun e => do + let type ← inferType e + let name := `h + evalAddDecl name e type (asLet := false) + -- Simplify to unfold the `prop_ty` projector + --let simpTheorems := ++ [``HasProp'.prop_ty] + let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) + -- Add the equational theorem for `HashProp'.prop_ty` + let simpTheorems ← simpTheorems.addDeclToUnfold ``HasProp'.prop_ty + let congrTheorems ← getSimpCongrTheorems + let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } + -- Where to apply the simplifier + let loc := Tactic.Location.targets #[mkIdent name] false + -- Apply the simplifier + let _ ← Tactic.simpLocation ctx (discharge? := .none) loc + pure () + -- simpLocation + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + intro_has_prop_instances + simp [*] + + end Arith -- cgit v1.2.3 From 6b319ece09b0f8a02529dd98bc20ffcb843020d6 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 17:33:17 +0200 Subject: Make minor modifications to Arith.lean --- backends/lean/Base/Arith.lean | 64 +++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index a792deb2..bb776b55 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -5,6 +5,8 @@ import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith +-- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet +--import Mathlib.Tactic.Omega import Base.Primitives /- @@ -77,26 +79,19 @@ instance (ty : ScalarTy) : IsScalar (Scalar ty) where example (ty : ScalarTy) : IsScalar (Scalar ty) := inferInstance --- TODO: lookup doesn't work -class HasProp {a : Type} (x : a) where - prop_ty : Prop - prop : prop_ty - -class HasProp' (a : Type) where +-- Remark: I tried a version of the shape `HasProp {a : Type} (x : a)` +-- but the lookup didn't work +class HasProp (a : Type) where prop_ty : a → Prop prop : ∀ x:a, prop_ty x -instance {ty : ScalarTy} (x : Scalar x) : HasProp x where - -- prop_ty is inferred - prop := And.intro x.hmin x.hmax - -instance (ty : ScalarTy) : HasProp' (Scalar ty) where +instance (ty : ScalarTy) : HasProp (Scalar ty) where -- prop_ty is inferred prop := λ x => And.intro x.hmin x.hmax -example {a : Type} (x : a) [HasProp x] : Prop := - let i : HasProp x := inferInstance - i.prop_ty +instance (a : Type) : HasProp (Vec a) where + prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize + prop := λ ⟨ _, l ⟩ => l open Lean Lean.Elab Command Term Lean.Meta @@ -117,8 +112,6 @@ def isScalarExpr (e : Expr) : MetaM Bool := do | .some _ => pure true | _ => pure false -#check @HasProp'.prop - -- Return an instance of `HasProp` for `e` if it has some def lookupHasProp (e : Expr) : MetaM (Option Expr) := do logInfo f!"lookupHasProp" @@ -127,7 +120,7 @@ def lookupHasProp (e : Expr) : MetaM (Option Expr) := do Lean.observing? do logInfo f!"lookupHasProp: observing" let ty ← Lean.Meta.inferType e - let hasProp ← mkAppM `Arith.HasProp' #[ty] + let hasProp ← mkAppM ``Arith.HasProp #[ty] let hasPropInst ← trySynthInstance hasProp match hasPropInst with | LOption.some i => @@ -212,9 +205,9 @@ elab "display_has_prop_instances" : tactic => do logInfo m!"+ HasProp instance: {e}" example (x : U32) : True := by - let i : HasProp' U32 := inferInstance - have p := @HasProp'.prop _ i x - simp only [HasProp'.prop_ty] at p + let i : HasProp U32 := inferInstance + have p := @HasProp.prop _ i x + simp only [HasProp.prop_ty] at p display_has_prop_instances simp @@ -304,10 +297,7 @@ example : Nat := by example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x -#check mkIdent -#check Syntax - --- Lookup the instances of `HasProp' for all the sub-expressions in the context, +-- Lookup the instances of `HasProp for all the sub-expressions in the context, -- and introduce the corresponding assumptions elab "intro_has_prop_instances" : tactic => do logInfo m!"Introducing the HasProp instances" @@ -317,10 +307,9 @@ elab "intro_has_prop_instances" : tactic => do let name := `h evalAddDecl name e type (asLet := false) -- Simplify to unfold the `prop_ty` projector - --let simpTheorems := ++ [``HasProp'.prop_ty] let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) -- Add the equational theorem for `HashProp'.prop_ty` - let simpTheorems ← simpTheorems.addDeclToUnfold ``HasProp'.prop_ty + let simpTheorems ← simpTheorems.addDeclToUnfold ``HasProp.prop_ty let congrTheorems ← getSimpCongrTheorems let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } -- Where to apply the simplifier @@ -328,11 +317,32 @@ elab "intro_has_prop_instances" : tactic => do -- Apply the simplifier let _ ← Tactic.simpLocation ctx (discharge? := .none) loc pure () - -- simpLocation example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by intro_has_prop_instances simp [*] +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + intro_has_prop_instances + simp_all [Scalar.max, Scalar.min] + +-- A tactic to solve linear arithmetic goals +syntax "int_tac" : tactic +macro_rules + | `(tactic| int_tac) => + `(tactic| + intro_has_prop_instances; + have := Scalar.cMin_bound ScalarTy.Usize; + have := Scalar.cMin_bound ScalarTy.Isize; + have := Scalar.cMax_bound ScalarTy.Usize; + have := Scalar.cMax_bound ScalarTy.Isize; + simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; + linarith) + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + int_tac + +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + int_tac end Arith -- cgit v1.2.3 From ffdc2f47bc4b21df491e1a2efb6cd19637fb399b Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 17:38:49 +0200 Subject: Start working on a better encoding of mut rec defs for Diverge --- backends/lean/Base/Diverge.lean | 102 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 2 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 1ff34516..a5cf3459 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -550,7 +550,7 @@ namespace Ex2 end Ex2 namespace Ex3 - /- Mutually recursive functions -/ + /- Mutually recursive functions - first encoding (see Ex4 for a better encoding) -/ open Primitives Fix /- Because we have mutually recursive functions, we use a sum for the inputs @@ -671,6 +671,104 @@ namespace Ex3 end Ex3 namespace Ex4 + /- Mutually recursive functions - 2nd encoding -/ + open Primitives Fix + + attribute [local simp] List.get + + /- We make the input type and output types dependent on a parameter -/ + @[simp] def input_ty (i : Fin 2) : Type := + [Int, Int].get i + + @[simp] def output_ty (i : Fin 2) : Type := + [Bool, Bool].get i + + /- The continuation -/ + variable (k : (i : Fin 2) → input_ty i → Result (output_ty i)) + + /- The bodies are more natural -/ + def is_even_body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i : Int) : Result Bool := + if i = 0 + then .ret true + else do + let b ← k 1 (i - 1) + .ret b + + def is_odd_body (i : Int) : Result Bool := + if i = 0 + then .ret false + else do + let b ← k 0 (i - 1) + .ret b + + inductive Funs : List (Type 0) → List (Type 0) → Type 1 := + | Nil : Funs [] [] + | Cons {ity oty : Type 0} {itys otys : List (Type 0)} (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) + + theorem Funs.length_eq {itys otys : List (Type 0)} (fl : Funs itys otys) : itys.length = otys.length := + match fl with + | .Nil => by simp + | .Cons f tl => + have h:= Funs.length_eq tl + by simp [h] + + @[simp] def Funs.cast_fin {itys otys : List (Type 0)} (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := + ⟨ i.val, by have h:= fl.length_eq; have h1:= i.isLt; simp_all ⟩ + + @[simp] def bodies (k : (i : Fin 2) → input_ty i → Result (output_ty i)) : Funs [Int, Int] [Bool, Bool] := + Funs.Cons (is_even_body k) (Funs.Cons (is_odd_body k) Funs.Nil) + + @[simp] def get_fun {itys otys : List (Type 0)} (fl : Funs itys otys) : + (i : Fin itys.length) → itys.get i → Result (otys.get (fl.cast_fin i)) := + match fl with + | .Nil => λ i => by have h:= i.isLt; simp at h + | @Funs.Cons ity oty itys1 otys1 f tl => + λ i => + if h: i.val = 0 then + Eq.mp (by cases i; simp_all [List.get]) f + else + let j := i.val - 1 + have Hj: j < itys1.length := by + have Hi := i.isLt + simp at Hi + revert Hi + cases Heq: i.val <;> simp_all + simp_arith + let j: Fin itys1.length := ⟨ j, Hj ⟩ + Eq.mp (by cases Heq: i; rename_i val isLt; cases Heq': j; rename_i val' isLt; cases val <;> simp_all [List.get]) (get_fun tl j) + + def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : input_ty i → Result (output_ty i) := get_fun (bodies k) i + + def fix_ {n : Nat} {ity oty : Fin n → Type 0} (f : ((i:Fin n) → ity i → Result (oty i)) → (i:Fin n) → ity i → Result (oty i)) : + (i:Fin n) → ity i → Result (oty i) := + sorry + + theorem body_fix_eq : fix_ body = body (fix_ body) := sorry + + def is_even (i : Int) : Result Bool := fix_ body 0 i + def is_odd (i : Int) : Result Bool := fix_ body 1 i + + theorem is_even_eq (i : Int) : is_even i = + (if i = 0 + then .ret true + else do + let b ← is_odd (i - 1) + .ret b) := by + simp [is_even, is_odd]; + conv => lhs; rw [body_fix_eq] + + theorem is_odd_eq (i : Int) : is_odd i = + (if i = 0 + then .ret false + else do + let b ← is_even (i - 1) + .ret b) := by + simp [is_even, is_odd]; + conv => lhs; rw [body_fix_eq] + +end Ex4 + +namespace Ex5 /- Higher-order example -/ open Primitives Fix @@ -736,6 +834,6 @@ namespace Ex4 simp [id] conv => lhs; rw [Heq]; simp; rw [id_body] -end Ex4 +end Ex5 end Diverge -- cgit v1.2.3 From 87fd14e74fe00752df7759372093543ae77a51ae Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 18:33:26 +0200 Subject: Make the definitions in Diverge.Fix dependently typed --- backends/lean/Base/Diverge.lean | 95 ++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index a5cf3459..d65e77a1 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -88,7 +88,8 @@ namespace Fix open Primitives open Result - variable {a b c d : Type} + variable {a : Type} {b : a → Type} + variable {c d : Type} /-! # The least fixed point definition and its properties -/ @@ -132,19 +133,23 @@ namespace Fix /-! # The fixed point definitions -/ - def fix_fuel (n : Nat) (f : (a → Result b) → a → Result b) (x : a) : Result b := + def fix_fuel (n : Nat) (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : + Result (b x) := match n with | 0 => .div | n + 1 => f (fix_fuel n f) x - @[simp] def fix_fuel_pred (f : (a → Result b) → a → Result b) (x : a) (n : Nat) := + @[simp] def fix_fuel_pred (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : a) (n : Nat) := not (div? (fix_fuel n f x)) - def fix_fuel_P (f : (a → Result b) → a → Result b) (x : a) (n : Nat) : Prop := + def fix_fuel_P (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : a) (n : Nat) : Prop := fix_fuel_pred f x n - noncomputable def fix (f : (a → Result b) → a → Result b) (x : a) : Result b := + noncomputable + def fix (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : Result (b x) := fix_fuel (least (fix_fuel_P f x)) f x /-! # The validity property -/ @@ -158,11 +163,11 @@ namespace Fix | ret _ => x2 = x1 -- TODO: generalize -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) - def karrow_rel (k1 k2 : a → Result b) : Prop := + def karrow_rel (k1 k2 : (x:a) → Result (b x)) : Prop := ∀ x, result_rel (k1 x) (k2 x) -- Monotonicity property for function bodies - def is_mono (f : (a → Result b) → a → Result b) : Prop := + def is_mono (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := ∀ {{k1 k2}}, karrow_rel k1 k2 → karrow_rel (f k1) (f k2) -- "Continuity" property. @@ -170,11 +175,12 @@ namespace Fix -- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf -- We define our "continuity" criteria so that it gives us what we need to -- prove the fixed-point equation, and we can also easily manipulate it. - def is_cont (f : (a → Result b) → a → Result b) : Prop := + def is_cont (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div /-! # The proof of the fixed-point equation -/ - theorem fix_fuel_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + theorem fix_fuel_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} + (Hmono : is_mono f) : ∀ {{n m}}, n ≤ m → karrow_rel (fix_fuel n f) (fix_fuel m f) := by intros n induction n @@ -195,12 +201,13 @@ namespace Fix simp [result_rel] at Hmono apply Hmono - @[simp] theorem neg_fix_fuel_P {f : (a → Result b) → a → Result b} {x : a} {n : Nat} : + @[simp] theorem neg_fix_fuel_P + {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} {x : a} {n : Nat} : ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by simp [fix_fuel_P, div?] cases fix_fuel n f x <;> simp - theorem fix_fuel_fix_mono {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + theorem fix_fuel_fix_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : ∀ n, karrow_rel (fix_fuel n f) (fix f) := by intros n x simp [result_rel] @@ -234,7 +241,7 @@ namespace Fix cases Heq':fix_fuel n f x <;> simp_all - theorem fix_fuel_P_least {f : (a → Result b) → a → Result b} (Hmono : is_mono f) : + theorem fix_fuel_P_least {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by intros x n Hf have Hfmono := fix_fuel_fix_mono Hmono n x @@ -247,7 +254,7 @@ namespace Fix -- Prove the fixed point equation in the case there exists some fuel for which -- the execution terminates - theorem fix_fixed_eq_terminates (f : (a → Result b) → a → Result b) (Hmono : is_mono f) + theorem fix_fixed_eq_terminates (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (Hmono : is_mono f) (x : a) (n : Nat) (He : fix_fuel_P f x n) : fix f x = f (fix f) x := by have Hl := fix_fuel_P_least Hmono He @@ -271,7 +278,7 @@ namespace Fix revert Hvm split <;> simp [*] <;> intros <;> simp [*] - theorem fix_fixed_eq_forall {{f : (a → Result b) → a → Result b}} + theorem fix_fixed_eq_forall {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} (Hmono : is_mono f) (Hcont : is_cont f) : ∀ x, fix f x = f (fix f) x := by intros x @@ -290,7 +297,7 @@ namespace Fix | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hmono x n He -- The final fixed point equation - theorem fix_fixed_eq {{f : (a → Result b) → a → Result b}} + theorem fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} (Hmono : is_mono f) (Hcont : is_cont f) : fix f = f (fix f) := by have Heq := fix_fixed_eq_forall Hmono Hcont @@ -301,7 +308,7 @@ namespace Fix /-! # Making the proofs of validity manageable (and automatable) -/ -- Monotonicity property for expressions - def is_mono_p (e : (a → Result b) → Result c) : Prop := + def is_mono_p (e : ((x:a) → Result (b x)) → Result c) : Prop := ∀ {{k1 k2}}, karrow_rel k1 k2 → result_rel (e k1) (e k2) theorem is_mono_p_same (x : Result c) : @@ -310,16 +317,17 @@ namespace Fix split <;> simp theorem is_mono_p_rec (x : a) : - @is_mono_p a b b (λ f => f x) := by + @is_mono_p a b (b x) (λ f => f x) := by simp_all [is_mono_p, karrow_rel, result_rel] -- The important lemma about `is_mono_p` + -- TODO: generalize d? theorem is_mono_p_bind - (g : (a → Result b) → Result c) - (h : c → (a → Result b) → Result d) : + (g : ((x:a) → Result (b x)) → Result c) + (h : c → ((x:a) → Result (b x)) → Result d) : is_mono_p g → (∀ y, is_mono_p (h y)) → - is_mono_p (λ k => do let y ← g k; h y k) := by + @is_mono_p a b d (λ k => do let y ← g k; h y k) := by intro hg hh simp [is_mono_p] intro fg fh Hrgh @@ -332,25 +340,26 @@ namespace Fix -- Continuity property for expressions - note that we take the continuation -- as parameter - def is_cont_p (k : (a → Result b) → a → Result b) - (e : (a → Result b) → Result c) : Prop := + def is_cont_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (e : ((x:a) → Result (b x)) → Result c) : Prop := (Hc : ∀ n, e (fix_fuel n k) = .div) → e (fix k) = .div - theorem is_cont_p_same (k : (a → Result b) → a → Result b) (x : Result c) : + theorem is_cont_p_same (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : Result c) : is_cont_p k (λ _ => x) := by simp [is_cont_p] - theorem is_cont_p_rec (f : (a → Result b) → a → Result b) (x : a) : + theorem is_cont_p_rec (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : is_cont_p f (λ f => f x) := by simp_all [is_cont_p, fix] -- The important lemma about `is_cont_p` theorem is_cont_p_bind - (k : (a → Result b) → a → Result b) + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (Hkmono : is_mono k) - (g : (a → Result b) → Result c) - (h : c → (a → Result b) → Result d) : + (g : ((x:a) → Result (b x)) → Result c) + (h : c → ((x:a) → Result (b x)) → Result d) : is_mono_p g → is_cont_p k g → (∀ y, is_mono_p (h y)) → @@ -402,16 +411,18 @@ namespace Fix apply Hhcont; assumption -- The validity property for an expression - def is_valid_p (k : (a → Result b) → a → Result b) - (e : (a → Result b) → Result c) : Prop := + def is_valid_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (e : ((x:a) → Result (b x)) → Result c) : Prop := is_mono_p e ∧ (is_mono k → is_cont_p k e) - @[simp] theorem is_valid_p_same (k : (a → Result b) → a → Result b) (x : Result c) : + @[simp] theorem is_valid_p_same + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : Result c) : is_valid_p k (λ _ => x) := by simp [is_valid_p, is_mono_p_same, is_cont_p_same] - @[simp] theorem is_valid_p_rec (k : (a → Result b) → a → Result b) (x : a) : + @[simp] theorem is_valid_p_rec + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : is_valid_p k (λ k => k x) := by simp_all [is_valid_p, is_mono_p_rec, is_cont_p_rec] @@ -419,9 +430,9 @@ namespace Fix -- (in particular, it will manage to figure out `g` and `h` when we -- apply the lemma) theorem is_valid_p_bind - {{k : (a → Result b) → a → Result b}} - {{g : (a → Result b) → Result c}} - {{h : c → (a → Result b) → Result d}} + {{k : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + {{g : ((x:a) → Result (b x)) → Result c}} + {{h : c → ((x:a) → Result (b x)) → Result d}} (Hgvalid : is_valid_p k g) (Hhvalid : ∀ y, is_valid_p k (h y)) : is_valid_p k (λ k => do let y ← g k; h y k) := by @@ -438,7 +449,7 @@ namespace Fix have Hhcont := Hhcont Hkmono apply is_cont_p_bind <;> assumption - theorem is_valid_p_imp_is_valid {{e : (a → Result b) → a → Result b}} + theorem is_valid_p_imp_is_valid {{e : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : is_mono e ∧ is_cont e := by have Hmono : is_mono e := by @@ -457,7 +468,7 @@ namespace Fix simp [*] simp [*] - theorem is_valid_p_fix_fixed_eq {{e : (a → Result b) → a → Result b}} + theorem is_valid_p_fix_fixed_eq {{e : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : fix e = e (fix e) := by have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid @@ -625,18 +636,6 @@ namespace Ex3 | .inl _ => .fail .panic | .inr b => .ret b - -- TODO: move - -- TODO: this is not enough - theorem swap_if_bind {a b : Type} (e : Prop) [Decidable e] - (x y : Result a) (f : a → Result b) : - (do - let z ← (if e then x else y) - f z) - = - (if e then do let z ← x; f z - else do let z ← y; f z) := by - split <;> simp - -- The unfolding equation for `is_even` - diverges if `i < 0` theorem is_even_eq (i : Int) : is_even i = (if i = 0 then .ret true else is_odd (i - 1)) -- cgit v1.2.3 From 4cc411a30b19f5c5eea67b2e4da232337af8f12b Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 18:40:47 +0200 Subject: Generalize some definitions --- backends/lean/Base/Diverge.lean | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index d65e77a1..0c1028bd 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -321,7 +321,6 @@ namespace Fix simp_all [is_mono_p, karrow_rel, result_rel] -- The important lemma about `is_mono_p` - -- TODO: generalize d? theorem is_mono_p_bind (g : ((x:a) → Result (b x)) → Result c) (h : c → ((x:a) → Result (b x)) → Result d) : @@ -700,24 +699,28 @@ namespace Ex4 let b ← k 0 (i - 1) .ret b - inductive Funs : List (Type 0) → List (Type 0) → Type 1 := + inductive Funs : List (Type u) → List (Type u) → Type (u + 1) := | Nil : Funs [] [] - | Cons {ity oty : Type 0} {itys otys : List (Type 0)} (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) + | Cons {ity oty : Type u} {itys otys : List (Type u)} + (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) - theorem Funs.length_eq {itys otys : List (Type 0)} (fl : Funs itys otys) : itys.length = otys.length := + theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs itys otys) : + itys.length = otys.length := match fl with | .Nil => by simp | .Cons f tl => have h:= Funs.length_eq tl by simp [h] - @[simp] def Funs.cast_fin {itys otys : List (Type 0)} (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := + @[simp] def Funs.cast_fin {itys otys : List (Type)} + (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := ⟨ i.val, by have h:= fl.length_eq; have h1:= i.isLt; simp_all ⟩ - @[simp] def bodies (k : (i : Fin 2) → input_ty i → Result (output_ty i)) : Funs [Int, Int] [Bool, Bool] := + @[simp] def bodies (k : (i : Fin 2) → input_ty i → Result (output_ty i)) : + Funs [Int, Int] [Bool, Bool] := Funs.Cons (is_even_body k) (Funs.Cons (is_odd_body k) Funs.Nil) - @[simp] def get_fun {itys otys : List (Type 0)} (fl : Funs itys otys) : + @[simp] def get_fun {itys otys : List (Type)} (fl : Funs itys otys) : (i : Fin itys.length) → itys.get i → Result (otys.get (fl.cast_fin i)) := match fl with | .Nil => λ i => by have h:= i.isLt; simp at h @@ -734,11 +737,18 @@ namespace Ex4 cases Heq: i.val <;> simp_all simp_arith let j: Fin itys1.length := ⟨ j, Hj ⟩ - Eq.mp (by cases Heq: i; rename_i val isLt; cases Heq': j; rename_i val' isLt; cases val <;> simp_all [List.get]) (get_fun tl j) - - def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : input_ty i → Result (output_ty i) := get_fun (bodies k) i - - def fix_ {n : Nat} {ity oty : Fin n → Type 0} (f : ((i:Fin n) → ity i → Result (oty i)) → (i:Fin n) → ity i → Result (oty i)) : + Eq.mp + (by + cases Heq: i; rename_i val isLt; + cases Heq': j; rename_i val' isLt; + cases val <;> simp_all [List.get]) + (get_fun tl j) + + def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : + input_ty i → Result (output_ty i) := get_fun (bodies k) i + + def fix_ {n : Nat} {ity oty : Fin n → Type} + (f : ((i:Fin n) → ity i → Result (oty i)) → (i:Fin n) → ity i → Result (oty i)) : (i:Fin n) → ity i → Result (oty i) := sorry -- cgit v1.2.3 From f4ee75da0959ff06ce4cfaab817de540fcd0433f Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 19:28:03 +0200 Subject: Add FixI in Diverge --- backends/lean/Base/Diverge.lean | 127 +++++++++++++++++++++++++++++++++------- 1 file changed, 105 insertions(+), 22 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 0c1028bd..907075d7 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -448,17 +448,20 @@ namespace Fix have Hhcont := Hhcont Hkmono apply is_cont_p_bind <;> assumption - theorem is_valid_p_imp_is_valid {{e : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : - is_mono e ∧ is_cont e := by - have Hmono : is_mono e := by + def is_valid (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := + ∀ k x, is_valid_p k (λ k => f k x) + + theorem is_valid_p_imp_is_valid {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hvalid : is_valid f) : + is_mono f ∧ is_cont f := by + have Hmono : is_mono f := by intro f h Hr x have Hmono := Hvalid (λ _ _ => .div) x have Hmono := Hmono.left apply Hmono; assumption - have Hcont : is_cont e := by + have Hcont : is_cont f := by intro x Hdiv - have Hcont := (Hvalid e x).right Hmono + have Hcont := (Hvalid f x).right Hmono simp [is_cont_p] at Hcont apply Hcont intro n @@ -467,14 +470,96 @@ namespace Fix simp [*] simp [*] - theorem is_valid_p_fix_fixed_eq {{e : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hvalid : ∀ k x, is_valid_p k (λ k => e k x)) : - fix e = e (fix e) := by + theorem is_valid_fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hvalid : is_valid f) : + fix f = f (fix f) := by have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid exact fix_fixed_eq Hmono Hcont end Fix +namespace FixI + /- Indexed fixed-point: definitions with indexed types, convenient to use for mutually + recursive definitions. We simply port the definitions and proofs from Fix to a more + specific case. + -/ + open Primitives Fix + + -- The index type + variable {id : Type} + + -- The input/output types + variable {a b : id → Type} + + -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) + def karrow_rel (k1 k2 : (i:id) → a i → Result (b i)) : Prop := + ∀ i x, result_rel (k1 i x) (k2 i x) + + def kk_to_gen (k : (i:id) → a i → Result (b i)) : + (x: (i:id) × a i) → Result (b x.fst) := + λ ⟨ i, x ⟩ => k i x + + def kk_of_gen (k : (x: (i:id) × a i) → Result (b x.fst)) : + (i:id) → a i → Result (b i) := + λ i x => k ⟨ i, x ⟩ + + def k_to_gen (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : + ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst) := + λ kk => kk_to_gen (k (kk_of_gen kk)) + + def k_of_gen (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : + ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i) := + λ kk => kk_of_gen (k (kk_to_gen kk)) + + def e_to_gen (e : ((i:id) → a i → Result (b i)) → Result c) : + ((x: (i:id) × a i) → Result (b x.fst)) → Result c := + λ k => e (kk_of_gen k) + + def is_valid_p (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) + (e : ((i:id) → a i → Result (b i)) → Result c) : Prop := + Fix.is_valid_p (k_to_gen k) (e_to_gen e) + + def is_valid (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : Prop := + ∀ k i x, is_valid_p k (λ k => f k i x) + + @[simp] theorem kk_to_gen_kk_of_gen + (k : (x: (i:id) × a i) → Result (b x.fst)) : + kk_to_gen (kk_of_gen kk) = kk := by + simp [kk_to_gen, kk_of_gen] + + @[simp] theorem k_to_gen_k_of_gen + (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : + k_to_gen (k_of_gen kk) = kk := by + simp [k_to_gen, k_of_gen] + apply funext + intro kk_1 + -- TODO: some simplifications don't work + simp [kk_to_gen, kk_of_gen] + + noncomputable def fix + (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : + (i:id) → a i → Result (b i) := + kk_of_gen (Fix.fix (k_to_gen f)) + + theorem is_valid_fix_fixed_eq + {{f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} + (Hvalid : is_valid f) : + fix f = f (fix f) := by + have Hvalid' : Fix.is_valid (k_to_gen f) := by + intro k x + simp [is_valid, is_valid_p] at Hvalid + --simp [Fix.is_valid_p] + let ⟨ i, x ⟩ := x + have Hvalid := Hvalid (k_of_gen k) i x + -- TODO: some simplifications don't work + simp [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid + refine Hvalid + have Heq := Fix.is_valid_fix_fixed_eq Hvalid' + simp [fix] + conv => lhs; rw [Heq] + +end FixI + namespace Ex1 /- An example of use of the fixed-point -/ open Primitives Fix @@ -507,7 +592,7 @@ namespace Ex1 if i = 0 then .ret hd else list_nth tl (i - 1) := by - have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_is_valid a) + have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) simp [list_nth] conv => lhs; rw [Heq] @@ -553,7 +638,7 @@ namespace Ex2 let y ← list_nth tl (i - 1) .ret y) := by - have Heq := is_valid_p_fix_fixed_eq (@list_nth_body_is_valid a) + have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) simp [list_nth] conv => lhs; rw [Heq] @@ -639,7 +724,7 @@ namespace Ex3 theorem is_even_eq (i : Int) : is_even i = (if i = 0 then .ret true else is_odd (i - 1)) := by - have Heq := is_valid_p_fix_fixed_eq is_even_is_odd_body_is_valid + have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid simp [is_even, is_odd] conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp -- Very annoying: we need to swap the matches @@ -657,7 +742,7 @@ namespace Ex3 theorem is_odd_eq (i : Int) : is_odd i = (if i = 0 then .ret false else is_even (i - 1)) := by - have Heq := is_valid_p_fix_fixed_eq is_even_is_odd_body_is_valid + have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid simp [is_even, is_odd] conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp -- Same remark as for `even` @@ -670,7 +755,7 @@ end Ex3 namespace Ex4 /- Mutually recursive functions - 2nd encoding -/ - open Primitives Fix + open Primitives FixI attribute [local simp] List.get @@ -747,15 +832,13 @@ namespace Ex4 def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : input_ty i → Result (output_ty i) := get_fun (bodies k) i - def fix_ {n : Nat} {ity oty : Fin n → Type} - (f : ((i:Fin n) → ity i → Result (oty i)) → (i:Fin n) → ity i → Result (oty i)) : - (i:Fin n) → ity i → Result (oty i) := - sorry + theorem body_is_valid : is_valid body := by sorry - theorem body_fix_eq : fix_ body = body (fix_ body) := sorry + theorem body_fix_eq : fix body = body (fix body) := + is_valid_fix_fixed_eq body_is_valid - def is_even (i : Int) : Result Bool := fix_ body 0 i - def is_odd (i : Int) : Result Bool := fix_ body 1 i + noncomputable def is_even (i : Int) : Result Bool := fix body 0 i + noncomputable def is_odd (i : Int) : Result Bool := fix body 1 i theorem is_even_eq (i : Int) : is_even i = (if i = 0 @@ -839,7 +922,7 @@ namespace Ex5 let tl ← map id tl .ret (.node tl)) := by - have Heq := is_valid_p_fix_fixed_eq (@id_body_is_valid a) + have Heq := is_valid_fix_fixed_eq (@id_body_is_valid a) simp [id] conv => lhs; rw [Heq]; simp; rw [id_body] -- cgit v1.2.3 From 7f3604c21bb9f923aecb98917b5c7a33bafd1bcb Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 26 Jun 2023 23:41:01 +0200 Subject: Make minor modifications --- backends/lean/Base/Diverge.lean | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 907075d7..f3fa4815 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -522,20 +522,6 @@ namespace FixI def is_valid (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : Prop := ∀ k i x, is_valid_p k (λ k => f k i x) - @[simp] theorem kk_to_gen_kk_of_gen - (k : (x: (i:id) × a i) → Result (b x.fst)) : - kk_to_gen (kk_of_gen kk) = kk := by - simp [kk_to_gen, kk_of_gen] - - @[simp] theorem k_to_gen_k_of_gen - (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : - k_to_gen (k_of_gen kk) = kk := by - simp [k_to_gen, k_of_gen] - apply funext - intro kk_1 - -- TODO: some simplifications don't work - simp [kk_to_gen, kk_of_gen] - noncomputable def fix (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : (i:id) → a i → Result (b i) := @@ -548,10 +534,8 @@ namespace FixI have Hvalid' : Fix.is_valid (k_to_gen f) := by intro k x simp [is_valid, is_valid_p] at Hvalid - --simp [Fix.is_valid_p] let ⟨ i, x ⟩ := x have Hvalid := Hvalid (k_of_gen k) i x - -- TODO: some simplifications don't work simp [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid refine Hvalid have Heq := Fix.is_valid_fix_fixed_eq Hvalid' -- cgit v1.2.3 From 0a62cf3f7d58b31c75344172bad1032e14a4082f Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 27 Jun 2023 10:52:07 +0200 Subject: Finish the proofs which use FixI --- backends/lean/Base/Diverge.lean | 199 +++++++++++++++++++++++++++++++--------- 1 file changed, 157 insertions(+), 42 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index f3fa4815..76f0543a 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -542,6 +542,147 @@ namespace FixI simp [fix] conv => lhs; rw [Heq] + /- Some utilities to define the mutually recursive functions -/ + + inductive Funs : List (Type u) → List (Type u) → Type (u + 1) := + | Nil : Funs [] [] + | Cons {ity oty : Type u} {itys otys : List (Type u)} + (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) + + theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs itys otys) : + itys.length = otys.length := + match fl with + | .Nil => by simp + | .Cons f tl => + have h:= Funs.length_eq tl + by simp [h] + + @[simp] def Funs.cast_fin {itys otys : List (Type)} + (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := + ⟨ i.val, by have h:= fl.length_eq; have h1:= i.isLt; simp_all ⟩ + + def get_fun {itys otys : List (Type)} (fl : Funs itys otys) : + (i : Fin itys.length) → itys.get i → Result (otys.get (fl.cast_fin i)) := + match fl with + | .Nil => λ i => by have h:= i.isLt; simp at h + | @Funs.Cons ity oty itys1 otys1 f tl => + λ i => + if h: i.val = 0 then + Eq.mp (by cases i; simp_all [List.get]) f + else + let j := i.val - 1 + have Hj: j < itys1.length := by + have Hi := i.isLt + simp at Hi + revert Hi + cases Heq: i.val <;> simp_all + simp_arith + let j: Fin itys1.length := ⟨ j, Hj ⟩ + Eq.mp + (by + cases Heq: i; rename_i val isLt; + cases Heq': j; rename_i val' isLt; + cases val <;> simp_all [List.get]) + (get_fun tl j) + + + -- TODO: move + theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by + -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... + simp [Nat.add_one_le_iff] + simp [Nat.lt_iff_le_and_ne] + simp_all + + def for_all_fin_aux {n : Nat} (f : Fin n → Prop) (m : Nat) (h : m ≤ n) : Prop := + if heq: m = n then True + else + f ⟨ m, by simp_all [Nat.lt_iff_le_and_ne] ⟩ ∧ + for_all_fin_aux f (m + 1) (by simp_all [add_one_le_iff_le_ne]) + termination_by for_all_fin_aux n _ m h => n - m + decreasing_by + simp_wf + apply Nat.sub_add_lt_sub <;> simp_all + simp_all [add_one_le_iff_le_ne] + + def for_all_fin {n : Nat} (f : Fin n → Prop) := for_all_fin_aux f 0 (by simp) + + theorem for_all_fin_aux_imp_forall {n : Nat} (f : Fin n → Prop) (m : Nat) : + (h : m ≤ n) → + for_all_fin_aux f m h → ∀ i, m ≤ i.val → f i + := by + generalize h: (n - m) = k + revert m + induction k + case zero => + simp_all + intro m h1 h2 + have h: n = m := by + linarith + unfold for_all_fin_aux; simp_all + simp_all + -- There is no i s.t. m ≤ i + intro i h3; cases i; simp_all + linarith + case succ k hi => + simp_all + intro m hk hmn + intro hf i hmi + have hne: m ≠ n := by + have hineq := Nat.lt_of_sub_eq_succ hk + linarith + -- m = i? + if heq: m = i then + -- Yes: simply use the `for_all_fin_aux` hyp + unfold for_all_fin_aux at hf + simp_all + tauto + else + -- No: use the induction hypothesis + have hlt: m < i := by simp_all [Nat.lt_iff_le_and_ne] + have hineq: m + 1 ≤ n := by + have hineq := Nat.lt_of_sub_eq_succ hk + simp [*, Nat.add_one_le_iff] + have heq1: n - (m + 1) = k := by + -- TODO: very annoying arithmetic proof + simp [Nat.sub_eq_iff_eq_add hineq] + have hineq1: m ≤ n := by linarith + simp [Nat.sub_eq_iff_eq_add hineq1] at hk + simp_arith [hk] + have hi := hi (m + 1) heq1 hineq + apply hi <;> simp_all + . unfold for_all_fin_aux at hf + simp_all + . simp_all [add_one_le_iff_le_ne] + + theorem for_all_fin_imp_forall (n : Nat) (f : Fin n → Prop) : + for_all_fin f → ∀ i, f i + := by + intro Hf i + apply for_all_fin_aux_imp_forall <;> try assumption + simp + + /- Automating the proofs -/ + @[simp] theorem is_valid_p_same + (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (x : Result c) : + is_valid_p k (λ _ => x) := by + simp [is_valid_p, k_to_gen, e_to_gen] + + @[simp] theorem is_valid_p_rec + (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (i : id) (x : a i) : + is_valid_p k (λ k => k i x) := by + simp [is_valid_p, k_to_gen, e_to_gen, kk_to_gen, kk_of_gen] + + theorem is_valid_p_bind + {{k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} + {{g : ((i:id) → a i → Result (b i)) → Result c}} + {{h : c → ((i:id) → a i → Result (b i)) → Result d}} + (Hgvalid : is_valid_p k g) + (Hhvalid : ∀ y, is_valid_p k (h y)) : + is_valid_p k (λ k => do let y ← g k; h y k) := by + apply Fix.is_valid_p_bind + . apply Hgvalid + . apply Hhvalid + end FixI namespace Ex1 @@ -768,55 +909,29 @@ namespace Ex4 let b ← k 0 (i - 1) .ret b - inductive Funs : List (Type u) → List (Type u) → Type (u + 1) := - | Nil : Funs [] [] - | Cons {ity oty : Type u} {itys otys : List (Type u)} - (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) - - theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs itys otys) : - itys.length = otys.length := - match fl with - | .Nil => by simp - | .Cons f tl => - have h:= Funs.length_eq tl - by simp [h] - - @[simp] def Funs.cast_fin {itys otys : List (Type)} - (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := - ⟨ i.val, by have h:= fl.length_eq; have h1:= i.isLt; simp_all ⟩ - @[simp] def bodies (k : (i : Fin 2) → input_ty i → Result (output_ty i)) : Funs [Int, Int] [Bool, Bool] := Funs.Cons (is_even_body k) (Funs.Cons (is_odd_body k) Funs.Nil) - @[simp] def get_fun {itys otys : List (Type)} (fl : Funs itys otys) : - (i : Fin itys.length) → itys.get i → Result (otys.get (fl.cast_fin i)) := - match fl with - | .Nil => λ i => by have h:= i.isLt; simp at h - | @Funs.Cons ity oty itys1 otys1 f tl => - λ i => - if h: i.val = 0 then - Eq.mp (by cases i; simp_all [List.get]) f - else - let j := i.val - 1 - have Hj: j < itys1.length := by - have Hi := i.isLt - simp at Hi - revert Hi - cases Heq: i.val <;> simp_all - simp_arith - let j: Fin itys1.length := ⟨ j, Hj ⟩ - Eq.mp - (by - cases Heq: i; rename_i val isLt; - cases Heq': j; rename_i val' isLt; - cases val <;> simp_all [List.get]) - (get_fun tl j) - def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : input_ty i → Result (output_ty i) := get_fun (bodies k) i - theorem body_is_valid : is_valid body := by sorry + theorem body_is_valid : is_valid body := by + -- Split the proof into proofs of validity of the individual bodies + rw [is_valid] + simp [body] + intro k + apply for_all_fin_imp_forall + simp [for_all_fin] + repeat (unfold for_all_fin_aux; simp) + simp [get_fun] + (repeat (apply And.intro)) <;> intro x <;> simp at x <;> + simp [is_even_body, is_odd_body] + -- Prove the validity of the individual bodies + . split <;> simp + apply is_valid_p_bind <;> simp + . split <;> simp + apply is_valid_p_bind <;> simp theorem body_fix_eq : fix body = body (fix body) := is_valid_fix_fixed_eq body_is_valid -- cgit v1.2.3 From 8db1af5afcb414b502a58a87f6bdcc1c08cbe3d2 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 27 Jun 2023 18:22:22 +0200 Subject: Finish some proofs in Diverge --- backends/lean/Base/Diverge.lean | 119 ++++++++++++++++++++++++++++++++++------ 1 file changed, 102 insertions(+), 17 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index 76f0543a..c97674dd 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -544,28 +544,40 @@ namespace FixI /- Some utilities to define the mutually recursive functions -/ - inductive Funs : List (Type u) → List (Type u) → Type (u + 1) := - | Nil : Funs [] [] + -- TODO: use more + @[simp] def kk_ty (id : Type) (a b : id → Type) := (i:id) → a i → Result (b i) + @[simp] def k_ty (id : Type) (a b : id → Type) := kk_ty id a b → kk_ty id a b + + -- Initially, we had left out the parameters id, a and b. + -- However, by parameterizing Funs with those parameters, we can state + -- and prove lemmas like Funs.is_valid_p_is_valid_p + inductive Funs (id : Type) (a b : id → Type) : + List (Type u) → List (Type u) → Type (u + 1) := + | Nil : Funs id a b [] [] | Cons {ity oty : Type u} {itys otys : List (Type u)} - (f : ity → Result oty) (tl : Funs itys otys) : Funs (ity :: itys) (oty :: otys) + (f : kk_ty id a b → ity → Result oty) (tl : Funs id a b itys otys) : + Funs id a b (ity :: itys) (oty :: otys) - theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs itys otys) : - itys.length = otys.length := + theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs id a b itys otys) : + otys.length = itys.length := match fl with | .Nil => by simp | .Cons f tl => have h:= Funs.length_eq tl by simp [h] + def fin_cast {n m : Nat} (h : m = n) (i : Fin n) : Fin m := + ⟨ i.val, by have h1:= i.isLt; simp_all ⟩ + @[simp] def Funs.cast_fin {itys otys : List (Type)} - (fl : Funs itys otys) (i : Fin itys.length) : Fin otys.length := - ⟨ i.val, by have h:= fl.length_eq; have h1:= i.isLt; simp_all ⟩ + (fl : Funs id a b itys otys) (i : Fin itys.length) : Fin otys.length := + fin_cast (fl.length_eq) i - def get_fun {itys otys : List (Type)} (fl : Funs itys otys) : - (i : Fin itys.length) → itys.get i → Result (otys.get (fl.cast_fin i)) := + def get_fun {itys otys : List (Type)} (fl : Funs id a b itys otys) : + (i : Fin itys.length) → kk_ty id a b → itys.get i → Result (otys.get (fl.cast_fin i)) := match fl with | .Nil => λ i => by have h:= i.isLt; simp at h - | @Funs.Cons ity oty itys1 otys1 f tl => + | @Funs.Cons id a b ity oty itys1 otys1 f tl => λ i => if h: i.val = 0 then Eq.mp (by cases i; simp_all [List.get]) f @@ -582,10 +594,9 @@ namespace FixI (by cases Heq: i; rename_i val isLt; cases Heq': j; rename_i val' isLt; - cases val <;> simp_all [List.get]) + cases val <;> simp_all [List.get, fin_cast]) (get_fun tl j) - -- TODO: move theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... @@ -612,7 +623,7 @@ namespace FixI := by generalize h: (n - m) = k revert m - induction k + induction k -- TODO: induction h rather? case zero => simp_all intro m h1 h2 @@ -683,6 +694,65 @@ namespace FixI . apply Hgvalid . apply Hhvalid + def Funs.is_valid_p + (k : k_ty id a b) + (fl : Funs id a b itys otys) : + Prop := + match fl with + | .Nil => True + | .Cons f fl => (∀ x, FixI.is_valid_p k (λ k => f k x)) ∧ fl.is_valid_p k + + #check Subtype + def Funs.is_valid_p_is_valid_p_aux + {k : k_ty id a b} + {itys otys : List Type} + (Heq : List.length otys = List.length itys) + (fl : Funs id a b itys otys) (Hvalid : is_valid_p k fl) : + ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) := by + -- Prepare the induction + have ⟨ n, Hn ⟩ : { n : Nat // itys.length = n } := ⟨ itys.length, by rfl ⟩ + revert itys otys Heq fl Hvalid + induction n + -- + case zero => + intro itys otys Heq fl Hvalid Hlen; + have Heq: itys = [] := by cases itys <;> simp_all + have Heq: otys = [] := by cases otys <;> simp_all + intro i x + simp_all + have Hi := i.isLt + simp_all + case succ n Hn => + intro itys otys Heq fl Hvalid Hlen i x; + cases fl <;> simp at * + rename_i ity oty itys otys f fl + have ⟨ Hvf, Hvalid ⟩ := Hvalid + have Hvf1: is_valid_p k fl := by + simp_all [Funs.is_valid_p] + have Hn := @Hn itys otys (by simp[*]) fl Hvf1 (by simp [*]) + -- Case disjunction on i + match i with + | ⟨ 0, _ ⟩ => + simp at x + simp [get_fun] + apply (Hvf x) + | ⟨ .succ j, HiLt ⟩ => + simp_arith at HiLt + simp at x + let j : Fin (List.length itys) := ⟨ j, by simp_arith [HiLt] ⟩ + have Hn := Hn j x + apply Hn + + def Funs.is_valid_p_is_valid_p + (itys otys : List (Type)) (Heq: otys.length = itys.length := by decide) + (k : k_ty (Fin (List.length itys)) (List.get itys) fun i => List.get otys (fin_cast Heq i)) + (fl : Funs (Fin itys.length) itys.get (λ i => otys.get (fin_cast Heq i)) itys otys) : + fl.is_valid_p k → + ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) + := by + intro Hvalid + apply is_valid_p_is_valid_p_aux <;> simp [*] + end FixI namespace Ex1 @@ -909,12 +979,12 @@ namespace Ex4 let b ← k 0 (i - 1) .ret b - @[simp] def bodies (k : (i : Fin 2) → input_ty i → Result (output_ty i)) : - Funs [Int, Int] [Bool, Bool] := - Funs.Cons (is_even_body k) (Funs.Cons (is_odd_body k) Funs.Nil) + @[simp] def bodies : + Funs (Fin 2) input_ty output_ty [Int, Int] [Bool, Bool] := + Funs.Cons (is_even_body) (Funs.Cons (is_odd_body) Funs.Nil) def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : - input_ty i → Result (output_ty i) := get_fun (bodies k) i + input_ty i → Result (output_ty i) := get_fun bodies i k theorem body_is_valid : is_valid body := by -- Split the proof into proofs of validity of the individual bodies @@ -933,6 +1003,21 @@ namespace Ex4 . split <;> simp apply is_valid_p_bind <;> simp + theorem body_is_valid' : is_valid body := by + -- Split the proof into proofs of validity of the individual bodies + rw [is_valid] + simp [body] + intro k + apply (Funs.is_valid_p_is_valid_p [Int, Int] [Bool, Bool]) + simp [Funs.is_valid_p] + (repeat (apply And.intro)) <;> intro x <;> simp at x <;> + simp [is_even_body, is_odd_body] + -- Prove the validity of the individual bodies + . split <;> simp + apply is_valid_p_bind <;> simp + . split <;> simp + apply is_valid_p_bind <;> simp + theorem body_fix_eq : fix body = body (fix body) := is_valid_fix_fixed_eq body_is_valid -- cgit v1.2.3 From 2554a0a64d761a82789b7eacbfa3ca2c88eec7df Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 27 Jun 2023 19:06:14 +0200 Subject: Reduce the time spent on some proofs --- backends/lean/Base/Diverge.lean | 48 +++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index c97674dd..c62e6dd5 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -25,6 +25,11 @@ TODO: - simplifier/rewriter have a strange behavior sometimes -/ + +/- TODO: this is very useful, but is there more? -/ +set_option profiler true +set_option profiler.threshold 100 + namespace Diverge namespace Primitives @@ -533,10 +538,10 @@ namespace FixI fix f = f (fix f) := by have Hvalid' : Fix.is_valid (k_to_gen f) := by intro k x - simp [is_valid, is_valid_p] at Hvalid + simp only [is_valid, is_valid_p] at Hvalid let ⟨ i, x ⟩ := x have Hvalid := Hvalid (k_of_gen k) i x - simp [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid + simp only [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid refine Hvalid have Heq := Fix.is_valid_fix_fixed_eq Hvalid' simp [fix] @@ -612,7 +617,7 @@ namespace FixI termination_by for_all_fin_aux n _ m h => n - m decreasing_by simp_wf - apply Nat.sub_add_lt_sub <;> simp_all + apply Nat.sub_add_lt_sub <;> simp simp_all [add_one_le_iff_le_ne] def for_all_fin {n : Nat} (f : Fin n → Prop) := for_all_fin_aux f 0 (by simp) @@ -665,6 +670,7 @@ namespace FixI simp_all . simp_all [add_one_le_iff_le_ne] + -- TODO: this is not necessary anymore theorem for_all_fin_imp_forall (n : Nat) (f : Fin n → Prop) : for_all_fin f → ∀ i, f i := by @@ -702,7 +708,6 @@ namespace FixI | .Nil => True | .Cons f fl => (∀ x, FixI.is_valid_p k (λ k => f k x)) ∧ fl.is_valid_p k - #check Subtype def Funs.is_valid_p_is_valid_p_aux {k : k_ty id a b} {itys otys : List Type} @@ -724,11 +729,11 @@ namespace FixI simp_all case succ n Hn => intro itys otys Heq fl Hvalid Hlen i x; - cases fl <;> simp at * + cases fl <;> simp at Hlen i x Heq Hvalid rename_i ity oty itys otys f fl have ⟨ Hvf, Hvalid ⟩ := Hvalid have Hvf1: is_valid_p k fl := by - simp_all [Funs.is_valid_p] + simp [Hvalid, Funs.is_valid_p] have Hn := @Hn itys otys (by simp[*]) fl Hvf1 (by simp [*]) -- Case disjunction on i match i with @@ -989,29 +994,12 @@ namespace Ex4 theorem body_is_valid : is_valid body := by -- Split the proof into proofs of validity of the individual bodies rw [is_valid] - simp [body] - intro k - apply for_all_fin_imp_forall - simp [for_all_fin] - repeat (unfold for_all_fin_aux; simp) - simp [get_fun] - (repeat (apply And.intro)) <;> intro x <;> simp at x <;> - simp [is_even_body, is_odd_body] - -- Prove the validity of the individual bodies - . split <;> simp - apply is_valid_p_bind <;> simp - . split <;> simp - apply is_valid_p_bind <;> simp - - theorem body_is_valid' : is_valid body := by - -- Split the proof into proofs of validity of the individual bodies - rw [is_valid] - simp [body] + simp only [body] intro k apply (Funs.is_valid_p_is_valid_p [Int, Int] [Bool, Bool]) simp [Funs.is_valid_p] (repeat (apply And.intro)) <;> intro x <;> simp at x <;> - simp [is_even_body, is_odd_body] + simp only [is_even_body, is_odd_body] -- Prove the validity of the individual bodies . split <;> simp apply is_valid_p_bind <;> simp @@ -1088,11 +1076,15 @@ namespace Ex5 theorem id_body_is_valid : ∀ k x, is_valid_p k (λ k => @id_body a k x) := by intro k x - simp [id_body] + simp only [id_body] split <;> simp - apply is_valid_p_bind <;> simp_all + apply is_valid_p_bind <;> simp [*] -- We have to show that `map k tl` is valid - apply map_is_valid; simp + apply map_is_valid; + -- Remark: if we don't do the intro, then the last step is expensive: + -- "typeclass inference of Nonempty took 119ms" + intro k x + simp only [is_valid_p_same, is_valid_p_rec] noncomputable def id (t : Tree a) := fix id_body t -- cgit v1.2.3 From 19bde89b84619defc2a822c3bf96bdca9c97eee7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 28 Jun 2023 12:16:10 +0200 Subject: Reorganize backends/lean/Base --- backends/lean/Base/Diverge.lean | 1104 +---------------------------- backends/lean/Base/Diverge/Base.lean | 1105 ++++++++++++++++++++++++++++++ backends/lean/Base/Diverge/Elab.lean | 182 +++++ backends/lean/Base/Diverge/ElabBase.lean | 9 + 4 files changed, 1298 insertions(+), 1102 deletions(-) create mode 100644 backends/lean/Base/Diverge/Base.lean create mode 100644 backends/lean/Base/Diverge/Elab.lean create mode 100644 backends/lean/Base/Diverge/ElabBase.lean diff --git a/backends/lean/Base/Diverge.lean b/backends/lean/Base/Diverge.lean index c62e6dd5..c9a2eec2 100644 --- a/backends/lean/Base/Diverge.lean +++ b/backends/lean/Base/Diverge.lean @@ -3,1105 +3,5 @@ import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith - -/- -TODO: -- we want an easier to use cases: - - keeps in the goal an equation of the shape: `t = case` - - if called on Prop terms, uses Classical.em - Actually, the cases from mathlib seems already quite powerful - (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) - For instance: cases h : e - Also: cases_matching -- better split tactic -- we need conversions to operate on the head of applications. - Actually, something like this works: - ``` - conv at Hl => - apply congr_fun - simp [fix_fuel_P] - ``` - Maybe we need a rpt ... ; focus? -- simplifier/rewriter have a strange behavior sometimes --/ - - -/- TODO: this is very useful, but is there more? -/ -set_option profiler true -set_option profiler.threshold 100 - -namespace Diverge - -namespace Primitives -/-! # Copy-pasting from Primitives to make the file self-contained -/ - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α - | div -deriving Repr, BEq - -open Result - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - | div => div - -@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] -@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] -@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : - (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : - (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_div (f : α → Result β) : - (do let y ← div; f y) = div := by simp [Bind.bind, bind] - -def div? {α: Type} (r: Result α): Bool := - match r with - | div => true - | ret _ | fail _ => false - -end Primitives - -namespace Fix - - open Primitives - open Result - - variable {a : Type} {b : a → Type} - variable {c d : Type} - - /-! # The least fixed point definition and its properties -/ - - def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) - noncomputable def least (p : Nat → Prop) : Nat := - Classical.epsilon (least_p p) - - -- Auxiliary theorem for [least_spec]: if there exists an `n` satisfying `p`, - -- there there exists a least `m` satisfying `p`. - theorem least_spec_aux (p : Nat → Prop) : ∀ (n : Nat), (hn : p n) → ∃ m, least_p p m := by - apply Nat.strongRec' - intros n hi hn - -- Case disjunction on: is n the smallest n satisfying p? - match Classical.em (∀ m, m < n → ¬ p m) with - | .inl hlt => - -- Yes: trivial - exists n - | .inr hlt => - simp at * - let ⟨ m, ⟨ hmlt, hm ⟩ ⟩ := hlt - have hi := hi m hmlt hm - apply hi - - -- The specification of [least]: either `p` is never satisfied, or it is satisfied - -- by `least p` and no `n < least p` satisfies `p`. - theorem least_spec (p : Nat → Prop) : (∀ n, ¬ p n) ∨ (p (least p) ∧ ∀ n, n < least p → ¬ p n) := by - -- Case disjunction on the existence of an `n` which satisfies `p` - match Classical.em (∀ n, ¬ p n) with - | .inl h => - -- There doesn't exist: trivial - apply (Or.inl h) - | .inr h => - -- There exists: we simply use `least_spec_aux` in combination with the property - -- of the epsilon operator - simp at * - let ⟨ n, hn ⟩ := h - apply Or.inr - have hl := least_spec_aux p n hn - have he := Classical.epsilon_spec hl - apply he - - /-! # The fixed point definitions -/ - - def fix_fuel (n : Nat) (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : - Result (b x) := - match n with - | 0 => .div - | n + 1 => - f (fix_fuel n f) x - - @[simp] def fix_fuel_pred (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (x : a) (n : Nat) := - not (div? (fix_fuel n f x)) - - def fix_fuel_P (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (x : a) (n : Nat) : Prop := - fix_fuel_pred f x n - - noncomputable - def fix (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : Result (b x) := - fix_fuel (least (fix_fuel_P f x)) f x - - /-! # The validity property -/ - - -- Monotonicity relation over results - -- TODO: generalize (we should parameterize the definition by a relation over `a`) - def result_rel {a : Type u} (x1 x2 : Result a) : Prop := - match x1 with - | div => True - | fail _ => x2 = x1 - | ret _ => x2 = x1 -- TODO: generalize - - -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) - def karrow_rel (k1 k2 : (x:a) → Result (b x)) : Prop := - ∀ x, result_rel (k1 x) (k2 x) - - -- Monotonicity property for function bodies - def is_mono (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := - ∀ {{k1 k2}}, karrow_rel k1 k2 → karrow_rel (f k1) (f k2) - - -- "Continuity" property. - -- We need this, and this looks a lot like continuity. Also see this paper: - -- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf - -- We define our "continuity" criteria so that it gives us what we need to - -- prove the fixed-point equation, and we can also easily manipulate it. - def is_cont (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := - ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div - - /-! # The proof of the fixed-point equation -/ - theorem fix_fuel_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} - (Hmono : is_mono f) : - ∀ {{n m}}, n ≤ m → karrow_rel (fix_fuel n f) (fix_fuel m f) := by - intros n - induction n - case zero => simp [karrow_rel, fix_fuel, result_rel] - case succ n1 Hi => - intros m Hle x - simp [result_rel] - match m with - | 0 => - exfalso - zify at * - linarith - | Nat.succ m1 => - simp_arith at Hle - simp [fix_fuel] - have Hi := Hi Hle - have Hmono := Hmono Hi x - simp [result_rel] at Hmono - apply Hmono - - @[simp] theorem neg_fix_fuel_P - {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} {x : a} {n : Nat} : - ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by - simp [fix_fuel_P, div?] - cases fix_fuel n f x <;> simp - - theorem fix_fuel_fix_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : - ∀ n, karrow_rel (fix_fuel n f) (fix f) := by - intros n x - simp [result_rel] - have Hl := least_spec (fix_fuel_P f x) - simp at Hl - match Hl with - | .inl Hl => simp [*] - | .inr ⟨ Hl, Hn ⟩ => - match Classical.em (fix_fuel n f x = div) with - | .inl Hd => - simp [*] - | .inr Hd => - have Hineq : least (fix_fuel_P f x) ≤ n := by - -- Proof by contradiction - cases Classical.em (least (fix_fuel_P f x) ≤ n) <;> simp [*] - simp at * - rename_i Hineq - have Hn := Hn n Hineq - contradiction - have Hfix : ¬ (fix f x = div) := by - simp [fix] - -- By property of the least upper bound - revert Hd Hl - -- TODO: there is no conversion to select the head of a function! - conv => lhs; apply congr_fun; apply congr_fun; apply congr_fun; simp [fix_fuel_P, div?] - cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp - have Hmono := fix_fuel_mono Hmono Hineq x - simp [result_rel] at Hmono - simp [fix] at * - cases Heq: fix_fuel (least (fix_fuel_P f x)) f x <;> - cases Heq':fix_fuel n f x <;> - simp_all - - theorem fix_fuel_P_least {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : - ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by - intros x n Hf - have Hfmono := fix_fuel_fix_mono Hmono n x - -- TODO: there is no conversion to select the head of a function! - conv => apply congr_fun; simp [fix_fuel_P] - simp [fix_fuel_P] at Hf - revert Hf Hfmono - simp [div?, result_rel, fix] - cases fix_fuel n f x <;> simp_all - - -- Prove the fixed point equation in the case there exists some fuel for which - -- the execution terminates - theorem fix_fixed_eq_terminates (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (Hmono : is_mono f) - (x : a) (n : Nat) (He : fix_fuel_P f x n) : - fix f x = f (fix f) x := by - have Hl := fix_fuel_P_least Hmono He - -- TODO: better control of simplification - conv at Hl => - apply congr_fun - simp [fix_fuel_P] - -- The least upper bound is > 0 - have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by - revert Hl - simp [div?] - cases least (fix_fuel_P f x) <;> simp [fix_fuel] - simp [Hsucc] at Hl - revert Hl - simp [*, div?, fix, fix_fuel] - -- Use the monotonicity - have Hfixmono := fix_fuel_fix_mono Hmono n - have Hvm := Hmono Hfixmono x - -- Use functional extensionality - simp [result_rel, fix] at Hvm - revert Hvm - split <;> simp [*] <;> intros <;> simp [*] - - theorem fix_fixed_eq_forall {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hmono : is_mono f) (Hcont : is_cont f) : - ∀ x, fix f x = f (fix f) x := by - intros x - -- Case disjunction: is there a fuel such that the execution successfully execute? - match Classical.em (∃ n, fix_fuel_P f x n) with - | .inr He => - -- No fuel: the fixed point evaluates to `div` - --simp [fix] at * - simp at * - conv => lhs; simp [fix] - have Hel := He (Nat.succ (least (fix_fuel_P f x))); simp [*, fix_fuel] at *; clear Hel - -- Use the "continuity" of `f` - have He : ∀ n, fix_fuel (.succ n) f x = div := by intros; simp [*] - have Hcont := Hcont x He - simp [Hcont] - | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hmono x n He - - -- The final fixed point equation - theorem fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hmono : is_mono f) (Hcont : is_cont f) : - fix f = f (fix f) := by - have Heq := fix_fixed_eq_forall Hmono Hcont - have Heq1 : fix f = (λ x => fix f x) := by simp - rw [Heq1] - conv => lhs; ext; simp [Heq] - - /-! # Making the proofs of validity manageable (and automatable) -/ - - -- Monotonicity property for expressions - def is_mono_p (e : ((x:a) → Result (b x)) → Result c) : Prop := - ∀ {{k1 k2}}, karrow_rel k1 k2 → result_rel (e k1) (e k2) - - theorem is_mono_p_same (x : Result c) : - @is_mono_p a b c (λ _ => x) := by - simp [is_mono_p, karrow_rel, result_rel] - split <;> simp - - theorem is_mono_p_rec (x : a) : - @is_mono_p a b (b x) (λ f => f x) := by - simp_all [is_mono_p, karrow_rel, result_rel] - - -- The important lemma about `is_mono_p` - theorem is_mono_p_bind - (g : ((x:a) → Result (b x)) → Result c) - (h : c → ((x:a) → Result (b x)) → Result d) : - is_mono_p g → - (∀ y, is_mono_p (h y)) → - @is_mono_p a b d (λ k => do let y ← g k; h y k) := by - intro hg hh - simp [is_mono_p] - intro fg fh Hrgh - simp [karrow_rel, result_rel] - have hg := hg Hrgh; simp [result_rel] at hg - cases heq0: g fg <;> simp_all - rename_i y _ - have hh := hh y Hrgh; simp [result_rel] at hh - simp_all - - -- Continuity property for expressions - note that we take the continuation - -- as parameter - def is_cont_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (e : ((x:a) → Result (b x)) → Result c) : Prop := - (Hc : ∀ n, e (fix_fuel n k) = .div) → - e (fix k) = .div - - theorem is_cont_p_same (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (x : Result c) : - is_cont_p k (λ _ => x) := by - simp [is_cont_p] - - theorem is_cont_p_rec (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : - is_cont_p f (λ f => f x) := by - simp_all [is_cont_p, fix] - - -- The important lemma about `is_cont_p` - theorem is_cont_p_bind - (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (Hkmono : is_mono k) - (g : ((x:a) → Result (b x)) → Result c) - (h : c → ((x:a) → Result (b x)) → Result d) : - is_mono_p g → - is_cont_p k g → - (∀ y, is_mono_p (h y)) → - (∀ y, is_cont_p k (h y)) → - is_cont_p k (λ k => do let y ← g k; h y k) := by - intro Hgmono Hgcont Hhmono Hhcont - simp [is_cont_p] - intro Hdiv - -- Case on `g (fix... k)`: is there an n s.t. it terminates? - cases Classical.em (∀ n, g (fix_fuel n k) = .div) <;> rename_i Hn - . -- Case 1: g diverges - have Hgcont := Hgcont Hn - simp_all - . -- Case 2: g doesn't diverge - simp at Hn - let ⟨ n, Hn ⟩ := Hn - have Hdivn := Hdiv n - have Hffmono := fix_fuel_fix_mono Hkmono n - have Hgeq := Hgmono Hffmono - simp [result_rel] at Hgeq - cases Heq: g (fix_fuel n k) <;> rename_i y <;> simp_all - -- Remains the .ret case - -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div - -- We do this in two steps: first we prove it for m ≥ n - have Hhdiv: ∀ m, h y (fix_fuel m k) = .div := by - have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m k) = .div := by - -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv - intro m Hle - have Hdivm := Hdiv m - -- Monotonicity of g - have Hffmono := fix_fuel_mono Hkmono Hle - have Hgmono := Hgmono Hffmono - -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv - clear Hdiv - simp_all [result_rel] - intro m - -- TODO: we shouldn't need the excluded middle here because it is decidable - cases Classical.em (n ≤ m) <;> rename_i Hl - . apply Hhdiv; assumption - . simp at Hl - -- Make a case disjunction on `h y (fix_fuel m k)`: if it is not equal - -- to div, use the monotonicity of `h y` - have Hle : m ≤ n := by linarith - have Hffmono := fix_fuel_mono Hkmono Hle - have Hmono := Hhmono y Hffmono - simp [result_rel] at Hmono - cases Heq: h y (fix_fuel m k) <;> simp_all - -- We can now use the continuity hypothesis for h - apply Hhcont; assumption - - -- The validity property for an expression - def is_valid_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) - (e : ((x:a) → Result (b x)) → Result c) : Prop := - is_mono_p e ∧ - (is_mono k → is_cont_p k e) - - @[simp] theorem is_valid_p_same - (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : Result c) : - is_valid_p k (λ _ => x) := by - simp [is_valid_p, is_mono_p_same, is_cont_p_same] - - @[simp] theorem is_valid_p_rec - (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : - is_valid_p k (λ k => k x) := by - simp_all [is_valid_p, is_mono_p_rec, is_cont_p_rec] - - -- Lean is good at unification: we can write a very general version - -- (in particular, it will manage to figure out `g` and `h` when we - -- apply the lemma) - theorem is_valid_p_bind - {{k : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - {{g : ((x:a) → Result (b x)) → Result c}} - {{h : c → ((x:a) → Result (b x)) → Result d}} - (Hgvalid : is_valid_p k g) - (Hhvalid : ∀ y, is_valid_p k (h y)) : - is_valid_p k (λ k => do let y ← g k; h y k) := by - let ⟨ Hgmono, Hgcont ⟩ := Hgvalid - simp [is_valid_p, forall_and] at Hhvalid - have ⟨ Hhmono, Hhcont ⟩ := Hhvalid - simp [← imp_forall_iff] at Hhcont - simp [is_valid_p]; constructor - . -- Monotonicity - apply is_mono_p_bind <;> assumption - . -- Continuity - intro Hkmono - have Hgcont := Hgcont Hkmono - have Hhcont := Hhcont Hkmono - apply is_cont_p_bind <;> assumption - - def is_valid (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := - ∀ k x, is_valid_p k (λ k => f k x) - - theorem is_valid_p_imp_is_valid {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hvalid : is_valid f) : - is_mono f ∧ is_cont f := by - have Hmono : is_mono f := by - intro f h Hr x - have Hmono := Hvalid (λ _ _ => .div) x - have Hmono := Hmono.left - apply Hmono; assumption - have Hcont : is_cont f := by - intro x Hdiv - have Hcont := (Hvalid f x).right Hmono - simp [is_cont_p] at Hcont - apply Hcont - intro n - have Hdiv := Hdiv n - simp [fix_fuel] at Hdiv - simp [*] - simp [*] - - theorem is_valid_fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} - (Hvalid : is_valid f) : - fix f = f (fix f) := by - have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid - exact fix_fixed_eq Hmono Hcont - -end Fix - -namespace FixI - /- Indexed fixed-point: definitions with indexed types, convenient to use for mutually - recursive definitions. We simply port the definitions and proofs from Fix to a more - specific case. - -/ - open Primitives Fix - - -- The index type - variable {id : Type} - - -- The input/output types - variable {a b : id → Type} - - -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) - def karrow_rel (k1 k2 : (i:id) → a i → Result (b i)) : Prop := - ∀ i x, result_rel (k1 i x) (k2 i x) - - def kk_to_gen (k : (i:id) → a i → Result (b i)) : - (x: (i:id) × a i) → Result (b x.fst) := - λ ⟨ i, x ⟩ => k i x - - def kk_of_gen (k : (x: (i:id) × a i) → Result (b x.fst)) : - (i:id) → a i → Result (b i) := - λ i x => k ⟨ i, x ⟩ - - def k_to_gen (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : - ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst) := - λ kk => kk_to_gen (k (kk_of_gen kk)) - - def k_of_gen (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : - ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i) := - λ kk => kk_of_gen (k (kk_to_gen kk)) - - def e_to_gen (e : ((i:id) → a i → Result (b i)) → Result c) : - ((x: (i:id) × a i) → Result (b x.fst)) → Result c := - λ k => e (kk_of_gen k) - - def is_valid_p (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) - (e : ((i:id) → a i → Result (b i)) → Result c) : Prop := - Fix.is_valid_p (k_to_gen k) (e_to_gen e) - - def is_valid (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : Prop := - ∀ k i x, is_valid_p k (λ k => f k i x) - - noncomputable def fix - (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : - (i:id) → a i → Result (b i) := - kk_of_gen (Fix.fix (k_to_gen f)) - - theorem is_valid_fix_fixed_eq - {{f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} - (Hvalid : is_valid f) : - fix f = f (fix f) := by - have Hvalid' : Fix.is_valid (k_to_gen f) := by - intro k x - simp only [is_valid, is_valid_p] at Hvalid - let ⟨ i, x ⟩ := x - have Hvalid := Hvalid (k_of_gen k) i x - simp only [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid - refine Hvalid - have Heq := Fix.is_valid_fix_fixed_eq Hvalid' - simp [fix] - conv => lhs; rw [Heq] - - /- Some utilities to define the mutually recursive functions -/ - - -- TODO: use more - @[simp] def kk_ty (id : Type) (a b : id → Type) := (i:id) → a i → Result (b i) - @[simp] def k_ty (id : Type) (a b : id → Type) := kk_ty id a b → kk_ty id a b - - -- Initially, we had left out the parameters id, a and b. - -- However, by parameterizing Funs with those parameters, we can state - -- and prove lemmas like Funs.is_valid_p_is_valid_p - inductive Funs (id : Type) (a b : id → Type) : - List (Type u) → List (Type u) → Type (u + 1) := - | Nil : Funs id a b [] [] - | Cons {ity oty : Type u} {itys otys : List (Type u)} - (f : kk_ty id a b → ity → Result oty) (tl : Funs id a b itys otys) : - Funs id a b (ity :: itys) (oty :: otys) - - theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs id a b itys otys) : - otys.length = itys.length := - match fl with - | .Nil => by simp - | .Cons f tl => - have h:= Funs.length_eq tl - by simp [h] - - def fin_cast {n m : Nat} (h : m = n) (i : Fin n) : Fin m := - ⟨ i.val, by have h1:= i.isLt; simp_all ⟩ - - @[simp] def Funs.cast_fin {itys otys : List (Type)} - (fl : Funs id a b itys otys) (i : Fin itys.length) : Fin otys.length := - fin_cast (fl.length_eq) i - - def get_fun {itys otys : List (Type)} (fl : Funs id a b itys otys) : - (i : Fin itys.length) → kk_ty id a b → itys.get i → Result (otys.get (fl.cast_fin i)) := - match fl with - | .Nil => λ i => by have h:= i.isLt; simp at h - | @Funs.Cons id a b ity oty itys1 otys1 f tl => - λ i => - if h: i.val = 0 then - Eq.mp (by cases i; simp_all [List.get]) f - else - let j := i.val - 1 - have Hj: j < itys1.length := by - have Hi := i.isLt - simp at Hi - revert Hi - cases Heq: i.val <;> simp_all - simp_arith - let j: Fin itys1.length := ⟨ j, Hj ⟩ - Eq.mp - (by - cases Heq: i; rename_i val isLt; - cases Heq': j; rename_i val' isLt; - cases val <;> simp_all [List.get, fin_cast]) - (get_fun tl j) - - -- TODO: move - theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by - -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... - simp [Nat.add_one_le_iff] - simp [Nat.lt_iff_le_and_ne] - simp_all - - def for_all_fin_aux {n : Nat} (f : Fin n → Prop) (m : Nat) (h : m ≤ n) : Prop := - if heq: m = n then True - else - f ⟨ m, by simp_all [Nat.lt_iff_le_and_ne] ⟩ ∧ - for_all_fin_aux f (m + 1) (by simp_all [add_one_le_iff_le_ne]) - termination_by for_all_fin_aux n _ m h => n - m - decreasing_by - simp_wf - apply Nat.sub_add_lt_sub <;> simp - simp_all [add_one_le_iff_le_ne] - - def for_all_fin {n : Nat} (f : Fin n → Prop) := for_all_fin_aux f 0 (by simp) - - theorem for_all_fin_aux_imp_forall {n : Nat} (f : Fin n → Prop) (m : Nat) : - (h : m ≤ n) → - for_all_fin_aux f m h → ∀ i, m ≤ i.val → f i - := by - generalize h: (n - m) = k - revert m - induction k -- TODO: induction h rather? - case zero => - simp_all - intro m h1 h2 - have h: n = m := by - linarith - unfold for_all_fin_aux; simp_all - simp_all - -- There is no i s.t. m ≤ i - intro i h3; cases i; simp_all - linarith - case succ k hi => - simp_all - intro m hk hmn - intro hf i hmi - have hne: m ≠ n := by - have hineq := Nat.lt_of_sub_eq_succ hk - linarith - -- m = i? - if heq: m = i then - -- Yes: simply use the `for_all_fin_aux` hyp - unfold for_all_fin_aux at hf - simp_all - tauto - else - -- No: use the induction hypothesis - have hlt: m < i := by simp_all [Nat.lt_iff_le_and_ne] - have hineq: m + 1 ≤ n := by - have hineq := Nat.lt_of_sub_eq_succ hk - simp [*, Nat.add_one_le_iff] - have heq1: n - (m + 1) = k := by - -- TODO: very annoying arithmetic proof - simp [Nat.sub_eq_iff_eq_add hineq] - have hineq1: m ≤ n := by linarith - simp [Nat.sub_eq_iff_eq_add hineq1] at hk - simp_arith [hk] - have hi := hi (m + 1) heq1 hineq - apply hi <;> simp_all - . unfold for_all_fin_aux at hf - simp_all - . simp_all [add_one_le_iff_le_ne] - - -- TODO: this is not necessary anymore - theorem for_all_fin_imp_forall (n : Nat) (f : Fin n → Prop) : - for_all_fin f → ∀ i, f i - := by - intro Hf i - apply for_all_fin_aux_imp_forall <;> try assumption - simp - - /- Automating the proofs -/ - @[simp] theorem is_valid_p_same - (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (x : Result c) : - is_valid_p k (λ _ => x) := by - simp [is_valid_p, k_to_gen, e_to_gen] - - @[simp] theorem is_valid_p_rec - (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (i : id) (x : a i) : - is_valid_p k (λ k => k i x) := by - simp [is_valid_p, k_to_gen, e_to_gen, kk_to_gen, kk_of_gen] - - theorem is_valid_p_bind - {{k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} - {{g : ((i:id) → a i → Result (b i)) → Result c}} - {{h : c → ((i:id) → a i → Result (b i)) → Result d}} - (Hgvalid : is_valid_p k g) - (Hhvalid : ∀ y, is_valid_p k (h y)) : - is_valid_p k (λ k => do let y ← g k; h y k) := by - apply Fix.is_valid_p_bind - . apply Hgvalid - . apply Hhvalid - - def Funs.is_valid_p - (k : k_ty id a b) - (fl : Funs id a b itys otys) : - Prop := - match fl with - | .Nil => True - | .Cons f fl => (∀ x, FixI.is_valid_p k (λ k => f k x)) ∧ fl.is_valid_p k - - def Funs.is_valid_p_is_valid_p_aux - {k : k_ty id a b} - {itys otys : List Type} - (Heq : List.length otys = List.length itys) - (fl : Funs id a b itys otys) (Hvalid : is_valid_p k fl) : - ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) := by - -- Prepare the induction - have ⟨ n, Hn ⟩ : { n : Nat // itys.length = n } := ⟨ itys.length, by rfl ⟩ - revert itys otys Heq fl Hvalid - induction n - -- - case zero => - intro itys otys Heq fl Hvalid Hlen; - have Heq: itys = [] := by cases itys <;> simp_all - have Heq: otys = [] := by cases otys <;> simp_all - intro i x - simp_all - have Hi := i.isLt - simp_all - case succ n Hn => - intro itys otys Heq fl Hvalid Hlen i x; - cases fl <;> simp at Hlen i x Heq Hvalid - rename_i ity oty itys otys f fl - have ⟨ Hvf, Hvalid ⟩ := Hvalid - have Hvf1: is_valid_p k fl := by - simp [Hvalid, Funs.is_valid_p] - have Hn := @Hn itys otys (by simp[*]) fl Hvf1 (by simp [*]) - -- Case disjunction on i - match i with - | ⟨ 0, _ ⟩ => - simp at x - simp [get_fun] - apply (Hvf x) - | ⟨ .succ j, HiLt ⟩ => - simp_arith at HiLt - simp at x - let j : Fin (List.length itys) := ⟨ j, by simp_arith [HiLt] ⟩ - have Hn := Hn j x - apply Hn - - def Funs.is_valid_p_is_valid_p - (itys otys : List (Type)) (Heq: otys.length = itys.length := by decide) - (k : k_ty (Fin (List.length itys)) (List.get itys) fun i => List.get otys (fin_cast Heq i)) - (fl : Funs (Fin itys.length) itys.get (λ i => otys.get (fin_cast Heq i)) itys otys) : - fl.is_valid_p k → - ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) - := by - intro Hvalid - apply is_valid_p_is_valid_p_aux <;> simp [*] - -end FixI - -namespace Ex1 - /- An example of use of the fixed-point -/ - open Primitives Fix - - variable {a : Type} (k : (List a × Int) → Result a) - - def list_nth_body (x : (List a × Int)) : Result a := - let (ls, i) := x - match ls with - | [] => .fail .panic - | hd :: tl => - if i = 0 then .ret hd - else k (tl, i - 1) - - theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by - intro k x - simp [list_nth_body] - split <;> simp - split <;> simp - - noncomputable - def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) - - -- The unfolding equation - diverges if `i < 0` - theorem list_nth_eq (ls : List a) (i : Int) : - list_nth ls i = - match ls with - | [] => .fail .panic - | hd :: tl => - if i = 0 then .ret hd - else list_nth tl (i - 1) - := by - have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) - simp [list_nth] - conv => lhs; rw [Heq] - -end Ex1 - -namespace Ex2 - /- Same as Ex1, but we make the body of nth non tail-rec (this is mostly - to see what happens when there are let-bindings) -/ - open Primitives Fix - - variable {a : Type} (k : (List a × Int) → Result a) - - def list_nth_body (x : (List a × Int)) : Result a := - let (ls, i) := x - match ls with - | [] => .fail .panic - | hd :: tl => - if i = 0 then .ret hd - else - do - let y ← k (tl, i - 1) - .ret y - - theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by - intro k x - simp [list_nth_body] - split <;> simp - split <;> simp - apply is_valid_p_bind <;> intros <;> simp_all - - noncomputable - def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) - - -- The unfolding equation - diverges if `i < 0` - theorem list_nth_eq (ls : List a) (i : Int) : - (list_nth ls i = - match ls with - | [] => .fail .panic - | hd :: tl => - if i = 0 then .ret hd - else - do - let y ← list_nth tl (i - 1) - .ret y) - := by - have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) - simp [list_nth] - conv => lhs; rw [Heq] - -end Ex2 - -namespace Ex3 - /- Mutually recursive functions - first encoding (see Ex4 for a better encoding) -/ - open Primitives Fix - - /- Because we have mutually recursive functions, we use a sum for the inputs - and the output types: - - inputs: the sum allows to select the function to call in the recursive - calls (and the functions may not have the same input types) - - outputs: this case is degenerate because `even` and `odd` have the same - return type `Bool`, but generally speaking we need a sum type because - the functions in the mutually recursive group may have different - return types. - -/ - variable (k : (Int ⊕ Int) → Result (Bool ⊕ Bool)) - - def is_even_is_odd_body (x : (Int ⊕ Int)) : Result (Bool ⊕ Bool) := - match x with - | .inl i => - -- Body of `is_even` - if i = 0 - then .ret (.inl true) -- We use .inl because this is `is_even` - else - do - let b ← - do - -- Call `odd`: we need to wrap the input value in `.inr`, then - -- extract the output value - let r ← k (.inr (i- 1)) - match r with - | .inl _ => .fail .panic -- Invalid output - | .inr b => .ret b - -- Wrap the return value - .ret (.inl b) - | .inr i => - -- Body of `is_odd` - if i = 0 - then .ret (.inr false) -- We use .inr because this is `is_odd` - else - do - let b ← - do - -- Call `is_even`: we need to wrap the input value in .inr, then - -- extract the output value - let r ← k (.inl (i- 1)) - match r with - | .inl b => .ret b - | .inr _ => .fail .panic -- Invalid output - -- Wrap the return value - .ret (.inr b) - - theorem is_even_is_odd_body_is_valid: - ∀ k x, is_valid_p k (λ k => is_even_is_odd_body k x) := by - intro k x - simp [is_even_is_odd_body] - split <;> simp <;> split <;> simp - apply is_valid_p_bind; simp - intros; split <;> simp - apply is_valid_p_bind; simp - intros; split <;> simp - - noncomputable - def is_even (i : Int): Result Bool := - do - let r ← fix is_even_is_odd_body (.inl i) - match r with - | .inl b => .ret b - | .inr _ => .fail .panic - - noncomputable - def is_odd (i : Int): Result Bool := - do - let r ← fix is_even_is_odd_body (.inr i) - match r with - | .inl _ => .fail .panic - | .inr b => .ret b - - -- The unfolding equation for `is_even` - diverges if `i < 0` - theorem is_even_eq (i : Int) : - is_even i = (if i = 0 then .ret true else is_odd (i - 1)) - := by - have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid - simp [is_even, is_odd] - conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp - -- Very annoying: we need to swap the matches - -- Doing this with rewriting lemmas is hard generally speaking - -- (especially as we may have to generate lemmas for user-defined - -- inductives on the fly). - -- The simplest is to repeatedly split then simplify (we identify - -- the outer match or monadic let-binding, and split on its scrutinee) - split <;> simp - cases H0 : fix is_even_is_odd_body (Sum.inr (i - 1)) <;> simp - rename_i v - split <;> simp - - -- The unfolding equation for `is_odd` - diverges if `i < 0` - theorem is_odd_eq (i : Int) : - is_odd i = (if i = 0 then .ret false else is_even (i - 1)) - := by - have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid - simp [is_even, is_odd] - conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp - -- Same remark as for `even` - split <;> simp - cases H0 : fix is_even_is_odd_body (Sum.inl (i - 1)) <;> simp - rename_i v - split <;> simp - -end Ex3 - -namespace Ex4 - /- Mutually recursive functions - 2nd encoding -/ - open Primitives FixI - - attribute [local simp] List.get - - /- We make the input type and output types dependent on a parameter -/ - @[simp] def input_ty (i : Fin 2) : Type := - [Int, Int].get i - - @[simp] def output_ty (i : Fin 2) : Type := - [Bool, Bool].get i - - /- The continuation -/ - variable (k : (i : Fin 2) → input_ty i → Result (output_ty i)) - - /- The bodies are more natural -/ - def is_even_body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i : Int) : Result Bool := - if i = 0 - then .ret true - else do - let b ← k 1 (i - 1) - .ret b - - def is_odd_body (i : Int) : Result Bool := - if i = 0 - then .ret false - else do - let b ← k 0 (i - 1) - .ret b - - @[simp] def bodies : - Funs (Fin 2) input_ty output_ty [Int, Int] [Bool, Bool] := - Funs.Cons (is_even_body) (Funs.Cons (is_odd_body) Funs.Nil) - - def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : - input_ty i → Result (output_ty i) := get_fun bodies i k - - theorem body_is_valid : is_valid body := by - -- Split the proof into proofs of validity of the individual bodies - rw [is_valid] - simp only [body] - intro k - apply (Funs.is_valid_p_is_valid_p [Int, Int] [Bool, Bool]) - simp [Funs.is_valid_p] - (repeat (apply And.intro)) <;> intro x <;> simp at x <;> - simp only [is_even_body, is_odd_body] - -- Prove the validity of the individual bodies - . split <;> simp - apply is_valid_p_bind <;> simp - . split <;> simp - apply is_valid_p_bind <;> simp - - theorem body_fix_eq : fix body = body (fix body) := - is_valid_fix_fixed_eq body_is_valid - - noncomputable def is_even (i : Int) : Result Bool := fix body 0 i - noncomputable def is_odd (i : Int) : Result Bool := fix body 1 i - - theorem is_even_eq (i : Int) : is_even i = - (if i = 0 - then .ret true - else do - let b ← is_odd (i - 1) - .ret b) := by - simp [is_even, is_odd]; - conv => lhs; rw [body_fix_eq] - - theorem is_odd_eq (i : Int) : is_odd i = - (if i = 0 - then .ret false - else do - let b ← is_even (i - 1) - .ret b) := by - simp [is_even, is_odd]; - conv => lhs; rw [body_fix_eq] - -end Ex4 - -namespace Ex5 - /- Higher-order example -/ - open Primitives Fix - - variable {a b : Type} - - /- An auxiliary function, which doesn't require the fixed-point -/ - def map (f : a → Result b) (ls : List a) : Result (List b) := - match ls with - | [] => .ret [] - | hd :: tl => - do - let hd ← f hd - let tl ← map f tl - .ret (hd :: tl) - - /- The validity theorem for `map`, generic in `f` -/ - theorem map_is_valid - {{f : (a → Result b) → a → Result c}} - (Hfvalid : ∀ k x, is_valid_p k (λ k => f k x)) - (k : (a → Result b) → a → Result b) - (ls : List a) : - is_valid_p k (λ k => map (f k) ls) := by - induction ls <;> simp [map] - apply is_valid_p_bind <;> simp_all - intros - apply is_valid_p_bind <;> simp_all - - /- An example which uses map -/ - inductive Tree (a : Type) := - | leaf (x : a) - | node (tl : List (Tree a)) - - def id_body (k : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := - match t with - | .leaf x => .ret (.leaf x) - | .node tl => - do - let tl ← map k tl - .ret (.node tl) - - theorem id_body_is_valid : - ∀ k x, is_valid_p k (λ k => @id_body a k x) := by - intro k x - simp only [id_body] - split <;> simp - apply is_valid_p_bind <;> simp [*] - -- We have to show that `map k tl` is valid - apply map_is_valid; - -- Remark: if we don't do the intro, then the last step is expensive: - -- "typeclass inference of Nonempty took 119ms" - intro k x - simp only [is_valid_p_same, is_valid_p_rec] - - noncomputable def id (t : Tree a) := fix id_body t - - -- The unfolding equation - theorem id_eq (t : Tree a) : - (id t = - match t with - | .leaf x => .ret (.leaf x) - | .node tl => - do - let tl ← map id tl - .ret (.node tl)) - := by - have Heq := is_valid_fix_fixed_eq (@id_body_is_valid a) - simp [id] - conv => lhs; rw [Heq]; simp; rw [id_body] - -end Ex5 - -end Diverge +import Base.Diverge.Base +import Base.Diverge.Elab diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean new file mode 100644 index 00000000..0f92e682 --- /dev/null +++ b/backends/lean/Base/Diverge/Base.lean @@ -0,0 +1,1105 @@ +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith + +/- +TODO: +- we want an easier to use cases: + - keeps in the goal an equation of the shape: `t = case` + - if called on Prop terms, uses Classical.em + Actually, the cases from mathlib seems already quite powerful + (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) + For instance: cases h : e + Also: cases_matching +- better split tactic +- we need conversions to operate on the head of applications. + Actually, something like this works: + ``` + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + ``` + Maybe we need a rpt ... ; focus? +- simplifier/rewriter have a strange behavior sometimes +-/ + + +/- TODO: this is very useful, but is there more? -/ +set_option profiler true +set_option profiler.threshold 100 + +namespace Diverge + +namespace Primitives +/-! # Copy-pasting from Primitives to make the file self-contained -/ + +inductive Error where + | assertionFailure: Error + | integerOverflow: Error + | divisionByZero: Error + | arrayOutOfBounds: Error + | maximumSizeExceeded: Error + | panic: Error +deriving Repr, BEq + +open Error + +inductive Result (α : Type u) where + | ret (v: α): Result α + | fail (e: Error): Result α + | div +deriving Repr, BEq + +open Result + +def bind (x: Result α) (f: α -> Result β) : Result β := + match x with + | ret v => f v + | fail v => fail v + | div => div + +@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] +@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] +@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] + +-- Allows using Result in do-blocks +instance : Bind Result where + bind := bind + +-- Allows using return x in do-blocks +instance : Pure Result where + pure := fun x => ret x + +@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : + (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : + (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_div (f : α → Result β) : + (do let y ← div; f y) = div := by simp [Bind.bind, bind] + +def div? {α: Type} (r: Result α): Bool := + match r with + | div => true + | ret _ | fail _ => false + +end Primitives + +namespace Fix + + open Primitives + open Result + + variable {a : Type} {b : a → Type} + variable {c d : Type} + + /-! # The least fixed point definition and its properties -/ + + def least_p (p : Nat → Prop) (n : Nat) : Prop := p n ∧ (∀ m, m < n → ¬ p m) + noncomputable def least (p : Nat → Prop) : Nat := + Classical.epsilon (least_p p) + + -- Auxiliary theorem for [least_spec]: if there exists an `n` satisfying `p`, + -- there there exists a least `m` satisfying `p`. + theorem least_spec_aux (p : Nat → Prop) : ∀ (n : Nat), (hn : p n) → ∃ m, least_p p m := by + apply Nat.strongRec' + intros n hi hn + -- Case disjunction on: is n the smallest n satisfying p? + match Classical.em (∀ m, m < n → ¬ p m) with + | .inl hlt => + -- Yes: trivial + exists n + | .inr hlt => + simp at * + let ⟨ m, ⟨ hmlt, hm ⟩ ⟩ := hlt + have hi := hi m hmlt hm + apply hi + + -- The specification of [least]: either `p` is never satisfied, or it is satisfied + -- by `least p` and no `n < least p` satisfies `p`. + theorem least_spec (p : Nat → Prop) : (∀ n, ¬ p n) ∨ (p (least p) ∧ ∀ n, n < least p → ¬ p n) := by + -- Case disjunction on the existence of an `n` which satisfies `p` + match Classical.em (∀ n, ¬ p n) with + | .inl h => + -- There doesn't exist: trivial + apply (Or.inl h) + | .inr h => + -- There exists: we simply use `least_spec_aux` in combination with the property + -- of the epsilon operator + simp at * + let ⟨ n, hn ⟩ := h + apply Or.inr + have hl := least_spec_aux p n hn + have he := Classical.epsilon_spec hl + apply he + + /-! # The fixed point definitions -/ + + def fix_fuel (n : Nat) (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : + Result (b x) := + match n with + | 0 => .div + | n + 1 => + f (fix_fuel n f) x + + @[simp] def fix_fuel_pred (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : a) (n : Nat) := + not (div? (fix_fuel n f x)) + + def fix_fuel_P (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : a) (n : Nat) : Prop := + fix_fuel_pred f x n + + noncomputable + def fix (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : Result (b x) := + fix_fuel (least (fix_fuel_P f x)) f x + + /-! # The validity property -/ + + -- Monotonicity relation over results + -- TODO: generalize (we should parameterize the definition by a relation over `a`) + def result_rel {a : Type u} (x1 x2 : Result a) : Prop := + match x1 with + | div => True + | fail _ => x2 = x1 + | ret _ => x2 = x1 -- TODO: generalize + + -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) + def karrow_rel (k1 k2 : (x:a) → Result (b x)) : Prop := + ∀ x, result_rel (k1 x) (k2 x) + + -- Monotonicity property for function bodies + def is_mono (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := + ∀ {{k1 k2}}, karrow_rel k1 k2 → karrow_rel (f k1) (f k2) + + -- "Continuity" property. + -- We need this, and this looks a lot like continuity. Also see this paper: + -- https://inria.hal.science/file/index/docid/216187/filename/tarski.pdf + -- We define our "continuity" criteria so that it gives us what we need to + -- prove the fixed-point equation, and we can also easily manipulate it. + def is_cont (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := + ∀ x, (Hdiv : ∀ n, fix_fuel (.succ n) f x = div) → f (fix f) x = div + + /-! # The proof of the fixed-point equation -/ + theorem fix_fuel_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} + (Hmono : is_mono f) : + ∀ {{n m}}, n ≤ m → karrow_rel (fix_fuel n f) (fix_fuel m f) := by + intros n + induction n + case zero => simp [karrow_rel, fix_fuel, result_rel] + case succ n1 Hi => + intros m Hle x + simp [result_rel] + match m with + | 0 => + exfalso + zify at * + linarith + | Nat.succ m1 => + simp_arith at Hle + simp [fix_fuel] + have Hi := Hi Hle + have Hmono := Hmono Hi x + simp [result_rel] at Hmono + apply Hmono + + @[simp] theorem neg_fix_fuel_P + {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} {x : a} {n : Nat} : + ¬ fix_fuel_P f x n ↔ (fix_fuel n f x = div) := by + simp [fix_fuel_P, div?] + cases fix_fuel n f x <;> simp + + theorem fix_fuel_fix_mono {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : + ∀ n, karrow_rel (fix_fuel n f) (fix f) := by + intros n x + simp [result_rel] + have Hl := least_spec (fix_fuel_P f x) + simp at Hl + match Hl with + | .inl Hl => simp [*] + | .inr ⟨ Hl, Hn ⟩ => + match Classical.em (fix_fuel n f x = div) with + | .inl Hd => + simp [*] + | .inr Hd => + have Hineq : least (fix_fuel_P f x) ≤ n := by + -- Proof by contradiction + cases Classical.em (least (fix_fuel_P f x) ≤ n) <;> simp [*] + simp at * + rename_i Hineq + have Hn := Hn n Hineq + contradiction + have Hfix : ¬ (fix f x = div) := by + simp [fix] + -- By property of the least upper bound + revert Hd Hl + -- TODO: there is no conversion to select the head of a function! + conv => lhs; apply congr_fun; apply congr_fun; apply congr_fun; simp [fix_fuel_P, div?] + cases fix_fuel (least (fix_fuel_P f x)) f x <;> simp + have Hmono := fix_fuel_mono Hmono Hineq x + simp [result_rel] at Hmono + simp [fix] at * + cases Heq: fix_fuel (least (fix_fuel_P f x)) f x <;> + cases Heq':fix_fuel n f x <;> + simp_all + + theorem fix_fuel_P_least {f : ((x:a) → Result (b x)) → (x:a) → Result (b x)} (Hmono : is_mono f) : + ∀ {{x n}}, fix_fuel_P f x n → fix_fuel_P f x (least (fix_fuel_P f x)) := by + intros x n Hf + have Hfmono := fix_fuel_fix_mono Hmono n x + -- TODO: there is no conversion to select the head of a function! + conv => apply congr_fun; simp [fix_fuel_P] + simp [fix_fuel_P] at Hf + revert Hf Hfmono + simp [div?, result_rel, fix] + cases fix_fuel n f x <;> simp_all + + -- Prove the fixed point equation in the case there exists some fuel for which + -- the execution terminates + theorem fix_fixed_eq_terminates (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (Hmono : is_mono f) + (x : a) (n : Nat) (He : fix_fuel_P f x n) : + fix f x = f (fix f) x := by + have Hl := fix_fuel_P_least Hmono He + -- TODO: better control of simplification + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + -- The least upper bound is > 0 + have ⟨ n, Hsucc ⟩ : ∃ n, least (fix_fuel_P f x) = Nat.succ n := by + revert Hl + simp [div?] + cases least (fix_fuel_P f x) <;> simp [fix_fuel] + simp [Hsucc] at Hl + revert Hl + simp [*, div?, fix, fix_fuel] + -- Use the monotonicity + have Hfixmono := fix_fuel_fix_mono Hmono n + have Hvm := Hmono Hfixmono x + -- Use functional extensionality + simp [result_rel, fix] at Hvm + revert Hvm + split <;> simp [*] <;> intros <;> simp [*] + + theorem fix_fixed_eq_forall {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hmono : is_mono f) (Hcont : is_cont f) : + ∀ x, fix f x = f (fix f) x := by + intros x + -- Case disjunction: is there a fuel such that the execution successfully execute? + match Classical.em (∃ n, fix_fuel_P f x n) with + | .inr He => + -- No fuel: the fixed point evaluates to `div` + --simp [fix] at * + simp at * + conv => lhs; simp [fix] + have Hel := He (Nat.succ (least (fix_fuel_P f x))); simp [*, fix_fuel] at *; clear Hel + -- Use the "continuity" of `f` + have He : ∀ n, fix_fuel (.succ n) f x = div := by intros; simp [*] + have Hcont := Hcont x He + simp [Hcont] + | .inl ⟨ n, He ⟩ => apply fix_fixed_eq_terminates f Hmono x n He + + -- The final fixed point equation + theorem fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hmono : is_mono f) (Hcont : is_cont f) : + fix f = f (fix f) := by + have Heq := fix_fixed_eq_forall Hmono Hcont + have Heq1 : fix f = (λ x => fix f x) := by simp + rw [Heq1] + conv => lhs; ext; simp [Heq] + + /-! # Making the proofs of validity manageable (and automatable) -/ + + -- Monotonicity property for expressions + def is_mono_p (e : ((x:a) → Result (b x)) → Result c) : Prop := + ∀ {{k1 k2}}, karrow_rel k1 k2 → result_rel (e k1) (e k2) + + theorem is_mono_p_same (x : Result c) : + @is_mono_p a b c (λ _ => x) := by + simp [is_mono_p, karrow_rel, result_rel] + split <;> simp + + theorem is_mono_p_rec (x : a) : + @is_mono_p a b (b x) (λ f => f x) := by + simp_all [is_mono_p, karrow_rel, result_rel] + + -- The important lemma about `is_mono_p` + theorem is_mono_p_bind + (g : ((x:a) → Result (b x)) → Result c) + (h : c → ((x:a) → Result (b x)) → Result d) : + is_mono_p g → + (∀ y, is_mono_p (h y)) → + @is_mono_p a b d (λ k => do let y ← g k; h y k) := by + intro hg hh + simp [is_mono_p] + intro fg fh Hrgh + simp [karrow_rel, result_rel] + have hg := hg Hrgh; simp [result_rel] at hg + cases heq0: g fg <;> simp_all + rename_i y _ + have hh := hh y Hrgh; simp [result_rel] at hh + simp_all + + -- Continuity property for expressions - note that we take the continuation + -- as parameter + def is_cont_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (e : ((x:a) → Result (b x)) → Result c) : Prop := + (Hc : ∀ n, e (fix_fuel n k) = .div) → + e (fix k) = .div + + theorem is_cont_p_same (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (x : Result c) : + is_cont_p k (λ _ => x) := by + simp [is_cont_p] + + theorem is_cont_p_rec (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : + is_cont_p f (λ f => f x) := by + simp_all [is_cont_p, fix] + + -- The important lemma about `is_cont_p` + theorem is_cont_p_bind + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (Hkmono : is_mono k) + (g : ((x:a) → Result (b x)) → Result c) + (h : c → ((x:a) → Result (b x)) → Result d) : + is_mono_p g → + is_cont_p k g → + (∀ y, is_mono_p (h y)) → + (∀ y, is_cont_p k (h y)) → + is_cont_p k (λ k => do let y ← g k; h y k) := by + intro Hgmono Hgcont Hhmono Hhcont + simp [is_cont_p] + intro Hdiv + -- Case on `g (fix... k)`: is there an n s.t. it terminates? + cases Classical.em (∀ n, g (fix_fuel n k) = .div) <;> rename_i Hn + . -- Case 1: g diverges + have Hgcont := Hgcont Hn + simp_all + . -- Case 2: g doesn't diverge + simp at Hn + let ⟨ n, Hn ⟩ := Hn + have Hdivn := Hdiv n + have Hffmono := fix_fuel_fix_mono Hkmono n + have Hgeq := Hgmono Hffmono + simp [result_rel] at Hgeq + cases Heq: g (fix_fuel n k) <;> rename_i y <;> simp_all + -- Remains the .ret case + -- Use Hdiv to prove that: ∀ n, h y (fix_fuel n f) = div + -- We do this in two steps: first we prove it for m ≥ n + have Hhdiv: ∀ m, h y (fix_fuel m k) = .div := by + have Hhdiv : ∀ m, n ≤ m → h y (fix_fuel m k) = .div := by + -- We use the fact that `g (fix_fuel n f) = .div`, combined with Hdiv + intro m Hle + have Hdivm := Hdiv m + -- Monotonicity of g + have Hffmono := fix_fuel_mono Hkmono Hle + have Hgmono := Hgmono Hffmono + -- We need to clear Hdiv because otherwise simp_all rewrites Hdivm with Hdiv + clear Hdiv + simp_all [result_rel] + intro m + -- TODO: we shouldn't need the excluded middle here because it is decidable + cases Classical.em (n ≤ m) <;> rename_i Hl + . apply Hhdiv; assumption + . simp at Hl + -- Make a case disjunction on `h y (fix_fuel m k)`: if it is not equal + -- to div, use the monotonicity of `h y` + have Hle : m ≤ n := by linarith + have Hffmono := fix_fuel_mono Hkmono Hle + have Hmono := Hhmono y Hffmono + simp [result_rel] at Hmono + cases Heq: h y (fix_fuel m k) <;> simp_all + -- We can now use the continuity hypothesis for h + apply Hhcont; assumption + + -- The validity property for an expression + def is_valid_p (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (e : ((x:a) → Result (b x)) → Result c) : Prop := + is_mono_p e ∧ + (is_mono k → is_cont_p k e) + + @[simp] theorem is_valid_p_same + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : Result c) : + is_valid_p k (λ _ => x) := by + simp [is_valid_p, is_mono_p_same, is_cont_p_same] + + @[simp] theorem is_valid_p_rec + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : + is_valid_p k (λ k => k x) := by + simp_all [is_valid_p, is_mono_p_rec, is_cont_p_rec] + + -- Lean is good at unification: we can write a very general version + -- (in particular, it will manage to figure out `g` and `h` when we + -- apply the lemma) + theorem is_valid_p_bind + {{k : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + {{g : ((x:a) → Result (b x)) → Result c}} + {{h : c → ((x:a) → Result (b x)) → Result d}} + (Hgvalid : is_valid_p k g) + (Hhvalid : ∀ y, is_valid_p k (h y)) : + is_valid_p k (λ k => do let y ← g k; h y k) := by + let ⟨ Hgmono, Hgcont ⟩ := Hgvalid + simp [is_valid_p, forall_and] at Hhvalid + have ⟨ Hhmono, Hhcont ⟩ := Hhvalid + simp [← imp_forall_iff] at Hhcont + simp [is_valid_p]; constructor + . -- Monotonicity + apply is_mono_p_bind <;> assumption + . -- Continuity + intro Hkmono + have Hgcont := Hgcont Hkmono + have Hhcont := Hhcont Hkmono + apply is_cont_p_bind <;> assumption + + def is_valid (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) : Prop := + ∀ k x, is_valid_p k (λ k => f k x) + + theorem is_valid_p_imp_is_valid {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hvalid : is_valid f) : + is_mono f ∧ is_cont f := by + have Hmono : is_mono f := by + intro f h Hr x + have Hmono := Hvalid (λ _ _ => .div) x + have Hmono := Hmono.left + apply Hmono; assumption + have Hcont : is_cont f := by + intro x Hdiv + have Hcont := (Hvalid f x).right Hmono + simp [is_cont_p] at Hcont + apply Hcont + intro n + have Hdiv := Hdiv n + simp [fix_fuel] at Hdiv + simp [*] + simp [*] + + theorem is_valid_fix_fixed_eq {{f : ((x:a) → Result (b x)) → (x:a) → Result (b x)}} + (Hvalid : is_valid f) : + fix f = f (fix f) := by + have ⟨ Hmono, Hcont ⟩ := is_valid_p_imp_is_valid Hvalid + exact fix_fixed_eq Hmono Hcont + +end Fix + +namespace FixI + /- Indexed fixed-point: definitions with indexed types, convenient to use for mutually + recursive definitions. We simply port the definitions and proofs from Fix to a more + specific case. + -/ + open Primitives Fix + + -- The index type + variable {id : Type} + + -- The input/output types + variable {a b : id → Type} + + -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) + def karrow_rel (k1 k2 : (i:id) → a i → Result (b i)) : Prop := + ∀ i x, result_rel (k1 i x) (k2 i x) + + def kk_to_gen (k : (i:id) → a i → Result (b i)) : + (x: (i:id) × a i) → Result (b x.fst) := + λ ⟨ i, x ⟩ => k i x + + def kk_of_gen (k : (x: (i:id) × a i) → Result (b x.fst)) : + (i:id) → a i → Result (b i) := + λ i x => k ⟨ i, x ⟩ + + def k_to_gen (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : + ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst) := + λ kk => kk_to_gen (k (kk_of_gen kk)) + + def k_of_gen (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : + ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i) := + λ kk => kk_of_gen (k (kk_to_gen kk)) + + def e_to_gen (e : ((i:id) → a i → Result (b i)) → Result c) : + ((x: (i:id) × a i) → Result (b x.fst)) → Result c := + λ k => e (kk_of_gen k) + + def is_valid_p (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) + (e : ((i:id) → a i → Result (b i)) → Result c) : Prop := + Fix.is_valid_p (k_to_gen k) (e_to_gen e) + + def is_valid (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : Prop := + ∀ k i x, is_valid_p k (λ k => f k i x) + + noncomputable def fix + (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : + (i:id) → a i → Result (b i) := + kk_of_gen (Fix.fix (k_to_gen f)) + + theorem is_valid_fix_fixed_eq + {{f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} + (Hvalid : is_valid f) : + fix f = f (fix f) := by + have Hvalid' : Fix.is_valid (k_to_gen f) := by + intro k x + simp only [is_valid, is_valid_p] at Hvalid + let ⟨ i, x ⟩ := x + have Hvalid := Hvalid (k_of_gen k) i x + simp only [k_to_gen, k_of_gen, kk_to_gen, kk_of_gen] at Hvalid + refine Hvalid + have Heq := Fix.is_valid_fix_fixed_eq Hvalid' + simp [fix] + conv => lhs; rw [Heq] + + /- Some utilities to define the mutually recursive functions -/ + + -- TODO: use more + @[simp] def kk_ty (id : Type) (a b : id → Type) := (i:id) → a i → Result (b i) + @[simp] def k_ty (id : Type) (a b : id → Type) := kk_ty id a b → kk_ty id a b + + -- Initially, we had left out the parameters id, a and b. + -- However, by parameterizing Funs with those parameters, we can state + -- and prove lemmas like Funs.is_valid_p_is_valid_p + inductive Funs (id : Type) (a b : id → Type) : + List (Type u) → List (Type u) → Type (u + 1) := + | Nil : Funs id a b [] [] + | Cons {ity oty : Type u} {itys otys : List (Type u)} + (f : kk_ty id a b → ity → Result oty) (tl : Funs id a b itys otys) : + Funs id a b (ity :: itys) (oty :: otys) + + theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs id a b itys otys) : + otys.length = itys.length := + match fl with + | .Nil => by simp + | .Cons f tl => + have h:= Funs.length_eq tl + by simp [h] + + def fin_cast {n m : Nat} (h : m = n) (i : Fin n) : Fin m := + ⟨ i.val, by have h1:= i.isLt; simp_all ⟩ + + @[simp] def Funs.cast_fin {itys otys : List (Type)} + (fl : Funs id a b itys otys) (i : Fin itys.length) : Fin otys.length := + fin_cast (fl.length_eq) i + + def get_fun {itys otys : List (Type)} (fl : Funs id a b itys otys) : + (i : Fin itys.length) → kk_ty id a b → itys.get i → Result (otys.get (fl.cast_fin i)) := + match fl with + | .Nil => λ i => by have h:= i.isLt; simp at h + | @Funs.Cons id a b ity oty itys1 otys1 f tl => + λ i => + if h: i.val = 0 then + Eq.mp (by cases i; simp_all [List.get]) f + else + let j := i.val - 1 + have Hj: j < itys1.length := by + have Hi := i.isLt + simp at Hi + revert Hi + cases Heq: i.val <;> simp_all + simp_arith + let j: Fin itys1.length := ⟨ j, Hj ⟩ + Eq.mp + (by + cases Heq: i; rename_i val isLt; + cases Heq': j; rename_i val' isLt; + cases val <;> simp_all [List.get, fin_cast]) + (get_fun tl j) + + -- TODO: move + theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by + -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... + simp [Nat.add_one_le_iff] + simp [Nat.lt_iff_le_and_ne] + simp_all + + def for_all_fin_aux {n : Nat} (f : Fin n → Prop) (m : Nat) (h : m ≤ n) : Prop := + if heq: m = n then True + else + f ⟨ m, by simp_all [Nat.lt_iff_le_and_ne] ⟩ ∧ + for_all_fin_aux f (m + 1) (by simp_all [add_one_le_iff_le_ne]) + termination_by for_all_fin_aux n _ m h => n - m + decreasing_by + simp_wf + apply Nat.sub_add_lt_sub <;> simp + simp_all [add_one_le_iff_le_ne] + + def for_all_fin {n : Nat} (f : Fin n → Prop) := for_all_fin_aux f 0 (by simp) + + theorem for_all_fin_aux_imp_forall {n : Nat} (f : Fin n → Prop) (m : Nat) : + (h : m ≤ n) → + for_all_fin_aux f m h → ∀ i, m ≤ i.val → f i + := by + generalize h: (n - m) = k + revert m + induction k -- TODO: induction h rather? + case zero => + simp_all + intro m h1 h2 + have h: n = m := by + linarith + unfold for_all_fin_aux; simp_all + simp_all + -- There is no i s.t. m ≤ i + intro i h3; cases i; simp_all + linarith + case succ k hi => + simp_all + intro m hk hmn + intro hf i hmi + have hne: m ≠ n := by + have hineq := Nat.lt_of_sub_eq_succ hk + linarith + -- m = i? + if heq: m = i then + -- Yes: simply use the `for_all_fin_aux` hyp + unfold for_all_fin_aux at hf + simp_all + tauto + else + -- No: use the induction hypothesis + have hlt: m < i := by simp_all [Nat.lt_iff_le_and_ne] + have hineq: m + 1 ≤ n := by + have hineq := Nat.lt_of_sub_eq_succ hk + simp [*, Nat.add_one_le_iff] + have heq1: n - (m + 1) = k := by + -- TODO: very annoying arithmetic proof + simp [Nat.sub_eq_iff_eq_add hineq] + have hineq1: m ≤ n := by linarith + simp [Nat.sub_eq_iff_eq_add hineq1] at hk + simp_arith [hk] + have hi := hi (m + 1) heq1 hineq + apply hi <;> simp_all + . unfold for_all_fin_aux at hf + simp_all + . simp_all [add_one_le_iff_le_ne] + + -- TODO: this is not necessary anymore + theorem for_all_fin_imp_forall (n : Nat) (f : Fin n → Prop) : + for_all_fin f → ∀ i, f i + := by + intro Hf i + apply for_all_fin_aux_imp_forall <;> try assumption + simp + + /- Automating the proofs -/ + @[simp] theorem is_valid_p_same + (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (x : Result c) : + is_valid_p k (λ _ => x) := by + simp [is_valid_p, k_to_gen, e_to_gen] + + @[simp] theorem is_valid_p_rec + (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (i : id) (x : a i) : + is_valid_p k (λ k => k i x) := by + simp [is_valid_p, k_to_gen, e_to_gen, kk_to_gen, kk_of_gen] + + theorem is_valid_p_bind + {{k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} + {{g : ((i:id) → a i → Result (b i)) → Result c}} + {{h : c → ((i:id) → a i → Result (b i)) → Result d}} + (Hgvalid : is_valid_p k g) + (Hhvalid : ∀ y, is_valid_p k (h y)) : + is_valid_p k (λ k => do let y ← g k; h y k) := by + apply Fix.is_valid_p_bind + . apply Hgvalid + . apply Hhvalid + + def Funs.is_valid_p + (k : k_ty id a b) + (fl : Funs id a b itys otys) : + Prop := + match fl with + | .Nil => True + | .Cons f fl => (∀ x, FixI.is_valid_p k (λ k => f k x)) ∧ fl.is_valid_p k + + def Funs.is_valid_p_is_valid_p_aux + {k : k_ty id a b} + {itys otys : List Type} + (Heq : List.length otys = List.length itys) + (fl : Funs id a b itys otys) (Hvalid : is_valid_p k fl) : + ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) := by + -- Prepare the induction + have ⟨ n, Hn ⟩ : { n : Nat // itys.length = n } := ⟨ itys.length, by rfl ⟩ + revert itys otys Heq fl Hvalid + induction n + -- + case zero => + intro itys otys Heq fl Hvalid Hlen; + have Heq: itys = [] := by cases itys <;> simp_all + have Heq: otys = [] := by cases otys <;> simp_all + intro i x + simp_all + have Hi := i.isLt + simp_all + case succ n Hn => + intro itys otys Heq fl Hvalid Hlen i x; + cases fl <;> simp at Hlen i x Heq Hvalid + rename_i ity oty itys otys f fl + have ⟨ Hvf, Hvalid ⟩ := Hvalid + have Hvf1: is_valid_p k fl := by + simp [Hvalid, Funs.is_valid_p] + have Hn := @Hn itys otys (by simp[*]) fl Hvf1 (by simp [*]) + -- Case disjunction on i + match i with + | ⟨ 0, _ ⟩ => + simp at x + simp [get_fun] + apply (Hvf x) + | ⟨ .succ j, HiLt ⟩ => + simp_arith at HiLt + simp at x + let j : Fin (List.length itys) := ⟨ j, by simp_arith [HiLt] ⟩ + have Hn := Hn j x + apply Hn + + def Funs.is_valid_p_is_valid_p + (itys otys : List (Type)) (Heq: otys.length = itys.length := by decide) + (k : k_ty (Fin (List.length itys)) (List.get itys) fun i => List.get otys (fin_cast Heq i)) + (fl : Funs (Fin itys.length) itys.get (λ i => otys.get (fin_cast Heq i)) itys otys) : + fl.is_valid_p k → + ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) + := by + intro Hvalid + apply is_valid_p_is_valid_p_aux <;> simp [*] + +end FixI + +namespace Ex1 + /- An example of use of the fixed-point -/ + open Primitives Fix + + variable {a : Type} (k : (List a × Int) → Result a) + + def list_nth_body (x : (List a × Int)) : Result a := + let (ls, i) := x + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else k (tl, i - 1) + + theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + intro k x + simp [list_nth_body] + split <;> simp + split <;> simp + + noncomputable + def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + + -- The unfolding equation - diverges if `i < 0` + theorem list_nth_eq (ls : List a) (i : Int) : + list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else list_nth tl (i - 1) + := by + have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) + simp [list_nth] + conv => lhs; rw [Heq] + +end Ex1 + +namespace Ex2 + /- Same as Ex1, but we make the body of nth non tail-rec (this is mostly + to see what happens when there are let-bindings) -/ + open Primitives Fix + + variable {a : Type} (k : (List a × Int) → Result a) + + def list_nth_body (x : (List a × Int)) : Result a := + let (ls, i) := x + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else + do + let y ← k (tl, i - 1) + .ret y + + theorem list_nth_body_is_valid: ∀ k x, is_valid_p k (λ k => @list_nth_body a k x) := by + intro k x + simp [list_nth_body] + split <;> simp + split <;> simp + apply is_valid_p_bind <;> intros <;> simp_all + + noncomputable + def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) + + -- The unfolding equation - diverges if `i < 0` + theorem list_nth_eq (ls : List a) (i : Int) : + (list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else + do + let y ← list_nth tl (i - 1) + .ret y) + := by + have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) + simp [list_nth] + conv => lhs; rw [Heq] + +end Ex2 + +namespace Ex3 + /- Mutually recursive functions - first encoding (see Ex4 for a better encoding) -/ + open Primitives Fix + + /- Because we have mutually recursive functions, we use a sum for the inputs + and the output types: + - inputs: the sum allows to select the function to call in the recursive + calls (and the functions may not have the same input types) + - outputs: this case is degenerate because `even` and `odd` have the same + return type `Bool`, but generally speaking we need a sum type because + the functions in the mutually recursive group may have different + return types. + -/ + variable (k : (Int ⊕ Int) → Result (Bool ⊕ Bool)) + + def is_even_is_odd_body (x : (Int ⊕ Int)) : Result (Bool ⊕ Bool) := + match x with + | .inl i => + -- Body of `is_even` + if i = 0 + then .ret (.inl true) -- We use .inl because this is `is_even` + else + do + let b ← + do + -- Call `odd`: we need to wrap the input value in `.inr`, then + -- extract the output value + let r ← k (.inr (i- 1)) + match r with + | .inl _ => .fail .panic -- Invalid output + | .inr b => .ret b + -- Wrap the return value + .ret (.inl b) + | .inr i => + -- Body of `is_odd` + if i = 0 + then .ret (.inr false) -- We use .inr because this is `is_odd` + else + do + let b ← + do + -- Call `is_even`: we need to wrap the input value in .inr, then + -- extract the output value + let r ← k (.inl (i- 1)) + match r with + | .inl b => .ret b + | .inr _ => .fail .panic -- Invalid output + -- Wrap the return value + .ret (.inr b) + + theorem is_even_is_odd_body_is_valid: + ∀ k x, is_valid_p k (λ k => is_even_is_odd_body k x) := by + intro k x + simp [is_even_is_odd_body] + split <;> simp <;> split <;> simp + apply is_valid_p_bind; simp + intros; split <;> simp + apply is_valid_p_bind; simp + intros; split <;> simp + + noncomputable + def is_even (i : Int): Result Bool := + do + let r ← fix is_even_is_odd_body (.inl i) + match r with + | .inl b => .ret b + | .inr _ => .fail .panic + + noncomputable + def is_odd (i : Int): Result Bool := + do + let r ← fix is_even_is_odd_body (.inr i) + match r with + | .inl _ => .fail .panic + | .inr b => .ret b + + -- The unfolding equation for `is_even` - diverges if `i < 0` + theorem is_even_eq (i : Int) : + is_even i = (if i = 0 then .ret true else is_odd (i - 1)) + := by + have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid + simp [is_even, is_odd] + conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp + -- Very annoying: we need to swap the matches + -- Doing this with rewriting lemmas is hard generally speaking + -- (especially as we may have to generate lemmas for user-defined + -- inductives on the fly). + -- The simplest is to repeatedly split then simplify (we identify + -- the outer match or monadic let-binding, and split on its scrutinee) + split <;> simp + cases H0 : fix is_even_is_odd_body (Sum.inr (i - 1)) <;> simp + rename_i v + split <;> simp + + -- The unfolding equation for `is_odd` - diverges if `i < 0` + theorem is_odd_eq (i : Int) : + is_odd i = (if i = 0 then .ret false else is_even (i - 1)) + := by + have Heq := is_valid_fix_fixed_eq is_even_is_odd_body_is_valid + simp [is_even, is_odd] + conv => lhs; rw [Heq]; simp; rw [is_even_is_odd_body]; simp + -- Same remark as for `even` + split <;> simp + cases H0 : fix is_even_is_odd_body (Sum.inl (i - 1)) <;> simp + rename_i v + split <;> simp + +end Ex3 + +namespace Ex4 + /- Mutually recursive functions - 2nd encoding -/ + open Primitives FixI + + attribute [local simp] List.get + + /- We make the input type and output types dependent on a parameter -/ + @[simp] def input_ty (i : Fin 2) : Type := + [Int, Int].get i + + @[simp] def output_ty (i : Fin 2) : Type := + [Bool, Bool].get i + + /- The continuation -/ + variable (k : (i : Fin 2) → input_ty i → Result (output_ty i)) + + /- The bodies are more natural -/ + def is_even_body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i : Int) : Result Bool := + if i = 0 + then .ret true + else do + let b ← k 1 (i - 1) + .ret b + + def is_odd_body (i : Int) : Result Bool := + if i = 0 + then .ret false + else do + let b ← k 0 (i - 1) + .ret b + + @[simp] def bodies : + Funs (Fin 2) input_ty output_ty [Int, Int] [Bool, Bool] := + Funs.Cons (is_even_body) (Funs.Cons (is_odd_body) Funs.Nil) + + def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : + input_ty i → Result (output_ty i) := get_fun bodies i k + + theorem body_is_valid : is_valid body := by + -- Split the proof into proofs of validity of the individual bodies + rw [is_valid] + simp only [body] + intro k + apply (Funs.is_valid_p_is_valid_p [Int, Int] [Bool, Bool]) + simp [Funs.is_valid_p] + (repeat (apply And.intro)) <;> intro x <;> simp at x <;> + simp only [is_even_body, is_odd_body] + -- Prove the validity of the individual bodies + . split <;> simp + apply is_valid_p_bind <;> simp + . split <;> simp + apply is_valid_p_bind <;> simp + + theorem body_fix_eq : fix body = body (fix body) := + is_valid_fix_fixed_eq body_is_valid + + noncomputable def is_even (i : Int) : Result Bool := fix body 0 i + noncomputable def is_odd (i : Int) : Result Bool := fix body 1 i + + theorem is_even_eq (i : Int) : is_even i = + (if i = 0 + then .ret true + else do + let b ← is_odd (i - 1) + .ret b) := by + simp [is_even, is_odd]; + conv => lhs; rw [body_fix_eq] + + theorem is_odd_eq (i : Int) : is_odd i = + (if i = 0 + then .ret false + else do + let b ← is_even (i - 1) + .ret b) := by + simp [is_even, is_odd]; + conv => lhs; rw [body_fix_eq] + +end Ex4 + +namespace Ex5 + /- Higher-order example -/ + open Primitives Fix + + variable {a b : Type} + + /- An auxiliary function, which doesn't require the fixed-point -/ + def map (f : a → Result b) (ls : List a) : Result (List b) := + match ls with + | [] => .ret [] + | hd :: tl => + do + let hd ← f hd + let tl ← map f tl + .ret (hd :: tl) + + /- The validity theorem for `map`, generic in `f` -/ + theorem map_is_valid + {{f : (a → Result b) → a → Result c}} + (Hfvalid : ∀ k x, is_valid_p k (λ k => f k x)) + (k : (a → Result b) → a → Result b) + (ls : List a) : + is_valid_p k (λ k => map (f k) ls) := by + induction ls <;> simp [map] + apply is_valid_p_bind <;> simp_all + intros + apply is_valid_p_bind <;> simp_all + + /- An example which uses map -/ + inductive Tree (a : Type) := + | leaf (x : a) + | node (tl : List (Tree a)) + + def id_body (k : Tree a → Result (Tree a)) (t : Tree a) : Result (Tree a) := + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + do + let tl ← map k tl + .ret (.node tl) + + theorem id_body_is_valid : + ∀ k x, is_valid_p k (λ k => @id_body a k x) := by + intro k x + simp only [id_body] + split <;> simp + apply is_valid_p_bind <;> simp [*] + -- We have to show that `map k tl` is valid + apply map_is_valid; + -- Remark: if we don't do the intro, then the last step is expensive: + -- "typeclass inference of Nonempty took 119ms" + intro k x + simp only [is_valid_p_same, is_valid_p_rec] + + noncomputable def id (t : Tree a) := fix id_body t + + -- The unfolding equation + theorem id_eq (t : Tree a) : + (id t = + match t with + | .leaf x => .ret (.leaf x) + | .node tl => + do + let tl ← map id tl + .ret (.node tl)) + := by + have Heq := is_valid_fix_fixed_eq (@id_body_is_valid a) + simp [id] + conv => lhs; rw [Heq]; simp; rw [id_body] + +end Ex5 diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean new file mode 100644 index 00000000..313c5a79 --- /dev/null +++ b/backends/lean/Base/Diverge/Elab.lean @@ -0,0 +1,182 @@ +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Base.Diverge.Base +import Base.Diverge.ElabBase + +namespace Diverge + +/- Automating the generation of the encoding and the proofs so as to use nice + syntactic sugar. -/ + +syntax (name := divergentDef) + declModifiers "divergent" "def" declId ppIndent(optDeclSig) declVal : command + +open Lean Elab Term Meta Primitives + +initialize registerTraceClass `Diverge.divRecursion (inherited := true) + +set_option trace.Diverge.divRecursion true + +/- The following was copied from the `wfRecursion` function. -/ + +open WF in +def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do + let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) + logInfo ("divRecursion: defs: " ++ msg) + + -- CHANGE HERE This function should add definitions with these names/types/values ^^ + -- Temporarily add the predefinitions as axioms + for preDef in preDefs do + addAsAxiom preDef + + -- TODO: what is this? + for preDef in preDefs do + applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation + + -- Process the definitions + addAndCompilePartialRec preDefs + +-- The following function is copy&pasted from Lean.Elab.PreDefinition.Main +-- This is the only part where we make actual changes and hook into the equation compiler. +-- (I've removed all the well-founded stuff to make it easier to read though.) + +open private ensureNoUnassignedMVarsAtPreDef betaReduceLetRecApps partitionPreDefs + addAndCompilePartial addAsAxioms from Lean.Elab.PreDefinition.Main + +def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := withLCtx {} {} do + for preDef in preDefs do + trace[Elab.definition.body] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" + let preDefs ← preDefs.mapM ensureNoUnassignedMVarsAtPreDef + let preDefs ← betaReduceLetRecApps preDefs + let cliques := partitionPreDefs preDefs + let mut hasErrors := false + for preDefs in cliques do + trace[Elab.definition.scc] "{preDefs.map (·.declName)}" + try + logInfo "calling divRecursion" + withRef (preDefs[0]!.ref) do + divRecursion preDefs + logInfo "divRecursion succeeded" + catch ex => + -- If it failed, we + logInfo "divRecursion failed" + hasErrors := true + logException ex + let s ← saveState + try + if preDefs.all fun preDef => preDef.kind == DefKind.def || + preDefs.all fun preDef => preDef.kind == DefKind.abbrev then + -- try to add as partial definition + try + addAndCompilePartial preDefs (useSorry := true) + catch _ => + -- Compilation failed try again just as axiom + s.restore + addAsAxioms preDefs + else return () + catch _ => s.restore + +-- The following two functions are copy&pasted from Lean.Elab.MutualDef + +open private elabHeaders levelMVarToParamHeaders getAllUserLevelNames withFunLocalDecls elabFunValues + instantiateMVarsAtHeader instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes withUsed from Lean.Elab.MutualDef + +def Term.elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := do + let scopeLevelNames ← getLevelNames + let headers ← elabHeaders views + let headers ← levelMVarToParamHeaders views headers + let allUserLevelNames := getAllUserLevelNames headers + withFunLocalDecls headers fun funFVars => do + for view in views, funFVar in funFVars do + addLocalVarInfo view.declId funFVar + let values ← + try + let values ← elabFunValues headers + Term.synthesizeSyntheticMVarsNoPostponing + values.mapM (instantiateMVars ·) + catch ex => + logException ex + headers.mapM fun header => mkSorry header.type (synthetic := true) + let headers ← headers.mapM instantiateMVarsAtHeader + let letRecsToLift ← getLetRecsToLift + let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift + checkLetRecsToLiftTypes funFVars letRecsToLift + withUsed vars headers values letRecsToLift fun vars => do + let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift + for preDef in preDefs do + trace[Elab.definition] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" + let preDefs ← withLevelNames allUserLevelNames <| levelMVarToParamPreDecls preDefs + let preDefs ← instantiateMVarsAtPreDecls preDefs + let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames + for preDef in preDefs do + trace[Elab.definition] "after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\n{preDef.value}" + checkForHiddenUnivLevels allUserLevelNames preDefs + addPreDefinitions preDefs + +open Command in +def Command.elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do + let views ← ds.mapM fun d => do + let `($mods:declModifiers divergent def $id:declId $sig:optDeclSig $val:declVal) := d + | throwUnsupportedSyntax + let modifiers ← elabModifiers mods + let (binders, type) := expandOptDeclSig sig + let deriving? := none + pure { ref := d, kind := DefKind.def, modifiers, + declId := id, binders, type? := type, value := val, deriving? } + runTermElabM fun vars => Term.elabMutualDef vars views + +-- Special command so that we don't fall back to the built-in mutual when we produce an error. +local syntax "_divergent" Parser.Command.mutual : command +elab_rules : command | `(_divergent mutual $decls* end) => Command.elabMutualDef decls + +macro_rules + | `(mutual $decls* end) => do + unless !decls.isEmpty && decls.all (·.1.getKind == ``divergentDef) do + Macro.throwUnsupported + `(command| _divergent mutual $decls* end) + +open private setDeclIdName from Lean.Elab.Declaration +elab_rules : command + | `($mods:declModifiers divergent%$tk def $id:declId $sig:optDeclSig $val:declVal) => do + let (name, _) := expandDeclIdCore id + if (`_root_).isPrefixOf name then throwUnsupportedSyntax + let view := extractMacroScopes name + let .str ns shortName := view.name | throwUnsupportedSyntax + let shortName' := { view with name := shortName }.review + let cmd ← `(mutual $mods:declModifiers divergent%$tk def $(⟨setDeclIdName id shortName'⟩):declId $sig:optDeclSig $val:declVal end) + if ns matches .anonymous then + Command.elabCommand cmd + else + Command.elabCommand <| ← `(namespace $(mkIdentFrom id ns) $cmd end $(mkIdentFrom id ns)) + +mutual + divergent def is_even (i : Int) : Result Bool := + if i = 0 then return true else return (← is_odd (i - 1)) + + divergent def is_odd (i : Int) : Result Bool := + if i = 0 then return false else return (← is_even (i - 1)) +end + +example (i : Int) : is_even i = .ret (i % 2 = 0) ∧ is_odd i = .ret (i % 2 ≠ 0) := by + induction i + unfold is_even + sorry + +divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := + match ls with + | [] => .fail .panic + | x :: ls => + if i = 0 then return x + else return (← list_nth ls (i - 1)) + +mutual + divergent def foo (i : Int) : Result Nat := + if i > 10 then return (← foo (i / 10)) + (← bar i) else bar 10 + + divergent def bar (i : Int) : Result Nat := + if i > 20 then foo (i / 20) else .ret 42 +end + +end Diverge diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean new file mode 100644 index 00000000..e693dce2 --- /dev/null +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -0,0 +1,9 @@ +import Lean + +namespace Diverge + +open Lean + +initialize registerTraceClass `Diverge.divRecursion (inherited := true) + +end Diverge -- cgit v1.2.3 From a6de153f3bfda7feb27d16fcdf2131d37f99c7a3 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 29 Jun 2023 11:22:32 +0200 Subject: Start working on Elab.lean --- backends/lean/Base/Diverge/Base.lean | 3 + backends/lean/Base/Diverge/Elab.lean | 138 ++++++++++++++++++++++++++++--- backends/lean/Base/Diverge/ElabBase.lean | 75 ++++++++++++++++- 3 files changed, 203 insertions(+), 13 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 0f92e682..2e60f6e8 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -4,6 +4,9 @@ import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith +-- For debugging +import Base.Diverge.ElabBase + /- TODO: - we want an easier to use cases: diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 313c5a79..22e0039f 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -15,16 +15,53 @@ syntax (name := divergentDef) open Lean Elab Term Meta Primitives -initialize registerTraceClass `Diverge.divRecursion (inherited := true) - -set_option trace.Diverge.divRecursion true +set_option trace.Diverge.def true /- The following was copied from the `wfRecursion` function. -/ open WF in + + + +-- Replace the recursive calls by a call to the continuation +-- def replace_rec_calls + +#check Lean.Meta.forallTelescope +#check Expr +#check withRef +#check MonadRef.withRef +#check Nat +#check Array +#check Lean.Meta.inferType +#check Nat +#check Int + +#check (0, 1) +#check Prod +#check () +#check Unit +#check Sigma + +-- print_decl is_even_body +#check instOfNatNat +#check OfNat.ofNat -- @OfNat.ofNat ℕ 2 ... +#check OfNat.ofNat -- @OfNat.ofNat (Fin 2) 1 ... +#check Fin.instOfNatFinHAddNatInstHAddInstAddNatOfNat + + +-- TODO: is there already such a utility somewhere? +-- TODO: change to mkSigmas +def mkProds (tys : List Expr) : MetaM Expr := + match tys with + | [] => do return (Expr.const ``PUnit.unit []) + | [ty] => do return ty + | ty :: tys => do + let pty ← mkProds tys + mkAppM ``Prod.mk #[ty, pty] + def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) - logInfo ("divRecursion: defs: " ++ msg) + trace[Diverge.def] ("divRecursion: defs: " ++ msg) -- CHANGE HERE This function should add definitions with these names/types/values ^^ -- Temporarily add the predefinitions as axioms @@ -35,6 +72,85 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do for preDef in preDefs do applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation + -- Retrieve the name of the first definition, that we will use as the namespace + -- for the definitions common to the group + let def0 := preDefs[0]! + let grName := def0.declName + trace[Diverge.def] "group name: {grName}" + + /- Compute the type of the continuation. + + We do the following + - we make sure all the definitions have the same universe parameters + (we can make this more general later) + - we group all the type parameters together, make sure all the + definitions have the same type parameters, and enforce + a uniform polymorphism (we can also lift this later). + This would require generalizing a bit our indexed fixed point to + make the output type parametric in the input. + - we group all the non-type parameters: we parameterize the continuation + by those + -/ + let grLvlParams := def0.levelParams + trace[Diverge.def] "def0 type: {def0.type}" + + -- Small utility: compute the list of type parameters + let getTypeParams (ty: Expr) : MetaM (List Expr × List Expr × Expr) := + Lean.Meta.forallTelescope ty fun tys out_ty => do + trace[Diverge.def] "types: {tys}" +/- let (_, params) ← StateT.run (do + for x in tys do + let ty ← Lean.Meta.inferType x + match ty with + | .sort _ => do + let st ← StateT.get + StateT.set (ty :: st) + | _ => do break + ) ([] : List Expr) + let params := params.reverse + trace[Diverge.def] " type parameters {params}" + return params -/ + let rec get_params (ls : List Expr) : MetaM (List Expr × List Expr) := + match ls with + | x :: tl => do + let ty ← Lean.Meta.inferType x + match ty with + | .sort _ => do + let (ty_params, params) ← get_params tl + return (x :: ty_params, params) + | _ => do return ([], ls) + | _ => do return ([], []) + let (ty_params, params) ← get_params tys.toList + trace[Diverge.def] " parameters: {ty_params}; {params}" + return (ty_params, params, out_ty) + let (grTyParams, _, _) ← do + getTypeParams def0.type + + -- Compute the input types and the output types + let all_tys ← preDefs.mapM fun preDef => do + let (tyParams, params, ret_ty) ← getTypeParams preDef.type + -- TODO: this is not complete, there are more checks to perform + if tyParams.length ≠ grTyParams.length then + throwError "Non-uniform polymorphism" + return (params, ret_ty) + + -- TODO: I think there are issues with the free variables + let (input_tys, output_tys) := List.unzip all_tys.toList + let input_tys : List Expr ← liftM (List.mapM mkProds input_tys) + + trace[Diverge.def] " in/out tys: {input_tys}; {output_tys}" + + -- Compute the names set + let names := preDefs.map PreDefinition.declName + let names := HashSet.empty.insertMany names + + -- + for preDef in preDefs do + trace[Diverge.def] "about to explore: {preDef.declName}" + explore_term "" preDef.value + + -- Compute the bodies + -- Process the definitions addAndCompilePartialRec preDefs @@ -47,21 +163,21 @@ open private ensureNoUnassignedMVarsAtPreDef betaReduceLetRecApps partitionPreDe def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := withLCtx {} {} do for preDef in preDefs do - trace[Elab.definition.body] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" + trace[Diverge.elab] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← preDefs.mapM ensureNoUnassignedMVarsAtPreDef let preDefs ← betaReduceLetRecApps preDefs let cliques := partitionPreDefs preDefs let mut hasErrors := false for preDefs in cliques do - trace[Elab.definition.scc] "{preDefs.map (·.declName)}" + trace[Diverge.elab] "{preDefs.map (·.declName)}" try - logInfo "calling divRecursion" + trace[Diverge.elab] "calling divRecursion" withRef (preDefs[0]!.ref) do divRecursion preDefs - logInfo "divRecursion succeeded" + trace[Diverge.elab] "divRecursion succeeded" catch ex => -- If it failed, we - logInfo "divRecursion failed" + trace[Diverge.elab] "divRecursion failed" hasErrors := true logException ex let s ← saveState @@ -106,12 +222,12 @@ def Term.elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM U withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift for preDef in preDefs do - trace[Elab.definition] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" + trace[Diverge.elab] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← withLevelNames allUserLevelNames <| levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames for preDef in preDefs do - trace[Elab.definition] "after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\n{preDef.value}" + trace[Diverge.elab] "after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\n{preDef.value}" checkForHiddenUnivLevels allUserLevelNames preDefs addPreDefinitions preDefs diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index e693dce2..84b73a30 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -2,8 +2,79 @@ import Lean namespace Diverge -open Lean +open Lean Elab Term Meta -initialize registerTraceClass `Diverge.divRecursion (inherited := true) +initialize registerTraceClass `Diverge.elab (inherited := true) +initialize registerTraceClass `Diverge.def (inherited := true) + +-- TODO: move +-- TODO: small helper +def explore_term (incr : String) (e : Expr) : TermElabM Unit := + match e with + | .bvar _ => do logInfo m!"{incr}bvar: {e}"; return () + | .fvar _ => do logInfo m!"{incr}fvar: {e}"; return () + | .mvar _ => do logInfo m!"{incr}mvar: {e}"; return () + | .sort _ => do logInfo m!"{incr}sort: {e}"; return () + | .const _ _ => do logInfo m!"{incr}const: {e}"; return () + | .app fn arg => do + logInfo m!"{incr}app: {e}" + explore_term (incr ++ " ") fn + explore_term (incr ++ " ") arg + | .lam _bName bTy body _binfo => do + logInfo m!"{incr}lam: {e}" + explore_term (incr ++ " ") bTy + explore_term (incr ++ " ") body + | .forallE _bName bTy body _bInfo => do + logInfo m!"{incr}forallE: {e}" + explore_term (incr ++ " ") bTy + explore_term (incr ++ " ") body + | .letE _dName ty val body _nonDep => do + logInfo m!"{incr}letE: {e}" + explore_term (incr ++ " ") ty + explore_term (incr ++ " ") val + explore_term (incr ++ " ") body + | .lit _ => do logInfo m!"{incr}lit: {e}"; return () + | .mdata _ e => do + logInfo m!"{incr}mdata: {e}" + explore_term (incr ++ " ") e + | .proj _ _ struct => do + logInfo m!"{incr}proj: {e}" + explore_term (incr ++ " ") struct + +def explore_decl (n : Name) : TermElabM Unit := do + logInfo m!"Name: {n}" + let env ← getEnv + let decl := env.constants.find! n + match decl with + | .defnInfo val => + logInfo m!"About to explore defn: {decl.name}" + logInfo m!"# Type:" + explore_term "" val.type + logInfo m!"# Value:" + explore_term "" val.value + | .axiomInfo _ => throwError m!"axiom: {n}" + | .thmInfo _ => throwError m!"thm: {n}" + | .opaqueInfo _ => throwError m!"opaque: {n}" + | .quotInfo _ => throwError m!"quot: {n}" + | .inductInfo _ => throwError m!"induct: {n}" + | .ctorInfo _ => throwError m!"ctor: {n}" + | .recInfo _ => throwError m!"rec: {n}" + +syntax (name := printDecl) "print_decl " ident : command + +open Lean.Elab.Command + +@[command_elab printDecl] def elabPrintDecl : CommandElab := fun stx => do + liftTermElabM do + let id := stx[1] + addCompletionInfo <| CompletionInfo.id id id.getId (danglingDot := false) {} none + let cs ← resolveGlobalConstWithInfos id + explore_decl cs[0]! + +private def test1 : Nat := 0 +private def test2 (x : Nat) : Nat := x + +print_decl test1 +print_decl test2 end Diverge -- cgit v1.2.3 From 0cee49de70bec6d3ec2221b64a532d19ad71e5e0 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 29 Jun 2023 14:51:53 +0200 Subject: Generalize a bit FixI and add an example --- backends/lean/Base/Diverge/Base.lean | 260 ++++++++++++++++++++--------------- 1 file changed, 151 insertions(+), 109 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 2e60f6e8..630c0bf6 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -57,7 +57,7 @@ deriving Repr, BEq open Result -def bind (x: Result α) (f: α -> Result β) : Result β := +def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := match x with | ret v => f v | fail v => fail v @@ -84,7 +84,7 @@ instance : Pure Result where @[simp] theorem bind_tc_div (f : α → Result β) : (do let y ← div; f y) = div := by simp [Bind.bind, bind] -def div? {α: Type} (r: Result α): Bool := +def div? {α: Type u} (r: Result α): Bool := match r with | div => true | ret _ | fail _ => false @@ -96,8 +96,8 @@ namespace Fix open Primitives open Result - variable {a : Type} {b : a → Type} - variable {c d : Type} + variable {a : Type u} {b : a → Type v} + variable {c d : Type w} -- TODO: why do we have to make them both : Type w? /-! # The least fixed point definition and its properties -/ @@ -334,7 +334,8 @@ namespace Fix (h : c → ((x:a) → Result (b x)) → Result d) : is_mono_p g → (∀ y, is_mono_p (h y)) → - @is_mono_p a b d (λ k => do let y ← g k; h y k) := by + @is_mono_p a b d (λ k => @Bind.bind Result _ c d (g k) (fun y => h y k)) := by +-- @is_mono_p a b d (λ k => do let (y : c) ← g k; h y k) := by intro hg hh simp [is_mono_p] intro fg fh Hrgh @@ -494,49 +495,49 @@ namespace FixI open Primitives Fix -- The index type - variable {id : Type} + variable {id : Type u} -- The input/output types - variable {a b : id → Type} + variable {a : id → Type v} {b : (i:id) → a i → Type w} -- Monotonicity relation over monadic arrows (i.e., Kleisli arrows) - def karrow_rel (k1 k2 : (i:id) → a i → Result (b i)) : Prop := + def karrow_rel (k1 k2 : (i:id) → (x:a i) → Result (b i x)) : Prop := ∀ i x, result_rel (k1 i x) (k2 i x) - def kk_to_gen (k : (i:id) → a i → Result (b i)) : - (x: (i:id) × a i) → Result (b x.fst) := + def kk_to_gen (k : (i:id) → (x:a i) → Result (b i x)) : + (x: (i:id) × a i) → Result (b x.fst x.snd) := λ ⟨ i, x ⟩ => k i x - def kk_of_gen (k : (x: (i:id) × a i) → Result (b x.fst)) : - (i:id) → a i → Result (b i) := + def kk_of_gen (k : (x: (i:id) × a i) → Result (b x.fst x.snd)) : + (i:id) → (x:a i) → Result (b i x) := λ i x => k ⟨ i, x ⟩ - def k_to_gen (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : - ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst) := + def k_to_gen (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) : + ((x: (i:id) × a i) → Result (b x.fst x.snd)) → (x: (i:id) × a i) → Result (b x.fst x.snd) := λ kk => kk_to_gen (k (kk_of_gen kk)) - def k_of_gen (k : ((x: (i:id) × a i) → Result (b x.fst)) → (x: (i:id) × a i) → Result (b x.fst)) : - ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i) := + def k_of_gen (k : ((x: (i:id) × a i) → Result (b x.fst x.snd)) → (x: (i:id) × a i) → Result (b x.fst x.snd)) : + ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x) := λ kk => kk_of_gen (k (kk_to_gen kk)) - def e_to_gen (e : ((i:id) → a i → Result (b i)) → Result c) : - ((x: (i:id) × a i) → Result (b x.fst)) → Result c := + def e_to_gen (e : ((i:id) → (x:a i) → Result (b i x)) → Result c) : + ((x: (i:id) × a i) → Result (b x.fst x.snd)) → Result c := λ k => e (kk_of_gen k) - def is_valid_p (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) - (e : ((i:id) → a i → Result (b i)) → Result c) : Prop := + def is_valid_p (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) + (e : ((i:id) → (x:a i) → Result (b i x)) → Result c) : Prop := Fix.is_valid_p (k_to_gen k) (e_to_gen e) - def is_valid (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : Prop := + def is_valid (f : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) : Prop := ∀ k i x, is_valid_p k (λ k => f k i x) noncomputable def fix - (f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) : - (i:id) → a i → Result (b i) := + (f : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) : + (i:id) → (x:a i) → Result (b i x) := kk_of_gen (Fix.fix (k_to_gen f)) theorem is_valid_fix_fixed_eq - {{f : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} + {{f : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)}} (Hvalid : is_valid f) : fix f = f (fix f) := by have Hvalid' : Fix.is_valid (k_to_gen f) := by @@ -553,57 +554,43 @@ namespace FixI /- Some utilities to define the mutually recursive functions -/ -- TODO: use more - @[simp] def kk_ty (id : Type) (a b : id → Type) := (i:id) → a i → Result (b i) - @[simp] def k_ty (id : Type) (a b : id → Type) := kk_ty id a b → kk_ty id a b + @[simp] def kk_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := + (i:id) → (x:a i) → Result (b i x) + @[simp] def k_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := + kk_ty id a b → kk_ty id a b + + def in_out_ty : Type (imax (u + 1) (v + 1)) := (in_ty : Type u) × ((x:in_ty) → Type v) + @[simp] def mk_in_out_ty (in_ty : Type u) (out_ty : in_ty → Type v) : + in_out_ty := + Sigma.mk in_ty out_ty -- Initially, we had left out the parameters id, a and b. -- However, by parameterizing Funs with those parameters, we can state -- and prove lemmas like Funs.is_valid_p_is_valid_p - inductive Funs (id : Type) (a b : id → Type) : - List (Type u) → List (Type u) → Type (u + 1) := - | Nil : Funs id a b [] [] - | Cons {ity oty : Type u} {itys otys : List (Type u)} - (f : kk_ty id a b → ity → Result oty) (tl : Funs id a b itys otys) : - Funs id a b (ity :: itys) (oty :: otys) - - theorem Funs.length_eq {itys otys : List (Type)} (fl : Funs id a b itys otys) : - otys.length = itys.length := - match fl with - | .Nil => by simp - | .Cons f tl => - have h:= Funs.length_eq tl - by simp [h] - - def fin_cast {n m : Nat} (h : m = n) (i : Fin n) : Fin m := - ⟨ i.val, by have h1:= i.isLt; simp_all ⟩ - - @[simp] def Funs.cast_fin {itys otys : List (Type)} - (fl : Funs id a b itys otys) (i : Fin itys.length) : Fin otys.length := - fin_cast (fl.length_eq) i - - def get_fun {itys otys : List (Type)} (fl : Funs id a b itys otys) : - (i : Fin itys.length) → kk_ty id a b → itys.get i → Result (otys.get (fl.cast_fin i)) := + inductive Funs (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) : + List in_out_ty.{v, w} → Type (max (u + 1) (max (v + 1) (w + 1))) := + | Nil : Funs id a b [] + | Cons {ity : Type v} {oty : ity → Type w} {tys : List in_out_ty} + (f : kk_ty id a b → (x:ity) → Result (oty x)) (tl : Funs id a b tys) : + Funs id a b (⟨ ity, oty ⟩ :: tys) + + def get_fun {tys : List in_out_ty} (fl : Funs id a b tys) : + (i : Fin tys.length) → kk_ty id a b → (x : (tys.get i).fst) → + Result ((tys.get i).snd x) := match fl with | .Nil => λ i => by have h:= i.isLt; simp at h - | @Funs.Cons id a b ity oty itys1 otys1 f tl => - λ i => - if h: i.val = 0 then - Eq.mp (by cases i; simp_all [List.get]) f - else - let j := i.val - 1 - have Hj: j < itys1.length := by - have Hi := i.isLt - simp at Hi - revert Hi - cases Heq: i.val <;> simp_all + | @Funs.Cons id a b ity oty tys1 f tl => + λ ⟨ i, iLt ⟩ => + match i with + | 0 => + Eq.mp (by simp [List.get]) f + | .succ j => + have jLt: j < tys1.length := by + simp at iLt + revert iLt simp_arith - let j: Fin itys1.length := ⟨ j, Hj ⟩ - Eq.mp - (by - cases Heq: i; rename_i val isLt; - cases Heq': j; rename_i val' isLt; - cases val <;> simp_all [List.get, fin_cast]) - (get_fun tl j) + let j: Fin tys1.length := ⟨ j, jLt ⟩ + Eq.mp (by simp) (get_fun tl j) -- TODO: move theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by @@ -683,19 +670,19 @@ namespace FixI /- Automating the proofs -/ @[simp] theorem is_valid_p_same - (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (x : Result c) : + (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) (x : Result c) : is_valid_p k (λ _ => x) := by simp [is_valid_p, k_to_gen, e_to_gen] @[simp] theorem is_valid_p_rec - (k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)) (i : id) (x : a i) : + (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) (i : id) (x : a i) : is_valid_p k (λ k => k i x) := by simp [is_valid_p, k_to_gen, e_to_gen, kk_to_gen, kk_of_gen] theorem is_valid_p_bind - {{k : ((i:id) → a i → Result (b i)) → (i:id) → a i → Result (b i)}} - {{g : ((i:id) → a i → Result (b i)) → Result c}} - {{h : c → ((i:id) → a i → Result (b i)) → Result d}} + {{k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)}} + {{g : ((i:id) → (x:a i) → Result (b i x)) → Result c}} + {{h : c → ((i:id) → (x:a i) → Result (b i x)) → Result d}} (Hgvalid : is_valid_p k g) (Hhvalid : ∀ y, is_valid_p k (h y)) : is_valid_p k (λ k => do let y ← g k; h y k) := by @@ -705,7 +692,7 @@ namespace FixI def Funs.is_valid_p (k : k_ty id a b) - (fl : Funs id a b itys otys) : + (fl : Funs id a b tys) : Prop := match fl with | .Nil => True @@ -713,31 +700,29 @@ namespace FixI def Funs.is_valid_p_is_valid_p_aux {k : k_ty id a b} - {itys otys : List Type} - (Heq : List.length otys = List.length itys) - (fl : Funs id a b itys otys) (Hvalid : is_valid_p k fl) : - ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) := by + {tys : List in_out_ty} + (fl : Funs id a b tys) (Hvalid : is_valid_p k fl) : + ∀ (i : Fin tys.length) (x : (tys.get i).fst), FixI.is_valid_p k (fun k => get_fun fl i k x) := by -- Prepare the induction - have ⟨ n, Hn ⟩ : { n : Nat // itys.length = n } := ⟨ itys.length, by rfl ⟩ - revert itys otys Heq fl Hvalid + have ⟨ n, Hn ⟩ : { n : Nat // tys.length = n } := ⟨ tys.length, by rfl ⟩ + revert tys fl Hvalid induction n -- case zero => - intro itys otys Heq fl Hvalid Hlen; - have Heq: itys = [] := by cases itys <;> simp_all - have Heq: otys = [] := by cases otys <;> simp_all + intro tys fl Hvalid Hlen; + have Heq: tys = [] := by cases tys <;> simp_all intro i x simp_all have Hi := i.isLt simp_all case succ n Hn => - intro itys otys Heq fl Hvalid Hlen i x; - cases fl <;> simp at Hlen i x Heq Hvalid - rename_i ity oty itys otys f fl + intro tys fl Hvalid Hlen i x; + cases fl <;> simp at Hlen i x Hvalid + rename_i ity oty tys f fl have ⟨ Hvf, Hvalid ⟩ := Hvalid have Hvf1: is_valid_p k fl := by simp [Hvalid, Funs.is_valid_p] - have Hn := @Hn itys otys (by simp[*]) fl Hvf1 (by simp [*]) + have Hn := @Hn tys fl Hvf1 (by simp [*]) -- Case disjunction on i match i with | ⟨ 0, _ ⟩ => @@ -747,19 +732,20 @@ namespace FixI | ⟨ .succ j, HiLt ⟩ => simp_arith at HiLt simp at x - let j : Fin (List.length itys) := ⟨ j, by simp_arith [HiLt] ⟩ + let j : Fin (List.length tys) := ⟨ j, by simp_arith [HiLt] ⟩ have Hn := Hn j x apply Hn def Funs.is_valid_p_is_valid_p - (itys otys : List (Type)) (Heq: otys.length = itys.length := by decide) - (k : k_ty (Fin (List.length itys)) (List.get itys) fun i => List.get otys (fin_cast Heq i)) - (fl : Funs (Fin itys.length) itys.get (λ i => otys.get (fin_cast Heq i)) itys otys) : + (tys : List in_out_ty) + (k : k_ty (Fin (List.length tys)) (λ i => (tys.get i).fst) (fun i x => (List.get tys i).snd x)) + (fl : Funs (Fin tys.length) (λ i => (tys.get i).fst) (λ i x => (tys.get i).snd x) tys) : fl.is_valid_p k → - ∀ (i : Fin itys.length) (x : itys.get i), FixI.is_valid_p k (fun k => get_fun fl i k x) + ∀ (i : Fin tys.length) (x : (tys.get i).fst), + FixI.is_valid_p k (fun k => get_fun fl i k x) := by intro Hvalid - apply is_valid_p_is_valid_p_aux <;> simp [*] + apply is_valid_p_is_valid_p_aux; simp [*] end FixI @@ -960,27 +946,21 @@ namespace Ex4 /- Mutually recursive functions - 2nd encoding -/ open Primitives FixI - attribute [local simp] List.get - /- We make the input type and output types dependent on a parameter -/ - @[simp] def input_ty (i : Fin 2) : Type := - [Int, Int].get i - - @[simp] def output_ty (i : Fin 2) : Type := - [Bool, Bool].get i - - /- The continuation -/ - variable (k : (i : Fin 2) → input_ty i → Result (output_ty i)) + @[simp] def tys : List in_out_ty := [mk_in_out_ty Int (λ _ => Bool), mk_in_out_ty Int (λ _ => Bool)] + @[simp] def input_ty (i : Fin 2) : Type := (tys.get i).fst + @[simp] def output_ty (i : Fin 2) (x : input_ty i) : Type := + (tys.get i).snd x /- The bodies are more natural -/ - def is_even_body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i : Int) : Result Bool := + def is_even_body (k : (i : Fin 2) → (x : input_ty i) → Result (output_ty i x)) (i : Int) : Result Bool := if i = 0 then .ret true else do let b ← k 1 (i - 1) .ret b - def is_odd_body (i : Int) : Result Bool := + def is_odd_body (k : (i : Fin 2) → (x : input_ty i) → Result (output_ty i x)) (i : Int) : Result Bool := if i = 0 then .ret false else do @@ -988,18 +968,19 @@ namespace Ex4 .ret b @[simp] def bodies : - Funs (Fin 2) input_ty output_ty [Int, Int] [Bool, Bool] := + Funs (Fin 2) input_ty output_ty + [mk_in_out_ty Int (λ _ => Bool), mk_in_out_ty Int (λ _ => Bool)] := Funs.Cons (is_even_body) (Funs.Cons (is_odd_body) Funs.Nil) - def body (k : (i : Fin 2) → input_ty i → Result (output_ty i)) (i: Fin 2) : - input_ty i → Result (output_ty i) := get_fun bodies i k + def body (k : (i : Fin 2) → (x : input_ty i) → Result (output_ty i x)) (i: Fin 2) : + (x : input_ty i) → Result (output_ty i x) := get_fun bodies i k theorem body_is_valid : is_valid body := by -- Split the proof into proofs of validity of the individual bodies rw [is_valid] simp only [body] intro k - apply (Funs.is_valid_p_is_valid_p [Int, Int] [Bool, Bool]) + apply (Funs.is_valid_p_is_valid_p tys) simp [Funs.is_valid_p] (repeat (apply And.intro)) <;> intro x <;> simp at x <;> simp only [is_even_body, is_odd_body] @@ -1106,3 +1087,64 @@ namespace Ex5 conv => lhs; rw [Heq]; simp; rw [id_body] end Ex5 + +namespace Ex6 + /- `list_nth` again, but this time we use FixI -/ + open Primitives FixI + + @[simp] def tys.{u} : List in_out_ty := + [mk_in_out_ty ((a:Type u) × (List a × Int)) (λ ⟨ a, _ ⟩ => a)] + + @[simp] def input_ty (i : Fin 1) := (tys.get i).fst + @[simp] def output_ty (i : Fin 1) (x : input_ty i) := + (tys.get i).snd x + + def list_nth_body.{u} (k : (i:Fin 1) → (x:input_ty i) → Result (output_ty i x)) + (x : (a : Type u) × List a × Int) : Result x.fst := + let ⟨ a, ls, i ⟩ := x + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else k 0 ⟨ a, tl, i - 1 ⟩ + + @[simp] def bodies : + Funs (Fin 1) input_ty output_ty tys := + Funs.Cons list_nth_body Funs.Nil + + def body (k : (i : Fin 1) → (x : input_ty i) → Result (output_ty i x)) (i: Fin 1) : + (x : input_ty i) → Result (output_ty i x) := get_fun bodies i k + + theorem list_nth_body_is_valid: is_valid body := by + -- Split the proof into proofs of validity of the individual bodies + rw [is_valid] + simp only [body] + intro k + apply (Funs.is_valid_p_is_valid_p tys) + simp [Funs.is_valid_p] + (repeat (apply And.intro)); intro x; simp at x + simp only [list_nth_body] + -- Prove the validity of the individual bodies + intro k x + simp [list_nth_body] + split <;> simp + split <;> simp + + noncomputable + def list_nth {a: Type u} (ls : List a) (i : Int) : Result a := + fix body 0 ⟨ a, ls , i ⟩ + + -- The unfolding equation - diverges if `i < 0` + theorem list_nth_eq (ls : List a) (i : Int) : + list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else list_nth tl (i - 1) + := by + have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) + simp [list_nth] + conv => lhs; rw [Heq] + +end Ex6 -- cgit v1.2.3 From fdc8693772ecb1978873018c790061854f00a015 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 29 Jun 2023 23:15:20 +0200 Subject: Write function to compute the input/output types --- backends/lean/Base/Diverge/Base.lean | 3 +- backends/lean/Base/Diverge/Elab.lean | 154 ++++++++++++++++++++++++------- backends/lean/Base/Diverge/ElabBase.lean | 1 + 3 files changed, 126 insertions(+), 32 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 630c0bf6..22b59bd0 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -560,6 +560,7 @@ namespace FixI kk_ty id a b → kk_ty id a b def in_out_ty : Type (imax (u + 1) (v + 1)) := (in_ty : Type u) × ((x:in_ty) → Type v) + -- TODO: remove? @[simp] def mk_in_out_ty (in_ty : Type u) (out_ty : in_ty → Type v) : in_out_ty := Sigma.mk in_ty out_ty @@ -1143,7 +1144,7 @@ namespace Ex6 if i = 0 then .ret hd else list_nth tl (i - 1) := by - have Heq := is_valid_fix_fixed_eq (@list_nth_body_is_valid a) + have Heq := is_valid_fix_fixed_eq list_nth_body_is_valid simp [list_nth] conv => lhs; rw [Heq] diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 22e0039f..116c5d8b 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -13,7 +13,7 @@ namespace Diverge syntax (name := divergentDef) declModifiers "divergent" "def" declId ppIndent(optDeclSig) declVal : command -open Lean Elab Term Meta Primitives +open Lean Elab Term Meta Primitives Lean.Meta set_option trace.Diverge.def true @@ -21,27 +21,9 @@ set_option trace.Diverge.def true open WF in - - -- Replace the recursive calls by a call to the continuation -- def replace_rec_calls -#check Lean.Meta.forallTelescope -#check Expr -#check withRef -#check MonadRef.withRef -#check Nat -#check Array -#check Lean.Meta.inferType -#check Nat -#check Int - -#check (0, 1) -#check Prod -#check () -#check Unit -#check Sigma - -- print_decl is_even_body #check instOfNatNat #check OfNat.ofNat -- @OfNat.ofNat ℕ 2 ... @@ -59,6 +41,100 @@ def mkProds (tys : List Expr) : MetaM Expr := let pty ← mkProds tys mkAppM ``Prod.mk #[ty, pty] +/- Generate the input type of a function body, which is a sigma type (i.e., a + dependent tuple) which groups all its inputs. + + Example: + - xl = [(a:Type), (ls:List a), (i:Int)] + + Generates: + `(a:Type) × (ls:List a) × (i:Int)` + + -/ +def mkSigmasTypesOfTypes (xl : List Expr) : MetaM Expr := + match xl with + | [] => do + trace[Diverge.def.sigmas] "mkSigmasOfTypes: []" + return (Expr.const ``PUnit.unit []) + | [x] => do + trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}]" + let ty ← Lean.Meta.inferType x + return ty + | x :: xl => do + trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}::{xl}]" + let alpha ← Lean.Meta.inferType x + let sty ← mkSigmasTypesOfTypes xl + trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}::{xl}]: alpha={alpha}, sty={sty}" + let beta ← mkLambdaFVars #[x] sty + trace[Diverge.def.sigmas] "mkSigmasOfTypes: ({alpha}) ({beta})" + mkAppOptM ``Sigma #[some alpha, some beta] + +def mk_indexed_name (index : Nat) : Name := .num (.str .anonymous "_uniq") index + +/- Generate the out_ty of the body of a function, which from an input (a sigma + type generated by `mkSigmasTypesOfTypes`) gives the output type of the function. + + Example: + - xl = `[a:Type, ls:List a, i:Int]` + - out_ty = `a` + - index = 0 -- For naming purposes: we use it to numerotate the "scrutinee" variables + + Generates: + ``` + match scrut0 with + | Sigma.mk x scrut1 => + match scrut1 with + | Sigma.mk ls i => + a + ``` +-/ +def mkSigmasOutType (xl : List Expr) (out_ty : Expr) (index : Nat := 0) : MetaM Expr := + match xl with + | [] => do + -- This would be unexpected + throwError "mkSigmasOutType: empyt list of input parameters" + | [x] => do + -- In the explanations above: inner match case + trace[Diverge.def.sigmas] "mkSigmasOutType: [{x}]" + mkLambdaFVars #[x] out_ty + | fst :: xl => do + -- In the explanations above: outer match case + -- Remark: for the naming purposes, we use the same convention as for the + -- fields and parameters in `Sigma.casesOn and `Sigma.mk + trace[Diverge.def.sigmas] "mkSigmasOutType: [{fst}::{xl}]" + let alpha ← Lean.Meta.inferType fst + let snd_ty ← mkSigmasTypesOfTypes xl + let beta ← mkLambdaFVars #[fst] snd_ty + let snd ← mkSigmasOutType xl out_ty (index + 1) + let scrut_ty ← mkSigmasTypesOfTypes (fst :: xl) + withLocalDeclD (mk_indexed_name index) scrut_ty fun scrut => do + let mk ← mkLambdaFVars #[fst] snd + trace[Diverge.def.sigmas] "mkSigmasOutType: scrut: ({scrut}) : ({← inferType scrut})" + let motive ← mkLambdaFVars #[scrut] (← inferType out_ty) + trace[Diverge.def.sigmas] "mkSigmasOutType:\n ({alpha})\n ({beta})\n ({motive})\n ({scrut})\n ({mk})" + let out ← mkAppOptM ``Sigma.casesOn #[some alpha, some beta, some motive, some scrut, some mk] + let out ← mkLambdaFVars #[scrut] out + trace[Diverge.def.sigmas] "mkSigmasOutType: out: {out}" + return out + +/- Small tests for list_nth: give a model of what `mkSigmasOutType` should generate -/ +private def list_nth_out_ty2 (a :Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) := + @Sigma.casesOn (List a) + (fun (_ls : List a) => Int) + (fun (_scrut1:@Sigma (List a) (fun (_ls : List a) => Int)) => Type) + scrut1 + (fun (_ls : List a) (_i : Int) => Diverge.Primitives.Result a) + +private def list_nth_out_ty1 (scrut0 : @Sigma (Type) (fun (a:Type) => + @Sigma (List a) (fun (_ls : List a) => Int))) := + @Sigma.casesOn (Type) + (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int)) + (fun (_scrut0:@Sigma (Type) (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int))) => Type) + scrut0 + (fun (a : Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) => + list_nth_out_ty2 a scrut1) +/- -/ + def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) trace[Diverge.def] ("divRecursion: defs: " ++ msg) @@ -94,7 +170,23 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let grLvlParams := def0.levelParams trace[Diverge.def] "def0 type: {def0.type}" - -- Small utility: compute the list of type parameters + -- Compute the list of pairs: (input type × output type) + let inOutTys : Array (Expr × Expr) ← + preDefs.mapM (fun preDef => do + -- Check the universe parameters - TODO: I'm not sure what the best thing + -- to do is. In practice, all the type parameters should be in Type 0, so + -- we shouldn't have universe issues. + if preDef.levelParams ≠ grLvlParams then + throwError "Non-uniform polymorphism in the universes" + forallTelescope preDef.type (fun in_tys out_ty => do + let in_ty ← liftM (mkSigmasTypesOfTypes in_tys.toList) + let out_ty ← liftM (mkSigmasOutType in_tys.toList out_ty) + return (in_ty, out_ty) + ) + ) + trace[Diverge.def] "inOutTys: {inOutTys}" + +/- -- Small utility: compute the list of type parameters let getTypeParams (ty: Expr) : MetaM (List Expr × List Expr × Expr) := Lean.Meta.forallTelescope ty fun tys out_ty => do trace[Diverge.def] "types: {tys}" @@ -138,16 +230,16 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let (input_tys, output_tys) := List.unzip all_tys.toList let input_tys : List Expr ← liftM (List.mapM mkProds input_tys) - trace[Diverge.def] " in/out tys: {input_tys}; {output_tys}" + trace[Diverge.def] " in/out tys: {input_tys}; {output_tys}" -/ -- Compute the names set let names := preDefs.map PreDefinition.declName let names := HashSet.empty.insertMany names -- - for preDef in preDefs do - trace[Diverge.def] "about to explore: {preDef.declName}" - explore_term "" preDef.value + -- for preDef in preDefs do + -- trace[Diverge.def] "about to explore: {preDef.declName}" + -- explore_term "" preDef.value -- Compute the bodies @@ -267,6 +359,13 @@ elab_rules : command else Command.elabCommand <| ← `(namespace $(mkIdentFrom id ns) $cmd end $(mkIdentFrom id ns)) +divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := + match ls with + | [] => .fail .panic + | x :: ls => + if i = 0 then return x + else return (← list_nth ls (i - 1)) + mutual divergent def is_even (i : Int) : Result Bool := if i = 0 then return true else return (← is_odd (i - 1)) @@ -280,13 +379,6 @@ example (i : Int) : is_even i = .ret (i % 2 = 0) ∧ is_odd i = .ret (i % 2 ≠ unfold is_even sorry -divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := - match ls with - | [] => .fail .panic - | x :: ls => - if i = 0 then return x - else return (← list_nth ls (i - 1)) - mutual divergent def foo (i : Int) : Result Nat := if i > 10 then return (← foo (i / 10)) + (← bar i) else bar 10 diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index 84b73a30..441b25f0 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -5,6 +5,7 @@ namespace Diverge open Lean Elab Term Meta initialize registerTraceClass `Diverge.elab (inherited := true) +initialize registerTraceClass `Diverge.def.sigmas (inherited := true) initialize registerTraceClass `Diverge.def (inherited := true) -- TODO: move -- cgit v1.2.3 From 1c9331ce92b68b9a83c601212149a6c24591708f Mon Sep 17 00:00:00 2001 From: Son Ho Date: Fri, 30 Jun 2023 15:53:39 +0200 Subject: Generate the fixed-point bodies in Elab.lean --- backends/lean/Base/Diverge/Base.lean | 8 +- backends/lean/Base/Diverge/Elab.lean | 451 +++++++++++++++++++++++-------- backends/lean/Base/Diverge/ElabBase.lean | 47 +++- 3 files changed, 391 insertions(+), 115 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 22b59bd0..aa0539ba 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -554,14 +554,14 @@ namespace FixI /- Some utilities to define the mutually recursive functions -/ -- TODO: use more - @[simp] def kk_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := + abbrev kk_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := (i:id) → (x:a i) → Result (b i x) - @[simp] def k_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := + abbrev k_ty (id : Type u) (a : id → Type v) (b : (i:id) → (x:a i) → Type w) := kk_ty id a b → kk_ty id a b - def in_out_ty : Type (imax (u + 1) (v + 1)) := (in_ty : Type u) × ((x:in_ty) → Type v) + abbrev in_out_ty : Type (imax (u + 1) (v + 1)) := (in_ty : Type u) × ((x:in_ty) → Type v) -- TODO: remove? - @[simp] def mk_in_out_ty (in_ty : Type u) (out_ty : in_ty → Type v) : + abbrev mk_in_out_ty (in_ty : Type u) (out_ty : in_ty → Type v) : in_out_ty := Sigma.mk in_ty out_ty diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 116c5d8b..f7de7518 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -16,31 +16,62 @@ syntax (name := divergentDef) open Lean Elab Term Meta Primitives Lean.Meta set_option trace.Diverge.def true +-- set_option trace.Diverge.def.sigmas true /- The following was copied from the `wfRecursion` function. -/ open WF in --- Replace the recursive calls by a call to the continuation --- def replace_rec_calls +def mkList (xl : List Expr) (ty : Expr) : MetaM Expr := + match xl with + | [] => + mkAppOptM ``List.nil #[some ty] + | x :: tl => do + let tl ← mkList tl ty + mkAppOptM ``List.cons #[some ty, some x, some tl] --- print_decl is_even_body -#check instOfNatNat -#check OfNat.ofNat -- @OfNat.ofNat ℕ 2 ... -#check OfNat.ofNat -- @OfNat.ofNat (Fin 2) 1 ... -#check Fin.instOfNatFinHAddNatInstHAddInstAddNatOfNat +def mkProd (x y : Expr) : MetaM Expr := + mkAppM ``Prod.mk #[x, y] +def mkInOutTy (x y : Expr) : MetaM Expr := + mkAppM ``FixI.mk_in_out_ty #[x, y] -- TODO: is there already such a utility somewhere? -- TODO: change to mkSigmas def mkProds (tys : List Expr) : MetaM Expr := match tys with - | [] => do return (Expr.const ``PUnit.unit []) - | [ty] => do return ty + | [] => do pure (Expr.const ``PUnit.unit []) + | [ty] => do pure ty | ty :: tys => do let pty ← mkProds tys mkAppM ``Prod.mk #[ty, pty] +-- Return the `a` in `Return a` +def get_result_ty (ty : Expr) : MetaM Expr := + ty.withApp fun f args => do + if ¬ f.isConstOf ``Result ∨ args.size ≠ 1 then + throwError "Invalid argument to get_result_ty: {ty}" + else + pure (args.get! 0) + +-- Group a list of expressions into a dependent tuple +def mkSigmas (xl : List Expr) : MetaM Expr := + match xl with + | [] => do + trace[Diverge.def.sigmas] "mkSigmas: []" + pure (Expr.const ``PUnit.unit []) + | [x] => do + trace[Diverge.def.sigmas] "mkSigmas: [{x}]" + pure x + | fst :: xl => do + trace[Diverge.def.sigmas] "mkSigmas: [{fst}::{xl}]" + let alpha ← Lean.Meta.inferType fst + let snd ← mkSigmas xl + let snd_ty ← inferType snd + let beta ← mkLambdaFVars #[fst] snd_ty + trace[Diverge.def.sigmas] "mkSigmas:\n{alpha}\n{beta}\n{fst}\n{snd}" + mkAppOptM ``Sigma.mk #[some alpha, some beta, some fst, some snd] + /- Generate the input type of a function body, which is a sigma type (i.e., a dependent tuple) which groups all its inputs. @@ -55,11 +86,11 @@ def mkSigmasTypesOfTypes (xl : List Expr) : MetaM Expr := match xl with | [] => do trace[Diverge.def.sigmas] "mkSigmasOfTypes: []" - return (Expr.const ``PUnit.unit []) + pure (Expr.const ``PUnit.unit []) | [x] => do trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}]" let ty ← Lean.Meta.inferType x - return ty + pure ty | x :: xl => do trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}::{xl}]" let alpha ← Lean.Meta.inferType x @@ -71,15 +102,26 @@ def mkSigmasTypesOfTypes (xl : List Expr) : MetaM Expr := def mk_indexed_name (index : Nat) : Name := .num (.str .anonymous "_uniq") index -/- Generate the out_ty of the body of a function, which from an input (a sigma - type generated by `mkSigmasTypesOfTypes`) gives the output type of the function. +/- Given a list of values `[x0:ty0, ..., xn:ty1]` where every `xi` might use the previous + `xj` (j < i) and a value `out` which uses `x0`, ..., `xn`, generate the following + expression: + ``` + fun x:((x0:ty0) × ... × (xn:tyn) => -- **Dependent** tuple + match x with + | (x0, ..., xn) => out + ``` + + The `index` parameter is used for naming purposes: we use it to numerotate the + bound variables that we introduce. Example: + ======== + More precisely: - xl = `[a:Type, ls:List a, i:Int]` - - out_ty = `a` - - index = 0 -- For naming purposes: we use it to numerotate the "scrutinee" variables + - out = `a` + - index = 0 - Generates: + generates: ``` match scrut0 with | Sigma.mk x scrut1 => @@ -88,36 +130,47 @@ def mk_indexed_name (index : Nat) : Name := .num (.str .anonymous "_uniq") index a ``` -/ -def mkSigmasOutType (xl : List Expr) (out_ty : Expr) (index : Nat := 0) : MetaM Expr := +partial def mkSigmasMatch (xl : List Expr) (out : Expr) (index : Nat := 0) : MetaM Expr := match xl with | [] => do -- This would be unexpected - throwError "mkSigmasOutType: empyt list of input parameters" + throwError "mkSigmasMatch: empyt list of input parameters" | [x] => do -- In the explanations above: inner match case - trace[Diverge.def.sigmas] "mkSigmasOutType: [{x}]" - mkLambdaFVars #[x] out_ty + trace[Diverge.def.sigmas] "mkSigmasMatch: [{x}]" + mkLambdaFVars #[x] out | fst :: xl => do -- In the explanations above: outer match case -- Remark: for the naming purposes, we use the same convention as for the -- fields and parameters in `Sigma.casesOn and `Sigma.mk - trace[Diverge.def.sigmas] "mkSigmasOutType: [{fst}::{xl}]" + trace[Diverge.def.sigmas] "mkSigmasMatch: [{fst}::{xl}]" let alpha ← Lean.Meta.inferType fst let snd_ty ← mkSigmasTypesOfTypes xl let beta ← mkLambdaFVars #[fst] snd_ty - let snd ← mkSigmasOutType xl out_ty (index + 1) + let snd ← mkSigmasMatch xl out (index + 1) let scrut_ty ← mkSigmasTypesOfTypes (fst :: xl) withLocalDeclD (mk_indexed_name index) scrut_ty fun scrut => do let mk ← mkLambdaFVars #[fst] snd - trace[Diverge.def.sigmas] "mkSigmasOutType: scrut: ({scrut}) : ({← inferType scrut})" - let motive ← mkLambdaFVars #[scrut] (← inferType out_ty) - trace[Diverge.def.sigmas] "mkSigmasOutType:\n ({alpha})\n ({beta})\n ({motive})\n ({scrut})\n ({mk})" - let out ← mkAppOptM ``Sigma.casesOn #[some alpha, some beta, some motive, some scrut, some mk] - let out ← mkLambdaFVars #[scrut] out - trace[Diverge.def.sigmas] "mkSigmasOutType: out: {out}" - return out - -/- Small tests for list_nth: give a model of what `mkSigmasOutType` should generate -/ + trace[Diverge.def.sigmas] "mkSigmasMatch: scrut: ({scrut}) : ({← inferType scrut})" + -- TODO: make the computation of the motive more efficient + let motive ← do + let out_ty ← inferType out + match out_ty with + | .sort _ | .lit _ | .const .. => + -- The type of the motive doesn't depend on the scrutinee + mkLambdaFVars #[scrut] out_ty + | _ => + -- The type of the motive *may* depend on the scrutinee + -- TODO: make this more efficient (we could change the output type of + -- mkSigmasMatch + mkSigmasMatch (fst :: xl) out_ty + trace[Diverge.def.sigmas] "mkSigmasMatch:\n ({alpha})\n ({beta})\n ({motive})\n ({scrut})\n ({mk})" + let sm ← mkAppOptM ``Sigma.casesOn #[some alpha, some beta, some motive, some scrut, some mk] + let sm ← mkLambdaFVars #[scrut] sm + trace[Diverge.def.sigmas] "mkSigmasMatch: sm: {sm}" + pure sm + +/- Small tests for list_nth: give a model of what `mkSigmasMatch` should generate -/ private def list_nth_out_ty2 (a :Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) := @Sigma.casesOn (List a) (fun (_ls : List a) => Int) @@ -135,14 +188,199 @@ private def list_nth_out_ty1 (scrut0 : @Sigma (Type) (fun (a:Type) => list_nth_out_ty2 a scrut1) /- -/ +-- TODO: move +-- TODO: we can use Array.mapIdx +@[specialize] def mapiAux (i : Nat) (f : Nat → α → β) : List α → List β + | [] => [] + | a::as => f i a :: mapiAux (i+1) f as + +@[specialize] def mapi (f : Nat → α → β) : List α → List β := mapiAux 0 f + +#check Array.map +-- Return the expression: `Fin n` +-- TODO: use more +def mkFin (n : Nat) : Expr := + mkAppN (.const ``Fin []) #[.lit (.natVal n)] + +-- Return the expression: `i : Fin n` +def mkFinVal (n i : Nat) : MetaM Expr := do + let n_lit : Expr := .lit (.natVal (n - 1)) + let i_lit : Expr := .lit (.natVal i) + -- We could use `trySynthInstance`, but as we know the instance that we are + -- going to use, we can save the lookup + let ofNat ← mkAppOptM ``Fin.instOfNatFinHAddNatInstHAddInstAddNatOfNat #[n_lit, i_lit] + mkAppOptM ``OfNat.ofNat #[none, none, ofNat] + +-- TODO: remove? +def mkFinValOld (n i : Nat) : MetaM Expr := do + let finTy := mkFin n + let ofNat ← mkAppM ``OfNat #[finTy, .lit (.natVal i)] + match ← trySynthInstance ofNat with + | LOption.some x => + mkAppOptM ``OfNat.ofNat #[none, none, x] + | _ => throwError "mkFinVal: could not synthesize an instance of {ofNat} " + +/- Generate and declare as individual definitions the bodies for the individual funcions: + - replace the recursive calls with calls to the continutation `k` + - make those bodies take one single dependent tuple as input + + We name the declarations: "[original_name].body". + We return the new declarations. + -/ +def mkDeclareUnaryBodies (grLvlParams : List Name) (k_var : Expr) + (preDefs : Array PreDefinition) : + MetaM (Array Expr) := do + let grSize := preDefs.size + + -- Compute the map from name to index - the continuation has an indexed type: + -- we use the index (a finite number of type `Fin`) to control the function + -- we call at the recursive call + let nameToId : HashMap Name Nat := + let namesIds := mapi (fun i d => (d.declName, i)) preDefs.toList + HashMap.ofList namesIds + + trace[Diverge.def.genBody] "nameToId: {nameToId.toList}" + + -- Auxiliary function to explore the function bodies and replace the + -- recursive calls + let visit_e (e : Expr) : MetaM Expr := do + trace[Diverge.def.genBody] "visiting expression: {e}" + match e with + | .app .. => do + e.withApp fun f args => do + trace[Diverge.def.genBody] "this is an app: {f} {args}" + -- Check if this is a recursive call + if f.isConst then + let name := f.constName! + match nameToId.find? name with + | none => pure e + | some id => + -- This is a recursive call: replace it + -- Compute the index + let i ← mkFinVal grSize id + -- Put the arguments in one big dependent tuple + let args ← mkSigmas args.toList + mkAppM' k_var #[i, args] + else + -- Not a recursive call: do nothing + pure e + | .const name _ => + -- Sanity check: we eliminated all the recursive calls + if (nameToId.find? name).isSome then + throwError "mkUnaryBodies: a recursive call was not eliminated" + else pure e + | _ => pure e + + -- Explore the bodies + preDefs.mapM fun preDef => do + -- Replace the recursive calls + let body ← mapVisit visit_e preDef.value + + -- Change the type + lambdaLetTelescope body fun args body => do + let body ← mkSigmasMatch args.toList body 0 + + -- Add the declaration + let value ← mkLambdaFVars #[k_var] body + let name := preDef.declName.append "body" + let levelParams := grLvlParams + let decl := Declaration.defnDecl { + name := name + levelParams := levelParams + type := ← inferType value -- TODO: change the type + value := value + hints := ReducibilityHints.regular (getMaxHeight (← getEnv) value + 1) + safety := .safe + all := [name] + } + addDecl decl + trace[Diverge.def] "individual body of {preDef.declName}: {body}" + -- Return the constant + let body := Lean.mkConst name (levelParams.map .param) + -- let body ← mkAppM' body #[k_var] + trace[Diverge.def] "individual body (after decl): {body}" + pure body + +-- Generate a unique function body from the bodies of the mutually recursive group, +-- and add it as a declaration in the context +def mkDeclareMutualBody (grName : Name) (grLvlParams : List Name) + (i_var k_var : Expr) + (in_ty out_ty : Expr) (inOutTys : List (Expr × Expr)) + (bodies : Array Expr) : MetaM Expr := do + -- Generate the body + let grSize := bodies.size + let finTypeExpr := mkFin grSize + -- TODO: not very clean + let inOutTyType ← do + let (x, y) := inOutTys.get! 0 + inferType (← mkInOutTy x y) + let rec mkFuns (inOutTys : List (Expr × Expr)) (bl : List Expr) : MetaM Expr := + match inOutTys, bl with + | [], [] => + mkAppOptM ``FixI.Funs.Nil #[finTypeExpr, in_ty, out_ty] + | (ity, oty) :: inOutTys, b :: bl => do + -- Retrieving ity and oty - this is not very clean + let inOutTysExpr ← mkList (← inOutTys.mapM (λ (x, y) => mkInOutTy x y)) inOutTyType + let fl ← mkFuns inOutTys bl + mkAppOptM ``FixI.Funs.Cons #[finTypeExpr, in_ty, out_ty, ity, oty, inOutTysExpr, b, fl] + | _, _ => throwError "mkDeclareMutualBody: `tys` and `bodies` don't have the same length" + let bodyFuns ← mkFuns inOutTys bodies.toList + -- Wrap in `get_fun` + let body ← mkAppM ``FixI.get_fun #[bodyFuns, i_var, k_var] + -- Add the index `i` and the continuation `k` as a variables + let body ← mkLambdaFVars #[k_var, i_var] body + trace[Diverge.def] "mkDeclareMutualBody: body: {body}" + -- Add the declaration + let name := grName.append "mutrec_body" + let levelParams := grLvlParams + let decl := Declaration.defnDecl { + name := name + levelParams := levelParams + type := ← inferType body + value := body + hints := ReducibilityHints.regular (getMaxHeight (← getEnv) body + 1) + safety := .safe + all := [name] + } + addDecl decl + -- Return the constant + pure (Lean.mkConst name (levelParams.map .param)) + +-- Generate the final definions by using the mutual body and the fixed point operator. +def mkDeclareFixDefs (mutBody : Expr) (preDefs : Array PreDefinition) : + TermElabM Unit := do + let grSize := preDefs.size + let _ ← preDefs.mapIdxM fun idx preDef => do + lambdaLetTelescope preDef.value fun xs _ => do + -- Create the index + let idx ← mkFinVal grSize idx.val + -- Group the inputs into a dependent tuple + let input ← mkSigmas xs.toList + -- Apply the fixed point + let fixedBody ← mkAppM ``FixI.fix #[mutBody, idx, input] + let fixedBody ← mkLambdaFVars xs fixedBody + -- Create the declaration + let name := preDef.declName + let decl := Declaration.defnDecl { + name := name + levelParams := preDef.levelParams + type := preDef.type + value := fixedBody + hints := ReducibilityHints.regular (getMaxHeight (← getEnv) fixedBody + 1) + safety := .safe + all := [name] + } + addDecl decl + pure () + def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) trace[Diverge.def] ("divRecursion: defs: " ++ msg) -- CHANGE HERE This function should add definitions with these names/types/values ^^ -- Temporarily add the predefinitions as axioms - for preDef in preDefs do - addAsAxiom preDef + -- for preDef in preDefs do + -- addAsAxiom preDef -- TODO: what is this? for preDef in preDefs do @@ -154,25 +392,14 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let grName := def0.declName trace[Diverge.def] "group name: {grName}" - /- Compute the type of the continuation. - - We do the following - - we make sure all the definitions have the same universe parameters - (we can make this more general later) - - we group all the type parameters together, make sure all the - definitions have the same type parameters, and enforce - a uniform polymorphism (we can also lift this later). - This would require generalizing a bit our indexed fixed point to - make the output type parametric in the input. - - we group all the non-type parameters: we parameterize the continuation - by those - -/ + /- # Compute the input/output types of the continuation `k`. -/ let grLvlParams := def0.levelParams - trace[Diverge.def] "def0 type: {def0.type}" + trace[Diverge.def] "def0 universe levels: {def0.levelParams}" - -- Compute the list of pairs: (input type × output type) + -- We first compute the list of pairs: (input type × output type) let inOutTys : Array (Expr × Expr) ← preDefs.mapM (fun preDef => do + withRef preDef.ref do -- is the withRef useful? -- Check the universe parameters - TODO: I'm not sure what the best thing -- to do is. In practice, all the type parameters should be in Type 0, so -- we shouldn't have universe issues. @@ -180,68 +407,74 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do throwError "Non-uniform polymorphism in the universes" forallTelescope preDef.type (fun in_tys out_ty => do let in_ty ← liftM (mkSigmasTypesOfTypes in_tys.toList) - let out_ty ← liftM (mkSigmasOutType in_tys.toList out_ty) - return (in_ty, out_ty) + -- Retrieve the type in the "Result" + let out_ty ← get_result_ty out_ty + let out_ty ← liftM (mkSigmasMatch in_tys.toList out_ty) + pure (in_ty, out_ty) ) ) trace[Diverge.def] "inOutTys: {inOutTys}" - -/- -- Small utility: compute the list of type parameters - let getTypeParams (ty: Expr) : MetaM (List Expr × List Expr × Expr) := - Lean.Meta.forallTelescope ty fun tys out_ty => do - trace[Diverge.def] "types: {tys}" -/- let (_, params) ← StateT.run (do - for x in tys do - let ty ← Lean.Meta.inferType x - match ty with - | .sort _ => do - let st ← StateT.get - StateT.set (ty :: st) - | _ => do break - ) ([] : List Expr) - let params := params.reverse - trace[Diverge.def] " type parameters {params}" - return params -/ - let rec get_params (ls : List Expr) : MetaM (List Expr × List Expr) := - match ls with - | x :: tl => do - let ty ← Lean.Meta.inferType x - match ty with - | .sort _ => do - let (ty_params, params) ← get_params tl - return (x :: ty_params, params) - | _ => do return ([], ls) - | _ => do return ([], []) - let (ty_params, params) ← get_params tys.toList - trace[Diverge.def] " parameters: {ty_params}; {params}" - return (ty_params, params, out_ty) - let (grTyParams, _, _) ← do - getTypeParams def0.type - - -- Compute the input types and the output types - let all_tys ← preDefs.mapM fun preDef => do - let (tyParams, params, ret_ty) ← getTypeParams preDef.type - -- TODO: this is not complete, there are more checks to perform - if tyParams.length ≠ grTyParams.length then - throwError "Non-uniform polymorphism" - return (params, ret_ty) - - -- TODO: I think there are issues with the free variables - let (input_tys, output_tys) := List.unzip all_tys.toList - let input_tys : List Expr ← liftM (List.mapM mkProds input_tys) - - trace[Diverge.def] " in/out tys: {input_tys}; {output_tys}" -/ - - -- Compute the names set - let names := preDefs.map PreDefinition.declName - let names := HashSet.empty.insertMany names - - -- - -- for preDef in preDefs do - -- trace[Diverge.def] "about to explore: {preDef.declName}" - -- explore_term "" preDef.value - - -- Compute the bodies + -- Turn the list of input/output type pairs into an expresion + let inOutTysExpr ← inOutTys.mapM (λ (x, y) => mkInOutTy x y) + let inOutTysExpr ← mkList inOutTysExpr.toList (← inferType (inOutTysExpr.get! 0)) + + -- From the list of pairs of input/output types, actually compute the + -- type of the continuation `k`. + -- We first introduce the index `i : Fin n` where `n` is the number of + -- functions in the group. + let i_var_ty := mkFin preDefs.size + withLocalDeclD (.num (.str .anonymous "i") 0) i_var_ty fun i_var => do + let in_out_ty ← mkAppM ``List.get #[inOutTysExpr, i_var] + trace[Diverge.def] "in_out_ty := {in_out_ty} : {← inferType in_out_ty}" + -- Add an auxiliary definition for `in_out_ty` + let in_out_ty ← do + let value ← mkLambdaFVars #[i_var] in_out_ty + let name := grName.append "in_out_ty" + let levelParams := grLvlParams + let decl := Declaration.defnDecl { + name := name + levelParams := levelParams + type := ← inferType value + value := value + hints := .abbrev + safety := .safe + all := [name] + } + addDecl decl + -- Return the constant + let in_out_ty := Lean.mkConst name (levelParams.map .param) + mkAppM' in_out_ty #[i_var] + trace[Diverge.def] "in_out_ty (after decl) := {in_out_ty} : {← inferType in_out_ty}" + let in_ty ← mkAppM ``Sigma.fst #[in_out_ty] + trace[Diverge.def] "in_ty: {in_ty}" + withLocalDeclD (.num (.str .anonymous "x") 1) in_ty fun input => do + let out_ty ← mkAppM' (← mkAppM ``Sigma.snd #[in_out_ty]) #[input] + trace[Diverge.def] "out_ty: {out_ty}" + + -- Introduce the continuation `k` + let in_ty ← mkLambdaFVars #[i_var] in_ty + let out_ty ← mkLambdaFVars #[i_var, input] out_ty + let k_var_ty ← mkAppM ``FixI.kk_ty #[i_var_ty, in_ty, out_ty] -- + trace[Diverge.def] "k_var_ty: {k_var_ty}" + withLocalDeclD (.num (.str .anonymous "k") 2) k_var_ty fun k_var => do + trace[Diverge.def] "k_var: {k_var}" + + -- Replace the recursive calls in all the function bodies by calls to the + -- continuation `k` and and generate for those bodies declarations + let bodies ← mkDeclareUnaryBodies grLvlParams k_var preDefs + -- Generate the mutually recursive body + let body ← mkDeclareMutualBody grName grLvlParams i_var k_var in_ty out_ty inOutTys.toList bodies + trace[Diverge.def] "mut rec body (after decl): {body}" + + -- Prove that the mut rec body satisfies the validity criteria required by + -- our fixed-point + -- TODO + + -- Generate the final definitions + let defs ← mkDeclareFixDefs body preDefs + + -- Prove the unfolding equations + -- TODO -- Process the definitions addAndCompilePartialRec preDefs @@ -366,6 +599,10 @@ divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := if i = 0 then return x else return (← list_nth ls (i - 1)) +#print list_nth.in_out_ty +#check list_nth.body +#print list_nth + mutual divergent def is_even (i : Int) : Result Bool := if i = 0 then return true else return (← is_odd (i - 1)) diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index 441b25f0..82f79f94 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -4,13 +4,14 @@ namespace Diverge open Lean Elab Term Meta -initialize registerTraceClass `Diverge.elab (inherited := true) -initialize registerTraceClass `Diverge.def.sigmas (inherited := true) -initialize registerTraceClass `Diverge.def (inherited := true) +initialize registerTraceClass `Diverge.elab +initialize registerTraceClass `Diverge.def +initialize registerTraceClass `Diverge.def.sigmas +initialize registerTraceClass `Diverge.def.genBody -- TODO: move -- TODO: small helper -def explore_term (incr : String) (e : Expr) : TermElabM Unit := +def explore_term (incr : String) (e : Expr) : MetaM Unit := match e with | .bvar _ => do logInfo m!"{incr}bvar: {e}"; return () | .fvar _ => do logInfo m!"{incr}fvar: {e}"; return () @@ -78,4 +79,42 @@ private def test2 (x : Nat) : Nat := x print_decl test1 print_decl test2 +-- We adapted this from AbstractNestedProofs.visit +-- A map visitor function for expressions +partial def mapVisit (k : Expr → MetaM Expr) (e : Expr) : MetaM Expr := do + let mapVisitBinders (xs : Array Expr) (k2 : MetaM Expr) : MetaM Expr := do + let localInstances ← getLocalInstances + let mut lctx ← getLCtx + for x in xs do + let xFVarId := x.fvarId! + let localDecl ← xFVarId.getDecl + let type ← mapVisit k localDecl.type + let localDecl := localDecl.setType type + let localDecl ← match localDecl.value? with + | some value => let value ← mapVisit k value; pure <| localDecl.setValue value + | none => pure localDecl + lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl + withLCtx lctx localInstances k2 + -- TODO: use a cache? (Lean.checkCache) + -- Explore + let e ← k e + match e with + | .bvar _ + | .fvar _ + | .mvar _ + | .sort _ + | .lit _ + | .const _ _ => pure e + | .app .. => do e.withApp fun f args => return mkAppN f (← args.mapM (mapVisit k)) + | .lam .. => + lambdaLetTelescope e fun xs b => + mapVisitBinders xs do mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) + | .forallE .. => do + forallTelescope e fun xs b => mapVisitBinders xs do mkForallFVars xs (← mapVisit k b) + | .letE .. => do + lambdaLetTelescope e fun xs b => mapVisitBinders xs do + mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) + | .mdata _ b => return e.updateMData! (← mapVisit k b) + | .proj _ _ b => return e.updateProj! (← mapVisit k b) + end Diverge -- cgit v1.2.3 From 37e5d5501e024869037bf0ea1559229a8be62da7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 3 Jul 2023 16:24:44 +0200 Subject: Generate the proofs of validity in Elab.lean --- backends/lean/Base/Diverge/Base.lean | 76 +++++- backends/lean/Base/Diverge/Elab.lean | 403 ++++++++++++++++++++++++++++--- backends/lean/Base/Diverge/ElabBase.lean | 1 + 3 files changed, 446 insertions(+), 34 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index aa0539ba..89365d25 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -434,6 +434,23 @@ namespace Fix is_valid_p k (λ k => k x) := by simp_all [is_valid_p, is_mono_p_rec, is_cont_p_rec] + theorem is_valid_p_ite + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (cond : Prop) [h : Decidable cond] + {e1 e2 : ((x:a) → Result (b x)) → Result c} + (he1: is_valid_p k e1) (he2 : is_valid_p k e2) : + is_valid_p k (ite cond e1 e2) := by + split <;> assumption + + theorem is_valid_p_dite + (k : ((x:a) → Result (b x)) → (x:a) → Result (b x)) + (cond : Prop) [h : Decidable cond] + {e1 : cond → ((x:a) → Result (b x)) → Result c} + {e2 : Not cond → ((x:a) → Result (b x)) → Result c} + (he1: ∀ x, is_valid_p k (e1 x)) (he2 : ∀ x, is_valid_p k (e2 x)) : + is_valid_p k (dite cond e1 e2) := by + split <;> simp [*] + -- Lean is good at unification: we can write a very general version -- (in particular, it will manage to figure out `g` and `h` when we -- apply the lemma) @@ -680,6 +697,24 @@ namespace FixI is_valid_p k (λ k => k i x) := by simp [is_valid_p, k_to_gen, e_to_gen, kk_to_gen, kk_of_gen] + theorem is_valid_p_ite + (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) + (cond : Prop) [h : Decidable cond] + {e1 e2 : ((i:id) → (x:a i) → Result (b i x)) → Result c} + (he1: is_valid_p k e1) (he2 : is_valid_p k e2) : + is_valid_p k (λ k => ite cond (e1 k) (e2 k)) := by + split <;> assumption + + theorem is_valid_p_dite + (k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) + (cond : Prop) [h : Decidable cond] + {e1 : ((i:id) → (x:a i) → Result (b i x)) → cond → Result c} + {e2 : ((i:id) → (x:a i) → Result (b i x)) → Not cond → Result c} + (he1: ∀ x, is_valid_p k (λ k => e1 k x)) + (he2 : ∀ x, is_valid_p k (λ k => e2 k x)) : + is_valid_p k (λ k => dite cond (e1 k) (e2 k)) := by + split <;> simp [*] + theorem is_valid_p_bind {{k : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)}} {{g : ((i:id) → (x:a i) → Result (b i x)) → Result c}} @@ -699,6 +734,9 @@ namespace FixI | .Nil => True | .Cons f fl => (∀ x, FixI.is_valid_p k (λ k => f k x)) ∧ fl.is_valid_p k + theorem Funs.is_valid_p_Nil (k : k_ty id a b) : + Funs.is_valid_p k Funs.Nil := by simp [Funs.is_valid_p] + def Funs.is_valid_p_is_valid_p_aux {k : k_ty id a b} {tys : List in_out_ty} @@ -1116,7 +1154,7 @@ namespace Ex6 def body (k : (i : Fin 1) → (x : input_ty i) → Result (output_ty i x)) (i: Fin 1) : (x : input_ty i) → Result (output_ty i x) := get_fun bodies i k - theorem list_nth_body_is_valid: is_valid body := by + theorem body_is_valid: is_valid body := by -- Split the proof into proofs of validity of the individual bodies rw [is_valid] simp only [body] @@ -1131,6 +1169,20 @@ namespace Ex6 split <;> simp split <;> simp + -- Writing the proof terms explicitly + theorem list_nth_body_is_valid' (k : k_ty (Fin 1) input_ty output_ty) + (x : (a : Type u) × List a × Int) : is_valid_p k (fun k => list_nth_body k x) := + let ⟨ a, ls, i ⟩ := x + match ls with + | [] => is_valid_p_same k (.fail .panic) + | hd :: tl => + is_valid_p_ite k (Eq i 0) (is_valid_p_same k (.ret hd)) (is_valid_p_rec k 0 ⟨a, tl, i-1⟩) + + theorem body_is_valid' : is_valid body := + fun k => + Funs.is_valid_p_is_valid_p tys k bodies + (And.intro (list_nth_body_is_valid' k) (Funs.is_valid_p_Nil k)) + noncomputable def list_nth {a: Type u} (ls : List a) (i : Int) : Result a := fix body 0 ⟨ a, ls , i ⟩ @@ -1144,8 +1196,28 @@ namespace Ex6 if i = 0 then .ret hd else list_nth tl (i - 1) := by - have Heq := is_valid_fix_fixed_eq list_nth_body_is_valid + have Heq := is_valid_fix_fixed_eq body_is_valid simp [list_nth] conv => lhs; rw [Heq] + -- Write the proof term explicitly: the generation of the proof term (without tactics) + -- is automatable, and the proof term is actually a lot simpler and smaller when we + -- don't use tactics. + theorem list_nth_eq'.{u} {a : Type u} (ls : List a) (i : Int) : + list_nth ls i = + match ls with + | [] => .fail .panic + | hd :: tl => + if i = 0 then .ret hd + else list_nth tl (i - 1) + := + -- Use the fixed-point equation + have Heq := is_valid_fix_fixed_eq body_is_valid.{u} + -- Add the index + have Heqi := congr_fun Heq 0 + -- Add the input + have Heqix := congr_fun Heqi { fst := a, snd := (ls, i) } + -- Done + Heqix + end Ex6 diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index f7de7518..cf40ea8f 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -16,6 +16,7 @@ syntax (name := divergentDef) open Lean Elab Term Meta Primitives Lean.Meta set_option trace.Diverge.def true +set_option trace.Diverge.def.valid true -- set_option trace.Diverge.def.sigmas true /- The following was copied from the `wfRecursion` function. -/ @@ -196,7 +197,6 @@ private def list_nth_out_ty1 (scrut0 : @Sigma (Type) (fun (a:Type) => @[specialize] def mapi (f : Nat → α → β) : List α → List β := mapiAux 0 f -#check Array.map -- Return the expression: `Fin n` -- TODO: use more def mkFin (n : Nat) : Expr := @@ -227,7 +227,7 @@ def mkFinValOld (n i : Nat) : MetaM Expr := do We name the declarations: "[original_name].body". We return the new declarations. -/ -def mkDeclareUnaryBodies (grLvlParams : List Name) (k_var : Expr) +def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) (preDefs : Array PreDefinition) : MetaM (Array Expr) := do let grSize := preDefs.size @@ -260,7 +260,7 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (k_var : Expr) let i ← mkFinVal grSize id -- Put the arguments in one big dependent tuple let args ← mkSigmas args.toList - mkAppM' k_var #[i, args] + mkAppM' kk_var #[i, args] else -- Not a recursive call: do nothing pure e @@ -281,8 +281,8 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (k_var : Expr) let body ← mkSigmasMatch args.toList body 0 -- Add the declaration - let value ← mkLambdaFVars #[k_var] body - let name := preDef.declName.append "body" + let value ← mkLambdaFVars #[kk_var] body + let name := preDef.declName.append "sbody" let levelParams := grLvlParams let decl := Declaration.defnDecl { name := name @@ -297,16 +297,17 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (k_var : Expr) trace[Diverge.def] "individual body of {preDef.declName}: {body}" -- Return the constant let body := Lean.mkConst name (levelParams.map .param) - -- let body ← mkAppM' body #[k_var] + -- let body ← mkAppM' body #[kk_var] trace[Diverge.def] "individual body (after decl): {body}" pure body -- Generate a unique function body from the bodies of the mutually recursive group, --- and add it as a declaration in the context -def mkDeclareMutualBody (grName : Name) (grLvlParams : List Name) - (i_var k_var : Expr) +-- and add it as a declaration in the context. +-- We return the list of bodies (of type `Funs ...`) and the mutually recursive body. +def mkDeclareMutRecBody (grName : Name) (grLvlParams : List Name) + (kk_var i_var : Expr) (in_ty out_ty : Expr) (inOutTys : List (Expr × Expr)) - (bodies : Array Expr) : MetaM Expr := do + (bodies : Array Expr) : MetaM (Expr × Expr) := do -- Generate the body let grSize := bodies.size let finTypeExpr := mkFin grSize @@ -323,15 +324,15 @@ def mkDeclareMutualBody (grName : Name) (grLvlParams : List Name) let inOutTysExpr ← mkList (← inOutTys.mapM (λ (x, y) => mkInOutTy x y)) inOutTyType let fl ← mkFuns inOutTys bl mkAppOptM ``FixI.Funs.Cons #[finTypeExpr, in_ty, out_ty, ity, oty, inOutTysExpr, b, fl] - | _, _ => throwError "mkDeclareMutualBody: `tys` and `bodies` don't have the same length" + | _, _ => throwError "mkDeclareMutRecBody: `tys` and `bodies` don't have the same length" let bodyFuns ← mkFuns inOutTys bodies.toList -- Wrap in `get_fun` - let body ← mkAppM ``FixI.get_fun #[bodyFuns, i_var, k_var] + let body ← mkAppM ``FixI.get_fun #[bodyFuns, i_var, kk_var] -- Add the index `i` and the continuation `k` as a variables - let body ← mkLambdaFVars #[k_var, i_var] body - trace[Diverge.def] "mkDeclareMutualBody: body: {body}" + let body ← mkLambdaFVars #[kk_var, i_var] body + trace[Diverge.def] "mkDeclareMutRecBody: body: {body}" -- Add the declaration - let name := grName.append "mutrec_body" + let name := grName.append "mut_rec_body" let levelParams := grLvlParams let decl := Declaration.defnDecl { name := name @@ -344,10 +345,348 @@ def mkDeclareMutualBody (grName : Name) (grLvlParams : List Name) } addDecl decl -- Return the constant - pure (Lean.mkConst name (levelParams.map .param)) + pure (bodyFuns, Lean.mkConst name (levelParams.map .param)) + +def isCasesExpr (e : Expr) : MetaM Bool := do + let e := e.getAppFn + if e.isConst then + return isCasesOnRecursor (← getEnv) e.constName + else return false + +structure MatchInfo where + matcherName : Name + matcherLevels : Array Level + params : Array Expr + motive : Expr + scruts : Array Expr + branchesNumParams : Array Nat + branches : Array Expr + +instance : ToMessageData MatchInfo where + -- This is not a very clean formatting, but we don't need more + toMessageData := fun me => m!"\n- matcherName: {me.matcherName}\n- params: {me.params}\n- motive: {me.motive}\n- scruts: {me.scruts}\n- branchesNumParams: {me.branchesNumParams}\n- branches: {me.branches}" + +-- An expression which doesn't use the continuation kk is valid +def proveNoKExprIsValid (k_var : Expr) (e : Expr) : MetaM Expr := do + trace[Diverge.def.valid] "proveNoKExprIsValid: {e}" + let eIsValid ← mkAppM ``FixI.is_valid_p_same #[k_var, e] + trace[Diverge.def.valid] "proveNoKExprIsValid: result:\n{eIsValid}:\n{← inferType eIsValid}" + pure eIsValid + +mutual + +partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do + trace[Diverge.def.valid] "proveValid: {e}" + match e with + | .bvar _ + | .fvar _ + | .mvar _ + | .sort _ + | .lit _ + | .const _ _ => throwError "Unimplemented" + | .lam .. => throwError "Unimplemented" + | .forallE .. => throwError "Unreachable" -- Shouldn't get there + | .letE .. => throwError "TODO" + -- lambdaLetTelescope e fun xs b => mapVisitBinders xs do + -- mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) + | .mdata _ b => proveExprIsValid k_var kk_var b + | .proj _ _ _ => + -- The projection shouldn't use the continuation + proveNoKExprIsValid k_var e + | .app .. => + e.withApp fun f args => do + -- There are several cases: first, check if this is a match/if + -- The expression is a (dependent) if then else + let isIte := e.isIte + if isIte || e.isDIte then do + e.withApp fun f args => do + trace[Diverge.def.valid] "ite/dite: {f}:\n{args}" + if args.size ≠ 5 then + throwError "Wrong number of parameters for {f}: {args}" + let cond := args.get! 1 + let dec := args.get! 2 + -- Prove that the branches are valid + let br0 := args.get! 3 + let br1 := args.get! 4 + let proveBranchValid (br : Expr) : MetaM Expr := + if isIte then proveExprIsValid k_var kk_var br + else do + -- There is a lambda -- TODO: how do we remove exacly *one* lambda? + lambdaLetTelescope br fun xs br => do + let x := xs.get! 0 + let xs := xs.extract 1 xs.size + let br ← mkLambdaFVars xs br + let brValid ← proveExprIsValid k_var kk_var br + mkLambdaFVars #[x] brValid + let br0Valid ← proveBranchValid br0 + let br1Valid ← proveBranchValid br1 + let const := if isIte then ``FixI.is_valid_p_ite else ``FixI.is_valid_p_dite + let eIsValid ← mkAppOptM const #[none, none, none, none, some k_var, some cond, some dec, none, none, some br0Valid, some br1Valid] + trace[Diverge.def.valid] "ite/dite: result:\n{eIsValid}:\n{← inferType eIsValid}" + pure eIsValid + -- The expression is a match (this case is for when the elaborator + -- introduces auxiliary definitions to hide the match behind syntactic + -- sugar) + else if let some me := ← matchMatcherApp? e then do + trace[Diverge.def.valid] + "matcherApp: + - params: {me.params} + - motive: {me.motive} + - discrs: {me.discrs} + - altNumParams: {me.altNumParams} + - alts: {me.alts} + - remaining: {me.remaining}" + -- matchMatcherApp has already done the work for us + if me.remaining.size ≠ 0 then + throwError "MatcherApp: non empty remaining array: {me.remaining}" + let me : MatchInfo := { + matcherName := me.matcherName + matcherLevels := me.matcherLevels + params := me.params + motive := me.motive + scruts := me.discrs + branchesNumParams := me.altNumParams + branches := me.alts + } + proveMatchIsValid k_var kk_var me + -- The expression is a raw match (this case is for when the expression + -- is a direct call to the primitive `casesOn` function, without + -- syntactic sugar) + else if ← isCasesExpr f then do + trace[Diverge.def.valid] "rawMatch: {e}" + -- The casesOn definition is always of the following shape: + -- input parameters (implicit parameters), then motive (implicit), + -- scrutinee (explicit), branches (explicit). + let matcherName := f.constName! + let matcherLevels := f.constLevels!.toArray + -- Find the first explicit parameter: this is the scrutinee + forallTelescope (← inferType f) fun xs _ => do + let rec findFirstExplicit (i : Nat) : MetaM Nat := do + if i ≥ xs.size then throwError "Unexpected: could not find an explicit parameter" + else + let x := xs.get! i + let xFVarId := x.fvarId! + let localDecl ← xFVarId.getDecl + match localDecl.binderInfo with + | .default => pure i + | _ => findFirstExplicit (i + 1) + let scrutIdx ← findFirstExplicit 0 + -- Split the arguments + let params := args.extract 0 (scrutIdx - 1) + let motive := args.get! (scrutIdx - 1) + let scrut := args.get! scrutIdx + let branches := args.extract (scrutIdx + 1) args.size + -- Compute the number of parameters for the branches: for this we use + -- the type of the uninstantiated casesOn constant + let branchesNumParams : Array Nat ← do + let env ← getEnv + let decl := env.constants.find! matcherName + let ty := decl.type + forallTelescope ty fun xs _ => do + let xs := xs.extract (scrutIdx + 1) xs.size + xs.mapM fun x => do + let xty ← inferType x + forallTelescope xty fun ys _ => do + pure ys.size + let me : MatchInfo := { + matcherName, + matcherLevels, + params, + motive, + scruts := #[scrut], + branchesNumParams, + branches, + } + proveMatchIsValid k_var kk_var me + -- Monadic let-binding + else if f.isConstOf ``Bind.bind then do + trace[Diverge.def.valid] "bind:\n{args}" + let x := args.get! 4 + let y := args.get! 5 + -- Prove that the subexpressions are valid + let xValid ← proveExprIsValid k_var kk_var x + trace[Diverge.def.valid] "bind: xValid:\n{xValid}:\n{← inferType xValid}" + let yValid ← do + -- This is a lambda expression -- TODO: how do we remove exacly *one* lambda? + lambdaLetTelescope y fun xs y => do + let x := xs.get! 0 + let xs := xs.extract 1 xs.size + let y ← mkLambdaFVars xs y + trace[Diverge.def.valid] "bind: y: {y}" + let yValid ← proveExprIsValid k_var kk_var y + trace[Diverge.def.valid] "bind: yValid (no forall): {yValid}" + trace[Diverge.def.valid] "bind: yValid: x: {x}" + let yValid ← mkLambdaFVars #[x] yValid + trace[Diverge.def.valid] "bind: yValid (forall): {yValid}: {← inferType yValid}" + pure yValid + -- Put everything together + trace[Diverge.def.valid] "bind:\n- xValid: {xValid}: {← inferType xValid}\n- yValid: {yValid}: {← inferType yValid}" + mkAppM ``FixI.is_valid_p_bind #[xValid, yValid] + -- Recursive call + else if f.isFVarOf kk_var.fvarId! then do + trace[Diverge.def.valid] "rec: args: \n{args}" + if args.size ≠ 2 then throwError "Recursive call with invalid number of parameters: {args}" + let i_arg := args.get! 0 + let x_arg := args.get! 1 + let eIsValid ← mkAppM ``FixI.is_valid_p_rec #[k_var, i_arg, x_arg] + trace[Diverge.def.valid] "rec: result: \n{eIsValid}" + pure eIsValid + else do + -- Remaining case: normal application. + -- It shouldn't use the continuation + proveNoKExprIsValid k_var e + +partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Expr := do + trace[Diverge.def.valid] "proveMatchIsValid: {me}" + -- Prove the validity of the branch expressions + let branchesValid:Array Expr ← me.branches.mapIdxM fun idx br => do + -- Go inside the lambdas - note that we have to be careful: some of the + -- binders might come from the match, and some of the binders might come + -- from the fact that the expression in the match is a lambda expression: + -- we use the branchesNumParams field for this reason + lambdaLetTelescope br fun xs br => do + let numParams := me.branchesNumParams.get! idx + let xs_beg := xs.extract 0 numParams + let xs_end := xs.extract numParams xs.size + let br ← mkLambdaFVars xs_end br + -- Prove that the branch expression is valid + let brValid ← proveExprIsValid k_var kk_var br + -- Reconstruct the lambda expression + mkLambdaFVars xs_beg brValid + trace[Diverge.def.valid] "branchesValid:\n{branchesValid}" + -- Put together: compute the motive. + -- It must be of the shape: + -- ``` + -- λ scrut => is_valid_p k (λ k => match scrut with ...) + -- ``` + let validMotive : Expr ← do + -- The motive is a function of the scrutinees (i.e., a lambda expression): + -- introduce binders for the scrutinees + let declInfos := me.scruts.mapIdx fun idx scrut => + let name : Name := (.num (.str .anonymous "scrut") idx) + let ty := λ (_ : Array Expr) => inferType scrut + (name, ty) + withLocalDeclsD declInfos fun scrutVars => do + -- Create a match expression but where the scrutinees have been replaced + -- by variables + let params : Array (Option Expr) := me.params.map some + let motive : Option Expr := some me.motive + let scruts : Array (Option Expr) := scrutVars.map some + let branches : Array (Option Expr) := me.branches.map some + let args := params ++ [motive] ++ scruts ++ branches + let matchE ← mkAppOptM me.matcherName args + -- let matchE ← mkLambdaFVars scrutVars (← mkAppOptM me.matcherName args) + -- Wrap in the `is_valid_p` predicate + let matchE ← mkLambdaFVars #[kk_var] matchE + let validMotive ← mkAppM ``FixI.is_valid_p #[k_var, matchE] + -- Abstract away the scrutinee variables + mkLambdaFVars scrutVars validMotive + trace[Diverge.def.valid] "valid motive: {validMotive}" + -- Put together + let valid ← do + let params : Array (Option Expr) := me.params.map (λ _ => none) + let motive := some validMotive + let scruts := me.scruts.map some + let branches := branchesValid.map some + let args := params ++ [motive] ++ scruts ++ branches + mkAppOptM me.matcherName args + trace[Diverge.def.valid] "proveMatchIsValid:\n{valid}:\n{← inferType valid}" + pure valid + +end + +-- Prove that a single body (in the mutually recursive group) is valid +partial def proveSingleBodyIsValid (k_var : Expr) (preDef : PreDefinition) (bodyConst : Expr) : + MetaM Expr := do + trace[Diverge.def.valid] "proveSingleBodyIsValid: bodyConst: {bodyConst}" + -- Lookup the definition (`bodyConst` is the definition of the body, we want + -- to retrieve the value itself to dive inside) + let name := bodyConst.constName! + let env ← getEnv + let body := (env.constants.find! name).value! + trace[Diverge.def.valid] "body: {body}" + lambdaLetTelescope body fun xs body => do + assert! xs.size = 2 + let kk_var := xs.get! 0 + let x_var := xs.get! 1 + -- State the type of the theorem to prove + let thmTy ← mkAppM ``FixI.is_valid_p + #[k_var, ← mkLambdaFVars #[kk_var] (← mkAppM' bodyConst #[kk_var, x_var])] + trace[Diverge.def.valid] "thmTy: {thmTy}" + -- Prove that the body is valid + let proof ← proveExprIsValid k_var kk_var body + let proof ← mkLambdaFVars #[k_var, x_var] proof + trace[Diverge.def.valid] "proveSingleBodyIsValid: proof:\n{proof}:\n{← inferType proof}" + -- The target type (we don't have to do this: this is simply a sanity check, + -- and this allows a nicer debugging output) + let thmTy ← do + let body ← mkAppM' bodyConst #[kk_var, x_var] + let body ← mkLambdaFVars #[kk_var] body + let ty ← mkAppM ``FixI.is_valid_p #[k_var, body] + mkForallFVars #[k_var, x_var] ty + trace[Diverge.def.valid] "proveSingleBodyIsValid: thmTy\n{thmTy}:\n{← inferType thmTy}" + -- Save the theorem + let name := preDef.declName ++ "sbody_is_valid" + let decl := Declaration.thmDecl { + name + levelParams := preDef.levelParams + type := thmTy + value := proof + all := [name] + } + addDecl decl + trace[Diverge.def.valid] "proveSingleBodyIsValid: added thm: {name}" + -- Return the theorem + pure (Expr.const name (preDef.levelParams.map .param)) + +partial def proveFunsBodyIsValid (inOutTys: Expr) (bodyFuns : Expr) + (k_var : Expr) (bodiesValid : Array Expr) : MetaM Expr := do + -- Create the big "and" expression, which groups the validity proof of the individual bodies + let rec mkValidConj (i : Nat) : MetaM Expr := do + if i = bodiesValid.size then + -- We reached the end + mkAppM ``FixI.Funs.is_valid_p_Nil #[k_var] + else do + -- We haven't reached the end: introduce a conjunction + let valid := bodiesValid.get! i + let valid ← mkAppM' valid #[k_var] + mkAppM ``And.intro #[valid, ← mkValidConj (i + 1)] + let andExpr ← mkValidConj 0 + -- Wrap in the `is_valid_p_is_valid_p` theorem, and abstract the continuation + let isValid ← mkAppM ``FixI.Funs.is_valid_p_is_valid_p #[inOutTys, k_var, bodyFuns, andExpr] + mkLambdaFVars #[k_var] isValid + +-- Prove that the mut rec body is valid +-- TODO: maybe this function should introduce k_var itself +def proveMutRecIsValid + (grName : Name) (grLvlParams : List Name) + (inOutTys : Expr) (bodyFuns mutRecBodyConst : Expr) + (k_var : Expr) (preDefs : Array PreDefinition) + (bodies : Array Expr) : MetaM Expr := do + -- First prove that the individual bodies are valid + let bodiesValid ← + bodies.mapIdxM fun idx body => do + let preDef := preDefs.get! idx + proveSingleBodyIsValid k_var preDef body + -- Then prove that the mut rec body is valid + let isValid ← proveFunsBodyIsValid inOutTys bodyFuns k_var bodiesValid + -- Save the theorem + let thmTy ← mkAppM ``FixI.is_valid #[mutRecBodyConst] + let name := grName ++ "mut_rec_body_is_valid" + let decl := Declaration.thmDecl { + name + levelParams := grLvlParams + type := thmTy + value := isValid + all := [name] + } + addDecl decl + trace[Diverge.def.valid] "proveFunsBodyIsValid: added thm: {name}:\n{thmTy}" + -- Return the theorem + pure (Expr.const name (grLvlParams.map .param)) -- Generate the final definions by using the mutual body and the fixed point operator. -def mkDeclareFixDefs (mutBody : Expr) (preDefs : Array PreDefinition) : +def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : TermElabM Unit := do let grSize := preDefs.size let _ ← preDefs.mapIdxM fun idx preDef => do @@ -357,7 +696,7 @@ def mkDeclareFixDefs (mutBody : Expr) (preDefs : Array PreDefinition) : -- Group the inputs into a dependent tuple let input ← mkSigmas xs.toList -- Apply the fixed point - let fixedBody ← mkAppM ``FixI.fix #[mutBody, idx, input] + let fixedBody ← mkAppM ``FixI.fix #[mutRecBody, idx, input] let fixedBody ← mkLambdaFVars xs fixedBody -- Create the declaration let name := preDef.declName @@ -454,24 +793,26 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- Introduce the continuation `k` let in_ty ← mkLambdaFVars #[i_var] in_ty let out_ty ← mkLambdaFVars #[i_var, input] out_ty - let k_var_ty ← mkAppM ``FixI.kk_ty #[i_var_ty, in_ty, out_ty] -- - trace[Diverge.def] "k_var_ty: {k_var_ty}" - withLocalDeclD (.num (.str .anonymous "k") 2) k_var_ty fun k_var => do - trace[Diverge.def] "k_var: {k_var}" + let kk_var_ty ← mkAppM ``FixI.kk_ty #[i_var_ty, in_ty, out_ty] + trace[Diverge.def] "kk_var_ty: {kk_var_ty}" + withLocalDeclD (.num (.str .anonymous "kk") 2) kk_var_ty fun kk_var => do + trace[Diverge.def] "kk_var: {kk_var}" -- Replace the recursive calls in all the function bodies by calls to the -- continuation `k` and and generate for those bodies declarations - let bodies ← mkDeclareUnaryBodies grLvlParams k_var preDefs + let bodies ← mkDeclareUnaryBodies grLvlParams kk_var preDefs -- Generate the mutually recursive body - let body ← mkDeclareMutualBody grName grLvlParams i_var k_var in_ty out_ty inOutTys.toList bodies - trace[Diverge.def] "mut rec body (after decl): {body}" + let (bodyFuns, mutRecBody) ← mkDeclareMutRecBody grName grLvlParams kk_var i_var in_ty out_ty inOutTys.toList bodies + trace[Diverge.def] "mut rec body (after decl): {mutRecBody}" -- Prove that the mut rec body satisfies the validity criteria required by -- our fixed-point - -- TODO + let k_var_ty ← mkAppM ``FixI.k_ty #[i_var_ty, in_ty, out_ty] + withLocalDeclD (.num (.str .anonymous "k") 3) k_var_ty fun k_var => do + let isValidThm ← proveMutRecIsValid grName grLvlParams inOutTysExpr bodyFuns mutRecBody k_var preDefs bodies -- Generate the final definitions - let defs ← mkDeclareFixDefs body preDefs + let defs ← mkDeclareFixDefs mutRecBody preDefs -- Prove the unfolding equations -- TODO @@ -496,13 +837,10 @@ def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := withLC for preDefs in cliques do trace[Diverge.elab] "{preDefs.map (·.declName)}" try - trace[Diverge.elab] "calling divRecursion" withRef (preDefs[0]!.ref) do divRecursion preDefs - trace[Diverge.elab] "divRecursion succeeded" catch ex => - -- If it failed, we - trace[Diverge.elab] "divRecursion failed" + -- If it failed, we add the functions as partial functions hasErrors := true logException ex let s ← saveState @@ -600,7 +938,8 @@ divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := else return (← list_nth ls (i - 1)) #print list_nth.in_out_ty -#check list_nth.body +#check list_nth.sbody +#check list_nth.mut_rec_body #print list_nth mutual diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index 82f79f94..281dbd6c 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -8,6 +8,7 @@ initialize registerTraceClass `Diverge.elab initialize registerTraceClass `Diverge.def initialize registerTraceClass `Diverge.def.sigmas initialize registerTraceClass `Diverge.def.genBody +initialize registerTraceClass `Diverge.def.valid -- TODO: move -- TODO: small helper -- cgit v1.2.3 From 7ceab6a725e5bd17c05bfd381753e453b15afaf7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 3 Jul 2023 16:46:59 +0200 Subject: Add a missing case in the validity proofs --- backends/lean/Base/Diverge/Elab.lean | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index cf40ea8f..063480a2 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -378,17 +378,22 @@ mutual partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do trace[Diverge.def.valid] "proveValid: {e}" match e with + | .const _ _ => throwError "Unimplemented" -- Shouldn't get there? | .bvar _ | .fvar _ - | .mvar _ - | .sort _ | .lit _ - | .const _ _ => throwError "Unimplemented" + | .mvar _ + | .sort _ => throwError "Unreachable" | .lam .. => throwError "Unimplemented" | .forallE .. => throwError "Unreachable" -- Shouldn't get there - | .letE .. => throwError "TODO" - -- lambdaLetTelescope e fun xs b => mapVisitBinders xs do - -- mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) + | .letE dName dTy dValue body _nonDep => do + -- Introduce a local declaration for the let-binding + withLetDecl dName dTy dValue fun decl => do + let isValid ← proveExprIsValid k_var kk_var body + -- Add the let-binding around (rem.: the let-binding should be + -- *inside* the `is_valid_p`, not outside, but because it reduces + -- in the end it doesn't matter) + mkLetFVars #[decl] isValid | .mdata _ b => proveExprIsValid k_var kk_var b | .proj _ _ _ => -- The projection shouldn't use the continuation @@ -963,4 +968,12 @@ mutual if i > 20 then foo (i / 20) else .ret 42 end +-- Testing dependent branching and let-bindings +-- TODO: why the linter warning? +divergent def is_non_zero (i : Int) : Result Bool := + if _h:i = 0 then return false + else + let b := true + return b + end Diverge -- cgit v1.2.3 From 9214484c471ad931924865855687f9a2ffe255dd Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 3 Jul 2023 18:02:52 +0200 Subject: Automate the proofs of the unfolding theorems for Diverge --- backends/lean/Base/Diverge/Elab.lean | 107 +++++++++++++++++++++++++------ backends/lean/Base/Diverge/ElabBase.lean | 1 + 2 files changed, 89 insertions(+), 19 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 063480a2..91c51a31 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -16,8 +16,9 @@ syntax (name := divergentDef) open Lean Elab Term Meta Primitives Lean.Meta set_option trace.Diverge.def true -set_option trace.Diverge.def.valid true +-- set_option trace.Diverge.def.valid true -- set_option trace.Diverge.def.sigmas true +set_option trace.Diverge.def.unfold true /- The following was copied from the `wfRecursion` function. -/ @@ -390,9 +391,10 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do -- Introduce a local declaration for the let-binding withLetDecl dName dTy dValue fun decl => do let isValid ← proveExprIsValid k_var kk_var body - -- Add the let-binding around (rem.: the let-binding should be - -- *inside* the `is_valid_p`, not outside, but because it reduces - -- in the end it doesn't matter) + -- Add the let-binding around. + -- Rem.: the let-binding should be *inside* the `is_valid_p`, not outside, + -- but because it reduces in the end it doesn't matter. More precisely: + -- `P (let x := v in y)` and `let x := v in P y` reduce to the same expression. mkLetFVars #[decl] isValid | .mdata _ b => proveExprIsValid k_var kk_var b | .proj _ _ _ => @@ -692,9 +694,9 @@ def proveMutRecIsValid -- Generate the final definions by using the mutual body and the fixed point operator. def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : - TermElabM Unit := do + TermElabM (Array Name) := do let grSize := preDefs.size - let _ ← preDefs.mapIdxM fun idx preDef => do + let defs ← preDefs.mapIdxM fun idx preDef => do lambdaLetTelescope preDef.value fun xs _ => do -- Create the index let idx ← mkFinVal grSize idx.val @@ -715,7 +717,58 @@ def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : all := [name] } addDecl decl - pure () + pure name + pure defs + +-- Prove the equations that we will use as unfolding theorems +partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinition) + (decls : Array Name) : MetaM Unit := do + let grSize := preDefs.size + let proveIdx (i : Nat) : MetaM Unit := do + let preDef := preDefs.get! i + let defName := decls.get! i + -- Retrieve the arguments + lambdaLetTelescope preDef.value fun xs body => do + trace[Diverge.def.unfold] "proveUnfoldingThms: xs: {xs}" + trace[Diverge.def.unfold] "proveUnfoldingThms: body: {body}" + -- The theorem statement + let thmTy ← do + -- The equation: the declaration gives the lhs, the pre-def gives the rhs + let lhs ← mkAppOptM defName (xs.map some) + let rhs := body + let eq ← mkAppM ``Eq #[lhs, rhs] + mkForallFVars xs eq + trace[Diverge.def.unfold] "proveUnfoldingThms: thm statement: {thmTy}" + -- The proof + -- Use the fixed-point equation + let proof ← mkAppM ``FixI.is_valid_fix_fixed_eq #[isValidThm] + -- Add the index + let idx ← mkFinVal grSize i + let proof ← mkAppM ``congr_fun #[proof, idx] + -- Add the input argument + let arg ← mkSigmas xs.toList + let proof ← mkAppM ``congr_fun #[proof, arg] + -- Abstract the arguments away + let proof ← mkLambdaFVars xs proof + trace[Diverge.def.unfold] "proveUnfoldingThms: proof: {proof}:\n{← inferType proof}" + -- Declare the theorem + let name := preDef.declName ++ "unfold" + let decl := Declaration.thmDecl { + name + levelParams := preDef.levelParams + type := thmTy + value := proof + all := [name] + } + addDecl decl + trace[Diverge.def.unfold] "proveUnfoldingThms: added thm: {name}:\n{thmTy}" + let rec prove (i : Nat) : MetaM Unit := do + if i = preDefs.size then pure () + else do + proveIdx i + prove (i + 1) + -- + prove 0 def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) @@ -817,12 +870,12 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let isValidThm ← proveMutRecIsValid grName grLvlParams inOutTysExpr bodyFuns mutRecBody k_var preDefs bodies -- Generate the final definitions - let defs ← mkDeclareFixDefs mutRecBody preDefs + let decls ← mkDeclareFixDefs mutRecBody preDefs - -- Prove the unfolding equations - -- TODO + -- Prove the unfolding theorems + proveUnfoldingThms isValidThm preDefs decls - -- Process the definitions + -- Process the definitions - TODO addAndCompilePartialRec preDefs -- The following function is copy&pasted from Lean.Elab.PreDefinition.Main @@ -942,10 +995,23 @@ divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := if i = 0 then return x else return (← list_nth ls (i - 1)) -#print list_nth.in_out_ty -#check list_nth.sbody -#check list_nth.mut_rec_body -#print list_nth +example {a: Type} (ls : List a) : + ∀ (i : Int), + 0 ≤ i → i < ls.length → + ∃ x, list_nth ls i = .ret x := by + induction ls + . intro i hpos h; simp at h; linarith + . rename_i hd tl ih + intro i hpos h + rw [list_nth.unfold]; simp + split <;> simp [*] + . tauto + . -- TODO: we shouldn't have to do that + have hneq : 0 < i := by cases i <;> rename_i a _ <;> simp_all; cases a <;> simp_all + simp at h + have ⟨ x, ih ⟩ := ih (i - 1) (by linarith) (by linarith) + simp [ih] + tauto mutual divergent def is_even (i : Int) : Result Bool := @@ -955,10 +1021,8 @@ mutual if i = 0 then return false else return (← is_even (i - 1)) end -example (i : Int) : is_even i = .ret (i % 2 = 0) ∧ is_odd i = .ret (i % 2 ≠ 0) := by - induction i - unfold is_even - sorry +#print is_even.unfold +#print is_odd.unfold mutual divergent def foo (i : Int) : Result Nat := @@ -968,6 +1032,9 @@ mutual if i > 20 then foo (i / 20) else .ret 42 end +#print foo.unfold +#print bar.unfold + -- Testing dependent branching and let-bindings -- TODO: why the linter warning? divergent def is_non_zero (i : Int) : Result Bool := @@ -976,4 +1043,6 @@ divergent def is_non_zero (i : Int) : Result Bool := let b := true return b +#print is_non_zero.unfold + end Diverge diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index 281dbd6c..fd95291e 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -9,6 +9,7 @@ initialize registerTraceClass `Diverge.def initialize registerTraceClass `Diverge.def.sigmas initialize registerTraceClass `Diverge.def.genBody initialize registerTraceClass `Diverge.def.valid +initialize registerTraceClass `Diverge.def.unfold -- TODO: move -- TODO: small helper -- cgit v1.2.3 From 75fae6384716f24fe137283d4a41836782b9aec7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 3 Jul 2023 19:26:27 +0200 Subject: Cleanup a bit Diverge/Elab.lean --- backends/lean/Base/Diverge/Elab.lean | 366 +++++++++++++++++++---------------- 1 file changed, 197 insertions(+), 169 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 91c51a31..cc580265 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -15,39 +15,16 @@ syntax (name := divergentDef) open Lean Elab Term Meta Primitives Lean.Meta -set_option trace.Diverge.def true --- set_option trace.Diverge.def.valid true --- set_option trace.Diverge.def.sigmas true -set_option trace.Diverge.def.unfold true - /- The following was copied from the `wfRecursion` function. -/ open WF in -def mkList (xl : List Expr) (ty : Expr) : MetaM Expr := - match xl with - | [] => - mkAppOptM ``List.nil #[some ty] - | x :: tl => do - let tl ← mkList tl ty - mkAppOptM ``List.cons #[some ty, some x, some tl] - def mkProd (x y : Expr) : MetaM Expr := mkAppM ``Prod.mk #[x, y] def mkInOutTy (x y : Expr) : MetaM Expr := mkAppM ``FixI.mk_in_out_ty #[x, y] --- TODO: is there already such a utility somewhere? --- TODO: change to mkSigmas -def mkProds (tys : List Expr) : MetaM Expr := - match tys with - | [] => do pure (Expr.const ``PUnit.unit []) - | [ty] => do pure ty - | ty :: tys => do - let pty ← mkProds tys - mkAppM ``Prod.mk #[ty, pty] - -- Return the `a` in `Return a` def get_result_ty (ty : Expr) : MetaM Expr := ty.withApp fun f args => do @@ -56,26 +33,31 @@ def get_result_ty (ty : Expr) : MetaM Expr := else pure (args.get! 0) --- Group a list of expressions into a dependent tuple -def mkSigmas (xl : List Expr) : MetaM Expr := +/- Group a list of expressions into a dependent tuple. + + Example: + xl = [`a : Type`, `ls : List a`] + returns: + `⟨ (a:Type), (ls: List a) ⟩` + -/ +def mkSigmasVal (xl : List Expr) : MetaM Expr := match xl with | [] => do - trace[Diverge.def.sigmas] "mkSigmas: []" + trace[Diverge.def.sigmas] "mkSigmasVal: []" pure (Expr.const ``PUnit.unit []) | [x] => do - trace[Diverge.def.sigmas] "mkSigmas: [{x}]" + trace[Diverge.def.sigmas] "mkSigmasVal: [{x}]" pure x | fst :: xl => do - trace[Diverge.def.sigmas] "mkSigmas: [{fst}::{xl}]" + trace[Diverge.def.sigmas] "mkSigmasVal: [{fst}::{xl}]" let alpha ← Lean.Meta.inferType fst - let snd ← mkSigmas xl + let snd ← mkSigmasVal xl let snd_ty ← inferType snd let beta ← mkLambdaFVars #[fst] snd_ty - trace[Diverge.def.sigmas] "mkSigmas:\n{alpha}\n{beta}\n{fst}\n{snd}" + trace[Diverge.def.sigmas] "mkSigmasVal:\n{alpha}\n{beta}\n{fst}\n{snd}" mkAppOptM ``Sigma.mk #[some alpha, some beta, some fst, some snd] -/- Generate the input type of a function body, which is a sigma type (i.e., a - dependent tuple) which groups all its inputs. +/- Generate a Sigma type from a list of expressions. Example: - xl = [(a:Type), (ls:List a), (i:Int)] @@ -84,7 +66,7 @@ def mkSigmas (xl : List Expr) : MetaM Expr := `(a:Type) × (ls:List a) × (i:Int)` -/ -def mkSigmasTypesOfTypes (xl : List Expr) : MetaM Expr := +def mkSigmasType (xl : List Expr) : MetaM Expr := match xl with | [] => do trace[Diverge.def.sigmas] "mkSigmasOfTypes: []" @@ -96,15 +78,16 @@ def mkSigmasTypesOfTypes (xl : List Expr) : MetaM Expr := | x :: xl => do trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}::{xl}]" let alpha ← Lean.Meta.inferType x - let sty ← mkSigmasTypesOfTypes xl + let sty ← mkSigmasType xl trace[Diverge.def.sigmas] "mkSigmasOfTypes: [{x}::{xl}]: alpha={alpha}, sty={sty}" let beta ← mkLambdaFVars #[x] sty trace[Diverge.def.sigmas] "mkSigmasOfTypes: ({alpha}) ({beta})" mkAppOptM ``Sigma #[some alpha, some beta] -def mk_indexed_name (index : Nat) : Name := .num (.str .anonymous "_uniq") index +def mkAnonymous (s : String) (i : Nat) : Name := + .num (.str .anonymous s) i -/- Given a list of values `[x0:ty0, ..., xn:ty1]` where every `xi` might use the previous +/- Given a list of values `[x0:ty0, ..., xn:ty1]`, where every `xi` might use the previous `xj` (j < i) and a value `out` which uses `x0`, ..., `xn`, generate the following expression: ``` @@ -112,20 +95,22 @@ def mk_indexed_name (index : Nat) : Name := .num (.str .anonymous "_uniq") index match x with | (x0, ..., xn) => out ``` - + The `index` parameter is used for naming purposes: we use it to numerotate the bound variables that we introduce. + We use this function to currify functions (the function bodies given to the + fixed-point operator must be unary functions). + Example: ======== - More precisely: - xl = `[a:Type, ls:List a, i:Int]` - out = `a` - index = 0 - generates: + generates (getting rid of most of the syntactic sugar): ``` - match scrut0 with + λ scrut0 => match scrut0 with | Sigma.mk x scrut1 => match scrut1 with | Sigma.mk ls i => @@ -138,21 +123,30 @@ partial def mkSigmasMatch (xl : List Expr) (out : Expr) (index : Nat := 0) : Met -- This would be unexpected throwError "mkSigmasMatch: empyt list of input parameters" | [x] => do - -- In the explanations above: inner match case + -- In the example given for the explanations: this is the inner match case trace[Diverge.def.sigmas] "mkSigmasMatch: [{x}]" mkLambdaFVars #[x] out | fst :: xl => do - -- In the explanations above: outer match case + -- In the example given for the explanations: this is the outer match case -- Remark: for the naming purposes, we use the same convention as for the - -- fields and parameters in `Sigma.casesOn and `Sigma.mk + -- fields and parameters in `Sigma.casesOn` and `Sigma.mk` (looking at + -- those definitions might help) + -- + -- We want to build the match expression: + -- ``` + -- λ scrut => + -- match scrut with + -- | Sigma.mk x ... -- the hole is given by a recursive call on the tail + -- ``` trace[Diverge.def.sigmas] "mkSigmasMatch: [{fst}::{xl}]" let alpha ← Lean.Meta.inferType fst - let snd_ty ← mkSigmasTypesOfTypes xl + let snd_ty ← mkSigmasType xl let beta ← mkLambdaFVars #[fst] snd_ty let snd ← mkSigmasMatch xl out (index + 1) - let scrut_ty ← mkSigmasTypesOfTypes (fst :: xl) - withLocalDeclD (mk_indexed_name index) scrut_ty fun scrut => do let mk ← mkLambdaFVars #[fst] snd + -- Introduce the "scrut" variable + let scrut_ty ← mkSigmasType (fst :: xl) + withLocalDeclD (mkAnonymous "scrut" index) scrut_ty fun scrut => do trace[Diverge.def.sigmas] "mkSigmasMatch: scrut: ({scrut}) : ({← inferType scrut})" -- TODO: make the computation of the motive more efficient let motive ← do @@ -166,38 +160,32 @@ partial def mkSigmasMatch (xl : List Expr) (out : Expr) (index : Nat := 0) : Met -- TODO: make this more efficient (we could change the output type of -- mkSigmasMatch mkSigmasMatch (fst :: xl) out_ty + -- The final expression: putting everything together trace[Diverge.def.sigmas] "mkSigmasMatch:\n ({alpha})\n ({beta})\n ({motive})\n ({scrut})\n ({mk})" let sm ← mkAppOptM ``Sigma.casesOn #[some alpha, some beta, some motive, some scrut, some mk] + -- Abstracting the "scrut" variable let sm ← mkLambdaFVars #[scrut] sm trace[Diverge.def.sigmas] "mkSigmasMatch: sm: {sm}" pure sm /- Small tests for list_nth: give a model of what `mkSigmasMatch` should generate -/ -private def list_nth_out_ty2 (a :Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) := +private def list_nth_out_ty_inner (a :Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) := @Sigma.casesOn (List a) (fun (_ls : List a) => Int) (fun (_scrut1:@Sigma (List a) (fun (_ls : List a) => Int)) => Type) scrut1 (fun (_ls : List a) (_i : Int) => Diverge.Primitives.Result a) -private def list_nth_out_ty1 (scrut0 : @Sigma (Type) (fun (a:Type) => +private def list_nth_out_ty_outer (scrut0 : @Sigma (Type) (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int))) := @Sigma.casesOn (Type) (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int)) (fun (_scrut0:@Sigma (Type) (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int))) => Type) scrut0 (fun (a : Type) (scrut1: @Sigma (List a) (fun (_ls : List a) => Int)) => - list_nth_out_ty2 a scrut1) + list_nth_out_ty_inner a scrut1) /- -/ --- TODO: move --- TODO: we can use Array.mapIdx -@[specialize] def mapiAux (i : Nat) (f : Nat → α → β) : List α → List β - | [] => [] - | a::as => f i a :: mapiAux (i+1) f as - -@[specialize] def mapi (f : Nat → α → β) : List α → List β := mapiAux 0 f - -- Return the expression: `Fin n` -- TODO: use more def mkFin (n : Nat) : Expr := @@ -212,15 +200,6 @@ def mkFinVal (n i : Nat) : MetaM Expr := do let ofNat ← mkAppOptM ``Fin.instOfNatFinHAddNatInstHAddInstAddNatOfNat #[n_lit, i_lit] mkAppOptM ``OfNat.ofNat #[none, none, ofNat] --- TODO: remove? -def mkFinValOld (n i : Nat) : MetaM Expr := do - let finTy := mkFin n - let ofNat ← mkAppM ``OfNat #[finTy, .lit (.natVal i)] - match ← trySynthInstance ofNat with - | LOption.some x => - mkAppOptM ``OfNat.ofNat #[none, none, x] - | _ => throwError "mkFinVal: could not synthesize an instance of {ofNat} " - /- Generate and declare as individual definitions the bodies for the individual funcions: - replace the recursive calls with calls to the continutation `k` - make those bodies take one single dependent tuple as input @@ -234,11 +213,11 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) let grSize := preDefs.size -- Compute the map from name to index - the continuation has an indexed type: - -- we use the index (a finite number of type `Fin`) to control the function - -- we call at the recursive call + -- we use the index (a finite number of type `Fin`) to control which function + -- we call at the recursive call site. let nameToId : HashMap Name Nat := - let namesIds := mapi (fun i d => (d.declName, i)) preDefs.toList - HashMap.ofList namesIds + let namesIds := preDefs.mapIdx (fun i d => (d.declName, i.val)) + HashMap.ofList namesIds.toList trace[Diverge.def.genBody] "nameToId: {nameToId.toList}" @@ -260,7 +239,7 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) -- Compute the index let i ← mkFinVal grSize id -- Put the arguments in one big dependent tuple - let args ← mkSigmas args.toList + let args ← mkSigmasVal args.toList mkAppM' kk_var #[i, args] else -- Not a recursive call: do nothing @@ -277,13 +256,14 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) -- Replace the recursive calls let body ← mapVisit visit_e preDef.value - -- Change the type + -- Currify the function by grouping the arguments into a dependent tuple + -- (over which we match to retrieve the individual arguments). lambdaLetTelescope body fun args body => do let body ← mkSigmasMatch args.toList body 0 -- Add the declaration let value ← mkLambdaFVars #[kk_var] body - let name := preDef.declName.append "sbody" + let name := preDef.declName.append "body" let levelParams := grLvlParams let decl := Declaration.defnDecl { name := name @@ -304,7 +284,7 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) -- Generate a unique function body from the bodies of the mutually recursive group, -- and add it as a declaration in the context. --- We return the list of bodies (of type `Funs ...`) and the mutually recursive body. +-- We return the list of bodies (of type `FixI.Funs ...`) and the mutually recursive body. def mkDeclareMutRecBody (grName : Name) (grLvlParams : List Name) (kk_var i_var : Expr) (in_ty out_ty : Expr) (inOutTys : List (Expr × Expr)) @@ -322,7 +302,7 @@ def mkDeclareMutRecBody (grName : Name) (grLvlParams : List Name) mkAppOptM ``FixI.Funs.Nil #[finTypeExpr, in_ty, out_ty] | (ity, oty) :: inOutTys, b :: bl => do -- Retrieving ity and oty - this is not very clean - let inOutTysExpr ← mkList (← inOutTys.mapM (λ (x, y) => mkInOutTy x y)) inOutTyType + let inOutTysExpr ← mkListLit inOutTyType (← inOutTys.mapM (λ (x, y) => mkInOutTy x y)) let fl ← mkFuns inOutTys bl mkAppOptM ``FixI.Funs.Cons #[finTypeExpr, in_ty, out_ty, ity, oty, inOutTysExpr, b, fl] | _, _ => throwError "mkDeclareMutRecBody: `tys` and `bodies` don't have the same length" @@ -345,7 +325,7 @@ def mkDeclareMutRecBody (grName : Name) (grLvlParams : List Name) all := [name] } addDecl decl - -- Return the constant + -- Return the bodies and the constant pure (bodyFuns, Lean.mkConst name (levelParams.map .param)) def isCasesExpr (e : Expr) : MetaM Bool := do @@ -367,7 +347,8 @@ instance : ToMessageData MatchInfo where -- This is not a very clean formatting, but we don't need more toMessageData := fun me => m!"\n- matcherName: {me.matcherName}\n- params: {me.params}\n- motive: {me.motive}\n- scruts: {me.scruts}\n- branchesNumParams: {me.branchesNumParams}\n- branches: {me.branches}" --- An expression which doesn't use the continuation kk is valid +-- Small helper: prove that an expression which doesn't use the continuation `kk` +-- is valid, and return the proof. def proveNoKExprIsValid (k_var : Expr) (e : Expr) : MetaM Expr := do trace[Diverge.def.valid] "proveNoKExprIsValid: {e}" let eIsValid ← mkAppM ``FixI.is_valid_p_same #[k_var, e] @@ -376,6 +357,14 @@ def proveNoKExprIsValid (k_var : Expr) (e : Expr) : MetaM Expr := do mutual +/- Prove that an expression is valid, and return the proof. + + More precisely, if `e` is an expression which potentially uses the continution + `kk`, return an expression of type: + ``` + is_valid_p k (λ kk => e) + ``` + -/ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do trace[Diverge.def.valid] "proveValid: {e}" match e with @@ -403,7 +392,9 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do | .app .. => e.withApp fun f args => do -- There are several cases: first, check if this is a match/if - -- The expression is a (dependent) if then else + -- Check if the expression is a (dependent) if then else. + -- We treat the if then else expressions differently from the other matches, + -- and have dedicated theorems for them. let isIte := e.isIte if isIte || e.isDIte then do e.withApp fun f args => do @@ -431,9 +422,9 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do let eIsValid ← mkAppOptM const #[none, none, none, none, some k_var, some cond, some dec, none, none, some br0Valid, some br1Valid] trace[Diverge.def.valid] "ite/dite: result:\n{eIsValid}:\n{← inferType eIsValid}" pure eIsValid - -- The expression is a match (this case is for when the elaborator + -- Check if the expression is a match (this case is for when the elaborator -- introduces auxiliary definitions to hide the match behind syntactic - -- sugar) + -- sugar): else if let some me := ← matchMatcherApp? e then do trace[Diverge.def.valid] "matcherApp: @@ -443,7 +434,8 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do - altNumParams: {me.altNumParams} - alts: {me.alts} - remaining: {me.remaining}" - -- matchMatcherApp has already done the work for us + -- matchMatcherApp does all the work for us: we simply need to gather + -- the information and call the auxiliary helper `proveMatchIsValid` if me.remaining.size ≠ 0 then throwError "MatcherApp: non empty remaining array: {me.remaining}" let me : MatchInfo := { @@ -456,14 +448,21 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do branches := me.alts } proveMatchIsValid k_var kk_var me - -- The expression is a raw match (this case is for when the expression - -- is a direct call to the primitive `casesOn` function, without - -- syntactic sugar) + -- Check if the expression is a raw match (this case is for when the expression + -- is a direct call to the primitive `casesOn` function, without syntactic sugar). + -- We have to check this case because functions like `mkSigmasMatch`, which we + -- use to currify function bodies, introduce such raw matches. else if ← isCasesExpr f then do trace[Diverge.def.valid] "rawMatch: {e}" + -- Deconstruct the match, and call the auxiliary helper `proveMatchIsValid`. + -- -- The casesOn definition is always of the following shape: - -- input parameters (implicit parameters), then motive (implicit), - -- scrutinee (explicit), branches (explicit). + -- - input parameters (implicit parameters) + -- - motive (implicit), -- the motive gives the return type of the match + -- - scrutinee (explicit) + -- - branches (explicit). + -- In particular, we notice that the scrutinee is the first *explicit* + -- parameter - this is how we spot it. let matcherName := f.constName! let matcherLevels := f.constLevels!.toArray -- Find the first explicit parameter: this is the scrutinee @@ -484,7 +483,9 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do let scrut := args.get! scrutIdx let branches := args.extract (scrutIdx + 1) args.size -- Compute the number of parameters for the branches: for this we use - -- the type of the uninstantiated casesOn constant + -- the type of the uninstantiated casesOn constant (we can't just + -- destruct the lambdas in the branch expressions because the result + -- of a match might be a lambda expression). let branchesNumParams : Array Nat ← do let env ← getEnv let decl := env.constants.find! matcherName @@ -505,9 +506,11 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do branches, } proveMatchIsValid k_var kk_var me - -- Monadic let-binding + -- Check if this is a monadic let-binding else if f.isConstOf ``Bind.bind then do trace[Diverge.def.valid] "bind:\n{args}" + -- We simply need to prove that the subexpressions are valid, and call + -- the appropriate lemma. let x := args.get! 4 let y := args.get! 5 -- Prove that the subexpressions are valid @@ -529,7 +532,7 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do -- Put everything together trace[Diverge.def.valid] "bind:\n- xValid: {xValid}: {← inferType xValid}\n- yValid: {yValid}: {← inferType yValid}" mkAppM ``FixI.is_valid_p_bind #[xValid, yValid] - -- Recursive call + -- Check if this is a recursive call, i.e., a call to the continuation `kk` else if f.isFVarOf kk_var.fvarId! then do trace[Diverge.def.valid] "rec: args: \n{args}" if args.size ≠ 2 then throwError "Recursive call with invalid number of parameters: {args}" @@ -540,9 +543,10 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do pure eIsValid else do -- Remaining case: normal application. - -- It shouldn't use the continuation + -- It shouldn't use the continuation. proveNoKExprIsValid k_var e +-- Prove that a match expression is valid. partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Expr := do trace[Diverge.def.valid] "proveMatchIsValid: {me}" -- Prove the validity of the branch expressions @@ -561,16 +565,18 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp -- Reconstruct the lambda expression mkLambdaFVars xs_beg brValid trace[Diverge.def.valid] "branchesValid:\n{branchesValid}" - -- Put together: compute the motive. - -- It must be of the shape: + -- Compute the motive, which has the following shape: -- ``` -- λ scrut => is_valid_p k (λ k => match scrut with ...) + -- ^^^^^^^^^^^^^^^^^^^^ + -- this is the original match expression, with the + -- the difference that the scrutinee(s) is a variable -- ``` let validMotive : Expr ← do -- The motive is a function of the scrutinees (i.e., a lambda expression): -- introduce binders for the scrutinees let declInfos := me.scruts.mapIdx fun idx scrut => - let name : Name := (.num (.str .anonymous "scrut") idx) + let name : Name := mkAnonymous "scrut" idx let ty := λ (_ : Array Expr) => inferType scrut (name, ty) withLocalDeclsD declInfos fun scrutVars => do @@ -582,7 +588,6 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp let branches : Array (Option Expr) := me.branches.map some let args := params ++ [motive] ++ scruts ++ branches let matchE ← mkAppOptM me.matcherName args - -- let matchE ← mkLambdaFVars scrutVars (← mkAppOptM me.matcherName args) -- Wrap in the `is_valid_p` predicate let matchE ← mkLambdaFVars #[kk_var] matchE let validMotive ← mkAppM ``FixI.is_valid_p #[k_var, matchE] @@ -591,6 +596,7 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp trace[Diverge.def.valid] "valid motive: {validMotive}" -- Put together let valid ← do + -- We let Lean infer the parameters let params : Array (Option Expr) := me.params.map (λ _ => none) let motive := some validMotive let scruts := me.scruts.map some @@ -602,12 +608,16 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp end --- Prove that a single body (in the mutually recursive group) is valid -partial def proveSingleBodyIsValid (k_var : Expr) (preDef : PreDefinition) (bodyConst : Expr) : +-- Prove that a single body (in the mutually recursive group) is valid. +-- +-- For instance, if we define the mutually recursive group [`is_even`, `is_odd`], +-- we prove that `is_even.body` and `is_odd.body` are valid. +partial def proveSingleBodyIsValid + (k_var : Expr) (preDef : PreDefinition) (bodyConst : Expr) : MetaM Expr := do trace[Diverge.def.valid] "proveSingleBodyIsValid: bodyConst: {bodyConst}" - -- Lookup the definition (`bodyConst` is the definition of the body, we want - -- to retrieve the value itself to dive inside) + -- Lookup the definition (`bodyConst` is a const, we want to retrieve its + -- definition to dive inside) let name := bodyConst.constName! let env ← getEnv let body := (env.constants.find! name).value! @@ -633,7 +643,7 @@ partial def proveSingleBodyIsValid (k_var : Expr) (preDef : PreDefinition) (body mkForallFVars #[k_var, x_var] ty trace[Diverge.def.valid] "proveSingleBodyIsValid: thmTy\n{thmTy}:\n{← inferType thmTy}" -- Save the theorem - let name := preDef.declName ++ "sbody_is_valid" + let name := preDef.declName ++ "body_is_valid" let decl := Declaration.thmDecl { name levelParams := preDef.levelParams @@ -646,6 +656,11 @@ partial def proveSingleBodyIsValid (k_var : Expr) (preDef : PreDefinition) (body -- Return the theorem pure (Expr.const name (preDef.levelParams.map .param)) +-- Prove that the list of bodies are valid. +-- +-- For instance, if we define the mutually recursive group [`is_even`, `is_odd`], +-- we prove that `Funs.Cons is_even.body (Funs.Cons is_odd.body Funs.Nil)` is +-- valid. partial def proveFunsBodyIsValid (inOutTys: Expr) (bodyFuns : Expr) (k_var : Expr) (bodiesValid : Array Expr) : MetaM Expr := do -- Create the big "and" expression, which groups the validity proof of the individual bodies @@ -663,7 +678,13 @@ partial def proveFunsBodyIsValid (inOutTys: Expr) (bodyFuns : Expr) let isValid ← mkAppM ``FixI.Funs.is_valid_p_is_valid_p #[inOutTys, k_var, bodyFuns, andExpr] mkLambdaFVars #[k_var] isValid --- Prove that the mut rec body is valid +-- Prove that the mut rec body (i.e., the unary body which groups the bodies +-- of all the functions in the mutually recursive group and on which we will +-- apply the fixed-point operator) is valid. +-- +-- We save the proof in the theorem "[GROUP_NAME]."mut_rec_body_is_valid", +-- which we return. +-- -- TODO: maybe this function should introduce k_var itself def proveMutRecIsValid (grName : Name) (grLvlParams : List Name) @@ -693,6 +714,12 @@ def proveMutRecIsValid pure (Expr.const name (grLvlParams.map .param)) -- Generate the final definions by using the mutual body and the fixed point operator. +-- +-- For instance: +-- ``` +-- def is_even (i : Int) : Result Bool := mut_rec_body 0 i +-- def is_odd (i : Int) : Result Bool := mut_rec_body 1 i +-- ``` def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : TermElabM (Array Name) := do let grSize := preDefs.size @@ -701,7 +728,7 @@ def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : -- Create the index let idx ← mkFinVal grSize idx.val -- Group the inputs into a dependent tuple - let input ← mkSigmas xs.toList + let input ← mkSigmasVal xs.toList -- Apply the fixed point let fixedBody ← mkAppM ``FixI.fix #[mutRecBody, idx, input] let fixedBody ← mkLambdaFVars xs fixedBody @@ -746,7 +773,7 @@ partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinitio let idx ← mkFinVal grSize i let proof ← mkAppM ``congr_fun #[proof, idx] -- Add the input argument - let arg ← mkSigmas xs.toList + let arg ← mkSigmasVal xs.toList let proof ← mkAppM ``congr_fun #[proof, arg] -- Abstract the arguments away let proof ← mkLambdaFVars xs proof @@ -774,11 +801,6 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) trace[Diverge.def] ("divRecursion: defs: " ++ msg) - -- CHANGE HERE This function should add definitions with these names/types/values ^^ - -- Temporarily add the predefinitions as axioms - -- for preDef in preDefs do - -- addAsAxiom preDef - -- TODO: what is this? for preDef in preDefs do applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation @@ -803,7 +825,7 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do if preDef.levelParams ≠ grLvlParams then throwError "Non-uniform polymorphism in the universes" forallTelescope preDef.type (fun in_tys out_ty => do - let in_ty ← liftM (mkSigmasTypesOfTypes in_tys.toList) + let in_ty ← liftM (mkSigmasType in_tys.toList) -- Retrieve the type in the "Result" let out_ty ← get_result_ty out_ty let out_ty ← liftM (mkSigmasMatch in_tys.toList out_ty) @@ -813,14 +835,14 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do trace[Diverge.def] "inOutTys: {inOutTys}" -- Turn the list of input/output type pairs into an expresion let inOutTysExpr ← inOutTys.mapM (λ (x, y) => mkInOutTy x y) - let inOutTysExpr ← mkList inOutTysExpr.toList (← inferType (inOutTysExpr.get! 0)) + let inOutTysExpr ← mkListLit (← inferType (inOutTysExpr.get! 0)) inOutTysExpr.toList -- From the list of pairs of input/output types, actually compute the -- type of the continuation `k`. -- We first introduce the index `i : Fin n` where `n` is the number of -- functions in the group. let i_var_ty := mkFin preDefs.size - withLocalDeclD (.num (.str .anonymous "i") 0) i_var_ty fun i_var => do + withLocalDeclD (mkAnonymous "i" 0) i_var_ty fun i_var => do let in_out_ty ← mkAppM ``List.get #[inOutTysExpr, i_var] trace[Diverge.def] "in_out_ty := {in_out_ty} : {← inferType in_out_ty}" -- Add an auxiliary definition for `in_out_ty` @@ -844,7 +866,7 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do trace[Diverge.def] "in_out_ty (after decl) := {in_out_ty} : {← inferType in_out_ty}" let in_ty ← mkAppM ``Sigma.fst #[in_out_ty] trace[Diverge.def] "in_ty: {in_ty}" - withLocalDeclD (.num (.str .anonymous "x") 1) in_ty fun input => do + withLocalDeclD (mkAnonymous "x" 1) in_ty fun input => do let out_ty ← mkAppM' (← mkAppM ``Sigma.snd #[in_out_ty]) #[input] trace[Diverge.def] "out_ty: {out_ty}" @@ -853,7 +875,7 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let out_ty ← mkLambdaFVars #[i_var, input] out_ty let kk_var_ty ← mkAppM ``FixI.kk_ty #[i_var_ty, in_ty, out_ty] trace[Diverge.def] "kk_var_ty: {kk_var_ty}" - withLocalDeclD (.num (.str .anonymous "kk") 2) kk_var_ty fun kk_var => do + withLocalDeclD (mkAnonymous "kk" 2) kk_var_ty fun kk_var => do trace[Diverge.def] "kk_var: {kk_var}" -- Replace the recursive calls in all the function bodies by calls to the @@ -866,7 +888,7 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- Prove that the mut rec body satisfies the validity criteria required by -- our fixed-point let k_var_ty ← mkAppM ``FixI.k_ty #[i_var_ty, in_ty, out_ty] - withLocalDeclD (.num (.str .anonymous "k") 3) k_var_ty fun k_var => do + withLocalDeclD (mkAnonymous "k" 3) k_var_ty fun k_var => do let isValidThm ← proveMutRecIsValid grName grLvlParams inOutTysExpr bodyFuns mutRecBody k_var preDefs bodies -- Generate the final definitions @@ -915,7 +937,7 @@ def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := withLC else return () catch _ => s.restore --- The following two functions are copy&pasted from Lean.Elab.MutualDef +-- The following two functions are copy-pasted from Lean.Elab.MutualDef open private elabHeaders levelMVarToParamHeaders getAllUserLevelNames withFunLocalDecls elabFunValues instantiateMVarsAtHeader instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes withUsed from Lean.Elab.MutualDef @@ -988,61 +1010,67 @@ elab_rules : command else Command.elabCommand <| ← `(namespace $(mkIdentFrom id ns) $cmd end $(mkIdentFrom id ns)) -divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := - match ls with - | [] => .fail .panic - | x :: ls => - if i = 0 then return x - else return (← list_nth ls (i - 1)) - -example {a: Type} (ls : List a) : - ∀ (i : Int), - 0 ≤ i → i < ls.length → - ∃ x, list_nth ls i = .ret x := by - induction ls - . intro i hpos h; simp at h; linarith - . rename_i hd tl ih - intro i hpos h - rw [list_nth.unfold]; simp - split <;> simp [*] - . tauto - . -- TODO: we shouldn't have to do that - have hneq : 0 < i := by cases i <;> rename_i a _ <;> simp_all; cases a <;> simp_all - simp at h - have ⟨ x, ih ⟩ := ih (i - 1) (by linarith) (by linarith) - simp [ih] - tauto - -mutual - divergent def is_even (i : Int) : Result Bool := - if i = 0 then return true else return (← is_odd (i - 1)) - - divergent def is_odd (i : Int) : Result Bool := - if i = 0 then return false else return (← is_even (i - 1)) -end - -#print is_even.unfold -#print is_odd.unfold - -mutual - divergent def foo (i : Int) : Result Nat := - if i > 10 then return (← foo (i / 10)) + (← bar i) else bar 10 - - divergent def bar (i : Int) : Result Nat := - if i > 20 then foo (i / 20) else .ret 42 -end - -#print foo.unfold -#print bar.unfold - --- Testing dependent branching and let-bindings --- TODO: why the linter warning? -divergent def is_non_zero (i : Int) : Result Bool := - if _h:i = 0 then return false - else - let b := true - return b +namespace Tests + /- Some examples of partial functions -/ + + divergent def list_nth {a: Type} (ls : List a) (i : Int) : Result a := + match ls with + | [] => .fail .panic + | x :: ls => + if i = 0 then return x + else return (← list_nth ls (i - 1)) + + #check list_nth.unfold + + example {a: Type} (ls : List a) : + ∀ (i : Int), + 0 ≤ i → i < ls.length → + ∃ x, list_nth ls i = .ret x := by + induction ls + . intro i hpos h; simp at h; linarith + . rename_i hd tl ih + intro i hpos h + rw [list_nth.unfold]; simp + split <;> simp [*] + . tauto + . -- TODO: we shouldn't have to do that + have hneq : 0 < i := by cases i <;> rename_i a _ <;> simp_all; cases a <;> simp_all + simp at h + have ⟨ x, ih ⟩ := ih (i - 1) (by linarith) (by linarith) + simp [ih] + tauto + + mutual + divergent def is_even (i : Int) : Result Bool := + if i = 0 then return true else return (← is_odd (i - 1)) + + divergent def is_odd (i : Int) : Result Bool := + if i = 0 then return false else return (← is_even (i - 1)) + end + + #check is_even.unfold + #check is_odd.unfold + + mutual + divergent def foo (i : Int) : Result Nat := + if i > 10 then return (← foo (i / 10)) + (← bar i) else bar 10 + + divergent def bar (i : Int) : Result Nat := + if i > 20 then foo (i / 20) else .ret 42 + end + + #check foo.unfold + #check bar.unfold + + -- Testing dependent branching and let-bindings + -- TODO: why the linter warning? + divergent def is_non_zero (i : Int) : Result Bool := + if _h:i = 0 then return false + else + let b := true + return b -#print is_non_zero.unfold + #check is_non_zero.unfold +end Tests end Diverge -- cgit v1.2.3 From 40e21034fa9e955734351b78a8cc5f16315418bd Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 12:13:09 +0200 Subject: Add an implemented_by attribute to fix --- backends/lean/Base/Diverge/Base.lean | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 89365d25..a8503107 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -57,6 +57,12 @@ deriving Repr, BEq open Result +instance Result_Inhabited (α : Type u) : Inhabited (Result α) := + Inhabited.mk (fail panic) + +instance Result_Nonempty (α : Type u) : Nonempty (Result α) := + Nonempty.intro div + def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := match x with | ret v => f v @@ -156,7 +162,14 @@ namespace Fix (x : a) (n : Nat) : Prop := fix_fuel_pred f x n - noncomputable + partial + def fixImpl (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : Result (b x) := + f (fixImpl f) x + + -- The fact that `fix` is implemented by `fixImpl` allows us to not mark the + -- functions defined with the fixed-point as noncomputable. One big advantage + -- is that it allows us to evaluate those functions, for instance with #eval. + @[implemented_by fixImpl] def fix (f : ((x:a) → Result (b x)) → (x:a) → Result (b x)) (x : a) : Result (b x) := fix_fuel (least (fix_fuel_P f x)) f x @@ -548,7 +561,7 @@ namespace FixI def is_valid (f : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) : Prop := ∀ k i x, is_valid_p k (λ k => f k i x) - noncomputable def fix + def fix (f : ((i:id) → (x:a i) → Result (b i x)) → (i:id) → (x:a i) → Result (b i x)) : (i:id) → (x:a i) → Result (b i x) := kk_of_gen (Fix.fix (k_to_gen f)) @@ -808,7 +821,6 @@ namespace Ex1 split <;> simp split <;> simp - noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) -- The unfolding equation - diverges if `i < 0` @@ -851,7 +863,6 @@ namespace Ex2 split <;> simp apply is_valid_p_bind <;> intros <;> simp_all - noncomputable def list_nth (ls : List a) (i : Int) : Result a := fix list_nth_body (ls, i) -- The unfolding equation - diverges if `i < 0` @@ -932,7 +943,6 @@ namespace Ex3 apply is_valid_p_bind; simp intros; split <;> simp - noncomputable def is_even (i : Int): Result Bool := do let r ← fix is_even_is_odd_body (.inl i) @@ -940,7 +950,6 @@ namespace Ex3 | .inl b => .ret b | .inr _ => .fail .panic - noncomputable def is_odd (i : Int): Result Bool := do let r ← fix is_even_is_odd_body (.inr i) @@ -1032,8 +1041,8 @@ namespace Ex4 theorem body_fix_eq : fix body = body (fix body) := is_valid_fix_fixed_eq body_is_valid - noncomputable def is_even (i : Int) : Result Bool := fix body 0 i - noncomputable def is_odd (i : Int) : Result Bool := fix body 1 i + def is_even (i : Int) : Result Bool := fix body 0 i + def is_odd (i : Int) : Result Bool := fix body 1 i theorem is_even_eq (i : Int) : is_even i = (if i = 0 @@ -1052,7 +1061,6 @@ namespace Ex4 .ret b) := by simp [is_even, is_odd]; conv => lhs; rw [body_fix_eq] - end Ex4 namespace Ex5 @@ -1109,7 +1117,7 @@ namespace Ex5 intro k x simp only [is_valid_p_same, is_valid_p_rec] - noncomputable def id (t : Tree a) := fix id_body t + def id (t : Tree a) := fix id_body t -- The unfolding equation theorem id_eq (t : Tree a) : @@ -1183,7 +1191,6 @@ namespace Ex6 Funs.is_valid_p_is_valid_p tys k bodies (And.intro (list_nth_body_is_valid' k) (Funs.is_valid_p_Nil k)) - noncomputable def list_nth {a: Type u} (ls : List a) (i : Int) : Result a := fix body 0 ⟨ a, ls , i ⟩ -- cgit v1.2.3 From 4fd17e4bb91eb46d4704643dfbfbbf0874837b07 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 12:49:37 +0200 Subject: Make Diverge use Primitives --- backends/lean/Base/Diverge/Base.lean | 65 +------------------------------- backends/lean/Base/Diverge/Elab.lean | 2 +- backends/lean/Base/Diverge/ElabBase.lean | 8 ++-- backends/lean/Base/Primitives.lean | 25 ++---------- 4 files changed, 10 insertions(+), 90 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index a8503107..e22eb914 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -4,8 +4,7 @@ import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith --- For debugging -import Base.Diverge.ElabBase +import Base.Primitives /- TODO: @@ -35,68 +34,6 @@ set_option profiler.threshold 100 namespace Diverge -namespace Primitives -/-! # Copy-pasting from Primitives to make the file self-contained -/ - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α - | div -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -instance Result_Nonempty (α : Type u) : Nonempty (Result α) := - Nonempty.intro div - -def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - | div => div - -@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] -@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] -@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : - (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : - (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_div (f : α → Result β) : - (do let y ← div; f y) = div := by simp [Bind.bind, bind] - -def div? {α: Type u} (r: Result α): Bool := - match r with - | div => true - | ret _ | fail _ => false - -end Primitives - namespace Fix open Primitives diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index cc580265..41209021 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -174,7 +174,7 @@ private def list_nth_out_ty_inner (a :Type) (scrut1: @Sigma (List a) (fun (_ls : (fun (_ls : List a) => Int) (fun (_scrut1:@Sigma (List a) (fun (_ls : List a) => Int)) => Type) scrut1 - (fun (_ls : List a) (_i : Int) => Diverge.Primitives.Result a) + (fun (_ls : List a) (_i : Int) => Primitives.Result a) private def list_nth_out_ty_outer (scrut0 : @Sigma (Type) (fun (a:Type) => @Sigma (List a) (fun (_ls : List a) => Int))) := diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index fd95291e..1c1062c0 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -4,6 +4,7 @@ namespace Diverge open Lean Elab Term Meta +-- We can't define and use trace classes in the same file initialize registerTraceClass `Diverge.elab initialize registerTraceClass `Diverge.def initialize registerTraceClass `Diverge.def.sigmas @@ -11,8 +12,8 @@ initialize registerTraceClass `Diverge.def.genBody initialize registerTraceClass `Diverge.def.valid initialize registerTraceClass `Diverge.def.unfold --- TODO: move --- TODO: small helper +-- Useful helper to explore definitions and figure out the variant +-- of their sub-expressions. def explore_term (incr : String) (e : Expr) : MetaM Unit := match e with | .bvar _ => do logInfo m!"{incr}bvar: {e}"; return () @@ -81,8 +82,7 @@ private def test2 (x : Nat) : Nat := x print_decl test1 print_decl test2 --- We adapted this from AbstractNestedProofs.visit --- A map visitor function for expressions +-- A map visitor function for expressions (adapted from `AbstractNestedProofs.visit`) partial def mapVisit (k : Expr → MetaM Expr) (e : Expr) : MetaM Expr := do let mapVisitBinders (xs : Array Expr) (k2 : MetaM Expr) : MetaM Expr := do let localInstances ← getLocalInstances diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 1185a07d..117f76a2 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -60,12 +60,12 @@ instance Result_Nonempty (α : Type u) : Nonempty (Result α) := /- HELPERS -/ -def ret? {α: Type} (r: Result α): Bool := +def ret? {α: Type u} (r: Result α): Bool := match r with | ret _ => true | fail _ | div => false -def div? {α: Type} (r: Result α): Bool := +def div? {α: Type u} (r: Result α): Bool := match r with | div => true | ret _ | fail _ => false @@ -73,14 +73,14 @@ def div? {α: Type} (r: Result α): Bool := def massert (b:Bool) : Result Unit := if b then ret () else fail assertionFailure -def eval_global {α: Type} (x: Result α) (_: ret? x): α := +def eval_global {α: Type u} (x: Result α) (_: ret? x): α := match x with | fail _ | div => by contradiction | ret x => x /- DO-DSL SUPPORT -/ -def bind (x: Result α) (f: α -> Result β) : Result β := +def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := match x with | ret v => f v | fail v => fail v @@ -111,23 +111,6 @@ def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := | fail e => fail e | div => div -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - @[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] -- cgit v1.2.3 From 87d6f6c7c90bf7b427397d6bd2e2c70d610678e3 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 14:57:51 +0200 Subject: Reorganize the Lean tests --- Makefile | 32 +- backends/lean/Base.lean | 1 - backends/lean/lake-manifest.json | 10 +- backends/lean/lean-toolchain | 2 +- compiler/Config.ml | 5 + compiler/Driver.ml | 6 + compiler/Extract.ml | 14 +- compiler/ExtractBase.ml | 10 + compiler/Translate.ml | 70 +- tests/lean/.gitignore | 4 +- tests/lean/BetreeMain.lean | 1 + tests/lean/BetreeMain/Funs.lean | 1071 ++++++++++++++++++++ tests/lean/BetreeMain/Opaque.lean | 31 + tests/lean/BetreeMain/Types.lean | 62 ++ tests/lean/Constants.lean | 132 +++ tests/lean/External.lean | 1 + tests/lean/External/Funs.lean | 88 ++ tests/lean/External/Opaque.lean | 28 + tests/lean/External/Types.lean | 11 + tests/lean/Hashmap.lean | 1 + tests/lean/Hashmap/Funs.lean | 474 +++++++++ tests/lean/Hashmap/Types.lean | 17 + tests/lean/HashmapMain.lean | 1 + tests/lean/HashmapMain/Funs.lean | 557 ++++++++++ tests/lean/HashmapMain/Opaque.lean | 16 + tests/lean/HashmapMain/Types.lean | 20 + tests/lean/Loops.lean | 1 + tests/lean/Loops/Funs.lean | 624 ++++++++++++ tests/lean/Loops/Types.lean | 10 + tests/lean/Makefile | 31 +- tests/lean/NoNestedBorrows.lean | 541 ++++++++++ tests/lean/Paper.lean | 125 +++ tests/lean/PoloniusList.lean | 33 + tests/lean/Tests.lean | 9 + tests/lean/hashmap/Base/Primitives.lean | 583 ----------- tests/lean/hashmap/Hashmap.lean | 1 - tests/lean/hashmap/Hashmap/Clauses/Clauses.lean | 107 -- tests/lean/hashmap/Hashmap/Clauses/Template.lean | 108 -- tests/lean/hashmap/Hashmap/Funs.lean | 513 ---------- tests/lean/hashmap/Hashmap/Types.lean | 16 - tests/lean/hashmap/lake-manifest.json | 27 - tests/lean/hashmap/lakefile.lean | 12 - tests/lean/hashmap/lean-toolchain | 1 - tests/lean/hashmap_on_disk/.gitignore | 5 - tests/lean/hashmap_on_disk/Base/Primitives.lean | 583 ----------- tests/lean/hashmap_on_disk/HashmapMain.lean | 1 - .../HashmapMain/Clauses/Clauses.lean | 110 -- .../HashmapMain/Clauses/Template.lean | 112 -- .../hashmap_on_disk/HashmapMain/ExternalFuns.lean | 5 - tests/lean/hashmap_on_disk/HashmapMain/Funs.lean | 590 ----------- tests/lean/hashmap_on_disk/HashmapMain/Opaque.lean | 15 - tests/lean/hashmap_on_disk/HashmapMain/Types.lean | 19 - tests/lean/hashmap_on_disk/lake-manifest.json | 27 - tests/lean/hashmap_on_disk/lakefile.lean | 12 - tests/lean/hashmap_on_disk/lean-toolchain | 1 - tests/lean/lake-manifest.json | 34 + tests/lean/lakefile.lean | 14 + tests/lean/lean-toolchain | 2 +- tests/lean/misc-constants/Base/Primitives.lean | 583 ----------- tests/lean/misc-constants/Constants.lean | 131 --- tests/lean/misc-constants/lake-manifest.json | 27 - tests/lean/misc-constants/lakefile.lean | 12 - tests/lean/misc-constants/lean-toolchain | 1 - tests/lean/misc-external/Base/Primitives.lean | 583 ----------- tests/lean/misc-external/External.lean | 1 - .../lean/misc-external/External/ExternalFuns.lean | 5 - tests/lean/misc-external/External/Funs.lean | 84 -- tests/lean/misc-external/External/Opaque.lean | 27 - tests/lean/misc-external/External/Types.lean | 10 - tests/lean/misc-external/lake-manifest.json | 27 - tests/lean/misc-external/lakefile.lean | 12 - tests/lean/misc-external/lean-toolchain | 1 - tests/lean/misc-loops/Base/Primitives.lean | 583 ----------- tests/lean/misc-loops/Loops.lean | 1 - tests/lean/misc-loops/Loops/Clauses/Clauses.lean | 205 ---- tests/lean/misc-loops/Loops/Clauses/Template.lean | 205 ---- tests/lean/misc-loops/Loops/Funs.lean | 705 ------------- tests/lean/misc-loops/Loops/Types.lean | 9 - tests/lean/misc-loops/lake-manifest.json | 27 - tests/lean/misc-loops/lakefile.lean | 12 - tests/lean/misc-loops/lean-toolchain | 1 - .../misc-no_nested_borrows/Base/Primitives.lean | 583 ----------- .../misc-no_nested_borrows/NoNestedBorrows.lean | 538 ---------- .../lean/misc-no_nested_borrows/lake-manifest.json | 27 - tests/lean/misc-no_nested_borrows/lakefile.lean | 12 - tests/lean/misc-no_nested_borrows/lean-toolchain | 1 - tests/lean/misc-paper/Base/Primitives.lean | 583 ----------- tests/lean/misc-paper/Paper.lean | 123 --- tests/lean/misc-paper/lake-manifest.json | 27 - tests/lean/misc-paper/lakefile.lean | 12 - tests/lean/misc-paper/lean-toolchain | 1 - tests/lean/misc-polonius_list/Base/Primitives.lean | 583 ----------- tests/lean/misc-polonius_list/PoloniusList.lean | 31 - tests/lean/misc-polonius_list/lake-manifest.json | 27 - tests/lean/misc-polonius_list/lakefile.lean | 12 - tests/lean/misc-polonius_list/lean-toolchain | 1 - 96 files changed, 4002 insertions(+), 8748 deletions(-) create mode 100644 tests/lean/BetreeMain.lean create mode 100644 tests/lean/BetreeMain/Funs.lean create mode 100644 tests/lean/BetreeMain/Opaque.lean create mode 100644 tests/lean/BetreeMain/Types.lean create mode 100644 tests/lean/Constants.lean create mode 100644 tests/lean/External.lean create mode 100644 tests/lean/External/Funs.lean create mode 100644 tests/lean/External/Opaque.lean create mode 100644 tests/lean/External/Types.lean create mode 100644 tests/lean/Hashmap.lean create mode 100644 tests/lean/Hashmap/Funs.lean create mode 100644 tests/lean/Hashmap/Types.lean create mode 100644 tests/lean/HashmapMain.lean create mode 100644 tests/lean/HashmapMain/Funs.lean create mode 100644 tests/lean/HashmapMain/Opaque.lean create mode 100644 tests/lean/HashmapMain/Types.lean create mode 100644 tests/lean/Loops.lean create mode 100644 tests/lean/Loops/Funs.lean create mode 100644 tests/lean/Loops/Types.lean create mode 100644 tests/lean/NoNestedBorrows.lean create mode 100644 tests/lean/Paper.lean create mode 100644 tests/lean/PoloniusList.lean create mode 100644 tests/lean/Tests.lean delete mode 100644 tests/lean/hashmap/Base/Primitives.lean delete mode 100644 tests/lean/hashmap/Hashmap.lean delete mode 100644 tests/lean/hashmap/Hashmap/Clauses/Clauses.lean delete mode 100644 tests/lean/hashmap/Hashmap/Clauses/Template.lean delete mode 100644 tests/lean/hashmap/Hashmap/Funs.lean delete mode 100644 tests/lean/hashmap/Hashmap/Types.lean delete mode 100644 tests/lean/hashmap/lake-manifest.json delete mode 100644 tests/lean/hashmap/lakefile.lean delete mode 100644 tests/lean/hashmap/lean-toolchain delete mode 100644 tests/lean/hashmap_on_disk/.gitignore delete mode 100644 tests/lean/hashmap_on_disk/Base/Primitives.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/Clauses/Clauses.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/Clauses/Template.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/ExternalFuns.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/Funs.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/Opaque.lean delete mode 100644 tests/lean/hashmap_on_disk/HashmapMain/Types.lean delete mode 100644 tests/lean/hashmap_on_disk/lake-manifest.json delete mode 100644 tests/lean/hashmap_on_disk/lakefile.lean delete mode 100644 tests/lean/hashmap_on_disk/lean-toolchain create mode 100644 tests/lean/lake-manifest.json create mode 100644 tests/lean/lakefile.lean delete mode 100644 tests/lean/misc-constants/Base/Primitives.lean delete mode 100644 tests/lean/misc-constants/Constants.lean delete mode 100644 tests/lean/misc-constants/lake-manifest.json delete mode 100644 tests/lean/misc-constants/lakefile.lean delete mode 100644 tests/lean/misc-constants/lean-toolchain delete mode 100644 tests/lean/misc-external/Base/Primitives.lean delete mode 100644 tests/lean/misc-external/External.lean delete mode 100644 tests/lean/misc-external/External/ExternalFuns.lean delete mode 100644 tests/lean/misc-external/External/Funs.lean delete mode 100644 tests/lean/misc-external/External/Opaque.lean delete mode 100644 tests/lean/misc-external/External/Types.lean delete mode 100644 tests/lean/misc-external/lake-manifest.json delete mode 100644 tests/lean/misc-external/lakefile.lean delete mode 100644 tests/lean/misc-external/lean-toolchain delete mode 100644 tests/lean/misc-loops/Base/Primitives.lean delete mode 100644 tests/lean/misc-loops/Loops.lean delete mode 100644 tests/lean/misc-loops/Loops/Clauses/Clauses.lean delete mode 100644 tests/lean/misc-loops/Loops/Clauses/Template.lean delete mode 100644 tests/lean/misc-loops/Loops/Funs.lean delete mode 100644 tests/lean/misc-loops/Loops/Types.lean delete mode 100644 tests/lean/misc-loops/lake-manifest.json delete mode 100644 tests/lean/misc-loops/lakefile.lean delete mode 100644 tests/lean/misc-loops/lean-toolchain delete mode 100644 tests/lean/misc-no_nested_borrows/Base/Primitives.lean delete mode 100644 tests/lean/misc-no_nested_borrows/NoNestedBorrows.lean delete mode 100644 tests/lean/misc-no_nested_borrows/lake-manifest.json delete mode 100644 tests/lean/misc-no_nested_borrows/lakefile.lean delete mode 100644 tests/lean/misc-no_nested_borrows/lean-toolchain delete mode 100644 tests/lean/misc-paper/Base/Primitives.lean delete mode 100644 tests/lean/misc-paper/Paper.lean delete mode 100644 tests/lean/misc-paper/lake-manifest.json delete mode 100644 tests/lean/misc-paper/lakefile.lean delete mode 100644 tests/lean/misc-paper/lean-toolchain delete mode 100644 tests/lean/misc-polonius_list/Base/Primitives.lean delete mode 100644 tests/lean/misc-polonius_list/PoloniusList.lean delete mode 100644 tests/lean/misc-polonius_list/lake-manifest.json delete mode 100644 tests/lean/misc-polonius_list/lakefile.lean delete mode 100644 tests/lean/misc-polonius_list/lean-toolchain diff --git a/Makefile b/Makefile index a5d1fd09..1b11592f 100644 --- a/Makefile +++ b/Makefile @@ -117,8 +117,8 @@ trans-no_nested_borrows trans-paper: \ OPTIONS += -test-units -test-trans-units -no-split-files -no-state trans-no_nested_borrows trans-paper: SUBDIR := misc tfstar-no_nested_borrows tfstar-paper: -tlean-no_nested_borrows: SUBDIR := misc-no_nested_borrows -tlean-paper: SUBDIR := misc-paper +tlean-no_nested_borrows: SUBDIR := +tlean-paper: SUBDIR := thol4-no_nested_borrows: SUBDIR := misc-no_nested_borrows thol4-paper: SUBDIR := misc-paper @@ -126,29 +126,29 @@ trans-loops: OPTIONS += -no-state trans-loops: SUBDIR := misc tfstar-loops: OPTIONS += -decreases-clauses -template-clauses tcoq-loops: OPTIONS += -use-fuel -no-split-files -tlean-loops: SUBDIR := misc-loops -tlean-loops: OPTIONS += -decreases-clauses -template-clauses +tlean-loops: SUBDIR := thol4-loops: SUBDIR := misc-loops trans-hashmap: OPTIONS += -no-state trans-hashmap: SUBDIR := hashmap tfstar-hashmap: OPTIONS += -decreases-clauses -template-clauses tcoq-hashmap: OPTIONS += -use-fuel -tlean-hashmap: OPTIONS += -decreases-clauses -template-clauses +tlean-hashmap: SUBDIR := +tlean-hashmap: OPTIONS += thol4-hashmap: OPTIONS += trans-hashmap_main: OPTIONS += trans-hashmap_main: SUBDIR := hashmap_on_disk tfstar-hashmap_main: OPTIONS += -decreases-clauses -template-clauses tcoq-hashmap_main: OPTIONS += -use-fuel -tlean-hashmap_main: OPTIONS += -decreases-clauses -template-clauses +tlean-hashmap_main: SUBDIR := thol4-hashmap_main: OPTIONS += transp-polonius_list: OPTIONS += -test-units -test-trans-units -no-split-files -no-state transp-polonius_list: SUBDIR := misc tfstarp-polonius_list: OPTIONS += tcoqp-polonius_list: OPTIONS += -tleanp-polonius_list: SUBDIR := misc-polonius_list +tleanp-polonius_list: SUBDIR := tleanp-polonius_list: OPTIONS += thol4p-polonius_list: SUBDIR := misc-polonius_list thol4p-polonius_list: OPTIONS += @@ -157,7 +157,7 @@ trans-constants: OPTIONS += -test-units -test-trans-units -no-split-files -no-st trans-constants: SUBDIR := misc tfstar-constants: OPTIONS += tcoq-constants: OPTIONS += -tlean-constants: SUBDIR := misc-constants +tlean-constants: SUBDIR := tlean-constants: OPTIONS += thol4-constants: SUBDIR := misc-constants thol4-constants: OPTIONS += @@ -166,7 +166,7 @@ trans-external: OPTIONS += trans-external: SUBDIR := misc tfstar-external: OPTIONS += tcoq-external: OPTIONS += -tlean-external: SUBDIR := misc-external +tlean-external: SUBDIR := tlean-external: OPTIONS += thol4-external: SUBDIR := misc-external thol4-external: OPTIONS += @@ -176,7 +176,8 @@ transp-betree_main: OPTIONS += -backward-no-state-update transp-betree_main: SUBDIR:=betree tfstarp-betree_main: OPTIONS += $(BETREE_FSTAR_OPTIONS) tcoqp-betree_main: OPTIONS += -use-fuel -tleanp-betree_main: OPTIONS += $(BETREE_FSTAR_OPTIONS) +tleanp-betree_main: SUBDIR := +tleanp-betree_main: OPTIONS += thol4-betree_main: OPTIONS += # Additional test on the betree: translate it without `-backward-no-state-update`. @@ -249,8 +250,7 @@ tcoqp-%: $(AENEAS_CMD) .PHONY: tlean-% -# TODO: add -test-trans-units once we remove all the sorry from Primitives.lean -tlean-%: OPTIONS += -backend lean +tlean-%: OPTIONS += -backend lean -test-trans-units tlean-%: BACKEND_SUBDIR := lean tlean-%: $(AENEAS_CMD) @@ -258,13 +258,7 @@ tlean-%: # "p" stands for "Polonius" .PHONY: tleanp-% -# TODO: for now we don't extract the betree for Lean because we need to implement -# proper support for the proofs of termination for the mutually recursive functions. -tleanp-betree_main: - echo "Ignoring Lean betree" - -# TODO: add -test-trans-units once we remove all the sorry from Primitives.lean -tleanp-%: OPTIONS += -backend lean +tleanp-%: OPTIONS += -backend lean -test-trans-units tleanp-%: BACKEND_SUBDIR := lean tleanp-%: $(AENEAS_CMD) diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index 6e9ff873..1f8cbc8e 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -1,4 +1,3 @@ import Base.Primitives import Base.Diverge -import Base.TestTactics import Base.Arith diff --git a/backends/lean/lake-manifest.json b/backends/lean/lake-manifest.json index e5d362fc..40eb1682 100644 --- a/backends/lean/lake-manifest.json +++ b/backends/lean/lake-manifest.json @@ -2,9 +2,15 @@ "packagesDir": "lake-packages", "packages": [{"git": + {"url": "https://github.com/EdAyers/ProofWidgets4", + "subDir?": null, + "rev": "c43db94a8f495dad37829e9d7ad65483d68c86b8", + "name": "proofwidgets", + "inputRev?": "v0.0.11"}}, + {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "cdb1b898e4317567699181f27533182046ebc544", + "rev": "4f103b3696795c62e76fb89d177efb91c29afdf5", "name": "mathlib", "inputRev?": null}}, {"git": @@ -22,6 +28,6 @@ {"git": {"url": "https://github.com/leanprover/std4", "subDir?": null, - "rev": "6932c4ea52914dc6b0488944e367459ddc4d01a6", + "rev": "e68aa8f5fe47aad78987df45f99094afbcb5e936", "name": "std", "inputRev?": "main"}}]} diff --git a/backends/lean/lean-toolchain b/backends/lean/lean-toolchain index 1211e372..42e7d786 100644 --- a/backends/lean/lean-toolchain +++ b/backends/lean/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:nightly-2023-05-31 \ No newline at end of file +leanprover/lean4:nightly-2023-06-20 \ No newline at end of file diff --git a/compiler/Config.ml b/compiler/Config.ml index ce9b0e0c..bfb9d161 100644 --- a/compiler/Config.ml +++ b/compiler/Config.ml @@ -162,6 +162,11 @@ let backward_no_state_update = ref false *) let split_files = ref true +(** For Lean, controls whether we generate a lakefile or not. + + *) +let lean_gen_lakefile = ref false + (** If true, treat the unit functions (function taking no inputs and returning no outputs) as unit tests: evaluate them with the interpreter and check that they don't panic. diff --git a/compiler/Driver.ml b/compiler/Driver.ml index 2ff9e295..f935a717 100644 --- a/compiler/Driver.ml +++ b/compiler/Driver.ml @@ -107,6 +107,9 @@ let () = Arg.Clear check_invariants, " Deactivate the invariant sanity checks performed at every evaluation \ step. Dramatically increases speed." ); + ( "-lean-default-lakefile", + Arg.Clear lean_gen_lakefile, + " Generate a default lakefile.lean (Lean only)" ); ] in @@ -130,6 +133,9 @@ let () = (not !use_fuel) || (not !extract_decreases_clauses) && not !extract_template_decreases_clauses); + if !lean_gen_lakefile && not (!backend = Lean) then + log#error + "The -lean-default-lakefile option is valid only for the Lean backend"; (* Check that the user specified a backend *) let _ = diff --git a/compiler/Extract.ml b/compiler/Extract.ml index d624d9ca..a54a2299 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -505,10 +505,10 @@ let fun_decl_kind_to_qualif (kind : decl_kind) : string option = | Lean -> ( match kind with | SingleNonRec -> Some "def" - | SingleRec -> Some "def" - | MutRecFirst -> Some "mutual def" - | MutRecInner -> Some "def" - | MutRecLast -> Some "def" + | SingleRec -> Some "divergent def" + | MutRecFirst -> Some "mutual divergent def" + | MutRecInner -> Some "divergent def" + | MutRecLast -> Some "divergent def" | Assumed -> Some "axiom" | Declared -> Some "axiom") | HOL4 -> None @@ -2327,9 +2327,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) match !backend with | FStar -> "=" | Coq -> ":=" - | Lean -> - (* TODO: switch to ⟵ once issues are fixed *) - if monadic then "←" else ":=" + | Lean -> if monadic then "←" else ":=" | HOL4 -> if monadic then "<-" else "=" in F.pp_print_string fmt eq; @@ -2409,7 +2407,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Open a box for the [if e] *) F.pp_open_hovbox fmt ctx.indent_incr; F.pp_print_string fmt "if"; - if !backend = Lean then F.pp_print_string fmt " h:"; + if !backend = Lean && ctx.use_dep_ite then F.pp_print_string fmt " h:"; F.pp_print_space fmt (); let scrut_inside = PureUtils.texpression_requires_parentheses scrut in extract_texpression ctx fmt scrut_inside scrut; diff --git a/compiler/ExtractBase.ml b/compiler/ExtractBase.ml index 0a5d7df2..14ce4119 100644 --- a/compiler/ExtractBase.ml +++ b/compiler/ExtractBase.ml @@ -539,6 +539,16 @@ type extraction_ctx = { use it. Also see {!names_map.opaque_ids}. *) + use_dep_ite : bool; + (** For Lean: do we use dependent-if then else expressions? + + Example: + {[ + if h: b then ... else ... + -- ^^ + -- makes the if then else dependent + ]} + *) } (** Debugging function, used when communicating name collisions to the user, diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 75fc7fe9..39b169c9 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -834,11 +834,13 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) custom_includes; Printf.fprintf out "Module %s.\n" module_name | Lean -> - Printf.fprintf out "import Base.Primitives\n"; + Printf.fprintf out "import Base\n"; (* Add the custom imports *) List.iter (fun m -> Printf.fprintf out "import %s\n" m) custom_imports; (* Add the custom includes *) - List.iter (fun m -> Printf.fprintf out "import %s\n" m) custom_includes + List.iter (fun m -> Printf.fprintf out "import %s\n" m) custom_includes; + (* Always open the Primitives namespace *) + Printf.fprintf out "open Primitives\n" | HOL4 -> Printf.fprintf out "open primitivesLib divDefLib\n"; (* Add the custom imports and includes *) @@ -903,6 +905,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : fmt; indent_incr = 2; use_opaque_pre = !Config.split_files; + use_dep_ite = !Config.backend = Lean && !Config.extract_decreases_clauses; } in @@ -1019,7 +1022,6 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : create more directories *) if !Config.backend = Lean then ( let ( ^^ ) = Filename.concat in - mkdir_if (dest_dir ^^ "Base"); if !Config.split_files then mkdir_if (dest_dir ^^ module_name); if needs_clauses_module then ( assert !Config.split_files; @@ -1033,7 +1035,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : match !Config.backend with | FStar -> Some ("/backends/fstar/Primitives.fst", "Primitives.fst") | Coq -> Some ("/backends/coq/Primitives.v", "Primitives.v") - | Lean -> Some ("/backends/lean/Primitives.lean", "Base/Primitives.lean") + | Lean -> None | HOL4 -> None in match primitives_src_dest with @@ -1265,38 +1267,36 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : log#linfo (lazy ("Generated: " ^ filename))); (* - * Generate the lakefile.lean file + * Generate the lakefile.lean file, if the user asks for it *) + if !Config.lean_gen_lakefile then ( + (* Open the file *) + let filename = Filename.concat dest_dir "lakefile.lean" in + let out = open_out filename in - (* Open the file *) - let filename = Filename.concat dest_dir "lakefile.lean" in - let out = open_out filename in - - (* Generate the content *) - Printf.fprintf out "import Lake\nopen Lake DSL\n\n"; - Printf.fprintf out "require mathlib from git\n"; - Printf.fprintf out - " \"https://github.com/leanprover-community/mathlib4.git\"\n\n"; - - let package_name = StringUtils.to_snake_case module_name in - Printf.fprintf out "package «%s» {}\n\n" package_name; - - Printf.fprintf out "lean_lib «Base» {}\n\n"; - - Printf.fprintf out "@[default_target]\nlean_lib «%s» {}\n" module_name; - - (* No default target for now. - Format would be: - {[ - @[default_target] - lean_exe «package_name» { - root := `Main - } - ]} - *) + (* Generate the content *) + Printf.fprintf out "import Lake\nopen Lake DSL\n\n"; + Printf.fprintf out "require mathlib from git\n"; + Printf.fprintf out + " \"https://github.com/leanprover-community/mathlib4.git\"\n\n"; + + let package_name = StringUtils.to_snake_case module_name in + Printf.fprintf out "package «%s» {}\n\n" package_name; + + Printf.fprintf out "@[default_target]\nlean_lib «%s» {}\n" module_name; + + (* No default target for now. + Format would be: + {[ + @[default_target] + lean_exe «package_name» { + root := `Main + } + ]} + *) - (* Flush and close the file *) - close_out out; + (* Flush and close the file *) + close_out out; - (* Logging *) - log#linfo (lazy ("Generated: " ^ filename)) + (* Logging *) + log#linfo (lazy ("Generated: " ^ filename))) diff --git a/tests/lean/.gitignore b/tests/lean/.gitignore index e74f9899..4d1c5853 100644 --- a/tests/lean/.gitignore +++ b/tests/lean/.gitignore @@ -1,2 +1,2 @@ -*/lake-packages/ -*/build/ \ No newline at end of file +lake-packages +build \ No newline at end of file diff --git a/tests/lean/BetreeMain.lean b/tests/lean/BetreeMain.lean new file mode 100644 index 00000000..5f307877 --- /dev/null +++ b/tests/lean/BetreeMain.lean @@ -0,0 +1 @@ +import BetreeMain.Funs diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean new file mode 100644 index 00000000..fb48b3a6 --- /dev/null +++ b/tests/lean/BetreeMain/Funs.lean @@ -0,0 +1,1071 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [betree_main]: function definitions +import Base +import BetreeMain.Types +import BetreeMain.ExternalFuns +open Primitives + +/- [betree_main::betree::load_internal_node] -/ +def betree_load_internal_node_fwd + (id : U64) (st : State) : + Result (State × (betree_list_t (U64 × betree_message_t))) + := + opaque_defs.betree_utils_load_internal_node_fwd id st + +/- [betree_main::betree::store_internal_node] -/ +def betree_store_internal_node_fwd + (id : U64) (content : betree_list_t (U64 × betree_message_t)) (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← + opaque_defs.betree_utils_store_internal_node_fwd id content st + Result.ret (st0, ()) + +/- [betree_main::betree::load_leaf_node] -/ +def betree_load_leaf_node_fwd + (id : U64) (st : State) : Result (State × (betree_list_t (U64 × U64))) := + opaque_defs.betree_utils_load_leaf_node_fwd id st + +/- [betree_main::betree::store_leaf_node] -/ +def betree_store_leaf_node_fwd + (id : U64) (content : betree_list_t (U64 × U64)) (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← opaque_defs.betree_utils_store_leaf_node_fwd id content st + Result.ret (st0, ()) + +/- [betree_main::betree::fresh_node_id] -/ +def betree_fresh_node_id_fwd (counter : U64) : Result U64 := + do + let _ ← counter + (U64.ofInt 1 (by intlit)) + Result.ret counter + +/- [betree_main::betree::fresh_node_id] -/ +def betree_fresh_node_id_back (counter : U64) : Result U64 := + counter + (U64.ofInt 1 (by intlit)) + +/- [betree_main::betree::NodeIdCounter::{0}::new] -/ +def betree_node_id_counter_new_fwd : Result betree_node_id_counter_t := + Result.ret + { betree_node_id_counter_next_node_id := (U64.ofInt 0 (by intlit)) } + +/- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ +def betree_node_id_counter_fresh_id_fwd + (self : betree_node_id_counter_t) : Result U64 := + do + let _ ← self.betree_node_id_counter_next_node_id + + (U64.ofInt 1 (by intlit)) + Result.ret self.betree_node_id_counter_next_node_id + +/- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ +def betree_node_id_counter_fresh_id_back + (self : betree_node_id_counter_t) : Result betree_node_id_counter_t := + do + let i ← self.betree_node_id_counter_next_node_id + + (U64.ofInt 1 (by intlit)) + Result.ret { betree_node_id_counter_next_node_id := i } + +/- [core::num::u64::{10}::MAX] -/ +def core_num_u64_max_body : Result U64 := + Result.ret (U64.ofInt 18446744073709551615 (by intlit)) +def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) + +/- [betree_main::betree::upsert_update] -/ +def betree_upsert_update_fwd + (prev : Option U64) (st : betree_upsert_fun_state_t) : Result U64 := + match h: prev with + | Option.none => + match h: st with + | betree_upsert_fun_state_t.Add v => Result.ret v + | betree_upsert_fun_state_t.Sub i => Result.ret (U64.ofInt 0 (by intlit)) + | Option.some prev0 => + match h: st with + | betree_upsert_fun_state_t.Add v => + do + let margin ← core_num_u64_max_c - prev0 + if margin >= v + then prev0 + v + else Result.ret core_num_u64_max_c + | betree_upsert_fun_state_t.Sub v => + if prev0 >= v + then prev0 - v + else Result.ret (U64.ofInt 0 (by intlit)) + +/- [betree_main::betree::List::{1}::len] -/ +divergent def betree_list_len_fwd + (T : Type) (self : betree_list_t T) : Result U64 := + match h: self with + | betree_list_t.Cons t tl => + do + let i ← betree_list_len_fwd T tl + (U64.ofInt 1 (by intlit)) + i + | betree_list_t.Nil => Result.ret (U64.ofInt 0 (by intlit)) + +/- [betree_main::betree::List::{1}::split_at] -/ +divergent def betree_list_split_at_fwd + (T : Type) (self : betree_list_t T) (n : U64) : + Result ((betree_list_t T) × (betree_list_t T)) + := + if n = (U64.ofInt 0 (by intlit)) + then Result.ret (betree_list_t.Nil, self) + else + match h: self with + | betree_list_t.Cons hd tl => + do + let i ← n - (U64.ofInt 1 (by intlit)) + let p ← betree_list_split_at_fwd T tl i + let (ls0, ls1) := p + let l := ls0 + Result.ret (betree_list_t.Cons hd l, ls1) + | betree_list_t.Nil => Result.fail Error.panic + +/- [betree_main::betree::List::{1}::push_front] -/ +def betree_list_push_front_fwd_back + (T : Type) (self : betree_list_t T) (x : T) : Result (betree_list_t T) := + let tl := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil + let l := tl + Result.ret (betree_list_t.Cons x l) + +/- [betree_main::betree::List::{1}::pop_front] -/ +def betree_list_pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := + let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil + match h: ls with + | betree_list_t.Cons x tl => Result.ret x + | betree_list_t.Nil => Result.fail Error.panic + +/- [betree_main::betree::List::{1}::pop_front] -/ +def betree_list_pop_front_back + (T : Type) (self : betree_list_t T) : Result (betree_list_t T) := + let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil + match h: ls with + | betree_list_t.Cons x tl => Result.ret tl + | betree_list_t.Nil => Result.fail Error.panic + +/- [betree_main::betree::List::{1}::hd] -/ +def betree_list_hd_fwd (T : Type) (self : betree_list_t T) : Result T := + match h: self with + | betree_list_t.Cons hd l => Result.ret hd + | betree_list_t.Nil => Result.fail Error.panic + +/- [betree_main::betree::List::{2}::head_has_key] -/ +def betree_list_head_has_key_fwd + (T : Type) (self : betree_list_t (U64 × T)) (key : U64) : Result Bool := + match h: self with + | betree_list_t.Cons hd l => let (i, _) := hd + Result.ret (i = key) + | betree_list_t.Nil => Result.ret false + +/- [betree_main::betree::List::{2}::partition_at_pivot] -/ +divergent def betree_list_partition_at_pivot_fwd + (T : Type) (self : betree_list_t (U64 × T)) (pivot : U64) : + Result ((betree_list_t (U64 × T)) × (betree_list_t (U64 × T))) + := + match h: self with + | betree_list_t.Cons hd tl => + let (i, t) := hd + if i >= pivot + then Result.ret (betree_list_t.Nil, betree_list_t.Cons (i, t) tl) + else + do + let p ← betree_list_partition_at_pivot_fwd T tl pivot + let (ls0, ls1) := p + let l := ls0 + Result.ret (betree_list_t.Cons (i, t) l, ls1) + | betree_list_t.Nil => Result.ret (betree_list_t.Nil, betree_list_t.Nil) + +/- [betree_main::betree::Leaf::{3}::split] -/ +def betree_leaf_split_fwd + (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) + (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) + (st : State) : + Result (State × betree_internal_t) + := + do + let p ← + betree_list_split_at_fwd (U64 × U64) content + params.betree_params_split_size + let (content0, content1) := p + let p0 ← betree_list_hd_fwd (U64 × U64) content1 + let (pivot, _) := p0 + let id0 ← betree_node_id_counter_fresh_id_fwd node_id_cnt + let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt + let id1 ← betree_node_id_counter_fresh_id_fwd node_id_cnt0 + let (st0, _) ← betree_store_leaf_node_fwd id0 content0 st + let (st1, _) ← betree_store_leaf_node_fwd id1 content1 st0 + let n := betree_node_t.Leaf + { + betree_leaf_id := id0, + betree_leaf_size := params.betree_params_split_size + } + let n0 := betree_node_t.Leaf + { + betree_leaf_id := id1, + betree_leaf_size := params.betree_params_split_size + } + Result.ret (st1, mkbetree_internal_t self.betree_leaf_id pivot n n0) + +/- [betree_main::betree::Leaf::{3}::split] -/ +def betree_leaf_split_back + (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) + (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) + (st : State) : + Result betree_node_id_counter_t + := + do + let p ← + betree_list_split_at_fwd (U64 × U64) content + params.betree_params_split_size + let (content0, content1) := p + let _ ← betree_list_hd_fwd (U64 × U64) content1 + let id0 ← betree_node_id_counter_fresh_id_fwd node_id_cnt + let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt + let id1 ← betree_node_id_counter_fresh_id_fwd node_id_cnt0 + let (st0, _) ← betree_store_leaf_node_fwd id0 content0 st + let _ ← betree_store_leaf_node_fwd id1 content1 st0 + betree_node_id_counter_fresh_id_back node_id_cnt0 + +/- [betree_main::betree::Node::{5}::lookup_in_bindings] -/ +divergent def betree_node_lookup_in_bindings_fwd + (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (Option U64) := + match h: bindings with + | betree_list_t.Cons hd tl => + let (i, i0) := hd + if i = key + then Result.ret (Option.some i0) + else + if i > key + then Result.ret Option.none + else betree_node_lookup_in_bindings_fwd key tl + | betree_list_t.Nil => Result.ret Option.none + +/- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ +divergent def betree_node_lookup_first_message_for_key_fwd + (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: msgs with + | betree_list_t.Cons x next_msgs => + let (i, m) := x + if i >= key + then Result.ret (betree_list_t.Cons (i, m) next_msgs) + else betree_node_lookup_first_message_for_key_fwd key next_msgs + | betree_list_t.Nil => Result.ret betree_list_t.Nil + +/- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ +divergent def betree_node_lookup_first_message_for_key_back + (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) + (ret0 : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: msgs with + | betree_list_t.Cons x next_msgs => + let (i, m) := x + if i >= key + then Result.ret ret0 + else + do + let next_msgs0 ← + betree_node_lookup_first_message_for_key_back key next_msgs ret0 + Result.ret (betree_list_t.Cons (i, m) next_msgs0) + | betree_list_t.Nil => Result.ret ret0 + +/- [betree_main::betree::Node::{5}::apply_upserts] -/ +divergent def betree_node_apply_upserts_fwd + (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) + (key : U64) (st : State) : + Result (State × U64) + := + do + let b ← betree_list_head_has_key_fwd betree_message_t msgs key + if b + then + do + let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs + let (_, m) := msg + match h: m with + | betree_message_t.Insert i => Result.fail Error.panic + | betree_message_t.Delete => Result.fail Error.panic + | betree_message_t.Upsert s => + do + let v ← betree_upsert_update_fwd prev s + let msgs0 ← + betree_list_pop_front_back (U64 × betree_message_t) msgs + betree_node_apply_upserts_fwd msgs0 (Option.some v) key st + else + do + let (st0, v) ← opaque_defs.core_option_option_unwrap_fwd U64 prev st + let _ ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs (key, + betree_message_t.Insert v) + Result.ret (st0, v) + +/- [betree_main::betree::Node::{5}::apply_upserts] -/ +divergent def betree_node_apply_upserts_back + (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) + (key : U64) (st : State) : + Result (betree_list_t (U64 × betree_message_t)) + := + do + let b ← betree_list_head_has_key_fwd betree_message_t msgs key + if b + then + do + let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs + let (_, m) := msg + match h: m with + | betree_message_t.Insert i => Result.fail Error.panic + | betree_message_t.Delete => Result.fail Error.panic + | betree_message_t.Upsert s => + do + let v ← betree_upsert_update_fwd prev s + let msgs0 ← + betree_list_pop_front_back (U64 × betree_message_t) msgs + betree_node_apply_upserts_back msgs0 (Option.some v) key st + else + do + let (_, v) ← opaque_defs.core_option_option_unwrap_fwd U64 prev st + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs (key, + betree_message_t.Insert v) + +/- [betree_main::betree::Node::{5}::lookup] -/ +mutual divergent def betree_node_lookup_fwd + (self : betree_node_t) (key : U64) (st : State) : + Result (State × (Option U64)) + := + match h: self with + | betree_node_t.Internal node => + do + let (mkbetree_internal_t i i0 n n0) := node + let (st0, msgs) ← betree_load_internal_node_fwd i st + let pending ← betree_node_lookup_first_message_for_key_fwd key msgs + match h: pending with + | betree_list_t.Cons p l => + let (k, msg) := p + if k != key + then + do + let (st1, opt) ← + betree_internal_lookup_in_children_fwd (mkbetree_internal_t i i0 + n n0) key st0 + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, msg) l) + Result.ret (st1, opt) + else + match h: msg with + | betree_message_t.Insert v => + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, betree_message_t.Insert v) l) + Result.ret (st0, Option.some v) + | betree_message_t.Delete => + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, betree_message_t.Delete) l) + Result.ret (st0, Option.none) + | betree_message_t.Upsert ufs => + do + let (st1, v) ← + betree_internal_lookup_in_children_fwd (mkbetree_internal_t i + i0 n n0) key st0 + let (st2, v0) ← + betree_node_apply_upserts_fwd (betree_list_t.Cons (k, + betree_message_t.Upsert ufs) l) v key st1 + let node0 ← + betree_internal_lookup_in_children_back (mkbetree_internal_t i + i0 n n0) key st0 + let (mkbetree_internal_t i1 _ _ _) := node0 + let pending0 ← + betree_node_apply_upserts_back (betree_list_t.Cons (k, + betree_message_t.Upsert ufs) l) v key st1 + let msgs0 ← + betree_node_lookup_first_message_for_key_back key msgs pending0 + let (st3, _) ← betree_store_internal_node_fwd i1 msgs0 st2 + Result.ret (st3, Option.some v0) + | betree_list_t.Nil => + do + let (st1, opt) ← + betree_internal_lookup_in_children_fwd (mkbetree_internal_t i i0 n + n0) key st0 + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + betree_list_t.Nil + Result.ret (st1, opt) + | betree_node_t.Leaf node => + do + let (st0, bindings) ← betree_load_leaf_node_fwd node.betree_leaf_id st + let opt ← betree_node_lookup_in_bindings_fwd key bindings + Result.ret (st0, opt) + +/- [betree_main::betree::Node::{5}::lookup] -/ +divergent def betree_node_lookup_back + (self : betree_node_t) (key : U64) (st : State) : Result betree_node_t := + match h: self with + | betree_node_t.Internal node => + do + let (mkbetree_internal_t i i0 n n0) := node + let (st0, msgs) ← betree_load_internal_node_fwd i st + let pending ← betree_node_lookup_first_message_for_key_fwd key msgs + match h: pending with + | betree_list_t.Cons p l => + let (k, msg) := p + if k != key + then + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, msg) l) + let node0 ← + betree_internal_lookup_in_children_back (mkbetree_internal_t i i0 + n n0) key st0 + Result.ret (betree_node_t.Internal node0) + else + match h: msg with + | betree_message_t.Insert v => + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, betree_message_t.Insert v) l) + Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n + n0)) + | betree_message_t.Delete => + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + (betree_list_t.Cons (k, betree_message_t.Delete) l) + Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n + n0)) + | betree_message_t.Upsert ufs => + do + let (st1, v) ← + betree_internal_lookup_in_children_fwd (mkbetree_internal_t i + i0 n n0) key st0 + let (st2, _) ← + betree_node_apply_upserts_fwd (betree_list_t.Cons (k, + betree_message_t.Upsert ufs) l) v key st1 + let node0 ← + betree_internal_lookup_in_children_back (mkbetree_internal_t i + i0 n n0) key st0 + let (mkbetree_internal_t i1 i2 n1 n2) := node0 + let pending0 ← + betree_node_apply_upserts_back (betree_list_t.Cons (k, + betree_message_t.Upsert ufs) l) v key st1 + let msgs0 ← + betree_node_lookup_first_message_for_key_back key msgs pending0 + let _ ← betree_store_internal_node_fwd i1 msgs0 st2 + Result.ret (betree_node_t.Internal (mkbetree_internal_t i1 i2 n1 + n2)) + | betree_list_t.Nil => + do + let _ ← + betree_node_lookup_first_message_for_key_back key msgs + betree_list_t.Nil + let node0 ← + betree_internal_lookup_in_children_back (mkbetree_internal_t i i0 n + n0) key st0 + Result.ret (betree_node_t.Internal node0) + | betree_node_t.Leaf node => + do + let (_, bindings) ← betree_load_leaf_node_fwd node.betree_leaf_id st + let _ ← betree_node_lookup_in_bindings_fwd key bindings + Result.ret (betree_node_t.Leaf node) + +/- [betree_main::betree::Internal::{4}::lookup_in_children] -/ +divergent def betree_internal_lookup_in_children_fwd + (self : betree_internal_t) (key : U64) (st : State) : + Result (State × (Option U64)) + := + let (mkbetree_internal_t _ i n n0) := self + if key < i + then betree_node_lookup_fwd n key st + else betree_node_lookup_fwd n0 key st + +/- [betree_main::betree::Internal::{4}::lookup_in_children] -/ +divergent def betree_internal_lookup_in_children_back + (self : betree_internal_t) (key : U64) (st : State) : + Result betree_internal_t + := + let (mkbetree_internal_t i i0 n n0) := self + if key < i0 + then + do + let n1 ← betree_node_lookup_back n key st + Result.ret (mkbetree_internal_t i i0 n1 n0) + else + do + let n1 ← betree_node_lookup_back n0 key st + Result.ret (mkbetree_internal_t i i0 n n1) + +end + +/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ +divergent def betree_node_lookup_mut_in_bindings_fwd + (key : U64) (bindings : betree_list_t (U64 × U64)) : + Result (betree_list_t (U64 × U64)) + := + match h: bindings with + | betree_list_t.Cons hd tl => + let (i, i0) := hd + if i >= key + then Result.ret (betree_list_t.Cons (i, i0) tl) + else betree_node_lookup_mut_in_bindings_fwd key tl + | betree_list_t.Nil => Result.ret betree_list_t.Nil + +/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ +divergent def betree_node_lookup_mut_in_bindings_back + (key : U64) (bindings : betree_list_t (U64 × U64)) + (ret0 : betree_list_t (U64 × U64)) : + Result (betree_list_t (U64 × U64)) + := + match h: bindings with + | betree_list_t.Cons hd tl => + let (i, i0) := hd + if i >= key + then Result.ret ret0 + else + do + let tl0 ← betree_node_lookup_mut_in_bindings_back key tl ret0 + Result.ret (betree_list_t.Cons (i, i0) tl0) + | betree_list_t.Nil => Result.ret ret0 + +/- [betree_main::betree::Node::{5}::apply_to_leaf] -/ +def betree_node_apply_to_leaf_fwd_back + (bindings : betree_list_t (U64 × U64)) (key : U64) + (new_msg : betree_message_t) : + Result (betree_list_t (U64 × U64)) + := + do + let bindings0 ← betree_node_lookup_mut_in_bindings_fwd key bindings + let b ← betree_list_head_has_key_fwd U64 bindings0 key + if b + then + do + let hd ← betree_list_pop_front_fwd (U64 × U64) bindings0 + match h: new_msg with + | betree_message_t.Insert v => + do + let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 + let bindings2 ← + betree_list_push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree_node_lookup_mut_in_bindings_back key bindings bindings2 + | betree_message_t.Delete => + do + let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 + betree_node_lookup_mut_in_bindings_back key bindings bindings1 + | betree_message_t.Upsert s => + do + let (_, i) := hd + let v ← betree_upsert_update_fwd (Option.some i) s + let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 + let bindings2 ← + betree_list_push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree_node_lookup_mut_in_bindings_back key bindings bindings2 + else + match h: new_msg with + | betree_message_t.Insert v => + do + let bindings1 ← + betree_list_push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree_node_lookup_mut_in_bindings_back key bindings bindings1 + | betree_message_t.Delete => + betree_node_lookup_mut_in_bindings_back key bindings bindings0 + | betree_message_t.Upsert s => + do + let v ← betree_upsert_update_fwd Option.none s + let bindings1 ← + betree_list_push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree_node_lookup_mut_in_bindings_back key bindings bindings1 + +/- [betree_main::betree::Node::{5}::apply_messages_to_leaf] -/ +divergent def betree_node_apply_messages_to_leaf_fwd_back + (bindings : betree_list_t (U64 × U64)) + (new_msgs : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × U64)) + := + match h: new_msgs with + | betree_list_t.Cons new_msg new_msgs_tl => + do + let (i, m) := new_msg + let bindings0 ← betree_node_apply_to_leaf_fwd_back bindings i m + betree_node_apply_messages_to_leaf_fwd_back bindings0 new_msgs_tl + | betree_list_t.Nil => Result.ret bindings + +/- [betree_main::betree::Node::{5}::filter_messages_for_key] -/ +divergent def betree_node_filter_messages_for_key_fwd_back + (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: msgs with + | betree_list_t.Cons p l => + let (k, m) := p + if k = key + then + do + let msgs0 ← + betree_list_pop_front_back (U64 × betree_message_t) + (betree_list_t.Cons (k, m) l) + betree_node_filter_messages_for_key_fwd_back key msgs0 + else Result.ret (betree_list_t.Cons (k, m) l) + | betree_list_t.Nil => Result.ret betree_list_t.Nil + +/- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ +divergent def betree_node_lookup_first_message_after_key_fwd + (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: msgs with + | betree_list_t.Cons p next_msgs => + let (k, m) := p + if k = key + then betree_node_lookup_first_message_after_key_fwd key next_msgs + else Result.ret (betree_list_t.Cons (k, m) next_msgs) + | betree_list_t.Nil => Result.ret betree_list_t.Nil + +/- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ +divergent def betree_node_lookup_first_message_after_key_back + (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) + (ret0 : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: msgs with + | betree_list_t.Cons p next_msgs => + let (k, m) := p + if k = key + then + do + let next_msgs0 ← + betree_node_lookup_first_message_after_key_back key next_msgs ret0 + Result.ret (betree_list_t.Cons (k, m) next_msgs0) + else Result.ret ret0 + | betree_list_t.Nil => Result.ret ret0 + +/- [betree_main::betree::Node::{5}::apply_to_internal] -/ +def betree_node_apply_to_internal_fwd_back + (msgs : betree_list_t (U64 × betree_message_t)) (key : U64) + (new_msg : betree_message_t) : + Result (betree_list_t (U64 × betree_message_t)) + := + do + let msgs0 ← betree_node_lookup_first_message_for_key_fwd key msgs + let b ← betree_list_head_has_key_fwd betree_message_t msgs0 key + if b + then + match h: new_msg with + | betree_message_t.Insert i => + do + let msgs1 ← betree_node_filter_messages_for_key_fwd_back key msgs0 + let msgs2 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + (key, betree_message_t.Insert i) + betree_node_lookup_first_message_for_key_back key msgs msgs2 + | betree_message_t.Delete => + do + let msgs1 ← betree_node_filter_messages_for_key_fwd_back key msgs0 + let msgs2 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + (key, betree_message_t.Delete) + betree_node_lookup_first_message_for_key_back key msgs msgs2 + | betree_message_t.Upsert s => + do + let p ← betree_list_hd_fwd (U64 × betree_message_t) msgs0 + let (_, m) := p + match h: m with + | betree_message_t.Insert prev => + do + let v ← betree_upsert_update_fwd (Option.some prev) s + let msgs1 ← + betree_list_pop_front_back (U64 × betree_message_t) msgs0 + let msgs2 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + (key, betree_message_t.Insert v) + betree_node_lookup_first_message_for_key_back key msgs msgs2 + | betree_message_t.Delete => + do + let v ← betree_upsert_update_fwd Option.none s + let msgs1 ← + betree_list_pop_front_back (U64 × betree_message_t) msgs0 + let msgs2 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + (key, betree_message_t.Insert v) + betree_node_lookup_first_message_for_key_back key msgs msgs2 + | betree_message_t.Upsert ufs => + do + let msgs1 ← + betree_node_lookup_first_message_after_key_fwd key msgs0 + let msgs2 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + (key, betree_message_t.Upsert s) + let msgs3 ← + betree_node_lookup_first_message_after_key_back key msgs0 msgs2 + betree_node_lookup_first_message_for_key_back key msgs msgs3 + else + do + let msgs1 ← + betree_list_push_front_fwd_back (U64 × betree_message_t) msgs0 (key, + new_msg) + betree_node_lookup_first_message_for_key_back key msgs msgs1 + +/- [betree_main::betree::Node::{5}::apply_messages_to_internal] -/ +divergent def betree_node_apply_messages_to_internal_fwd_back + (msgs : betree_list_t (U64 × betree_message_t)) + (new_msgs : betree_list_t (U64 × betree_message_t)) : + Result (betree_list_t (U64 × betree_message_t)) + := + match h: new_msgs with + | betree_list_t.Cons new_msg new_msgs_tl => + do + let (i, m) := new_msg + let msgs0 ← betree_node_apply_to_internal_fwd_back msgs i m + betree_node_apply_messages_to_internal_fwd_back msgs0 new_msgs_tl + | betree_list_t.Nil => Result.ret msgs + +/- [betree_main::betree::Node::{5}::apply_messages] -/ +mutual divergent def betree_node_apply_messages_fwd + (self : betree_node_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) + (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : + Result (State × Unit) + := + match h: self with + | betree_node_t.Internal node => + do + let (mkbetree_internal_t i i0 n n0) := node + let (st0, content) ← betree_load_internal_node_fwd i st + let content0 ← + betree_node_apply_messages_to_internal_fwd_back content msgs + let num_msgs ← betree_list_len_fwd (U64 × betree_message_t) content0 + if num_msgs >= params.betree_params_min_flush_size + then + do + let (st1, content1) ← + betree_internal_flush_fwd (mkbetree_internal_t i i0 n n0) params + node_id_cnt content0 st0 + let (node0, _) ← + betree_internal_flush_back (mkbetree_internal_t i i0 n n0) params + node_id_cnt content0 st0 + let (mkbetree_internal_t i1 _ _ _) := node0 + let (st2, _) ← betree_store_internal_node_fwd i1 content1 st1 + Result.ret (st2, ()) + else + do + let (st1, _) ← betree_store_internal_node_fwd i content0 st0 + Result.ret (st1, ()) + | betree_node_t.Leaf node => + do + let (st0, content) ← betree_load_leaf_node_fwd node.betree_leaf_id st + let content0 ← betree_node_apply_messages_to_leaf_fwd_back content msgs + let len ← betree_list_len_fwd (U64 × U64) content0 + let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size + if len >= i + then + do + let (st1, _) ← + betree_leaf_split_fwd node content0 params node_id_cnt st0 + let (st2, _) ← + betree_store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil + st1 + Result.ret (st2, ()) + else + do + let (st1, _) ← + betree_store_leaf_node_fwd node.betree_leaf_id content0 st0 + Result.ret (st1, ()) + +/- [betree_main::betree::Node::{5}::apply_messages] -/ +divergent def betree_node_apply_messages_back + (self : betree_node_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) + (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : + Result (betree_node_t × betree_node_id_counter_t) + := + match h: self with + | betree_node_t.Internal node => + do + let (mkbetree_internal_t i i0 n n0) := node + let (st0, content) ← betree_load_internal_node_fwd i st + let content0 ← + betree_node_apply_messages_to_internal_fwd_back content msgs + let num_msgs ← betree_list_len_fwd (U64 × betree_message_t) content0 + if num_msgs >= params.betree_params_min_flush_size + then + do + let (st1, content1) ← + betree_internal_flush_fwd (mkbetree_internal_t i i0 n n0) params + node_id_cnt content0 st0 + let (node0, node_id_cnt0) ← + betree_internal_flush_back (mkbetree_internal_t i i0 n n0) params + node_id_cnt content0 st0 + let (mkbetree_internal_t i1 i2 n1 n2) := node0 + let _ ← betree_store_internal_node_fwd i1 content1 st1 + Result.ret (betree_node_t.Internal (mkbetree_internal_t i1 i2 n1 n2), + node_id_cnt0) + else + do + let _ ← betree_store_internal_node_fwd i content0 st0 + Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n n0), + node_id_cnt) + | betree_node_t.Leaf node => + do + let (st0, content) ← betree_load_leaf_node_fwd node.betree_leaf_id st + let content0 ← betree_node_apply_messages_to_leaf_fwd_back content msgs + let len ← betree_list_len_fwd (U64 × U64) content0 + let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size + if len >= i + then + do + let (st1, new_node) ← + betree_leaf_split_fwd node content0 params node_id_cnt st0 + let _ ← + betree_store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil + st1 + let node_id_cnt0 ← + betree_leaf_split_back node content0 params node_id_cnt st0 + Result.ret (betree_node_t.Internal new_node, node_id_cnt0) + else + do + let _ ← betree_store_leaf_node_fwd node.betree_leaf_id content0 st0 + Result.ret (betree_node_t.Leaf { node with betree_leaf_size := len }, + node_id_cnt) + +/- [betree_main::betree::Internal::{4}::flush] -/ +divergent def betree_internal_flush_fwd + (self : betree_internal_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) + (content : betree_list_t (U64 × betree_message_t)) (st : State) : + Result (State × (betree_list_t (U64 × betree_message_t))) + := + do + let (mkbetree_internal_t _ i n n0) := self + let p ← betree_list_partition_at_pivot_fwd betree_message_t content i + let (msgs_left, msgs_right) := p + let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left + if len_left >= params.betree_params_min_flush_size + then + do + let (st0, _) ← + betree_node_apply_messages_fwd n params node_id_cnt msgs_left st + let (_, node_id_cnt0) ← + betree_node_apply_messages_back n params node_id_cnt msgs_left st + let len_right ← + betree_list_len_fwd (U64 × betree_message_t) msgs_right + if len_right >= params.betree_params_min_flush_size + then + do + let (st1, _) ← + betree_node_apply_messages_fwd n0 params node_id_cnt0 msgs_right + st0 + let _ ← + betree_node_apply_messages_back n0 params node_id_cnt0 msgs_right + st0 + Result.ret (st1, betree_list_t.Nil) + else Result.ret (st0, msgs_right) + else + do + let (st0, _) ← + betree_node_apply_messages_fwd n0 params node_id_cnt msgs_right st + let _ ← + betree_node_apply_messages_back n0 params node_id_cnt msgs_right st + Result.ret (st0, msgs_left) + +/- [betree_main::betree::Internal::{4}::flush] -/ +divergent def betree_internal_flush_back + (self : betree_internal_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) + (content : betree_list_t (U64 × betree_message_t)) (st : State) : + Result (betree_internal_t × betree_node_id_counter_t) + := + do + let (mkbetree_internal_t i i0 n n0) := self + let p ← betree_list_partition_at_pivot_fwd betree_message_t content i0 + let (msgs_left, msgs_right) := p + let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left + if len_left >= params.betree_params_min_flush_size + then + do + let (st0, _) ← + betree_node_apply_messages_fwd n params node_id_cnt msgs_left st + let (n1, node_id_cnt0) ← + betree_node_apply_messages_back n params node_id_cnt msgs_left st + let len_right ← + betree_list_len_fwd (U64 × betree_message_t) msgs_right + if len_right >= params.betree_params_min_flush_size + then + do + let (n2, node_id_cnt1) ← + betree_node_apply_messages_back n0 params node_id_cnt0 msgs_right + st0 + Result.ret (mkbetree_internal_t i i0 n1 n2, node_id_cnt1) + else Result.ret (mkbetree_internal_t i i0 n1 n0, node_id_cnt0) + else + do + let (n1, node_id_cnt0) ← + betree_node_apply_messages_back n0 params node_id_cnt msgs_right st + Result.ret (mkbetree_internal_t i i0 n n1, node_id_cnt0) + +end + +/- [betree_main::betree::Node::{5}::apply] -/ +def betree_node_apply_fwd + (self : betree_node_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) (key : U64) + (new_msg : betree_message_t) (st : State) : + Result (State × Unit) + := + do + let l := betree_list_t.Nil + let (st0, _) ← + betree_node_apply_messages_fwd self params node_id_cnt + (betree_list_t.Cons (key, new_msg) l) st + let _ ← + betree_node_apply_messages_back self params node_id_cnt + (betree_list_t.Cons (key, new_msg) l) st + Result.ret (st0, ()) + +/- [betree_main::betree::Node::{5}::apply] -/ +def betree_node_apply_back + (self : betree_node_t) (params : betree_params_t) + (node_id_cnt : betree_node_id_counter_t) (key : U64) + (new_msg : betree_message_t) (st : State) : + Result (betree_node_t × betree_node_id_counter_t) + := + let l := betree_list_t.Nil + betree_node_apply_messages_back self params node_id_cnt (betree_list_t.Cons + (key, new_msg) l) st + +/- [betree_main::betree::BeTree::{6}::new] -/ +def betree_be_tree_new_fwd + (min_flush_size : U64) (split_size : U64) (st : State) : + Result (State × betree_be_tree_t) + := + do + let node_id_cnt ← betree_node_id_counter_new_fwd + let id ← betree_node_id_counter_fresh_id_fwd node_id_cnt + let (st0, _) ← betree_store_leaf_node_fwd id betree_list_t.Nil st + let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt + Result.ret (st0, + { + betree_be_tree_params := + { + betree_params_min_flush_size := min_flush_size, + betree_params_split_size := split_size + }, + betree_be_tree_node_id_cnt := node_id_cnt0, + betree_be_tree_root := + (betree_node_t.Leaf + { + betree_leaf_id := id, + betree_leaf_size := (U64.ofInt 0 (by intlit)) + }) + }) + +/- [betree_main::betree::BeTree::{6}::apply] -/ +def betree_be_tree_apply_fwd + (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← + betree_node_apply_fwd self.betree_be_tree_root self.betree_be_tree_params + self.betree_be_tree_node_id_cnt key msg st + let _ ← + betree_node_apply_back self.betree_be_tree_root + self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st + Result.ret (st0, ()) + +/- [betree_main::betree::BeTree::{6}::apply] -/ +def betree_be_tree_apply_back + (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : + Result betree_be_tree_t + := + do + let (n, nic) ← + betree_node_apply_back self.betree_be_tree_root + self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st + Result.ret + { self with betree_be_tree_node_id_cnt := nic, betree_be_tree_root := n } + +/- [betree_main::betree::BeTree::{6}::insert] -/ +def betree_be_tree_insert_fwd + (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← + betree_be_tree_apply_fwd self key (betree_message_t.Insert value) st + let _ ← + betree_be_tree_apply_back self key (betree_message_t.Insert value) st + Result.ret (st0, ()) + +/- [betree_main::betree::BeTree::{6}::insert] -/ +def betree_be_tree_insert_back + (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : + Result betree_be_tree_t + := + betree_be_tree_apply_back self key (betree_message_t.Insert value) st + +/- [betree_main::betree::BeTree::{6}::delete] -/ +def betree_be_tree_delete_fwd + (self : betree_be_tree_t) (key : U64) (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← + betree_be_tree_apply_fwd self key betree_message_t.Delete st + let _ ← betree_be_tree_apply_back self key betree_message_t.Delete st + Result.ret (st0, ()) + +/- [betree_main::betree::BeTree::{6}::delete] -/ +def betree_be_tree_delete_back + (self : betree_be_tree_t) (key : U64) (st : State) : + Result betree_be_tree_t + := + betree_be_tree_apply_back self key betree_message_t.Delete st + +/- [betree_main::betree::BeTree::{6}::upsert] -/ +def betree_be_tree_upsert_fwd + (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) + (st : State) : + Result (State × Unit) + := + do + let (st0, _) ← + betree_be_tree_apply_fwd self key (betree_message_t.Upsert upd) st + let _ ← + betree_be_tree_apply_back self key (betree_message_t.Upsert upd) st + Result.ret (st0, ()) + +/- [betree_main::betree::BeTree::{6}::upsert] -/ +def betree_be_tree_upsert_back + (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) + (st : State) : + Result betree_be_tree_t + := + betree_be_tree_apply_back self key (betree_message_t.Upsert upd) st + +/- [betree_main::betree::BeTree::{6}::lookup] -/ +def betree_be_tree_lookup_fwd + (self : betree_be_tree_t) (key : U64) (st : State) : + Result (State × (Option U64)) + := + betree_node_lookup_fwd self.betree_be_tree_root key st + +/- [betree_main::betree::BeTree::{6}::lookup] -/ +def betree_be_tree_lookup_back + (self : betree_be_tree_t) (key : U64) (st : State) : + Result betree_be_tree_t + := + do + let n ← betree_node_lookup_back self.betree_be_tree_root key st + Result.ret { self with betree_be_tree_root := n } + +/- [betree_main::main] -/ +def main_fwd : Result Unit := + Result.ret () + +/- Unit test for [betree_main::main] -/ +#assert (main_fwd == .ret ()) + diff --git a/tests/lean/BetreeMain/Opaque.lean b/tests/lean/BetreeMain/Opaque.lean new file mode 100644 index 00000000..c8226d4e --- /dev/null +++ b/tests/lean/BetreeMain/Opaque.lean @@ -0,0 +1,31 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [betree_main]: opaque function definitions +import Base +import BetreeMain.Types +open Primitives + +structure OpaqueDefs where + + /- [betree_main::betree_utils::load_internal_node] -/ + betree_utils_load_internal_node_fwd + : + U64 -> State -> Result (State × (betree_list_t (U64 × betree_message_t))) + + /- [betree_main::betree_utils::store_internal_node] -/ + betree_utils_store_internal_node_fwd + : + U64 -> betree_list_t (U64 × betree_message_t) -> State -> Result (State × + Unit) + + /- [betree_main::betree_utils::load_leaf_node] -/ + betree_utils_load_leaf_node_fwd + : U64 -> State -> Result (State × (betree_list_t (U64 × U64))) + + /- [betree_main::betree_utils::store_leaf_node] -/ + betree_utils_store_leaf_node_fwd + : U64 -> betree_list_t (U64 × U64) -> State -> Result (State × Unit) + + /- [core::option::Option::{0}::unwrap] -/ + core_option_option_unwrap_fwd + (T : Type) : Option T -> State -> Result (State × T) + diff --git a/tests/lean/BetreeMain/Types.lean b/tests/lean/BetreeMain/Types.lean new file mode 100644 index 00000000..4875a8ba --- /dev/null +++ b/tests/lean/BetreeMain/Types.lean @@ -0,0 +1,62 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [betree_main]: type definitions +import Base +open Primitives + +/- [betree_main::betree::List] -/ +inductive betree_list_t (T : Type) := +| Cons : T -> betree_list_t T -> betree_list_t T +| Nil : betree_list_t T + +/- [betree_main::betree::UpsertFunState] -/ +inductive betree_upsert_fun_state_t := +| Add : U64 -> betree_upsert_fun_state_t +| Sub : U64 -> betree_upsert_fun_state_t + +/- [betree_main::betree::Message] -/ +inductive betree_message_t := +| Insert : U64 -> betree_message_t +| Delete : betree_message_t +| Upsert : betree_upsert_fun_state_t -> betree_message_t + +/- [betree_main::betree::Leaf] -/ +structure betree_leaf_t where + betree_leaf_id : U64 + betree_leaf_size : U64 + +mutual + +/- [betree_main::betree::Node] -/ +inductive betree_node_t := +| Internal : betree_internal_t -> betree_node_t +| Leaf : betree_leaf_t -> betree_node_t + +/- [betree_main::betree::Internal] -/ +inductive betree_internal_t := +| mkbetree_internal_t : + U64 -> + U64 -> + betree_node_t -> + betree_node_t -> + betree_internal_t + +end + +/- [betree_main::betree::Params] -/ +structure betree_params_t where + betree_params_min_flush_size : U64 + betree_params_split_size : U64 + +/- [betree_main::betree::NodeIdCounter] -/ +structure betree_node_id_counter_t where + betree_node_id_counter_next_node_id : U64 + +/- [betree_main::betree::BeTree] -/ +structure betree_be_tree_t where + betree_be_tree_params : betree_params_t + betree_be_tree_node_id_cnt : betree_node_id_counter_t + betree_be_tree_root : betree_node_t + +/- The state type used in the state-error monad -/ +axiom State : Type + diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean new file mode 100644 index 00000000..cd2f88f5 --- /dev/null +++ b/tests/lean/Constants.lean @@ -0,0 +1,132 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [constants] +import Base +open Primitives + +/- [constants::X0] -/ +def x0_body : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) +def x0_c : U32 := eval_global x0_body (by simp) + +/- [core::num::u32::{9}::MAX] -/ +def core_num_u32_max_body : Result U32 := + Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) + +/- [constants::X1] -/ +def x1_body : Result U32 := Result.ret core_num_u32_max_c +def x1_c : U32 := eval_global x1_body (by simp) + +/- [constants::X2] -/ +def x2_body : Result U32 := Result.ret (U32.ofInt 3 (by intlit)) +def x2_c : U32 := eval_global x2_body (by simp) + +/- [constants::incr] -/ +def incr_fwd (n : U32) : Result U32 := + n + (U32.ofInt 1 (by intlit)) + +/- [constants::X3] -/ +def x3_body : Result U32 := incr_fwd (U32.ofInt 32 (by intlit)) +def x3_c : U32 := eval_global x3_body (by simp) + +/- [constants::mk_pair0] -/ +def mk_pair0_fwd (x : U32) (y : U32) : Result (U32 × U32) := + Result.ret (x, y) + +/- [constants::Pair] -/ +structure pair_t (T1 T2 : Type) where + pair_x : T1 + pair_y : T2 + +/- [constants::mk_pair1] -/ +def mk_pair1_fwd (x : U32) (y : U32) : Result (pair_t U32 U32) := + Result.ret { pair_x := x, pair_y := y } + +/- [constants::P0] -/ +def p0_body : Result (U32 × U32) := + mk_pair0_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) +def p0_c : (U32 × U32) := eval_global p0_body (by simp) + +/- [constants::P1] -/ +def p1_body : Result (pair_t U32 U32) := + mk_pair1_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) +def p1_c : pair_t U32 U32 := eval_global p1_body (by simp) + +/- [constants::P2] -/ +def p2_body : Result (U32 × U32) := + Result.ret ((U32.ofInt 0 (by intlit)), (U32.ofInt 1 (by intlit))) +def p2_c : (U32 × U32) := eval_global p2_body (by simp) + +/- [constants::P3] -/ +def p3_body : Result (pair_t U32 U32) := + Result.ret + { pair_x := (U32.ofInt 0 (by intlit)), pair_y := (U32.ofInt 1 (by intlit)) } +def p3_c : pair_t U32 U32 := eval_global p3_body (by simp) + +/- [constants::Wrap] -/ +structure wrap_t (T : Type) where + wrap_val : T + +/- [constants::Wrap::{0}::new] -/ +def wrap_new_fwd (T : Type) (val : T) : Result (wrap_t T) := + Result.ret { wrap_val := val } + +/- [constants::Y] -/ +def y_body : Result (wrap_t I32) := wrap_new_fwd I32 (I32.ofInt 2 (by intlit)) +def y_c : wrap_t I32 := eval_global y_body (by simp) + +/- [constants::unwrap_y] -/ +def unwrap_y_fwd : Result I32 := + Result.ret y_c.wrap_val + +/- [constants::YVAL] -/ +def yval_body : Result I32 := unwrap_y_fwd +def yval_c : I32 := eval_global yval_body (by simp) + +/- [constants::get_z1::Z1] -/ +def get_z1_z1_body : Result I32 := Result.ret (I32.ofInt 3 (by intlit)) +def get_z1_z1_c : I32 := eval_global get_z1_z1_body (by simp) + +/- [constants::get_z1] -/ +def get_z1_fwd : Result I32 := + Result.ret get_z1_z1_c + +/- [constants::add] -/ +def add_fwd (a : I32) (b : I32) : Result I32 := + a + b + +/- [constants::Q1] -/ +def q1_body : Result I32 := Result.ret (I32.ofInt 5 (by intlit)) +def q1_c : I32 := eval_global q1_body (by simp) + +/- [constants::Q2] -/ +def q2_body : Result I32 := Result.ret q1_c +def q2_c : I32 := eval_global q2_body (by simp) + +/- [constants::Q3] -/ +def q3_body : Result I32 := add_fwd q2_c (I32.ofInt 3 (by intlit)) +def q3_c : I32 := eval_global q3_body (by simp) + +/- [constants::get_z2] -/ +def get_z2_fwd : Result I32 := + do + let i ← get_z1_fwd + let i0 ← add_fwd i q3_c + add_fwd q1_c i0 + +/- [constants::S1] -/ +def s1_body : Result U32 := Result.ret (U32.ofInt 6 (by intlit)) +def s1_c : U32 := eval_global s1_body (by simp) + +/- [constants::S2] -/ +def s2_body : Result U32 := incr_fwd s1_c +def s2_c : U32 := eval_global s2_body (by simp) + +/- [constants::S3] -/ +def s3_body : Result (pair_t U32 U32) := Result.ret p3_c +def s3_c : pair_t U32 U32 := eval_global s3_body (by simp) + +/- [constants::S4] -/ +def s4_body : Result (pair_t U32 U32) := + mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) +def s4_c : pair_t U32 U32 := eval_global s4_body (by simp) + diff --git a/tests/lean/External.lean b/tests/lean/External.lean new file mode 100644 index 00000000..b95db309 --- /dev/null +++ b/tests/lean/External.lean @@ -0,0 +1 @@ +import External.Funs diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean new file mode 100644 index 00000000..73e45938 --- /dev/null +++ b/tests/lean/External/Funs.lean @@ -0,0 +1,88 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [external]: function definitions +import Base +import External.Types +import External.ExternalFuns +open Primitives + +/- [external::swap] -/ +def swap_fwd + (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := + do + let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st + let (st1, _) ← opaque_defs.core_mem_swap_back0 T x y st st0 + let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 + Result.ret (st2, ()) + +/- [external::swap] -/ +def swap_back + (T : Type) (x : T) (y : T) (st : State) (st0 : State) : + Result (State × (T × T)) + := + do + let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st + let (st2, x0) ← opaque_defs.core_mem_swap_back0 T x y st st1 + let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 + Result.ret (st0, (x0, y0)) + +/- [external::test_new_non_zero_u32] -/ +def test_new_non_zero_u32_fwd + (x : U32) (st : State) : Result (State × core_num_nonzero_non_zero_u32_t) := + do + let (st0, opt) ← opaque_defs.core_num_nonzero_non_zero_u32_new_fwd x st + opaque_defs.core_option_option_unwrap_fwd core_num_nonzero_non_zero_u32_t + opt st0 + +/- [external::test_vec] -/ +def test_vec_fwd : Result Unit := + do + let v := vec_new U32 + let _ ← vec_push_back U32 v (U32.ofInt 0 (by intlit)) + Result.ret () + +/- Unit test for [external::test_vec] -/ +#assert (test_vec_fwd == .ret ()) + +/- [external::custom_swap] -/ +def custom_swap_fwd + (T : Type) (x : T) (y : T) (st : State) : Result (State × T) := + do + let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st + let (st1, x0) ← opaque_defs.core_mem_swap_back0 T x y st st0 + let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 + Result.ret (st2, x0) + +/- [external::custom_swap] -/ +def custom_swap_back + (T : Type) (x : T) (y : T) (st : State) (ret0 : T) (st0 : State) : + Result (State × (T × T)) + := + do + let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st + let (st2, _) ← opaque_defs.core_mem_swap_back0 T x y st st1 + let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 + Result.ret (st0, (ret0, y0)) + +/- [external::test_custom_swap] -/ +def test_custom_swap_fwd + (x : U32) (y : U32) (st : State) : Result (State × Unit) := + do + let (st0, _) ← custom_swap_fwd U32 x y st + Result.ret (st0, ()) + +/- [external::test_custom_swap] -/ +def test_custom_swap_back + (x : U32) (y : U32) (st : State) (st0 : State) : + Result (State × (U32 × U32)) + := + custom_swap_back U32 x y st (U32.ofInt 1 (by intlit)) st0 + +/- [external::test_swap_non_zero] -/ +def test_swap_non_zero_fwd (x : U32) (st : State) : Result (State × U32) := + do + let (st0, _) ← swap_fwd U32 x (U32.ofInt 0 (by intlit)) st + let (st1, (x0, _)) ← swap_back U32 x (U32.ofInt 0 (by intlit)) st st0 + if x0 = (U32.ofInt 0 (by intlit)) + then Result.fail Error.panic + else Result.ret (st1, x0) + diff --git a/tests/lean/External/Opaque.lean b/tests/lean/External/Opaque.lean new file mode 100644 index 00000000..5483c3a9 --- /dev/null +++ b/tests/lean/External/Opaque.lean @@ -0,0 +1,28 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [external]: opaque function definitions +import Base +import External.Types +open Primitives + +structure OpaqueDefs where + + /- [core::mem::swap] -/ + core_mem_swap_fwd (T : Type) : T -> T -> State -> Result (State × Unit) + + /- [core::mem::swap] -/ + core_mem_swap_back0 + (T : Type) : T -> T -> State -> State -> Result (State × T) + + /- [core::mem::swap] -/ + core_mem_swap_back1 + (T : Type) : T -> T -> State -> State -> Result (State × T) + + /- [core::num::nonzero::NonZeroU32::{14}::new] -/ + core_num_nonzero_non_zero_u32_new_fwd + : + U32 -> State -> Result (State × (Option core_num_nonzero_non_zero_u32_t)) + + /- [core::option::Option::{0}::unwrap] -/ + core_option_option_unwrap_fwd + (T : Type) : Option T -> State -> Result (State × T) + diff --git a/tests/lean/External/Types.lean b/tests/lean/External/Types.lean new file mode 100644 index 00000000..25907da2 --- /dev/null +++ b/tests/lean/External/Types.lean @@ -0,0 +1,11 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [external]: type definitions +import Base +open Primitives + +/- [core::num::nonzero::NonZeroU32] -/ +axiom core_num_nonzero_non_zero_u32_t : Type + +/- The state type used in the state-error monad -/ +axiom State : Type + diff --git a/tests/lean/Hashmap.lean b/tests/lean/Hashmap.lean new file mode 100644 index 00000000..41630205 --- /dev/null +++ b/tests/lean/Hashmap.lean @@ -0,0 +1 @@ +import Hashmap.Funs diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean new file mode 100644 index 00000000..26742d5d --- /dev/null +++ b/tests/lean/Hashmap/Funs.lean @@ -0,0 +1,474 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap]: function definitions +import Base +import Hashmap.Types +open Primitives + +/- [hashmap::hash_key] -/ +def hash_key_fwd (k : Usize) : Result Usize := + Result.ret k + +/- [hashmap::HashMap::{0}::allocate_slots] -/ +divergent def hash_map_allocate_slots_loop_fwd + (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := + if n > (Usize.ofInt 0 (by intlit)) + then + do + let slots0 ← vec_push_back (list_t T) slots list_t.Nil + let n0 ← n - (Usize.ofInt 1 (by intlit)) + hash_map_allocate_slots_loop_fwd T slots0 n0 + else Result.ret slots + +/- [hashmap::HashMap::{0}::allocate_slots] -/ +def hash_map_allocate_slots_fwd + (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := + hash_map_allocate_slots_loop_fwd T slots n + +/- [hashmap::HashMap::{0}::new_with_capacity] -/ +def hash_map_new_with_capacity_fwd + (T : Type) (capacity : Usize) (max_load_dividend : Usize) + (max_load_divisor : Usize) : + Result (hash_map_t T) + := + do + let v := vec_new (list_t T) + let slots ← hash_map_allocate_slots_fwd T v capacity + let i ← capacity * max_load_dividend + let i0 ← i / max_load_divisor + Result.ret + { + hash_map_num_entries := (Usize.ofInt 0 (by intlit)), + hash_map_max_load_factor := (max_load_dividend, max_load_divisor), + hash_map_max_load := i0, + hash_map_slots := slots + } + +/- [hashmap::HashMap::{0}::new] -/ +def hash_map_new_fwd (T : Type) : Result (hash_map_t T) := + hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) + (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) + +/- [hashmap::HashMap::{0}::clear] -/ +divergent def hash_map_clear_loop_fwd_back + (T : Type) (slots : Vec (list_t T)) (i : Usize) : Result (Vec (list_t T)) := + let i0 := vec_len (list_t T) slots + if i < i0 + then + do + let i1 ← i + (Usize.ofInt 1 (by intlit)) + let slots0 ← vec_index_mut_back (list_t T) slots i list_t.Nil + hash_map_clear_loop_fwd_back T slots0 i1 + else Result.ret slots + +/- [hashmap::HashMap::{0}::clear] -/ +def hash_map_clear_fwd_back + (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := + do + let v ← + hash_map_clear_loop_fwd_back T self.hash_map_slots + (Usize.ofInt 0 (by intlit)) + Result.ret + { + self + with + hash_map_num_entries := (Usize.ofInt 0 (by intlit)), + hash_map_slots := v + } + +/- [hashmap::HashMap::{0}::len] -/ +def hash_map_len_fwd (T : Type) (self : hash_map_t T) : Result Usize := + Result.ret self.hash_map_num_entries + +/- [hashmap::HashMap::{0}::insert_in_list] -/ +divergent def hash_map_insert_in_list_loop_fwd + (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := + match h: ls with + | list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret false + else hash_map_insert_in_list_loop_fwd T key value tl + | list_t.Nil => Result.ret true + +/- [hashmap::HashMap::{0}::insert_in_list] -/ +def hash_map_insert_in_list_fwd + (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := + hash_map_insert_in_list_loop_fwd T key value ls + +/- [hashmap::HashMap::{0}::insert_in_list] -/ +divergent def hash_map_insert_in_list_loop_back + (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := + match h: ls with + | list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret (list_t.Cons ckey value tl) + else + do + let tl0 ← hash_map_insert_in_list_loop_back T key value tl + Result.ret (list_t.Cons ckey cvalue tl0) + | list_t.Nil => let l := list_t.Nil + Result.ret (list_t.Cons key value l) + +/- [hashmap::HashMap::{0}::insert_in_list] -/ +def hash_map_insert_in_list_back + (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := + hash_map_insert_in_list_loop_back T key value ls + +/- [hashmap::HashMap::{0}::insert_no_resize] -/ +def hash_map_insert_no_resize_fwd_back + (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : + Result (hash_map_t T) + := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let inserted ← hash_map_insert_in_list_fwd T key value l + if inserted + then + do + let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) + let l0 ← hash_map_insert_in_list_back T key value l + let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + Result.ret + { self with hash_map_num_entries := i0, hash_map_slots := v } + else + do + let l0 ← hash_map_insert_in_list_back T key value l + let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + Result.ret { self with hash_map_slots := v } + +/- [core::num::u32::{9}::MAX] -/ +def core_num_u32_max_body : Result U32 := + Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) + +/- [hashmap::HashMap::{0}::move_elements_from_list] -/ +divergent def hash_map_move_elements_from_list_loop_fwd_back + (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := + match h: ls with + | list_t.Cons k v tl => + do + let ntable0 ← hash_map_insert_no_resize_fwd_back T ntable k v + hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl + | list_t.Nil => Result.ret ntable + +/- [hashmap::HashMap::{0}::move_elements_from_list] -/ +def hash_map_move_elements_from_list_fwd_back + (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := + hash_map_move_elements_from_list_loop_fwd_back T ntable ls + +/- [hashmap::HashMap::{0}::move_elements] -/ +divergent def hash_map_move_elements_loop_fwd_back + (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : + Result ((hash_map_t T) × (Vec (list_t T))) + := + let i0 := vec_len (list_t T) slots + if i < i0 + then + do + let l ← vec_index_mut_fwd (list_t T) slots i + let ls := mem_replace_fwd (list_t T) l list_t.Nil + let ntable0 ← hash_map_move_elements_from_list_fwd_back T ntable ls + let i1 ← i + (Usize.ofInt 1 (by intlit)) + let l0 := mem_replace_back (list_t T) l list_t.Nil + let slots0 ← vec_index_mut_back (list_t T) slots i l0 + hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 + else Result.ret (ntable, slots) + +/- [hashmap::HashMap::{0}::move_elements] -/ +def hash_map_move_elements_fwd_back + (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : + Result ((hash_map_t T) × (Vec (list_t T))) + := + hash_map_move_elements_loop_fwd_back T ntable slots i + +/- [hashmap::HashMap::{0}::try_resize] -/ +def hash_map_try_resize_fwd_back + (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := + do + let max_usize ← Scalar.cast .Usize core_num_u32_max_c + let capacity := vec_len (list_t T) self.hash_map_slots + let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) + let (i, i0) := self.hash_map_max_load_factor + let i1 ← n1 / i + if capacity <= i1 + then + do + let i2 ← capacity * (Usize.ofInt 2 (by intlit)) + let ntable ← hash_map_new_with_capacity_fwd T i2 i i0 + let (ntable0, _) ← + hash_map_move_elements_fwd_back T ntable self.hash_map_slots + (Usize.ofInt 0 (by intlit)) + Result.ret + { + ntable0 + with + hash_map_num_entries := self.hash_map_num_entries, + hash_map_max_load_factor := (i, i0) + } + else Result.ret { self with hash_map_max_load_factor := (i, i0) } + +/- [hashmap::HashMap::{0}::insert] -/ +def hash_map_insert_fwd_back + (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : + Result (hash_map_t T) + := + do + let self0 ← hash_map_insert_no_resize_fwd_back T self key value + let i ← hash_map_len_fwd T self0 + if i > self0.hash_map_max_load + then hash_map_try_resize_fwd_back T self0 + else Result.ret self0 + +/- [hashmap::HashMap::{0}::contains_key_in_list] -/ +divergent def hash_map_contains_key_in_list_loop_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result Bool := + match h: ls with + | list_t.Cons ckey t tl => + if ckey = key + then Result.ret true + else hash_map_contains_key_in_list_loop_fwd T key tl + | list_t.Nil => Result.ret false + +/- [hashmap::HashMap::{0}::contains_key_in_list] -/ +def hash_map_contains_key_in_list_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result Bool := + hash_map_contains_key_in_list_loop_fwd T key ls + +/- [hashmap::HashMap::{0}::contains_key] -/ +def hash_map_contains_key_fwd + (T : Type) (self : hash_map_t T) (key : Usize) : Result Bool := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod + hash_map_contains_key_in_list_fwd T key l + +/- [hashmap::HashMap::{0}::get_in_list] -/ +divergent def hash_map_get_in_list_loop_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result T := + match h: ls with + | list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret cvalue + else hash_map_get_in_list_loop_fwd T key tl + | list_t.Nil => Result.fail Error.panic + +/- [hashmap::HashMap::{0}::get_in_list] -/ +def hash_map_get_in_list_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result T := + hash_map_get_in_list_loop_fwd T key ls + +/- [hashmap::HashMap::{0}::get] -/ +def hash_map_get_fwd + (T : Type) (self : hash_map_t T) (key : Usize) : Result T := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod + hash_map_get_in_list_fwd T key l + +/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +divergent def hash_map_get_mut_in_list_loop_fwd + (T : Type) (ls : list_t T) (key : Usize) : Result T := + match h: ls with + | list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret cvalue + else hash_map_get_mut_in_list_loop_fwd T tl key + | list_t.Nil => Result.fail Error.panic + +/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +def hash_map_get_mut_in_list_fwd + (T : Type) (ls : list_t T) (key : Usize) : Result T := + hash_map_get_mut_in_list_loop_fwd T ls key + +/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +divergent def hash_map_get_mut_in_list_loop_back + (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := + match h: ls with + | list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret (list_t.Cons ckey ret0 tl) + else + do + let tl0 ← hash_map_get_mut_in_list_loop_back T tl key ret0 + Result.ret (list_t.Cons ckey cvalue tl0) + | list_t.Nil => Result.fail Error.panic + +/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +def hash_map_get_mut_in_list_back + (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := + hash_map_get_mut_in_list_loop_back T ls key ret0 + +/- [hashmap::HashMap::{0}::get_mut] -/ +def hash_map_get_mut_fwd + (T : Type) (self : hash_map_t T) (key : Usize) : Result T := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + hash_map_get_mut_in_list_fwd T l key + +/- [hashmap::HashMap::{0}::get_mut] -/ +def hash_map_get_mut_back + (T : Type) (self : hash_map_t T) (key : Usize) (ret0 : T) : + Result (hash_map_t T) + := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l0 ← hash_map_get_mut_in_list_back T l key ret0 + let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + Result.ret { self with hash_map_slots := v } + +/- [hashmap::HashMap::{0}::remove_from_list] -/ +divergent def hash_map_remove_from_list_loop_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := + match h: ls with + | list_t.Cons ckey t tl => + if ckey = key + then + let mv_ls := + mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil + match h: mv_ls with + | list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) + | list_t.Nil => Result.fail Error.panic + else hash_map_remove_from_list_loop_fwd T key tl + | list_t.Nil => Result.ret Option.none + +/- [hashmap::HashMap::{0}::remove_from_list] -/ +def hash_map_remove_from_list_fwd + (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := + hash_map_remove_from_list_loop_fwd T key ls + +/- [hashmap::HashMap::{0}::remove_from_list] -/ +divergent def hash_map_remove_from_list_loop_back + (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := + match h: ls with + | list_t.Cons ckey t tl => + if ckey = key + then + let mv_ls := + mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil + match h: mv_ls with + | list_t.Cons i cvalue tl0 => Result.ret tl0 + | list_t.Nil => Result.fail Error.panic + else + do + let tl0 ← hash_map_remove_from_list_loop_back T key tl + Result.ret (list_t.Cons ckey t tl0) + | list_t.Nil => Result.ret list_t.Nil + +/- [hashmap::HashMap::{0}::remove_from_list] -/ +def hash_map_remove_from_list_back + (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := + hash_map_remove_from_list_loop_back T key ls + +/- [hashmap::HashMap::{0}::remove] -/ +def hash_map_remove_fwd + (T : Type) (self : hash_map_t T) (key : Usize) : Result (Option T) := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let x ← hash_map_remove_from_list_fwd T key l + match h: x with + | Option.none => Result.ret Option.none + | Option.some x0 => + do + let _ ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) + Result.ret (Option.some x0) + +/- [hashmap::HashMap::{0}::remove] -/ +def hash_map_remove_back + (T : Type) (self : hash_map_t T) (key : Usize) : Result (hash_map_t T) := + do + let hash ← hash_key_fwd key + let i := vec_len (list_t T) self.hash_map_slots + let hash_mod ← hash % i + let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let x ← hash_map_remove_from_list_fwd T key l + match h: x with + | Option.none => + do + let l0 ← hash_map_remove_from_list_back T key l + let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + Result.ret { self with hash_map_slots := v } + | Option.some x0 => + do + let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) + let l0 ← hash_map_remove_from_list_back T key l + let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + Result.ret + { self with hash_map_num_entries := i0, hash_map_slots := v } + +/- [hashmap::test1] -/ +def test1_fwd : Result Unit := + do + let hm ← hash_map_new_fwd U64 + let hm0 ← + hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + (U64.ofInt 42 (by intlit)) + let hm1 ← + hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + (U64.ofInt 18 (by intlit)) + let hm2 ← + hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + (U64.ofInt 138 (by intlit)) + let hm3 ← + hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + (U64.ofInt 256 (by intlit)) + let i ← hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + if not (i = (U64.ofInt 18 (by intlit))) + then Result.fail Error.panic + else + do + let hm4 ← + hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) + (U64.ofInt 56 (by intlit)) + let i0 ← hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + if not (i0 = (U64.ofInt 56 (by intlit))) + then Result.fail Error.panic + else + do + let x ← + hash_map_remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + match h: x with + | Option.none => Result.fail Error.panic + | Option.some x0 => + if not (x0 = (U64.ofInt 56 (by intlit))) + then Result.fail Error.panic + else + do + let hm5 ← + hash_map_remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) + let i1 ← + hash_map_get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) + if not (i1 = (U64.ofInt 42 (by intlit))) + then Result.fail Error.panic + else + do + let i2 ← + hash_map_get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) + if not (i2 = (U64.ofInt 18 (by intlit))) + then Result.fail Error.panic + else + do + let i3 ← + hash_map_get_fwd U64 hm5 + (Usize.ofInt 1056 (by intlit)) + if not (i3 = (U64.ofInt 256 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [hashmap::test1] -/ +#assert (test1_fwd == .ret ()) + diff --git a/tests/lean/Hashmap/Types.lean b/tests/lean/Hashmap/Types.lean new file mode 100644 index 00000000..af26f363 --- /dev/null +++ b/tests/lean/Hashmap/Types.lean @@ -0,0 +1,17 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap]: type definitions +import Base +open Primitives + +/- [hashmap::List] -/ +inductive list_t (T : Type) := +| Cons : Usize -> T -> list_t T -> list_t T +| Nil : list_t T + +/- [hashmap::HashMap] -/ +structure hash_map_t (T : Type) where + hash_map_num_entries : Usize + hash_map_max_load_factor : (Usize × Usize) + hash_map_max_load : Usize + hash_map_slots : Vec (list_t T) + diff --git a/tests/lean/HashmapMain.lean b/tests/lean/HashmapMain.lean new file mode 100644 index 00000000..1a4e7f82 --- /dev/null +++ b/tests/lean/HashmapMain.lean @@ -0,0 +1 @@ +import HashmapMain.Funs diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean new file mode 100644 index 00000000..a59a9f26 --- /dev/null +++ b/tests/lean/HashmapMain/Funs.lean @@ -0,0 +1,557 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap_main]: function definitions +import Base +import HashmapMain.Types +import HashmapMain.ExternalFuns +open Primitives + +/- [hashmap_main::hashmap::hash_key] -/ +def hashmap_hash_key_fwd (k : Usize) : Result Usize := + Result.ret k + +/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ +divergent def hashmap_hash_map_allocate_slots_loop_fwd + (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : + Result (Vec (hashmap_list_t T)) + := + if n > (Usize.ofInt 0 (by intlit)) + then + do + let slots0 ← vec_push_back (hashmap_list_t T) slots hashmap_list_t.Nil + let n0 ← n - (Usize.ofInt 1 (by intlit)) + hashmap_hash_map_allocate_slots_loop_fwd T slots0 n0 + else Result.ret slots + +/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ +def hashmap_hash_map_allocate_slots_fwd + (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : + Result (Vec (hashmap_list_t T)) + := + hashmap_hash_map_allocate_slots_loop_fwd T slots n + +/- [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] -/ +def hashmap_hash_map_new_with_capacity_fwd + (T : Type) (capacity : Usize) (max_load_dividend : Usize) + (max_load_divisor : Usize) : + Result (hashmap_hash_map_t T) + := + do + let v := vec_new (hashmap_list_t T) + let slots ← hashmap_hash_map_allocate_slots_fwd T v capacity + let i ← capacity * max_load_dividend + let i0 ← i / max_load_divisor + Result.ret + { + hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), + hashmap_hash_map_max_load_factor := + (max_load_dividend, max_load_divisor), + hashmap_hash_map_max_load := i0, + hashmap_hash_map_slots := slots + } + +/- [hashmap_main::hashmap::HashMap::{0}::new] -/ +def hashmap_hash_map_new_fwd (T : Type) : Result (hashmap_hash_map_t T) := + hashmap_hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) + (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) + +/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ +divergent def hashmap_hash_map_clear_loop_fwd_back + (T : Type) (slots : Vec (hashmap_list_t T)) (i : Usize) : + Result (Vec (hashmap_list_t T)) + := + let i0 := vec_len (hashmap_list_t T) slots + if i < i0 + then + do + let i1 ← i + (Usize.ofInt 1 (by intlit)) + let slots0 ← + vec_index_mut_back (hashmap_list_t T) slots i hashmap_list_t.Nil + hashmap_hash_map_clear_loop_fwd_back T slots0 i1 + else Result.ret slots + +/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ +def hashmap_hash_map_clear_fwd_back + (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := + do + let v ← + hashmap_hash_map_clear_loop_fwd_back T self.hashmap_hash_map_slots + (Usize.ofInt 0 (by intlit)) + Result.ret + { + self + with + hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), + hashmap_hash_map_slots := v + } + +/- [hashmap_main::hashmap::HashMap::{0}::len] -/ +def hashmap_hash_map_len_fwd + (T : Type) (self : hashmap_hash_map_t T) : Result Usize := + Result.ret self.hashmap_hash_map_num_entries + +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +divergent def hashmap_hash_map_insert_in_list_loop_fwd + (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := + match h: ls with + | hashmap_list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret false + else hashmap_hash_map_insert_in_list_loop_fwd T key value tl + | hashmap_list_t.Nil => Result.ret true + +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +def hashmap_hash_map_insert_in_list_fwd + (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := + hashmap_hash_map_insert_in_list_loop_fwd T key value ls + +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +divergent def hashmap_hash_map_insert_in_list_loop_back + (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : + Result (hashmap_list_t T) + := + match h: ls with + | hashmap_list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret (hashmap_list_t.Cons ckey value tl) + else + do + let tl0 ← hashmap_hash_map_insert_in_list_loop_back T key value tl + Result.ret (hashmap_list_t.Cons ckey cvalue tl0) + | hashmap_list_t.Nil => + let l := hashmap_list_t.Nil + Result.ret (hashmap_list_t.Cons key value l) + +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +def hashmap_hash_map_insert_in_list_back + (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : + Result (hashmap_list_t T) + := + hashmap_hash_map_insert_in_list_loop_back T key value ls + +/- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] -/ +def hashmap_hash_map_insert_no_resize_fwd_back + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : + Result (hashmap_hash_map_t T) + := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + let inserted ← hashmap_hash_map_insert_in_list_fwd T key value l + if inserted + then + do + let i0 ← self.hashmap_hash_map_num_entries + + (Usize.ofInt 1 (by intlit)) + let l0 ← hashmap_hash_map_insert_in_list_back T key value l + let v ← + vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + hash_mod l0 + Result.ret + { + self + with + hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v + } + else + do + let l0 ← hashmap_hash_map_insert_in_list_back T key value l + let v ← + vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + hash_mod l0 + Result.ret { self with hashmap_hash_map_slots := v } + +/- [core::num::u32::{9}::MAX] -/ +def core_num_u32_max_body : Result U32 := + Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) + +/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ +divergent def hashmap_hash_map_move_elements_from_list_loop_fwd_back + (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : + Result (hashmap_hash_map_t T) + := + match h: ls with + | hashmap_list_t.Cons k v tl => + do + let ntable0 ← hashmap_hash_map_insert_no_resize_fwd_back T ntable k v + hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl + | hashmap_list_t.Nil => Result.ret ntable + +/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ +def hashmap_hash_map_move_elements_from_list_fwd_back + (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : + Result (hashmap_hash_map_t T) + := + hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable ls + +/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ +divergent def hashmap_hash_map_move_elements_loop_fwd_back + (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) + (i : Usize) : + Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) + := + let i0 := vec_len (hashmap_list_t T) slots + if i < i0 + then + do + let l ← vec_index_mut_fwd (hashmap_list_t T) slots i + let ls := mem_replace_fwd (hashmap_list_t T) l hashmap_list_t.Nil + let ntable0 ← + hashmap_hash_map_move_elements_from_list_fwd_back T ntable ls + let i1 ← i + (Usize.ofInt 1 (by intlit)) + let l0 := mem_replace_back (hashmap_list_t T) l hashmap_list_t.Nil + let slots0 ← vec_index_mut_back (hashmap_list_t T) slots i l0 + hashmap_hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 + else Result.ret (ntable, slots) + +/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ +def hashmap_hash_map_move_elements_fwd_back + (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) + (i : Usize) : + Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) + := + hashmap_hash_map_move_elements_loop_fwd_back T ntable slots i + +/- [hashmap_main::hashmap::HashMap::{0}::try_resize] -/ +def hashmap_hash_map_try_resize_fwd_back + (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := + do + let max_usize ← Scalar.cast .Usize core_num_u32_max_c + let capacity := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) + let (i, i0) := self.hashmap_hash_map_max_load_factor + let i1 ← n1 / i + if capacity <= i1 + then + do + let i2 ← capacity * (Usize.ofInt 2 (by intlit)) + let ntable ← hashmap_hash_map_new_with_capacity_fwd T i2 i i0 + let (ntable0, _) ← + hashmap_hash_map_move_elements_fwd_back T ntable + self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) + Result.ret + { + ntable0 + with + hashmap_hash_map_num_entries := self.hashmap_hash_map_num_entries, + hashmap_hash_map_max_load_factor := (i, i0) + } + else Result.ret { self with hashmap_hash_map_max_load_factor := (i, i0) } + +/- [hashmap_main::hashmap::HashMap::{0}::insert] -/ +def hashmap_hash_map_insert_fwd_back + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : + Result (hashmap_hash_map_t T) + := + do + let self0 ← hashmap_hash_map_insert_no_resize_fwd_back T self key value + let i ← hashmap_hash_map_len_fwd T self0 + if i > self0.hashmap_hash_map_max_load + then hashmap_hash_map_try_resize_fwd_back T self0 + else Result.ret self0 + +/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ +divergent def hashmap_hash_map_contains_key_in_list_loop_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := + match h: ls with + | hashmap_list_t.Cons ckey t tl => + if ckey = key + then Result.ret true + else hashmap_hash_map_contains_key_in_list_loop_fwd T key tl + | hashmap_list_t.Nil => Result.ret false + +/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ +def hashmap_hash_map_contains_key_in_list_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := + hashmap_hash_map_contains_key_in_list_loop_fwd T key ls + +/- [hashmap_main::hashmap::HashMap::{0}::contains_key] -/ +def hashmap_hash_map_contains_key_fwd + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result Bool := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + hashmap_hash_map_contains_key_in_list_fwd T key l + +/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ +divergent def hashmap_hash_map_get_in_list_loop_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := + match h: ls with + | hashmap_list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret cvalue + else hashmap_hash_map_get_in_list_loop_fwd T key tl + | hashmap_list_t.Nil => Result.fail Error.panic + +/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ +def hashmap_hash_map_get_in_list_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := + hashmap_hash_map_get_in_list_loop_fwd T key ls + +/- [hashmap_main::hashmap::HashMap::{0}::get] -/ +def hashmap_hash_map_get_fwd + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + hashmap_hash_map_get_in_list_fwd T key l + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +divergent def hashmap_hash_map_get_mut_in_list_loop_fwd + (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := + match h: ls with + | hashmap_list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret cvalue + else hashmap_hash_map_get_mut_in_list_loop_fwd T tl key + | hashmap_list_t.Nil => Result.fail Error.panic + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +def hashmap_hash_map_get_mut_in_list_fwd + (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := + hashmap_hash_map_get_mut_in_list_loop_fwd T ls key + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +divergent def hashmap_hash_map_get_mut_in_list_loop_back + (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : + Result (hashmap_list_t T) + := + match h: ls with + | hashmap_list_t.Cons ckey cvalue tl => + if ckey = key + then Result.ret (hashmap_list_t.Cons ckey ret0 tl) + else + do + let tl0 ← hashmap_hash_map_get_mut_in_list_loop_back T tl key ret0 + Result.ret (hashmap_list_t.Cons ckey cvalue tl0) + | hashmap_list_t.Nil => Result.fail Error.panic + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +def hashmap_hash_map_get_mut_in_list_back + (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : + Result (hashmap_list_t T) + := + hashmap_hash_map_get_mut_in_list_loop_back T ls key ret0 + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ +def hashmap_hash_map_get_mut_fwd + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + hashmap_hash_map_get_mut_in_list_fwd T l key + +/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ +def hashmap_hash_map_get_mut_back + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (ret0 : T) : + Result (hashmap_hash_map_t T) + := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + let l0 ← hashmap_hash_map_get_mut_in_list_back T l key ret0 + let v ← + vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + hash_mod l0 + Result.ret { self with hashmap_hash_map_slots := v } + +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +divergent def hashmap_hash_map_remove_from_list_loop_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := + match h: ls with + | hashmap_list_t.Cons ckey t tl => + if ckey = key + then + let mv_ls := + mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) + hashmap_list_t.Nil + match h: mv_ls with + | hashmap_list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) + | hashmap_list_t.Nil => Result.fail Error.panic + else hashmap_hash_map_remove_from_list_loop_fwd T key tl + | hashmap_list_t.Nil => Result.ret Option.none + +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +def hashmap_hash_map_remove_from_list_fwd + (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := + hashmap_hash_map_remove_from_list_loop_fwd T key ls + +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +divergent def hashmap_hash_map_remove_from_list_loop_back + (T : Type) (key : Usize) (ls : hashmap_list_t T) : + Result (hashmap_list_t T) + := + match h: ls with + | hashmap_list_t.Cons ckey t tl => + if ckey = key + then + let mv_ls := + mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) + hashmap_list_t.Nil + match h: mv_ls with + | hashmap_list_t.Cons i cvalue tl0 => Result.ret tl0 + | hashmap_list_t.Nil => Result.fail Error.panic + else + do + let tl0 ← hashmap_hash_map_remove_from_list_loop_back T key tl + Result.ret (hashmap_list_t.Cons ckey t tl0) + | hashmap_list_t.Nil => Result.ret hashmap_list_t.Nil + +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +def hashmap_hash_map_remove_from_list_back + (T : Type) (key : Usize) (ls : hashmap_list_t T) : + Result (hashmap_list_t T) + := + hashmap_hash_map_remove_from_list_loop_back T key ls + +/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ +def hashmap_hash_map_remove_fwd + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result (Option T) := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + let x ← hashmap_hash_map_remove_from_list_fwd T key l + match h: x with + | Option.none => Result.ret Option.none + | Option.some x0 => + do + let _ ← self.hashmap_hash_map_num_entries - + (Usize.ofInt 1 (by intlit)) + Result.ret (Option.some x0) + +/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ +def hashmap_hash_map_remove_back + (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : + Result (hashmap_hash_map_t T) + := + do + let hash ← hashmap_hash_key_fwd key + let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let hash_mod ← hash % i + let l ← + vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + let x ← hashmap_hash_map_remove_from_list_fwd T key l + match h: x with + | Option.none => + do + let l0 ← hashmap_hash_map_remove_from_list_back T key l + let v ← + vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + hash_mod l0 + Result.ret { self with hashmap_hash_map_slots := v } + | Option.some x0 => + do + let i0 ← self.hashmap_hash_map_num_entries - + (Usize.ofInt 1 (by intlit)) + let l0 ← hashmap_hash_map_remove_from_list_back T key l + let v ← + vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + hash_mod l0 + Result.ret + { + self + with + hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v + } + +/- [hashmap_main::hashmap::test1] -/ +def hashmap_test1_fwd : Result Unit := + do + let hm ← hashmap_hash_map_new_fwd U64 + let hm0 ← + hashmap_hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + (U64.ofInt 42 (by intlit)) + let hm1 ← + hashmap_hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + (U64.ofInt 18 (by intlit)) + let hm2 ← + hashmap_hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + (U64.ofInt 138 (by intlit)) + let hm3 ← + hashmap_hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + (U64.ofInt 256 (by intlit)) + let i ← hashmap_hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + if not (i = (U64.ofInt 18 (by intlit))) + then Result.fail Error.panic + else + do + let hm4 ← + hashmap_hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) + (U64.ofInt 56 (by intlit)) + let i0 ← + hashmap_hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + if not (i0 = (U64.ofInt 56 (by intlit))) + then Result.fail Error.panic + else + do + let x ← + hashmap_hash_map_remove_fwd U64 hm4 + (Usize.ofInt 1024 (by intlit)) + match h: x with + | Option.none => Result.fail Error.panic + | Option.some x0 => + if not (x0 = (U64.ofInt 56 (by intlit))) + then Result.fail Error.panic + else + do + let hm5 ← + hashmap_hash_map_remove_back U64 hm4 + (Usize.ofInt 1024 (by intlit)) + let i1 ← + hashmap_hash_map_get_fwd U64 hm5 + (Usize.ofInt 0 (by intlit)) + if not (i1 = (U64.ofInt 42 (by intlit))) + then Result.fail Error.panic + else + do + let i2 ← + hashmap_hash_map_get_fwd U64 hm5 + (Usize.ofInt 128 (by intlit)) + if not (i2 = (U64.ofInt 18 (by intlit))) + then Result.fail Error.panic + else + do + let i3 ← + hashmap_hash_map_get_fwd U64 hm5 + (Usize.ofInt 1056 (by intlit)) + if not (i3 = (U64.ofInt 256 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [hashmap_main::hashmap::test1] -/ +#assert (hashmap_test1_fwd == .ret ()) + +/- [hashmap_main::insert_on_disk] -/ +def insert_on_disk_fwd + (key : Usize) (value : U64) (st : State) : Result (State × Unit) := + do + let (st0, hm) ← opaque_defs.hashmap_utils_deserialize_fwd st + let hm0 ← hashmap_hash_map_insert_fwd_back U64 hm key value + let (st1, _) ← opaque_defs.hashmap_utils_serialize_fwd hm0 st0 + Result.ret (st1, ()) + +/- [hashmap_main::main] -/ +def main_fwd : Result Unit := + Result.ret () + +/- Unit test for [hashmap_main::main] -/ +#assert (main_fwd == .ret ()) + diff --git a/tests/lean/HashmapMain/Opaque.lean b/tests/lean/HashmapMain/Opaque.lean new file mode 100644 index 00000000..bef4f3fb --- /dev/null +++ b/tests/lean/HashmapMain/Opaque.lean @@ -0,0 +1,16 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap_main]: opaque function definitions +import Base +import HashmapMain.Types +open Primitives + +structure OpaqueDefs where + + /- [hashmap_main::hashmap_utils::deserialize] -/ + hashmap_utils_deserialize_fwd + : State -> Result (State × (hashmap_hash_map_t U64)) + + /- [hashmap_main::hashmap_utils::serialize] -/ + hashmap_utils_serialize_fwd + : hashmap_hash_map_t U64 -> State -> Result (State × Unit) + diff --git a/tests/lean/HashmapMain/Types.lean b/tests/lean/HashmapMain/Types.lean new file mode 100644 index 00000000..858e1c51 --- /dev/null +++ b/tests/lean/HashmapMain/Types.lean @@ -0,0 +1,20 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap_main]: type definitions +import Base +open Primitives + +/- [hashmap_main::hashmap::List] -/ +inductive hashmap_list_t (T : Type) := +| Cons : Usize -> T -> hashmap_list_t T -> hashmap_list_t T +| Nil : hashmap_list_t T + +/- [hashmap_main::hashmap::HashMap] -/ +structure hashmap_hash_map_t (T : Type) where + hashmap_hash_map_num_entries : Usize + hashmap_hash_map_max_load_factor : (Usize × Usize) + hashmap_hash_map_max_load : Usize + hashmap_hash_map_slots : Vec (hashmap_list_t T) + +/- The state type used in the state-error monad -/ +axiom State : Type + diff --git a/tests/lean/Loops.lean b/tests/lean/Loops.lean new file mode 100644 index 00000000..60c73776 --- /dev/null +++ b/tests/lean/Loops.lean @@ -0,0 +1 @@ +import Loops.Funs diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean new file mode 100644 index 00000000..7d5f7595 --- /dev/null +++ b/tests/lean/Loops/Funs.lean @@ -0,0 +1,624 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [loops]: function definitions +import Base +import Loops.Types +open Primitives + +/- [loops::sum] -/ +divergent def sum_loop_fwd (max : U32) (i : U32) (s : U32) : Result U32 := + if i < max + then + do + let s0 ← s + i + let i0 ← i + (U32.ofInt 1 (by intlit)) + sum_loop_fwd max i0 s0 + else s * (U32.ofInt 2 (by intlit)) + +/- [loops::sum] -/ +def sum_fwd (max : U32) : Result U32 := + sum_loop_fwd max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) + +/- [loops::sum_with_mut_borrows] -/ +divergent def sum_with_mut_borrows_loop_fwd + (max : U32) (mi : U32) (ms : U32) : Result U32 := + if mi < max + then + do + let ms0 ← ms + mi + let mi0 ← mi + (U32.ofInt 1 (by intlit)) + sum_with_mut_borrows_loop_fwd max mi0 ms0 + else ms * (U32.ofInt 2 (by intlit)) + +/- [loops::sum_with_mut_borrows] -/ +def sum_with_mut_borrows_fwd (max : U32) : Result U32 := + sum_with_mut_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) + (U32.ofInt 0 (by intlit)) + +/- [loops::sum_with_shared_borrows] -/ +divergent def sum_with_shared_borrows_loop_fwd + (max : U32) (i : U32) (s : U32) : Result U32 := + if i < max + then + do + let i0 ← i + (U32.ofInt 1 (by intlit)) + let s0 ← s + i0 + sum_with_shared_borrows_loop_fwd max i0 s0 + else s * (U32.ofInt 2 (by intlit)) + +/- [loops::sum_with_shared_borrows] -/ +def sum_with_shared_borrows_fwd (max : U32) : Result U32 := + sum_with_shared_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) + (U32.ofInt 0 (by intlit)) + +/- [loops::clear] -/ +divergent def clear_loop_fwd_back + (v : Vec U32) (i : Usize) : Result (Vec U32) := + let i0 := vec_len U32 v + if i < i0 + then + do + let i1 ← i + (Usize.ofInt 1 (by intlit)) + let v0 ← vec_index_mut_back U32 v i (U32.ofInt 0 (by intlit)) + clear_loop_fwd_back v0 i1 + else Result.ret v + +/- [loops::clear] -/ +def clear_fwd_back (v : Vec U32) : Result (Vec U32) := + clear_loop_fwd_back v (Usize.ofInt 0 (by intlit)) + +/- [loops::list_mem] -/ +divergent def list_mem_loop_fwd (x : U32) (ls : list_t U32) : Result Bool := + match h: ls with + | list_t.Cons y tl => + if y = x + then Result.ret true + else list_mem_loop_fwd x tl + | list_t.Nil => Result.ret false + +/- [loops::list_mem] -/ +def list_mem_fwd (x : U32) (ls : list_t U32) : Result Bool := + list_mem_loop_fwd x ls + +/- [loops::list_nth_mut_loop] -/ +divergent def list_nth_mut_loop_loop_fwd + (T : Type) (ls : list_t T) (i : U32) : Result T := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_loop_loop_fwd T tl i0 + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop] -/ +def list_nth_mut_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := + list_nth_mut_loop_loop_fwd T ls i + +/- [loops::list_nth_mut_loop] -/ +divergent def list_nth_mut_loop_loop_back + (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl0 ← list_nth_mut_loop_loop_back T tl i0 ret0 + Result.ret (list_t.Cons x tl0) + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop] -/ +def list_nth_mut_loop_back + (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + list_nth_mut_loop_loop_back T ls i ret0 + +/- [loops::list_nth_shared_loop] -/ +divergent def list_nth_shared_loop_loop_fwd + (T : Type) (ls : list_t T) (i : U32) : Result T := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_loop_loop_fwd T tl i0 + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_loop] -/ +def list_nth_shared_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := + list_nth_shared_loop_loop_fwd T ls i + +/- [loops::get_elem_mut] -/ +divergent def get_elem_mut_loop_fwd + (x : Usize) (ls : list_t Usize) : Result Usize := + match h: ls with + | list_t.Cons y tl => + if y = x + then Result.ret y + else get_elem_mut_loop_fwd x tl + | list_t.Nil => Result.fail Error.panic + +/- [loops::get_elem_mut] -/ +def get_elem_mut_fwd (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := + do + let l ← + vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + get_elem_mut_loop_fwd x l + +/- [loops::get_elem_mut] -/ +divergent def get_elem_mut_loop_back + (x : Usize) (ls : list_t Usize) (ret0 : Usize) : Result (list_t Usize) := + match h: ls with + | list_t.Cons y tl => + if y = x + then Result.ret (list_t.Cons ret0 tl) + else + do + let tl0 ← get_elem_mut_loop_back x tl ret0 + Result.ret (list_t.Cons y tl0) + | list_t.Nil => Result.fail Error.panic + +/- [loops::get_elem_mut] -/ +def get_elem_mut_back + (slots : Vec (list_t Usize)) (x : Usize) (ret0 : Usize) : + Result (Vec (list_t Usize)) + := + do + let l ← + vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + let l0 ← get_elem_mut_loop_back x l ret0 + vec_index_mut_back (list_t Usize) slots (Usize.ofInt 0 (by intlit)) l0 + +/- [loops::get_elem_shared] -/ +divergent def get_elem_shared_loop_fwd + (x : Usize) (ls : list_t Usize) : Result Usize := + match h: ls with + | list_t.Cons y tl => + if y = x + then Result.ret y + else get_elem_shared_loop_fwd x tl + | list_t.Nil => Result.fail Error.panic + +/- [loops::get_elem_shared] -/ +def get_elem_shared_fwd + (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := + do + let l ← vec_index_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + get_elem_shared_loop_fwd x l + +/- [loops::id_mut] -/ +def id_mut_fwd (T : Type) (ls : list_t T) : Result (list_t T) := + Result.ret ls + +/- [loops::id_mut] -/ +def id_mut_back + (T : Type) (ls : list_t T) (ret0 : list_t T) : Result (list_t T) := + Result.ret ret0 + +/- [loops::id_shared] -/ +def id_shared_fwd (T : Type) (ls : list_t T) : Result (list_t T) := + Result.ret ls + +/- [loops::list_nth_mut_loop_with_id] -/ +divergent def list_nth_mut_loop_with_id_loop_fwd + (T : Type) (i : U32) (ls : list_t T) : Result T := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_loop_with_id_loop_fwd T i0 tl + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_with_id] -/ +def list_nth_mut_loop_with_id_fwd + (T : Type) (ls : list_t T) (i : U32) : Result T := + do + let ls0 ← id_mut_fwd T ls + list_nth_mut_loop_with_id_loop_fwd T i ls0 + +/- [loops::list_nth_mut_loop_with_id] -/ +divergent def list_nth_mut_loop_with_id_loop_back + (T : Type) (i : U32) (ls : list_t T) (ret0 : T) : Result (list_t T) := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl0 ← list_nth_mut_loop_with_id_loop_back T i0 tl ret0 + Result.ret (list_t.Cons x tl0) + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_with_id] -/ +def list_nth_mut_loop_with_id_back + (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + do + let ls0 ← id_mut_fwd T ls + let l ← list_nth_mut_loop_with_id_loop_back T i ls0 ret0 + id_mut_back T ls l + +/- [loops::list_nth_shared_loop_with_id] -/ +divergent def list_nth_shared_loop_with_id_loop_fwd + (T : Type) (i : U32) (ls : list_t T) : Result T := + match h: ls with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_loop_with_id_loop_fwd T i0 tl + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_loop_with_id] -/ +def list_nth_shared_loop_with_id_fwd + (T : Type) (ls : list_t T) (i : U32) : Result T := + do + let ls0 ← id_shared_fwd T ls + list_nth_shared_loop_with_id_loop_fwd T i ls0 + +/- [loops::list_nth_mut_loop_pair] -/ +divergent def list_nth_mut_loop_pair_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_loop_pair_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_pair] -/ +def list_nth_mut_loop_pair_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_mut_loop_pair_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_loop_pair] -/ +divergent def list_nth_mut_loop_pair_loop_back'a + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl0) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl00 ← list_nth_mut_loop_pair_loop_back'a T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x0 tl00) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_pair] -/ +def list_nth_mut_loop_pair_back'a + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_mut_loop_pair_loop_back'a T ls0 ls1 i ret0 + +/- [loops::list_nth_mut_loop_pair] -/ +divergent def list_nth_mut_loop_pair_loop_back'b + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl10 ← list_nth_mut_loop_pair_loop_back'b T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x1 tl10) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_pair] -/ +def list_nth_mut_loop_pair_back'b + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_mut_loop_pair_loop_back'b T ls0 ls1 i ret0 + +/- [loops::list_nth_shared_loop_pair] -/ +divergent def list_nth_shared_loop_pair_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_loop_pair_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_loop_pair] -/ +def list_nth_shared_loop_pair_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_shared_loop_pair_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_loop_pair_merge] -/ +divergent def list_nth_mut_loop_pair_merge_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_pair_merge] -/ +def list_nth_mut_loop_pair_merge_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_mut_loop_pair_merge_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_loop_pair_merge] -/ +divergent def list_nth_mut_loop_pair_merge_loop_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : + Result ((list_t T) × (list_t T)) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then + let (t, t0) := ret0 + Result.ret (list_t.Cons t tl0, list_t.Cons t0 tl1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let (tl00, tl10) ← + list_nth_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x0 tl00, list_t.Cons x1 tl10) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_loop_pair_merge] -/ +def list_nth_mut_loop_pair_merge_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : + Result ((list_t T) × (list_t T)) + := + list_nth_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 + +/- [loops::list_nth_shared_loop_pair_merge] -/ +divergent def list_nth_shared_loop_pair_merge_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_loop_pair_merge] -/ +def list_nth_shared_loop_pair_merge_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_shared_loop_pair_merge_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_shared_loop_pair] -/ +divergent def list_nth_mut_shared_loop_pair_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_shared_loop_pair_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_shared_loop_pair] -/ +def list_nth_mut_shared_loop_pair_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_mut_shared_loop_pair_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_shared_loop_pair] -/ +divergent def list_nth_mut_shared_loop_pair_loop_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl0) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl00 ← + list_nth_mut_shared_loop_pair_loop_back T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x0 tl00) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_shared_loop_pair] -/ +def list_nth_mut_shared_loop_pair_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_mut_shared_loop_pair_loop_back T ls0 ls1 i ret0 + +/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +divergent def list_nth_mut_shared_loop_pair_merge_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +def list_nth_mut_shared_loop_pair_merge_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_mut_shared_loop_pair_merge_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +divergent def list_nth_mut_shared_loop_pair_merge_loop_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl0) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl00 ← + list_nth_mut_shared_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x0 tl00) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +def list_nth_mut_shared_loop_pair_merge_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_mut_shared_loop_pair_merge_loop_back T ls0 ls1 i ret0 + +/- [loops::list_nth_shared_mut_loop_pair] -/ +divergent def list_nth_shared_mut_loop_pair_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_mut_loop_pair_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_mut_loop_pair] -/ +def list_nth_shared_mut_loop_pair_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_shared_mut_loop_pair_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_shared_mut_loop_pair] -/ +divergent def list_nth_shared_mut_loop_pair_loop_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl10 ← + list_nth_shared_mut_loop_pair_loop_back T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x1 tl10) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_mut_loop_pair] -/ +def list_nth_shared_mut_loop_pair_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_shared_mut_loop_pair_loop_back T ls0 ls1 i ret0 + +/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +divergent def list_nth_shared_mut_loop_pair_merge_loop_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (x0, x1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +def list_nth_shared_mut_loop_pair_merge_fwd + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + list_nth_shared_mut_loop_pair_merge_loop_fwd T ls0 ls1 i + +/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +divergent def list_nth_shared_mut_loop_pair_merge_loop_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + match h: ls0 with + | list_t.Cons x0 tl0 => + match h: ls1 with + | list_t.Cons x1 tl1 => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl1) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl10 ← + list_nth_shared_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 + Result.ret (list_t.Cons x1 tl10) + | list_t.Nil => Result.fail Error.panic + | list_t.Nil => Result.fail Error.panic + +/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +def list_nth_shared_mut_loop_pair_merge_back + (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : + Result (list_t T) + := + list_nth_shared_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 + diff --git a/tests/lean/Loops/Types.lean b/tests/lean/Loops/Types.lean new file mode 100644 index 00000000..e14f9766 --- /dev/null +++ b/tests/lean/Loops/Types.lean @@ -0,0 +1,10 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [loops]: type definitions +import Base +open Primitives + +/- [loops::List] -/ +inductive list_t (T : Type) := +| Cons : T -> list_t T -> list_t T +| Nil : list_t T + diff --git a/tests/lean/Makefile b/tests/lean/Makefile index ed3b3e3b..3ccfbec2 100644 --- a/tests/lean/Makefile +++ b/tests/lean/Makefile @@ -1,40 +1,35 @@ ALL_DIRS ?= $(filter-out %~ lean-toolchain% Makefile%, $(wildcard *)) +# TODO: remove UPDATE_DIRS = $(addprefix update-,$(ALL_DIRS)) +# TODO: remove VERIFY_DIRS = $(addprefix verif-,$(ALL_DIRS)) +# TODO: remove CLEAN_DIRS = $(addprefix clean-,$(ALL_DIRS)) +# TODO: remove COPY_LEAN_TOOLCHAIN = $(addprefix copy-lean-toolchain-,$(ALL_DIRS)) .PHONY: all all: prepare-projects verify .PHONY: prepare-projects -prepare-projects: $(COPY_LEAN_TOOLCHAIN) +prepare-projects: copy-lean-toolchain .PHONY: prepare-projects -copy-lean-toolchain-%: - cp lean-toolchain $* +copy-lean-toolchain: + cp ../../backends/lean/lean-toolchain . .PHONY: update -update: $(UPDATE_DIRS) - -.PHONY: update-% -update-%: - cd $* && lake update +update: + lake update .PHONY: verify -verify: $(VERIFY_DIRS) - -.PHONY: verif-% -verif-%: - cd $* && lake build +verify: + lake build .PHONY: clean -clean: $(CLEAN_DIRS) - -.PHONY: clean-% -clean-%: - cd $* && lake clean +clean: + lake clean diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean new file mode 100644 index 00000000..67ef4b20 --- /dev/null +++ b/tests/lean/NoNestedBorrows.lean @@ -0,0 +1,541 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [no_nested_borrows] +import Base +open Primitives + +/- [no_nested_borrows::Pair] -/ +structure pair_t (T1 T2 : Type) where + pair_x : T1 + pair_y : T2 + +/- [no_nested_borrows::List] -/ +inductive list_t (T : Type) := +| Cons : T -> list_t T -> list_t T +| Nil : list_t T + +/- [no_nested_borrows::One] -/ +inductive one_t (T1 : Type) := +| One : T1 -> one_t T1 + +/- [no_nested_borrows::EmptyEnum] -/ +inductive empty_enum_t := +| Empty : empty_enum_t + +/- [no_nested_borrows::Enum] -/ +inductive enum_t := +| Variant1 : enum_t +| Variant2 : enum_t + +/- [no_nested_borrows::EmptyStruct] -/ +structure empty_struct_t where + +/- [no_nested_borrows::Sum] -/ +inductive sum_t (T1 T2 : Type) := +| Left : T1 -> sum_t T1 T2 +| Right : T2 -> sum_t T1 T2 + +/- [no_nested_borrows::neg_test] -/ +def neg_test_fwd (x : I32) : Result I32 := + - x + +/- [no_nested_borrows::add_test] -/ +def add_test_fwd (x : U32) (y : U32) : Result U32 := + x + y + +/- [no_nested_borrows::subs_test] -/ +def subs_test_fwd (x : U32) (y : U32) : Result U32 := + x - y + +/- [no_nested_borrows::div_test] -/ +def div_test_fwd (x : U32) (y : U32) : Result U32 := + x / y + +/- [no_nested_borrows::div_test1] -/ +def div_test1_fwd (x : U32) : Result U32 := + x / (U32.ofInt 2 (by intlit)) + +/- [no_nested_borrows::rem_test] -/ +def rem_test_fwd (x : U32) (y : U32) : Result U32 := + x % y + +/- [no_nested_borrows::cast_test] -/ +def cast_test_fwd (x : U32) : Result I32 := + Scalar.cast .I32 x + +/- [no_nested_borrows::test2] -/ +def test2_fwd : Result Unit := + do + let _ ← (U32.ofInt 23 (by intlit)) + (U32.ofInt 44 (by intlit)) + Result.ret () + +/- Unit test for [no_nested_borrows::test2] -/ +#assert (test2_fwd == .ret ()) + +/- [no_nested_borrows::get_max] -/ +def get_max_fwd (x : U32) (y : U32) : Result U32 := + if x >= y + then Result.ret x + else Result.ret y + +/- [no_nested_borrows::test3] -/ +def test3_fwd : Result Unit := + do + let x ← get_max_fwd (U32.ofInt 4 (by intlit)) (U32.ofInt 3 (by intlit)) + let y ← get_max_fwd (U32.ofInt 10 (by intlit)) (U32.ofInt 11 (by intlit)) + let z ← x + y + if not (z = (U32.ofInt 15 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test3] -/ +#assert (test3_fwd == .ret ()) + +/- [no_nested_borrows::test_neg1] -/ +def test_neg1_fwd : Result Unit := + do + let y ← - (I32.ofInt 3 (by intlit)) + if not (y = (I32.ofInt (-(3:Int)) (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_neg1] -/ +#assert (test_neg1_fwd == .ret ()) + +/- [no_nested_borrows::refs_test1] -/ +def refs_test1_fwd : Result Unit := + if not ((I32.ofInt 1 (by intlit)) = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::refs_test1] -/ +#assert (refs_test1_fwd == .ret ()) + +/- [no_nested_borrows::refs_test2] -/ +def refs_test2_fwd : Result Unit := + if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + then Result.fail Error.panic + else + if not ((I32.ofInt 0 (by intlit)) = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else + if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + then Result.fail Error.panic + else + if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::refs_test2] -/ +#assert (refs_test2_fwd == .ret ()) + +/- [no_nested_borrows::test_list1] -/ +def test_list1_fwd : Result Unit := + Result.ret () + +/- Unit test for [no_nested_borrows::test_list1] -/ +#assert (test_list1_fwd == .ret ()) + +/- [no_nested_borrows::test_box1] -/ +def test_box1_fwd : Result Unit := + let b := (I32.ofInt 1 (by intlit)) + let x := b + if not (x = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_box1] -/ +#assert (test_box1_fwd == .ret ()) + +/- [no_nested_borrows::copy_int] -/ +def copy_int_fwd (x : I32) : Result I32 := + Result.ret x + +/- [no_nested_borrows::test_unreachable] -/ +def test_unreachable_fwd (b : Bool) : Result Unit := + if b + then Result.fail Error.panic + else Result.ret () + +/- [no_nested_borrows::test_panic] -/ +def test_panic_fwd (b : Bool) : Result Unit := + if b + then Result.fail Error.panic + else Result.ret () + +/- [no_nested_borrows::test_copy_int] -/ +def test_copy_int_fwd : Result Unit := + do + let y ← copy_int_fwd (I32.ofInt 0 (by intlit)) + if not ((I32.ofInt 0 (by intlit)) = y) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_copy_int] -/ +#assert (test_copy_int_fwd == .ret ()) + +/- [no_nested_borrows::is_cons] -/ +def is_cons_fwd (T : Type) (l : list_t T) : Result Bool := + match h: l with + | list_t.Cons t l0 => Result.ret true + | list_t.Nil => Result.ret false + +/- [no_nested_borrows::test_is_cons] -/ +def test_is_cons_fwd : Result Unit := + do + let l := list_t.Nil + let b ← is_cons_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) + if not b + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_is_cons] -/ +#assert (test_is_cons_fwd == .ret ()) + +/- [no_nested_borrows::split_list] -/ +def split_list_fwd (T : Type) (l : list_t T) : Result (T × (list_t T)) := + match h: l with + | list_t.Cons hd tl => Result.ret (hd, tl) + | list_t.Nil => Result.fail Error.panic + +/- [no_nested_borrows::test_split_list] -/ +def test_split_list_fwd : Result Unit := + do + let l := list_t.Nil + let p ← split_list_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) + let (hd, _) := p + if not (hd = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_split_list] -/ +#assert (test_split_list_fwd == .ret ()) + +/- [no_nested_borrows::choose] -/ +def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := + if b + then Result.ret x + else Result.ret y + +/- [no_nested_borrows::choose] -/ +def choose_back + (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := + if b + then Result.ret (ret0, y) + else Result.ret (x, ret0) + +/- [no_nested_borrows::choose_test] -/ +def choose_test_fwd : Result Unit := + do + let z ← + choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) + let z0 ← z + (I32.ofInt 1 (by intlit)) + if not (z0 = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let (x, y) ← + choose_back I32 true (I32.ofInt 0 (by intlit)) + (I32.ofInt 0 (by intlit)) z0 + if not (x = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + if not (y = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::choose_test] -/ +#assert (choose_test_fwd == .ret ()) + +/- [no_nested_borrows::test_char] -/ +def test_char_fwd : Result Char := + Result.ret 'a' + +mutual + +/- [no_nested_borrows::NodeElem] -/ +inductive node_elem_t (T : Type) := +| Cons : tree_t T -> node_elem_t T -> node_elem_t T +| Nil : node_elem_t T + +/- [no_nested_borrows::Tree] -/ +inductive tree_t (T : Type) := +| Leaf : T -> tree_t T +| Node : T -> node_elem_t T -> tree_t T -> tree_t T + +end + +/- [no_nested_borrows::list_length] -/ +divergent def list_length_fwd (T : Type) (l : list_t T) : Result U32 := + match h: l with + | list_t.Cons t l1 => + do + let i ← list_length_fwd T l1 + (U32.ofInt 1 (by intlit)) + i + | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) + +/- [no_nested_borrows::list_nth_shared] -/ +divergent def list_nth_shared_fwd + (T : Type) (l : list_t T) (i : U32) : Result T := + match h: l with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared_fwd T tl i0 + | list_t.Nil => Result.fail Error.panic + +/- [no_nested_borrows::list_nth_mut] -/ +divergent def list_nth_mut_fwd + (T : Type) (l : list_t T) (i : U32) : Result T := + match h: l with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_fwd T tl i0 + | list_t.Nil => Result.fail Error.panic + +/- [no_nested_borrows::list_nth_mut] -/ +divergent def list_nth_mut_back + (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + match h: l with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl0 ← list_nth_mut_back T tl i0 ret0 + Result.ret (list_t.Cons x tl0) + | list_t.Nil => Result.fail Error.panic + +/- [no_nested_borrows::list_rev_aux] -/ +divergent def list_rev_aux_fwd + (T : Type) (li : list_t T) (lo : list_t T) : Result (list_t T) := + match h: li with + | list_t.Cons hd tl => list_rev_aux_fwd T tl (list_t.Cons hd lo) + | list_t.Nil => Result.ret lo + +/- [no_nested_borrows::list_rev] -/ +def list_rev_fwd_back (T : Type) (l : list_t T) : Result (list_t T) := + let li := mem_replace_fwd (list_t T) l list_t.Nil + list_rev_aux_fwd T li list_t.Nil + +/- [no_nested_borrows::test_list_functions] -/ +def test_list_functions_fwd : Result Unit := + do + let l := list_t.Nil + let l0 := list_t.Cons (I32.ofInt 2 (by intlit)) l + let l1 := list_t.Cons (I32.ofInt 1 (by intlit)) l0 + let i ← list_length_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) + if not (i = (U32.ofInt 3 (by intlit))) + then Result.fail Error.panic + else + do + let i0 ← + list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) + (U32.ofInt 0 (by intlit)) + if not (i0 = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else + do + let i1 ← + list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) + l1) (U32.ofInt 1 (by intlit)) + if not (i1 = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let i2 ← + list_nth_shared_fwd I32 (list_t.Cons + (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 2 (by intlit)) + if not (i2 = (I32.ofInt 2 (by intlit))) + then Result.fail Error.panic + else + do + let ls ← + list_nth_mut_back I32 (list_t.Cons + (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) + (I32.ofInt 3 (by intlit)) + let i3 ← + list_nth_shared_fwd I32 ls (U32.ofInt 0 (by intlit)) + if not (i3 = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else + do + let i4 ← + list_nth_shared_fwd I32 ls (U32.ofInt 1 (by intlit)) + if not (i4 = (I32.ofInt 3 (by intlit))) + then Result.fail Error.panic + else + do + let i5 ← + list_nth_shared_fwd I32 ls + (U32.ofInt 2 (by intlit)) + if not (i5 = (I32.ofInt 2 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_list_functions] -/ +#assert (test_list_functions_fwd == .ret ()) + +/- [no_nested_borrows::id_mut_pair1] -/ +def id_mut_pair1_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := + Result.ret (x, y) + +/- [no_nested_borrows::id_mut_pair1] -/ +def id_mut_pair1_back + (T1 T2 : Type) (x : T1) (y : T2) (ret0 : (T1 × T2)) : Result (T1 × T2) := + let (t, t0) := ret0 + Result.ret (t, t0) + +/- [no_nested_borrows::id_mut_pair2] -/ +def id_mut_pair2_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := + let (t, t0) := p + Result.ret (t, t0) + +/- [no_nested_borrows::id_mut_pair2] -/ +def id_mut_pair2_back + (T1 T2 : Type) (p : (T1 × T2)) (ret0 : (T1 × T2)) : Result (T1 × T2) := + let (t, t0) := ret0 + Result.ret (t, t0) + +/- [no_nested_borrows::id_mut_pair3] -/ +def id_mut_pair3_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := + Result.ret (x, y) + +/- [no_nested_borrows::id_mut_pair3] -/ +def id_mut_pair3_back'a + (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T1) : Result T1 := + Result.ret ret0 + +/- [no_nested_borrows::id_mut_pair3] -/ +def id_mut_pair3_back'b + (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T2) : Result T2 := + Result.ret ret0 + +/- [no_nested_borrows::id_mut_pair4] -/ +def id_mut_pair4_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := + let (t, t0) := p + Result.ret (t, t0) + +/- [no_nested_borrows::id_mut_pair4] -/ +def id_mut_pair4_back'a + (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T1) : Result T1 := + Result.ret ret0 + +/- [no_nested_borrows::id_mut_pair4] -/ +def id_mut_pair4_back'b + (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T2) : Result T2 := + Result.ret ret0 + +/- [no_nested_borrows::StructWithTuple] -/ +structure struct_with_tuple_t (T1 T2 : Type) where + struct_with_tuple_p : (T1 × T2) + +/- [no_nested_borrows::new_tuple1] -/ +def new_tuple1_fwd : Result (struct_with_tuple_t U32 U32) := + Result.ret + { + struct_with_tuple_p := + ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) + } + +/- [no_nested_borrows::new_tuple2] -/ +def new_tuple2_fwd : Result (struct_with_tuple_t I16 I16) := + Result.ret + { + struct_with_tuple_p := + ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) + } + +/- [no_nested_borrows::new_tuple3] -/ +def new_tuple3_fwd : Result (struct_with_tuple_t U64 I64) := + Result.ret + { + struct_with_tuple_p := + ((U64.ofInt 1 (by intlit)), (I64.ofInt 2 (by intlit))) + } + +/- [no_nested_borrows::StructWithPair] -/ +structure struct_with_pair_t (T1 T2 : Type) where + struct_with_pair_p : pair_t T1 T2 + +/- [no_nested_borrows::new_pair1] -/ +def new_pair1_fwd : Result (struct_with_pair_t U32 U32) := + Result.ret + { + struct_with_pair_p := + { + pair_x := (U32.ofInt 1 (by intlit)), + pair_y := (U32.ofInt 2 (by intlit)) + } + } + +/- [no_nested_borrows::test_constants] -/ +def test_constants_fwd : Result Unit := + do + let swt ← new_tuple1_fwd + let (i, _) := swt.struct_with_tuple_p + if not (i = (U32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let swt0 ← new_tuple2_fwd + let (i0, _) := swt0.struct_with_tuple_p + if not (i0 = (I16.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let swt1 ← new_tuple3_fwd + let (i1, _) := swt1.struct_with_tuple_p + if not (i1 = (U64.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let swp ← new_pair1_fwd + if not (swp.struct_with_pair_p.pair_x = + (U32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [no_nested_borrows::test_constants] -/ +#assert (test_constants_fwd == .ret ()) + +/- [no_nested_borrows::test_weird_borrows1] -/ +def test_weird_borrows1_fwd : Result Unit := + Result.ret () + +/- Unit test for [no_nested_borrows::test_weird_borrows1] -/ +#assert (test_weird_borrows1_fwd == .ret ()) + +/- [no_nested_borrows::test_mem_replace] -/ +def test_mem_replace_fwd_back (px : U32) : Result U32 := + let y := mem_replace_fwd U32 px (U32.ofInt 1 (by intlit)) + if not (y = (U32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else Result.ret (U32.ofInt 2 (by intlit)) + +/- [no_nested_borrows::test_shared_borrow_bool1] -/ +def test_shared_borrow_bool1_fwd (b : Bool) : Result U32 := + if b + then Result.ret (U32.ofInt 0 (by intlit)) + else Result.ret (U32.ofInt 1 (by intlit)) + +/- [no_nested_borrows::test_shared_borrow_bool2] -/ +def test_shared_borrow_bool2_fwd : Result U32 := + Result.ret (U32.ofInt 0 (by intlit)) + +/- [no_nested_borrows::test_shared_borrow_enum1] -/ +def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := + match h: l with + | list_t.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) + | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) + +/- [no_nested_borrows::test_shared_borrow_enum2] -/ +def test_shared_borrow_enum2_fwd : Result U32 := + Result.ret (U32.ofInt 0 (by intlit)) + diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean new file mode 100644 index 00000000..9019b694 --- /dev/null +++ b/tests/lean/Paper.lean @@ -0,0 +1,125 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [paper] +import Base +open Primitives + +/- [paper::ref_incr] -/ +def ref_incr_fwd_back (x : I32) : Result I32 := + x + (I32.ofInt 1 (by intlit)) + +/- [paper::test_incr] -/ +def test_incr_fwd : Result Unit := + do + let x ← ref_incr_fwd_back (I32.ofInt 0 (by intlit)) + if not (x = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [paper::test_incr] -/ +#assert (test_incr_fwd == .ret ()) + +/- [paper::choose] -/ +def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := + if b + then Result.ret x + else Result.ret y + +/- [paper::choose] -/ +def choose_back + (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := + if b + then Result.ret (ret0, y) + else Result.ret (x, ret0) + +/- [paper::test_choose] -/ +def test_choose_fwd : Result Unit := + do + let z ← + choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) + let z0 ← z + (I32.ofInt 1 (by intlit)) + if not (z0 = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + do + let (x, y) ← + choose_back I32 true (I32.ofInt 0 (by intlit)) + (I32.ofInt 0 (by intlit)) z0 + if not (x = (I32.ofInt 1 (by intlit))) + then Result.fail Error.panic + else + if not (y = (I32.ofInt 0 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [paper::test_choose] -/ +#assert (test_choose_fwd == .ret ()) + +/- [paper::List] -/ +inductive list_t (T : Type) := +| Cons : T -> list_t T -> list_t T +| Nil : list_t T + +/- [paper::list_nth_mut] -/ +divergent def list_nth_mut_fwd + (T : Type) (l : list_t T) (i : U32) : Result T := + match h: l with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret x + else do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_mut_fwd T tl i0 + | list_t.Nil => Result.fail Error.panic + +/- [paper::list_nth_mut] -/ +divergent def list_nth_mut_back + (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + match h: l with + | list_t.Cons x tl => + if i = (U32.ofInt 0 (by intlit)) + then Result.ret (list_t.Cons ret0 tl) + else + do + let i0 ← i - (U32.ofInt 1 (by intlit)) + let tl0 ← list_nth_mut_back T tl i0 ret0 + Result.ret (list_t.Cons x tl0) + | list_t.Nil => Result.fail Error.panic + +/- [paper::sum] -/ +divergent def sum_fwd (l : list_t I32) : Result I32 := + match h: l with + | list_t.Cons x tl => do + let i ← sum_fwd tl + x + i + | list_t.Nil => Result.ret (I32.ofInt 0 (by intlit)) + +/- [paper::test_nth] -/ +def test_nth_fwd : Result Unit := + do + let l := list_t.Nil + let l0 := list_t.Cons (I32.ofInt 3 (by intlit)) l + let l1 := list_t.Cons (I32.ofInt 2 (by intlit)) l0 + let x ← + list_nth_mut_fwd I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) + (U32.ofInt 2 (by intlit)) + let x0 ← x + (I32.ofInt 1 (by intlit)) + let l2 ← + list_nth_mut_back I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) + (U32.ofInt 2 (by intlit)) x0 + let i ← sum_fwd l2 + if not (i = (I32.ofInt 7 (by intlit))) + then Result.fail Error.panic + else Result.ret () + +/- Unit test for [paper::test_nth] -/ +#assert (test_nth_fwd == .ret ()) + +/- [paper::call_choose] -/ +def call_choose_fwd (p : (U32 × U32)) : Result U32 := + do + let (px, py) := p + let pz ← choose_fwd U32 true px py + let pz0 ← pz + (U32.ofInt 1 (by intlit)) + let (px0, _) ← choose_back U32 true px py pz0 + Result.ret px0 + diff --git a/tests/lean/PoloniusList.lean b/tests/lean/PoloniusList.lean new file mode 100644 index 00000000..671f54ea --- /dev/null +++ b/tests/lean/PoloniusList.lean @@ -0,0 +1,33 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [polonius_list] +import Base +open Primitives + +/- [polonius_list::List] -/ +inductive list_t (T : Type) := +| Cons : T -> list_t T -> list_t T +| Nil : list_t T + +/- [polonius_list::get_list_at_x] -/ +divergent def get_list_at_x_fwd + (ls : list_t U32) (x : U32) : Result (list_t U32) := + match h: ls with + | list_t.Cons hd tl => + if hd = x + then Result.ret (list_t.Cons hd tl) + else get_list_at_x_fwd tl x + | list_t.Nil => Result.ret list_t.Nil + +/- [polonius_list::get_list_at_x] -/ +divergent def get_list_at_x_back + (ls : list_t U32) (x : U32) (ret0 : list_t U32) : Result (list_t U32) := + match h: ls with + | list_t.Cons hd tl => + if hd = x + then Result.ret ret0 + else + do + let tl0 ← get_list_at_x_back tl x ret0 + Result.ret (list_t.Cons hd tl0) + | list_t.Nil => Result.ret ret0 + diff --git a/tests/lean/Tests.lean b/tests/lean/Tests.lean new file mode 100644 index 00000000..9b12270e --- /dev/null +++ b/tests/lean/Tests.lean @@ -0,0 +1,9 @@ +import BetreeMain +import Constants +import External +import Hashmap +import HashmapMain +import Loops +import NoNestedBorrows +import Paper +import PoloniusList diff --git a/tests/lean/hashmap/Base/Primitives.lean b/tests/lean/hashmap/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/hashmap/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/hashmap/Hashmap.lean b/tests/lean/hashmap/Hashmap.lean deleted file mode 100644 index 41630205..00000000 --- a/tests/lean/hashmap/Hashmap.lean +++ /dev/null @@ -1 +0,0 @@ -import Hashmap.Funs diff --git a/tests/lean/hashmap/Hashmap/Clauses/Clauses.lean b/tests/lean/hashmap/Hashmap/Clauses/Clauses.lean deleted file mode 100644 index 197b0a6a..00000000 --- a/tests/lean/hashmap/Hashmap/Clauses/Clauses.lean +++ /dev/null @@ -1,107 +0,0 @@ --- [hashmap]: templates for the decreases clauses -import Base.Primitives -import Hashmap.Types - -/- [hashmap::HashMap::{0}::allocate_slots]: termination measure -/ -@[simp] -def hash_map_allocate_slots_loop_terminates (T : Type) (slots : Vec (list_t T)) - (n : Usize) := - (slots, n) - -/- [hashmap::HashMap::{0}::allocate_slots]: decreases_by tactic -/ -syntax "hash_map_allocate_slots_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_allocate_slots_loop_decreases $slots $n) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::clear]: termination measure -/ -@[simp] -def hash_map_clear_loop_terminates (T : Type) (slots : Vec (list_t T)) - (i : Usize) := - (slots, i) - -/- [hashmap::HashMap::{0}::clear]: decreases_by tactic -/ -syntax "hash_map_clear_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_clear_loop_decreases $slots $i) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::insert_in_list]: termination measure -/ -@[simp] -def hash_map_insert_in_list_loop_terminates (T : Type) (key : Usize) - (value : T) (ls : list_t T) := - (key, value, ls) - -/- [hashmap::HashMap::{0}::insert_in_list]: decreases_by tactic -/ -syntax "hash_map_insert_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_insert_in_list_loop_decreases $key $value $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::move_elements_from_list]: termination measure -/ -@[simp] -def hash_map_move_elements_from_list_loop_terminates (T : Type) - (ntable : hash_map_t T) (ls : list_t T) := - (ntable, ls) - -/- [hashmap::HashMap::{0}::move_elements_from_list]: decreases_by tactic -/ -syntax "hash_map_move_elements_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_move_elements_from_list_loop_decreases $ntable $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::move_elements]: termination measure -/ -@[simp] -def hash_map_move_elements_loop_terminates (T : Type) (ntable : hash_map_t T) - (slots : Vec (list_t T)) (i : Usize) := - (ntable, slots, i) - -/- [hashmap::HashMap::{0}::move_elements]: decreases_by tactic -/ -syntax "hash_map_move_elements_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_move_elements_loop_decreases $ntable $slots $i) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::contains_key_in_list]: termination measure -/ -@[simp] -def hash_map_contains_key_in_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::contains_key_in_list]: decreases_by tactic -/ -syntax "hash_map_contains_key_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_contains_key_in_list_loop_decreases $key $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::get_in_list]: termination measure -/ -@[simp] -def hash_map_get_in_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::get_in_list]: decreases_by tactic -/ -syntax "hash_map_get_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_get_in_list_loop_decreases $key $ls) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::get_mut_in_list]: termination measure -/ -@[simp] -def hash_map_get_mut_in_list_loop_terminates (T : Type) (ls : list_t T) - (key : Usize) := - (ls, key) - -/- [hashmap::HashMap::{0}::get_mut_in_list]: decreases_by tactic -/ -syntax "hash_map_get_mut_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_get_mut_in_list_loop_decreases $ls $key) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::remove_from_list]: termination measure -/ -@[simp] -def hash_map_remove_from_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::remove_from_list]: decreases_by tactic -/ -syntax "hash_map_remove_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_remove_from_list_loop_decreases $key $ls) =>`(tactic| sorry) - diff --git a/tests/lean/hashmap/Hashmap/Clauses/Template.lean b/tests/lean/hashmap/Hashmap/Clauses/Template.lean deleted file mode 100644 index 560592c8..00000000 --- a/tests/lean/hashmap/Hashmap/Clauses/Template.lean +++ /dev/null @@ -1,108 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap]: templates for the decreases clauses -import Base.Primitives -import Hashmap.Types - -/- [hashmap::HashMap::{0}::allocate_slots]: termination measure -/ -@[simp] -def hash_map_allocate_slots_loop_terminates (T : Type) (slots : Vec (list_t T)) - (n : Usize) := - (slots, n) - -/- [hashmap::HashMap::{0}::allocate_slots]: decreases_by tactic -/ -syntax "hash_map_allocate_slots_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_allocate_slots_loop_decreases $slots $n) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::clear]: termination measure -/ -@[simp] -def hash_map_clear_loop_terminates (T : Type) (slots : Vec (list_t T)) - (i : Usize) := - (slots, i) - -/- [hashmap::HashMap::{0}::clear]: decreases_by tactic -/ -syntax "hash_map_clear_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_clear_loop_decreases $slots $i) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::insert_in_list]: termination measure -/ -@[simp] -def hash_map_insert_in_list_loop_terminates (T : Type) (key : Usize) - (value : T) (ls : list_t T) := - (key, value, ls) - -/- [hashmap::HashMap::{0}::insert_in_list]: decreases_by tactic -/ -syntax "hash_map_insert_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_insert_in_list_loop_decreases $key $value $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::move_elements_from_list]: termination measure -/ -@[simp] -def hash_map_move_elements_from_list_loop_terminates (T : Type) - (ntable : hash_map_t T) (ls : list_t T) := - (ntable, ls) - -/- [hashmap::HashMap::{0}::move_elements_from_list]: decreases_by tactic -/ -syntax "hash_map_move_elements_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_move_elements_from_list_loop_decreases $ntable $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::move_elements]: termination measure -/ -@[simp] -def hash_map_move_elements_loop_terminates (T : Type) (ntable : hash_map_t T) - (slots : Vec (list_t T)) (i : Usize) := - (ntable, slots, i) - -/- [hashmap::HashMap::{0}::move_elements]: decreases_by tactic -/ -syntax "hash_map_move_elements_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_move_elements_loop_decreases $ntable $slots $i) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::contains_key_in_list]: termination measure -/ -@[simp] -def hash_map_contains_key_in_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::contains_key_in_list]: decreases_by tactic -/ -syntax "hash_map_contains_key_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_contains_key_in_list_loop_decreases $key $ls) => - `(tactic| sorry) - -/- [hashmap::HashMap::{0}::get_in_list]: termination measure -/ -@[simp] -def hash_map_get_in_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::get_in_list]: decreases_by tactic -/ -syntax "hash_map_get_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_get_in_list_loop_decreases $key $ls) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::get_mut_in_list]: termination measure -/ -@[simp] -def hash_map_get_mut_in_list_loop_terminates (T : Type) (ls : list_t T) - (key : Usize) := - (ls, key) - -/- [hashmap::HashMap::{0}::get_mut_in_list]: decreases_by tactic -/ -syntax "hash_map_get_mut_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_get_mut_in_list_loop_decreases $ls $key) =>`(tactic| sorry) - -/- [hashmap::HashMap::{0}::remove_from_list]: termination measure -/ -@[simp] -def hash_map_remove_from_list_loop_terminates (T : Type) (key : Usize) - (ls : list_t T) := - (key, ls) - -/- [hashmap::HashMap::{0}::remove_from_list]: decreases_by tactic -/ -syntax "hash_map_remove_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hash_map_remove_from_list_loop_decreases $key $ls) =>`(tactic| sorry) - diff --git a/tests/lean/hashmap/Hashmap/Funs.lean b/tests/lean/hashmap/Hashmap/Funs.lean deleted file mode 100644 index 77b1a157..00000000 --- a/tests/lean/hashmap/Hashmap/Funs.lean +++ /dev/null @@ -1,513 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap]: function definitions -import Base.Primitives -import Hashmap.Types -import Hashmap.Clauses.Clauses - -/- [hashmap::hash_key] -/ -def hash_key_fwd (k : Usize) : Result Usize := - Result.ret k - -/- [hashmap::HashMap::{0}::allocate_slots] -/ -def hash_map_allocate_slots_loop_fwd - (T : Type) (slots : Vec (list_t T)) (n : Usize) : - (Result (Vec (list_t T))) - := - if h: n > (Usize.ofInt 0 (by intlit)) - then - do - let slots0 ← vec_push_back (list_t T) slots list_t.Nil - let n0 ← n - (Usize.ofInt 1 (by intlit)) - hash_map_allocate_slots_loop_fwd T slots0 n0 - else Result.ret slots -termination_by hash_map_allocate_slots_loop_fwd slots n => - hash_map_allocate_slots_loop_terminates T slots n -decreasing_by hash_map_allocate_slots_loop_decreases slots n - -/- [hashmap::HashMap::{0}::allocate_slots] -/ -def hash_map_allocate_slots_fwd - (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := - hash_map_allocate_slots_loop_fwd T slots n - -/- [hashmap::HashMap::{0}::new_with_capacity] -/ -def hash_map_new_with_capacity_fwd - (T : Type) (capacity : Usize) (max_load_dividend : Usize) - (max_load_divisor : Usize) : - Result (hash_map_t T) - := - do - let v := vec_new (list_t T) - let slots ← hash_map_allocate_slots_fwd T v capacity - let i ← capacity * max_load_dividend - let i0 ← i / max_load_divisor - Result.ret - { - hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hash_map_max_load_factor := (max_load_dividend, max_load_divisor), - hash_map_max_load := i0, - hash_map_slots := slots - } - -/- [hashmap::HashMap::{0}::new] -/ -def hash_map_new_fwd (T : Type) : Result (hash_map_t T) := - hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) - (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) - -/- [hashmap::HashMap::{0}::clear] -/ -def hash_map_clear_loop_fwd_back - (T : Type) (slots : Vec (list_t T)) (i : Usize) : - (Result (Vec (list_t T))) - := - let i0 := vec_len (list_t T) slots - if h: i < i0 - then - do - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let slots0 ← vec_index_mut_back (list_t T) slots i list_t.Nil - hash_map_clear_loop_fwd_back T slots0 i1 - else Result.ret slots -termination_by hash_map_clear_loop_fwd_back slots i => - hash_map_clear_loop_terminates T slots i -decreasing_by hash_map_clear_loop_decreases slots i - -/- [hashmap::HashMap::{0}::clear] -/ -def hash_map_clear_fwd_back - (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := - do - let v ← - hash_map_clear_loop_fwd_back T self.hash_map_slots - (Usize.ofInt 0 (by intlit)) - Result.ret - { - self - with - hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hash_map_slots := v - } - -/- [hashmap::HashMap::{0}::len] -/ -def hash_map_len_fwd (T : Type) (self : hash_map_t T) : Result Usize := - Result.ret self.hash_map_num_entries - -/- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_loop_fwd - (T : Type) (key : Usize) (value : T) (ls : list_t T) : (Result Bool) := - match h: ls with - | list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret false - else hash_map_insert_in_list_loop_fwd T key value tl - | list_t.Nil => Result.ret true -termination_by hash_map_insert_in_list_loop_fwd key value ls => - hash_map_insert_in_list_loop_terminates T key value ls -decreasing_by hash_map_insert_in_list_loop_decreases key value ls - -/- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_fwd - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := - hash_map_insert_in_list_loop_fwd T key value ls - -/- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_loop_back - (T : Type) (key : Usize) (value : T) (ls : list_t T) : (Result (list_t T)) := - match h: ls with - | list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret (list_t.Cons ckey value tl) - else - do - let tl0 ← hash_map_insert_in_list_loop_back T key value tl - Result.ret (list_t.Cons ckey cvalue tl0) - | list_t.Nil => let l := list_t.Nil - Result.ret (list_t.Cons key value l) -termination_by hash_map_insert_in_list_loop_back key value ls => - hash_map_insert_in_list_loop_terminates T key value ls -decreasing_by hash_map_insert_in_list_loop_decreases key value ls - -/- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_back - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := - hash_map_insert_in_list_loop_back T key value ls - -/- [hashmap::HashMap::{0}::insert_no_resize] -/ -def hash_map_insert_no_resize_fwd_back - (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : - Result (hash_map_t T) - := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let inserted ← hash_map_insert_in_list_fwd T key value l - if h: inserted - then - do - let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) - let l0 ← hash_map_insert_in_list_back T key value l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 - Result.ret - { self with hash_map_num_entries := i0, hash_map_slots := v } - else - do - let l0 ← hash_map_insert_in_list_back T key value l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } - -/- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) -def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) - -/- [hashmap::HashMap::{0}::move_elements_from_list] -/ -def hash_map_move_elements_from_list_loop_fwd_back - (T : Type) (ntable : hash_map_t T) (ls : list_t T) : - (Result (hash_map_t T)) - := - match h: ls with - | list_t.Cons k v tl => - do - let ntable0 ← hash_map_insert_no_resize_fwd_back T ntable k v - hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl - | list_t.Nil => Result.ret ntable -termination_by hash_map_move_elements_from_list_loop_fwd_back ntable ls => - hash_map_move_elements_from_list_loop_terminates T ntable ls -decreasing_by hash_map_move_elements_from_list_loop_decreases ntable ls - -/- [hashmap::HashMap::{0}::move_elements_from_list] -/ -def hash_map_move_elements_from_list_fwd_back - (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := - hash_map_move_elements_from_list_loop_fwd_back T ntable ls - -/- [hashmap::HashMap::{0}::move_elements] -/ -def hash_map_move_elements_loop_fwd_back - (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : - (Result ((hash_map_t T) × (Vec (list_t T)))) - := - let i0 := vec_len (list_t T) slots - if h: i < i0 - then - do - let l ← vec_index_mut_fwd (list_t T) slots i - let ls := mem_replace_fwd (list_t T) l list_t.Nil - let ntable0 ← hash_map_move_elements_from_list_fwd_back T ntable ls - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (list_t T) l list_t.Nil - let slots0 ← vec_index_mut_back (list_t T) slots i l0 - hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 - else Result.ret (ntable, slots) -termination_by hash_map_move_elements_loop_fwd_back ntable slots i => - hash_map_move_elements_loop_terminates T ntable slots i -decreasing_by hash_map_move_elements_loop_decreases ntable slots i - -/- [hashmap::HashMap::{0}::move_elements] -/ -def hash_map_move_elements_fwd_back - (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : - Result ((hash_map_t T) × (Vec (list_t T))) - := - hash_map_move_elements_loop_fwd_back T ntable slots i - -/- [hashmap::HashMap::{0}::try_resize] -/ -def hash_map_try_resize_fwd_back - (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := - do - let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (list_t T) self.hash_map_slots - let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) - let (i, i0) := self.hash_map_max_load_factor - let i1 ← n1 / i - if h: capacity <= i1 - then - do - let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← hash_map_new_with_capacity_fwd T i2 i i0 - let (ntable0, _) ← - hash_map_move_elements_fwd_back T ntable self.hash_map_slots - (Usize.ofInt 0 (by intlit)) - Result.ret - { - ntable0 - with - hash_map_num_entries := self.hash_map_num_entries, - hash_map_max_load_factor := (i, i0) - } - else Result.ret { self with hash_map_max_load_factor := (i, i0) } - -/- [hashmap::HashMap::{0}::insert] -/ -def hash_map_insert_fwd_back - (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : - Result (hash_map_t T) - := - do - let self0 ← hash_map_insert_no_resize_fwd_back T self key value - let i ← hash_map_len_fwd T self0 - if h: i > self0.hash_map_max_load - then hash_map_try_resize_fwd_back T self0 - else Result.ret self0 - -/- [hashmap::HashMap::{0}::contains_key_in_list] -/ -def hash_map_contains_key_in_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : (Result Bool) := - match h: ls with - | list_t.Cons ckey t tl => - if h: ckey = key - then Result.ret true - else hash_map_contains_key_in_list_loop_fwd T key tl - | list_t.Nil => Result.ret false -termination_by hash_map_contains_key_in_list_loop_fwd key ls => - hash_map_contains_key_in_list_loop_terminates T key ls -decreasing_by hash_map_contains_key_in_list_loop_decreases key ls - -/- [hashmap::HashMap::{0}::contains_key_in_list] -/ -def hash_map_contains_key_in_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result Bool := - hash_map_contains_key_in_list_loop_fwd T key ls - -/- [hashmap::HashMap::{0}::contains_key] -/ -def hash_map_contains_key_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result Bool := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_contains_key_in_list_fwd T key l - -/- [hashmap::HashMap::{0}::get_in_list] -/ -def hash_map_get_in_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : (Result T) := - match h: ls with - | list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret cvalue - else hash_map_get_in_list_loop_fwd T key tl - | list_t.Nil => Result.fail Error.panic -termination_by hash_map_get_in_list_loop_fwd key ls => - hash_map_get_in_list_loop_terminates T key ls -decreasing_by hash_map_get_in_list_loop_decreases key ls - -/- [hashmap::HashMap::{0}::get_in_list] -/ -def hash_map_get_in_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result T := - hash_map_get_in_list_loop_fwd T key ls - -/- [hashmap::HashMap::{0}::get] -/ -def hash_map_get_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result T := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_get_in_list_fwd T key l - -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_loop_fwd - (T : Type) (ls : list_t T) (key : Usize) : (Result T) := - match h: ls with - | list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret cvalue - else hash_map_get_mut_in_list_loop_fwd T tl key - | list_t.Nil => Result.fail Error.panic -termination_by hash_map_get_mut_in_list_loop_fwd ls key => - hash_map_get_mut_in_list_loop_terminates T ls key -decreasing_by hash_map_get_mut_in_list_loop_decreases ls key - -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_fwd - (T : Type) (ls : list_t T) (key : Usize) : Result T := - hash_map_get_mut_in_list_loop_fwd T ls key - -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_loop_back - (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : (Result (list_t T)) := - match h: ls with - | list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret (list_t.Cons ckey ret0 tl) - else - do - let tl0 ← hash_map_get_mut_in_list_loop_back T tl key ret0 - Result.ret (list_t.Cons ckey cvalue tl0) - | list_t.Nil => Result.fail Error.panic -termination_by hash_map_get_mut_in_list_loop_back ls key ret0 => - hash_map_get_mut_in_list_loop_terminates T ls key -decreasing_by hash_map_get_mut_in_list_loop_decreases ls key - -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_back - (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := - hash_map_get_mut_in_list_loop_back T ls key ret0 - -/- [hashmap::HashMap::{0}::get_mut] -/ -def hash_map_get_mut_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result T := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_get_mut_in_list_fwd T l key - -/- [hashmap::HashMap::{0}::get_mut] -/ -def hash_map_get_mut_back - (T : Type) (self : hash_map_t T) (key : Usize) (ret0 : T) : - Result (hash_map_t T) - := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let l0 ← hash_map_get_mut_in_list_back T l key ret0 - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } - -/- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : (Result (Option T)) := - match h: ls with - | list_t.Cons ckey t tl => - if h: ckey = key - then - let mv_ls := - mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil - match h: mv_ls with - | list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) - | list_t.Nil => Result.fail Error.panic - else hash_map_remove_from_list_loop_fwd T key tl - | list_t.Nil => Result.ret Option.none -termination_by hash_map_remove_from_list_loop_fwd key ls => - hash_map_remove_from_list_loop_terminates T key ls -decreasing_by hash_map_remove_from_list_loop_decreases key ls - -/- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := - hash_map_remove_from_list_loop_fwd T key ls - -/- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_loop_back - (T : Type) (key : Usize) (ls : list_t T) : (Result (list_t T)) := - match h: ls with - | list_t.Cons ckey t tl => - if h: ckey = key - then - let mv_ls := - mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil - match h: mv_ls with - | list_t.Cons i cvalue tl0 => Result.ret tl0 - | list_t.Nil => Result.fail Error.panic - else - do - let tl0 ← hash_map_remove_from_list_loop_back T key tl - Result.ret (list_t.Cons ckey t tl0) - | list_t.Nil => Result.ret list_t.Nil -termination_by hash_map_remove_from_list_loop_back key ls => - hash_map_remove_from_list_loop_terminates T key ls -decreasing_by hash_map_remove_from_list_loop_decreases key ls - -/- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_back - (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := - hash_map_remove_from_list_loop_back T key ls - -/- [hashmap::HashMap::{0}::remove] -/ -def hash_map_remove_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result (Option T) := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let x ← hash_map_remove_from_list_fwd T key l - match h: x with - | Option.none => Result.ret Option.none - | Option.some x0 => - do - let _ ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) - Result.ret (Option.some x0) - -/- [hashmap::HashMap::{0}::remove] -/ -def hash_map_remove_back - (T : Type) (self : hash_map_t T) (key : Usize) : Result (hash_map_t T) := - do - let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots - let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let x ← hash_map_remove_from_list_fwd T key l - match h: x with - | Option.none => - do - let l0 ← hash_map_remove_from_list_back T key l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } - | Option.some x0 => - do - let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) - let l0 ← hash_map_remove_from_list_back T key l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 - Result.ret - { self with hash_map_num_entries := i0, hash_map_slots := v } - -/- [hashmap::test1] -/ -def test1_fwd : Result Unit := - do - let hm ← hash_map_new_fwd U64 - let hm0 ← - hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) - (U64.ofInt 42 (by intlit)) - let hm1 ← - hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) - (U64.ofInt 18 (by intlit)) - let hm2 ← - hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 138 (by intlit)) - let hm3 ← - hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) - (U64.ofInt 256 (by intlit)) - let i ← hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) - if h: not (i = (U64.ofInt 18 (by intlit))) - then Result.fail Error.panic - else - do - let hm4 ← - hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 56 (by intlit)) - let i0 ← hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) - if h: not (i0 = (U64.ofInt 56 (by intlit))) - then Result.fail Error.panic - else - do - let x ← - hash_map_remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) - match h: x with - | Option.none => Result.fail Error.panic - | Option.some x0 => - if h: not (x0 = (U64.ofInt 56 (by intlit))) - then Result.fail Error.panic - else - do - let hm5 ← - hash_map_remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) - let i1 ← - hash_map_get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) - if h: not (i1 = (U64.ofInt 42 (by intlit))) - then Result.fail Error.panic - else - do - let i2 ← - hash_map_get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) - if h: not (i2 = (U64.ofInt 18 (by intlit))) - then Result.fail Error.panic - else - do - let i3 ← - hash_map_get_fwd U64 hm5 - (Usize.ofInt 1056 (by intlit)) - if h: not (i3 = (U64.ofInt 256 (by intlit))) - then Result.fail Error.panic - else Result.ret () - diff --git a/tests/lean/hashmap/Hashmap/Types.lean b/tests/lean/hashmap/Hashmap/Types.lean deleted file mode 100644 index 6eabf7da..00000000 --- a/tests/lean/hashmap/Hashmap/Types.lean +++ /dev/null @@ -1,16 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap]: type definitions -import Base.Primitives - -/- [hashmap::List] -/ -inductive list_t (T : Type) := -| Cons : Usize -> T -> list_t T -> list_t T -| Nil : list_t T - -/- [hashmap::HashMap] -/ -structure hash_map_t (T : Type) where - hash_map_num_entries : Usize - hash_map_max_load_factor : (Usize × Usize) - hash_map_max_load : Usize - hash_map_slots : Vec (list_t T) - diff --git a/tests/lean/hashmap/lake-manifest.json b/tests/lean/hashmap/lake-manifest.json deleted file mode 100644 index 88e446e5..00000000 --- a/tests/lean/hashmap/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "1c5ed7840906e29e1f8ca7dbf088cf155e5397e9", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/hashmap/lakefile.lean b/tests/lean/hashmap/lakefile.lean deleted file mode 100644 index 713785f6..00000000 --- a/tests/lean/hashmap/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «hashmap» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «Hashmap» {} diff --git a/tests/lean/hashmap/lean-toolchain b/tests/lean/hashmap/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/hashmap/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/hashmap_on_disk/.gitignore b/tests/lean/hashmap_on_disk/.gitignore deleted file mode 100644 index a1735e7c..00000000 --- a/tests/lean/hashmap_on_disk/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/build -/lean_packages/* -!/lean_packages/manifest.json -/build -/lake-packages/* diff --git a/tests/lean/hashmap_on_disk/Base/Primitives.lean b/tests/lean/hashmap_on_disk/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/hashmap_on_disk/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/hashmap_on_disk/HashmapMain.lean b/tests/lean/hashmap_on_disk/HashmapMain.lean deleted file mode 100644 index 1a4e7f82..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain.lean +++ /dev/null @@ -1 +0,0 @@ -import HashmapMain.Funs diff --git a/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Clauses.lean b/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Clauses.lean deleted file mode 100644 index a4dc996a..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Clauses.lean +++ /dev/null @@ -1,110 +0,0 @@ -import Base.Primitives -import HashmapMain.Types - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: termination measure -/ -@[simp] -def hashmap_hash_map_allocate_slots_loop_terminates (T : Type) - (slots : Vec (hashmap_list_t T)) (n : Usize) := - (slots, n) - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: decreases_by tactic -/ -syntax "hashmap_hash_map_allocate_slots_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_allocate_slots_loop_decreases $slots $n) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::clear]: termination measure -/ -@[simp] -def hashmap_hash_map_clear_loop_terminates (T : Type) - (slots : Vec (hashmap_list_t T)) (i : Usize) := - (slots, i) - -/- [hashmap_main::hashmap::HashMap::{0}::clear]: decreases_by tactic -/ -syntax "hashmap_hash_map_clear_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_clear_loop_decreases $slots $i) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_insert_in_list_loop_terminates (T : Type) (key : Usize) - (value : T) (ls : hashmap_list_t T) := - (key, value, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_insert_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_insert_in_list_loop_decreases $key $value $ls) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: termination measure -/ -@[simp] -def hashmap_hash_map_move_elements_from_list_loop_terminates (T : Type) - (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) := - (ntable, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_move_elements_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_move_elements_from_list_loop_decreases $ntable -$ls) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: termination measure -/ -@[simp] -def hashmap_hash_map_move_elements_loop_terminates (T : Type) - (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) (i : Usize) - := - (ntable, slots, i) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: decreases_by tactic -/ -syntax "hashmap_hash_map_move_elements_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_move_elements_loop_decreases $ntable $slots $i) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_contains_key_in_list_loop_terminates (T : Type) - (key : Usize) (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_contains_key_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_contains_key_in_list_loop_decreases $key $ls) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_get_in_list_loop_terminates (T : Type) (key : Usize) - (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_get_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_get_in_list_loop_decreases $key $ls) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_get_mut_in_list_loop_terminates (T : Type) - (ls : hashmap_list_t T) (key : Usize) := - (ls, key) - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_get_mut_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_get_mut_in_list_loop_decreases $ls $key) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: termination measure -/ -@[simp] -def hashmap_hash_map_remove_from_list_loop_terminates (T : Type) (key : Usize) - (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_remove_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_remove_from_list_loop_decreases $key $ls) => - `(tactic| sorry) - diff --git a/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Template.lean b/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Template.lean deleted file mode 100644 index 33802597..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/Clauses/Template.lean +++ /dev/null @@ -1,112 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap_main]: templates for the decreases clauses -import Base.Primitives -import HashmapMain.Types - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: termination measure -/ -@[simp] -def hashmap_hash_map_allocate_slots_loop_terminates (T : Type) - (slots : Vec (hashmap_list_t T)) (n : Usize) := - (slots, n) - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: decreases_by tactic -/ -syntax "hashmap_hash_map_allocate_slots_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_allocate_slots_loop_decreases $slots $n) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::clear]: termination measure -/ -@[simp] -def hashmap_hash_map_clear_loop_terminates (T : Type) - (slots : Vec (hashmap_list_t T)) (i : Usize) := - (slots, i) - -/- [hashmap_main::hashmap::HashMap::{0}::clear]: decreases_by tactic -/ -syntax "hashmap_hash_map_clear_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_clear_loop_decreases $slots $i) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_insert_in_list_loop_terminates (T : Type) (key : Usize) - (value : T) (ls : hashmap_list_t T) := - (key, value, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_insert_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_insert_in_list_loop_decreases $key $value $ls) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: termination measure -/ -@[simp] -def hashmap_hash_map_move_elements_from_list_loop_terminates (T : Type) - (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) := - (ntable, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_move_elements_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_move_elements_from_list_loop_decreases $ntable -$ls) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: termination measure -/ -@[simp] -def hashmap_hash_map_move_elements_loop_terminates (T : Type) - (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) (i : Usize) - := - (ntable, slots, i) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: decreases_by tactic -/ -syntax "hashmap_hash_map_move_elements_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_move_elements_loop_decreases $ntable $slots $i) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_contains_key_in_list_loop_terminates (T : Type) - (key : Usize) (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_contains_key_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_contains_key_in_list_loop_decreases $key $ls) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_get_in_list_loop_terminates (T : Type) (key : Usize) - (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_get_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_get_in_list_loop_decreases $key $ls) =>`(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: termination measure -/ -@[simp] -def hashmap_hash_map_get_mut_in_list_loop_terminates (T : Type) - (ls : hashmap_list_t T) (key : Usize) := - (ls, key) - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_get_mut_in_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_get_mut_in_list_loop_decreases $ls $key) => - `(tactic| sorry) - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: termination measure -/ -@[simp] -def hashmap_hash_map_remove_from_list_loop_terminates (T : Type) (key : Usize) - (ls : hashmap_list_t T) := - (key, ls) - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: decreases_by tactic -/ -syntax "hashmap_hash_map_remove_from_list_loop_decreases" term+ : tactic -macro_rules -| `(tactic| hashmap_hash_map_remove_from_list_loop_decreases $key $ls) => - `(tactic| sorry) - diff --git a/tests/lean/hashmap_on_disk/HashmapMain/ExternalFuns.lean b/tests/lean/hashmap_on_disk/HashmapMain/ExternalFuns.lean deleted file mode 100644 index a5103acc..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/ExternalFuns.lean +++ /dev/null @@ -1,5 +0,0 @@ -import Base.Primitives -import HashmapMain.Types -import HashmapMain.Opaque - -def opaque_defs : OpaqueDefs := by sorry diff --git a/tests/lean/hashmap_on_disk/HashmapMain/Funs.lean b/tests/lean/hashmap_on_disk/HashmapMain/Funs.lean deleted file mode 100644 index 342c3833..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/Funs.lean +++ /dev/null @@ -1,590 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap_main]: function definitions -import Base.Primitives -import HashmapMain.Types -import HashmapMain.ExternalFuns -import HashmapMain.Clauses.Clauses - -/- [hashmap_main::hashmap::hash_key] -/ -def hashmap_hash_key_fwd (k : Usize) : Result Usize := - Result.ret k - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -def hashmap_hash_map_allocate_slots_loop_fwd - (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : - (Result (Vec (hashmap_list_t T))) - := - if h: n > (Usize.ofInt 0 (by intlit)) - then - do - let slots0 ← vec_push_back (hashmap_list_t T) slots hashmap_list_t.Nil - let n0 ← n - (Usize.ofInt 1 (by intlit)) - hashmap_hash_map_allocate_slots_loop_fwd T slots0 n0 - else Result.ret slots -termination_by hashmap_hash_map_allocate_slots_loop_fwd slots n => - hashmap_hash_map_allocate_slots_loop_terminates T slots n -decreasing_by hashmap_hash_map_allocate_slots_loop_decreases slots n - -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -def hashmap_hash_map_allocate_slots_fwd - (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : - Result (Vec (hashmap_list_t T)) - := - hashmap_hash_map_allocate_slots_loop_fwd T slots n - -/- [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] -/ -def hashmap_hash_map_new_with_capacity_fwd - (T : Type) (capacity : Usize) (max_load_dividend : Usize) - (max_load_divisor : Usize) : - Result (hashmap_hash_map_t T) - := - do - let v := vec_new (hashmap_list_t T) - let slots ← hashmap_hash_map_allocate_slots_fwd T v capacity - let i ← capacity * max_load_dividend - let i0 ← i / max_load_divisor - Result.ret - { - hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hashmap_hash_map_max_load_factor := - (max_load_dividend, max_load_divisor), - hashmap_hash_map_max_load := i0, - hashmap_hash_map_slots := slots - } - -/- [hashmap_main::hashmap::HashMap::{0}::new] -/ -def hashmap_hash_map_new_fwd (T : Type) : Result (hashmap_hash_map_t T) := - hashmap_hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) - (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) - -/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -def hashmap_hash_map_clear_loop_fwd_back - (T : Type) (slots : Vec (hashmap_list_t T)) (i : Usize) : - (Result (Vec (hashmap_list_t T))) - := - let i0 := vec_len (hashmap_list_t T) slots - if h: i < i0 - then - do - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let slots0 ← - vec_index_mut_back (hashmap_list_t T) slots i hashmap_list_t.Nil - hashmap_hash_map_clear_loop_fwd_back T slots0 i1 - else Result.ret slots -termination_by hashmap_hash_map_clear_loop_fwd_back slots i => - hashmap_hash_map_clear_loop_terminates T slots i -decreasing_by hashmap_hash_map_clear_loop_decreases slots i - -/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -def hashmap_hash_map_clear_fwd_back - (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := - do - let v ← - hashmap_hash_map_clear_loop_fwd_back T self.hashmap_hash_map_slots - (Usize.ofInt 0 (by intlit)) - Result.ret - { - self - with - hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hashmap_hash_map_slots := v - } - -/- [hashmap_main::hashmap::HashMap::{0}::len] -/ -def hashmap_hash_map_len_fwd - (T : Type) (self : hashmap_hash_map_t T) : Result Usize := - Result.ret self.hashmap_hash_map_num_entries - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_loop_fwd - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : - (Result Bool) - := - match h: ls with - | hashmap_list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret false - else hashmap_hash_map_insert_in_list_loop_fwd T key value tl - | hashmap_list_t.Nil => Result.ret true -termination_by hashmap_hash_map_insert_in_list_loop_fwd key value ls => - hashmap_hash_map_insert_in_list_loop_terminates T key value ls -decreasing_by hashmap_hash_map_insert_in_list_loop_decreases key value ls - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_fwd - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := - hashmap_hash_map_insert_in_list_loop_fwd T key value ls - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_loop_back - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : - (Result (hashmap_list_t T)) - := - match h: ls with - | hashmap_list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret (hashmap_list_t.Cons ckey value tl) - else - do - let tl0 ← hashmap_hash_map_insert_in_list_loop_back T key value tl - Result.ret (hashmap_list_t.Cons ckey cvalue tl0) - | hashmap_list_t.Nil => - let l := hashmap_list_t.Nil - Result.ret (hashmap_list_t.Cons key value l) -termination_by hashmap_hash_map_insert_in_list_loop_back key value ls => - hashmap_hash_map_insert_in_list_loop_terminates T key value ls -decreasing_by hashmap_hash_map_insert_in_list_loop_decreases key value ls - -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_back - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) - := - hashmap_hash_map_insert_in_list_loop_back T key value ls - -/- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] -/ -def hashmap_hash_map_insert_no_resize_fwd_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : - Result (hashmap_hash_map_t T) - := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let inserted ← hashmap_hash_map_insert_in_list_fwd T key value l - if h: inserted - then - do - let i0 ← self.hashmap_hash_map_num_entries + - (Usize.ofInt 1 (by intlit)) - let l0 ← hashmap_hash_map_insert_in_list_back T key value l - let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret - { - self - with - hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v - } - else - do - let l0 ← hashmap_hash_map_insert_in_list_back T key value l - let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret { self with hashmap_hash_map_slots := v } - -/- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) -def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -def hashmap_hash_map_move_elements_from_list_loop_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : - (Result (hashmap_hash_map_t T)) - := - match h: ls with - | hashmap_list_t.Cons k v tl => - do - let ntable0 ← hashmap_hash_map_insert_no_resize_fwd_back T ntable k v - hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl - | hashmap_list_t.Nil => Result.ret ntable -termination_by hashmap_hash_map_move_elements_from_list_loop_fwd_back ntable ls - => - hashmap_hash_map_move_elements_from_list_loop_terminates T ntable ls -decreasing_by hashmap_hash_map_move_elements_from_list_loop_decreases ntable ls - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -def hashmap_hash_map_move_elements_from_list_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : - Result (hashmap_hash_map_t T) - := - hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable ls - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -def hashmap_hash_map_move_elements_loop_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) - (i : Usize) : - (Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T)))) - := - let i0 := vec_len (hashmap_list_t T) slots - if h: i < i0 - then - do - let l ← vec_index_mut_fwd (hashmap_list_t T) slots i - let ls := mem_replace_fwd (hashmap_list_t T) l hashmap_list_t.Nil - let ntable0 ← - hashmap_hash_map_move_elements_from_list_fwd_back T ntable ls - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (hashmap_list_t T) l hashmap_list_t.Nil - let slots0 ← vec_index_mut_back (hashmap_list_t T) slots i l0 - hashmap_hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 - else Result.ret (ntable, slots) -termination_by hashmap_hash_map_move_elements_loop_fwd_back ntable slots i => - hashmap_hash_map_move_elements_loop_terminates T ntable slots i -decreasing_by hashmap_hash_map_move_elements_loop_decreases ntable slots i - -/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -def hashmap_hash_map_move_elements_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) - (i : Usize) : - Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) - := - hashmap_hash_map_move_elements_loop_fwd_back T ntable slots i - -/- [hashmap_main::hashmap::HashMap::{0}::try_resize] -/ -def hashmap_hash_map_try_resize_fwd_back - (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := - do - let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) - let (i, i0) := self.hashmap_hash_map_max_load_factor - let i1 ← n1 / i - if h: capacity <= i1 - then - do - let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← hashmap_hash_map_new_with_capacity_fwd T i2 i i0 - let (ntable0, _) ← - hashmap_hash_map_move_elements_fwd_back T ntable - self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) - Result.ret - { - ntable0 - with - hashmap_hash_map_num_entries := self.hashmap_hash_map_num_entries, - hashmap_hash_map_max_load_factor := (i, i0) - } - else Result.ret { self with hashmap_hash_map_max_load_factor := (i, i0) } - -/- [hashmap_main::hashmap::HashMap::{0}::insert] -/ -def hashmap_hash_map_insert_fwd_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : - Result (hashmap_hash_map_t T) - := - do - let self0 ← hashmap_hash_map_insert_no_resize_fwd_back T self key value - let i ← hashmap_hash_map_len_fwd T self0 - if h: i > self0.hashmap_hash_map_max_load - then hashmap_hash_map_try_resize_fwd_back T self0 - else Result.ret self0 - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -def hashmap_hash_map_contains_key_in_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : (Result Bool) := - match h: ls with - | hashmap_list_t.Cons ckey t tl => - if h: ckey = key - then Result.ret true - else hashmap_hash_map_contains_key_in_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.ret false -termination_by hashmap_hash_map_contains_key_in_list_loop_fwd key ls => - hashmap_hash_map_contains_key_in_list_loop_terminates T key ls -decreasing_by hashmap_hash_map_contains_key_in_list_loop_decreases key ls - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -def hashmap_hash_map_contains_key_in_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := - hashmap_hash_map_contains_key_in_list_loop_fwd T key ls - -/- [hashmap_main::hashmap::HashMap::{0}::contains_key] -/ -def hashmap_hash_map_contains_key_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result Bool := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_contains_key_in_list_fwd T key l - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -def hashmap_hash_map_get_in_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : (Result T) := - match h: ls with - | hashmap_list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret cvalue - else hashmap_hash_map_get_in_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.fail Error.panic -termination_by hashmap_hash_map_get_in_list_loop_fwd key ls => - hashmap_hash_map_get_in_list_loop_terminates T key ls -decreasing_by hashmap_hash_map_get_in_list_loop_decreases key ls - -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -def hashmap_hash_map_get_in_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := - hashmap_hash_map_get_in_list_loop_fwd T key ls - -/- [hashmap_main::hashmap::HashMap::{0}::get] -/ -def hashmap_hash_map_get_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_get_in_list_fwd T key l - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_loop_fwd - (T : Type) (ls : hashmap_list_t T) (key : Usize) : (Result T) := - match h: ls with - | hashmap_list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret cvalue - else hashmap_hash_map_get_mut_in_list_loop_fwd T tl key - | hashmap_list_t.Nil => Result.fail Error.panic -termination_by hashmap_hash_map_get_mut_in_list_loop_fwd ls key => - hashmap_hash_map_get_mut_in_list_loop_terminates T ls key -decreasing_by hashmap_hash_map_get_mut_in_list_loop_decreases ls key - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_fwd - (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := - hashmap_hash_map_get_mut_in_list_loop_fwd T ls key - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_loop_back - (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : - (Result (hashmap_list_t T)) - := - match h: ls with - | hashmap_list_t.Cons ckey cvalue tl => - if h: ckey = key - then Result.ret (hashmap_list_t.Cons ckey ret0 tl) - else - do - let tl0 ← hashmap_hash_map_get_mut_in_list_loop_back T tl key ret0 - Result.ret (hashmap_list_t.Cons ckey cvalue tl0) - | hashmap_list_t.Nil => Result.fail Error.panic -termination_by hashmap_hash_map_get_mut_in_list_loop_back ls key ret0 => - hashmap_hash_map_get_mut_in_list_loop_terminates T ls key -decreasing_by hashmap_hash_map_get_mut_in_list_loop_decreases ls key - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_back - (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : - Result (hashmap_list_t T) - := - hashmap_hash_map_get_mut_in_list_loop_back T ls key ret0 - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ -def hashmap_hash_map_get_mut_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_get_mut_in_list_fwd T l key - -/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ -def hashmap_hash_map_get_mut_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (ret0 : T) : - Result (hashmap_hash_map_t T) - := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let l0 ← hashmap_hash_map_get_mut_in_list_back T l key ret0 - let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret { self with hashmap_hash_map_slots := v } - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : (Result (Option T)) := - match h: ls with - | hashmap_list_t.Cons ckey t tl => - if h: ckey = key - then - let mv_ls := - mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) - hashmap_list_t.Nil - match h: mv_ls with - | hashmap_list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) - | hashmap_list_t.Nil => Result.fail Error.panic - else hashmap_hash_map_remove_from_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.ret Option.none -termination_by hashmap_hash_map_remove_from_list_loop_fwd key ls => - hashmap_hash_map_remove_from_list_loop_terminates T key ls -decreasing_by hashmap_hash_map_remove_from_list_loop_decreases key ls - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := - hashmap_hash_map_remove_from_list_loop_fwd T key ls - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_loop_back - (T : Type) (key : Usize) (ls : hashmap_list_t T) : - (Result (hashmap_list_t T)) - := - match h: ls with - | hashmap_list_t.Cons ckey t tl => - if h: ckey = key - then - let mv_ls := - mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) - hashmap_list_t.Nil - match h: mv_ls with - | hashmap_list_t.Cons i cvalue tl0 => Result.ret tl0 - | hashmap_list_t.Nil => Result.fail Error.panic - else - do - let tl0 ← hashmap_hash_map_remove_from_list_loop_back T key tl - Result.ret (hashmap_list_t.Cons ckey t tl0) - | hashmap_list_t.Nil => Result.ret hashmap_list_t.Nil -termination_by hashmap_hash_map_remove_from_list_loop_back key ls => - hashmap_hash_map_remove_from_list_loop_terminates T key ls -decreasing_by hashmap_hash_map_remove_from_list_loop_decreases key ls - -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_back - (T : Type) (key : Usize) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) - := - hashmap_hash_map_remove_from_list_loop_back T key ls - -/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ -def hashmap_hash_map_remove_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result (Option T) := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap_hash_map_remove_from_list_fwd T key l - match h: x with - | Option.none => Result.ret Option.none - | Option.some x0 => - do - let _ ← self.hashmap_hash_map_num_entries - - (Usize.ofInt 1 (by intlit)) - Result.ret (Option.some x0) - -/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ -def hashmap_hash_map_remove_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : - Result (hashmap_hash_map_t T) - := - do - let hash ← hashmap_hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots - let hash_mod ← hash % i - let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap_hash_map_remove_from_list_fwd T key l - match h: x with - | Option.none => - do - let l0 ← hashmap_hash_map_remove_from_list_back T key l - let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret { self with hashmap_hash_map_slots := v } - | Option.some x0 => - do - let i0 ← self.hashmap_hash_map_num_entries - - (Usize.ofInt 1 (by intlit)) - let l0 ← hashmap_hash_map_remove_from_list_back T key l - let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret - { - self - with - hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v - } - -/- [hashmap_main::hashmap::test1] -/ -def hashmap_test1_fwd : Result Unit := - do - let hm ← hashmap_hash_map_new_fwd U64 - let hm0 ← - hashmap_hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) - (U64.ofInt 42 (by intlit)) - let hm1 ← - hashmap_hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) - (U64.ofInt 18 (by intlit)) - let hm2 ← - hashmap_hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 138 (by intlit)) - let hm3 ← - hashmap_hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) - (U64.ofInt 256 (by intlit)) - let i ← hashmap_hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) - if h: not (i = (U64.ofInt 18 (by intlit))) - then Result.fail Error.panic - else - do - let hm4 ← - hashmap_hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 56 (by intlit)) - let i0 ← - hashmap_hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) - if h: not (i0 = (U64.ofInt 56 (by intlit))) - then Result.fail Error.panic - else - do - let x ← - hashmap_hash_map_remove_fwd U64 hm4 - (Usize.ofInt 1024 (by intlit)) - match h: x with - | Option.none => Result.fail Error.panic - | Option.some x0 => - if h: not (x0 = (U64.ofInt 56 (by intlit))) - then Result.fail Error.panic - else - do - let hm5 ← - hashmap_hash_map_remove_back U64 hm4 - (Usize.ofInt 1024 (by intlit)) - let i1 ← - hashmap_hash_map_get_fwd U64 hm5 - (Usize.ofInt 0 (by intlit)) - if h: not (i1 = (U64.ofInt 42 (by intlit))) - then Result.fail Error.panic - else - do - let i2 ← - hashmap_hash_map_get_fwd U64 hm5 - (Usize.ofInt 128 (by intlit)) - if h: not (i2 = (U64.ofInt 18 (by intlit))) - then Result.fail Error.panic - else - do - let i3 ← - hashmap_hash_map_get_fwd U64 hm5 - (Usize.ofInt 1056 (by intlit)) - if h: not (i3 = (U64.ofInt 256 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- [hashmap_main::insert_on_disk] -/ -def insert_on_disk_fwd - (key : Usize) (value : U64) (st : State) : Result (State × Unit) := - do - let (st0, hm) ← opaque_defs.hashmap_utils_deserialize_fwd st - let hm0 ← hashmap_hash_map_insert_fwd_back U64 hm key value - let (st1, _) ← opaque_defs.hashmap_utils_serialize_fwd hm0 st0 - Result.ret (st1, ()) - -/- [hashmap_main::main] -/ -def main_fwd : Result Unit := - Result.ret () - diff --git a/tests/lean/hashmap_on_disk/HashmapMain/Opaque.lean b/tests/lean/hashmap_on_disk/HashmapMain/Opaque.lean deleted file mode 100644 index d98f431a..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/Opaque.lean +++ /dev/null @@ -1,15 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap_main]: opaque function definitions -import Base.Primitives -import HashmapMain.Types - -structure OpaqueDefs where - - /- [hashmap_main::hashmap_utils::deserialize] -/ - hashmap_utils_deserialize_fwd - : State -> Result (State × (hashmap_hash_map_t U64)) - - /- [hashmap_main::hashmap_utils::serialize] -/ - hashmap_utils_serialize_fwd - : hashmap_hash_map_t U64 -> State -> Result (State × Unit) - diff --git a/tests/lean/hashmap_on_disk/HashmapMain/Types.lean b/tests/lean/hashmap_on_disk/HashmapMain/Types.lean deleted file mode 100644 index 0509fbbd..00000000 --- a/tests/lean/hashmap_on_disk/HashmapMain/Types.lean +++ /dev/null @@ -1,19 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [hashmap_main]: type definitions -import Base.Primitives - -/- [hashmap_main::hashmap::List] -/ -inductive hashmap_list_t (T : Type) := -| Cons : Usize -> T -> hashmap_list_t T -> hashmap_list_t T -| Nil : hashmap_list_t T - -/- [hashmap_main::hashmap::HashMap] -/ -structure hashmap_hash_map_t (T : Type) where - hashmap_hash_map_num_entries : Usize - hashmap_hash_map_max_load_factor : (Usize × Usize) - hashmap_hash_map_max_load : Usize - hashmap_hash_map_slots : Vec (hashmap_list_t T) - -/- The state type used in the state-error monad -/ -axiom State : Type - diff --git a/tests/lean/hashmap_on_disk/lake-manifest.json b/tests/lean/hashmap_on_disk/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/hashmap_on_disk/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/hashmap_on_disk/lakefile.lean b/tests/lean/hashmap_on_disk/lakefile.lean deleted file mode 100644 index 70daf427..00000000 --- a/tests/lean/hashmap_on_disk/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «hashmap_main» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «HashmapMain» {} diff --git a/tests/lean/hashmap_on_disk/lean-toolchain b/tests/lean/hashmap_on_disk/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/hashmap_on_disk/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json new file mode 100644 index 00000000..1397c6f0 --- /dev/null +++ b/tests/lean/lake-manifest.json @@ -0,0 +1,34 @@ +{"version": 4, + "packagesDir": "lake-packages", + "packages": + [{"git": + {"url": "https://github.com/EdAyers/ProofWidgets4", + "subDir?": null, + "rev": "c43db94a8f495dad37829e9d7ad65483d68c86b8", + "name": "proofwidgets", + "inputRev?": "v0.0.11"}}, + {"path": {"name": "Base", "dir": "./../../backends/lean"}}, + {"git": + {"url": "https://github.com/leanprover-community/mathlib4.git", + "subDir?": null, + "rev": "cb02d09e1d5611d22efc2b406e7893f246b2f51e", + "name": "mathlib", + "inputRev?": null}}, + {"git": + {"url": "https://github.com/gebner/quote4", + "subDir?": null, + "rev": "c71f94e34c1cda52eef5c93dc9da409ab2727420", + "name": "Qq", + "inputRev?": "master"}}, + {"git": + {"url": "https://github.com/JLimperg/aesop", + "subDir?": null, + "rev": "ca73109cc40837bc61df8024c9016da4b4f99d4c", + "name": "aesop", + "inputRev?": "master"}}, + {"git": + {"url": "https://github.com/leanprover/std4", + "subDir?": null, + "rev": "e68aa8f5fe47aad78987df45f99094afbcb5e936", + "name": "std", + "inputRev?": "main"}}]} diff --git a/tests/lean/lakefile.lean b/tests/lean/lakefile.lean new file mode 100644 index 00000000..da4293dd --- /dev/null +++ b/tests/lean/lakefile.lean @@ -0,0 +1,14 @@ +import Lake +open Lake DSL + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" + +require Base from "../../backends/lean" + +package «tests» {} + +@[default_target] +lean_lib «Tests» {} + +lean_lib hashmap diff --git a/tests/lean/lean-toolchain b/tests/lean/lean-toolchain index bbf57f10..42e7d786 100644 --- a/tests/lean/lean-toolchain +++ b/tests/lean/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:nightly-2023-01-21 +leanprover/lean4:nightly-2023-06-20 \ No newline at end of file diff --git a/tests/lean/misc-constants/Base/Primitives.lean b/tests/lean/misc-constants/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-constants/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-constants/Constants.lean b/tests/lean/misc-constants/Constants.lean deleted file mode 100644 index 8306ed85..00000000 --- a/tests/lean/misc-constants/Constants.lean +++ /dev/null @@ -1,131 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [constants] -import Base.Primitives - -/- [constants::X0] -/ -def x0_body : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) -def x0_c : U32 := eval_global x0_body (by simp) - -/- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) -def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) - -/- [constants::X1] -/ -def x1_body : Result U32 := Result.ret core_num_u32_max_c -def x1_c : U32 := eval_global x1_body (by simp) - -/- [constants::X2] -/ -def x2_body : Result U32 := Result.ret (U32.ofInt 3 (by intlit)) -def x2_c : U32 := eval_global x2_body (by simp) - -/- [constants::incr] -/ -def incr_fwd (n : U32) : Result U32 := - n + (U32.ofInt 1 (by intlit)) - -/- [constants::X3] -/ -def x3_body : Result U32 := incr_fwd (U32.ofInt 32 (by intlit)) -def x3_c : U32 := eval_global x3_body (by simp) - -/- [constants::mk_pair0] -/ -def mk_pair0_fwd (x : U32) (y : U32) : Result (U32 × U32) := - Result.ret (x, y) - -/- [constants::Pair] -/ -structure pair_t (T1 T2 : Type) where - pair_x : T1 - pair_y : T2 - -/- [constants::mk_pair1] -/ -def mk_pair1_fwd (x : U32) (y : U32) : Result (pair_t U32 U32) := - Result.ret { pair_x := x, pair_y := y } - -/- [constants::P0] -/ -def p0_body : Result (U32 × U32) := - mk_pair0_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) -def p0_c : (U32 × U32) := eval_global p0_body (by simp) - -/- [constants::P1] -/ -def p1_body : Result (pair_t U32 U32) := - mk_pair1_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) -def p1_c : pair_t U32 U32 := eval_global p1_body (by simp) - -/- [constants::P2] -/ -def p2_body : Result (U32 × U32) := - Result.ret ((U32.ofInt 0 (by intlit)), (U32.ofInt 1 (by intlit))) -def p2_c : (U32 × U32) := eval_global p2_body (by simp) - -/- [constants::P3] -/ -def p3_body : Result (pair_t U32 U32) := - Result.ret - { pair_x := (U32.ofInt 0 (by intlit)), pair_y := (U32.ofInt 1 (by intlit)) } -def p3_c : pair_t U32 U32 := eval_global p3_body (by simp) - -/- [constants::Wrap] -/ -structure wrap_t (T : Type) where - wrap_val : T - -/- [constants::Wrap::{0}::new] -/ -def wrap_new_fwd (T : Type) (val : T) : Result (wrap_t T) := - Result.ret { wrap_val := val } - -/- [constants::Y] -/ -def y_body : Result (wrap_t I32) := wrap_new_fwd I32 (I32.ofInt 2 (by intlit)) -def y_c : wrap_t I32 := eval_global y_body (by simp) - -/- [constants::unwrap_y] -/ -def unwrap_y_fwd : Result I32 := - Result.ret y_c.wrap_val - -/- [constants::YVAL] -/ -def yval_body : Result I32 := unwrap_y_fwd -def yval_c : I32 := eval_global yval_body (by simp) - -/- [constants::get_z1::Z1] -/ -def get_z1_z1_body : Result I32 := Result.ret (I32.ofInt 3 (by intlit)) -def get_z1_z1_c : I32 := eval_global get_z1_z1_body (by simp) - -/- [constants::get_z1] -/ -def get_z1_fwd : Result I32 := - Result.ret get_z1_z1_c - -/- [constants::add] -/ -def add_fwd (a : I32) (b : I32) : Result I32 := - a + b - -/- [constants::Q1] -/ -def q1_body : Result I32 := Result.ret (I32.ofInt 5 (by intlit)) -def q1_c : I32 := eval_global q1_body (by simp) - -/- [constants::Q2] -/ -def q2_body : Result I32 := Result.ret q1_c -def q2_c : I32 := eval_global q2_body (by simp) - -/- [constants::Q3] -/ -def q3_body : Result I32 := add_fwd q2_c (I32.ofInt 3 (by intlit)) -def q3_c : I32 := eval_global q3_body (by simp) - -/- [constants::get_z2] -/ -def get_z2_fwd : Result I32 := - do - let i ← get_z1_fwd - let i0 ← add_fwd i q3_c - add_fwd q1_c i0 - -/- [constants::S1] -/ -def s1_body : Result U32 := Result.ret (U32.ofInt 6 (by intlit)) -def s1_c : U32 := eval_global s1_body (by simp) - -/- [constants::S2] -/ -def s2_body : Result U32 := incr_fwd s1_c -def s2_c : U32 := eval_global s2_body (by simp) - -/- [constants::S3] -/ -def s3_body : Result (pair_t U32 U32) := Result.ret p3_c -def s3_c : pair_t U32 U32 := eval_global s3_body (by simp) - -/- [constants::S4] -/ -def s4_body : Result (pair_t U32 U32) := - mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) -def s4_c : pair_t U32 U32 := eval_global s4_body (by simp) - diff --git a/tests/lean/misc-constants/lake-manifest.json b/tests/lean/misc-constants/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-constants/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-constants/lakefile.lean b/tests/lean/misc-constants/lakefile.lean deleted file mode 100644 index 01aacb90..00000000 --- a/tests/lean/misc-constants/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «constants» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «Constants» {} diff --git a/tests/lean/misc-constants/lean-toolchain b/tests/lean/misc-constants/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-constants/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/misc-external/Base/Primitives.lean b/tests/lean/misc-external/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-external/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-external/External.lean b/tests/lean/misc-external/External.lean deleted file mode 100644 index b95db309..00000000 --- a/tests/lean/misc-external/External.lean +++ /dev/null @@ -1 +0,0 @@ -import External.Funs diff --git a/tests/lean/misc-external/External/ExternalFuns.lean b/tests/lean/misc-external/External/ExternalFuns.lean deleted file mode 100644 index 6bd4f4a9..00000000 --- a/tests/lean/misc-external/External/ExternalFuns.lean +++ /dev/null @@ -1,5 +0,0 @@ -import Base.Primitives -import External.Types -import External.Opaque - -def opaque_defs : OpaqueDefs := sorry diff --git a/tests/lean/misc-external/External/Funs.lean b/tests/lean/misc-external/External/Funs.lean deleted file mode 100644 index eeb83989..00000000 --- a/tests/lean/misc-external/External/Funs.lean +++ /dev/null @@ -1,84 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [external]: function definitions -import Base.Primitives -import External.Types -import External.ExternalFuns - -/- [external::swap] -/ -def swap_fwd - (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := - do - let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st1, _) ← opaque_defs.core_mem_swap_back0 T x y st st0 - let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 - Result.ret (st2, ()) - -/- [external::swap] -/ -def swap_back - (T : Type) (x : T) (y : T) (st : State) (st0 : State) : - Result (State × (T × T)) - := - do - let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st2, x0) ← opaque_defs.core_mem_swap_back0 T x y st st1 - let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 - Result.ret (st0, (x0, y0)) - -/- [external::test_new_non_zero_u32] -/ -def test_new_non_zero_u32_fwd - (x : U32) (st : State) : Result (State × core_num_nonzero_non_zero_u32_t) := - do - let (st0, opt) ← opaque_defs.core_num_nonzero_non_zero_u32_new_fwd x st - opaque_defs.core_option_option_unwrap_fwd core_num_nonzero_non_zero_u32_t - opt st0 - -/- [external::test_vec] -/ -def test_vec_fwd : Result Unit := - do - let v := vec_new U32 - let _ ← vec_push_back U32 v (U32.ofInt 0 (by intlit)) - Result.ret () - -/- [external::custom_swap] -/ -def custom_swap_fwd - (T : Type) (x : T) (y : T) (st : State) : Result (State × T) := - do - let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st1, x0) ← opaque_defs.core_mem_swap_back0 T x y st st0 - let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 - Result.ret (st2, x0) - -/- [external::custom_swap] -/ -def custom_swap_back - (T : Type) (x : T) (y : T) (st : State) (ret0 : T) (st0 : State) : - Result (State × (T × T)) - := - do - let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st2, _) ← opaque_defs.core_mem_swap_back0 T x y st st1 - let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 - Result.ret (st0, (ret0, y0)) - -/- [external::test_custom_swap] -/ -def test_custom_swap_fwd - (x : U32) (y : U32) (st : State) : Result (State × Unit) := - do - let (st0, _) ← custom_swap_fwd U32 x y st - Result.ret (st0, ()) - -/- [external::test_custom_swap] -/ -def test_custom_swap_back - (x : U32) (y : U32) (st : State) (st0 : State) : - Result (State × (U32 × U32)) - := - custom_swap_back U32 x y st (U32.ofInt 1 (by intlit)) st0 - -/- [external::test_swap_non_zero] -/ -def test_swap_non_zero_fwd (x : U32) (st : State) : Result (State × U32) := - do - let (st0, _) ← swap_fwd U32 x (U32.ofInt 0 (by intlit)) st - let (st1, (x0, _)) ← swap_back U32 x (U32.ofInt 0 (by intlit)) st st0 - if h: x0 = (U32.ofInt 0 (by intlit)) - then Result.fail Error.panic - else Result.ret (st1, x0) - diff --git a/tests/lean/misc-external/External/Opaque.lean b/tests/lean/misc-external/External/Opaque.lean deleted file mode 100644 index d641912b..00000000 --- a/tests/lean/misc-external/External/Opaque.lean +++ /dev/null @@ -1,27 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [external]: opaque function definitions -import Base.Primitives -import External.Types - -structure OpaqueDefs where - - /- [core::mem::swap] -/ - core_mem_swap_fwd (T : Type) : T -> T -> State -> Result (State × Unit) - - /- [core::mem::swap] -/ - core_mem_swap_back0 - (T : Type) : T -> T -> State -> State -> Result (State × T) - - /- [core::mem::swap] -/ - core_mem_swap_back1 - (T : Type) : T -> T -> State -> State -> Result (State × T) - - /- [core::num::nonzero::NonZeroU32::{14}::new] -/ - core_num_nonzero_non_zero_u32_new_fwd - : - U32 -> State -> Result (State × (Option core_num_nonzero_non_zero_u32_t)) - - /- [core::option::Option::{0}::unwrap] -/ - core_option_option_unwrap_fwd - (T : Type) : Option T -> State -> Result (State × T) - diff --git a/tests/lean/misc-external/External/Types.lean b/tests/lean/misc-external/External/Types.lean deleted file mode 100644 index ed1842be..00000000 --- a/tests/lean/misc-external/External/Types.lean +++ /dev/null @@ -1,10 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [external]: type definitions -import Base.Primitives - -/- [core::num::nonzero::NonZeroU32] -/ -axiom core_num_nonzero_non_zero_u32_t : Type - -/- The state type used in the state-error monad -/ -axiom State : Type - diff --git a/tests/lean/misc-external/lake-manifest.json b/tests/lean/misc-external/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-external/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-external/lakefile.lean b/tests/lean/misc-external/lakefile.lean deleted file mode 100644 index 6cc4aae4..00000000 --- a/tests/lean/misc-external/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «external» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «External» {} diff --git a/tests/lean/misc-external/lean-toolchain b/tests/lean/misc-external/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-external/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/misc-loops/Base/Primitives.lean b/tests/lean/misc-loops/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-loops/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-loops/Loops.lean b/tests/lean/misc-loops/Loops.lean deleted file mode 100644 index 60c73776..00000000 --- a/tests/lean/misc-loops/Loops.lean +++ /dev/null @@ -1 +0,0 @@ -import Loops.Funs diff --git a/tests/lean/misc-loops/Loops/Clauses/Clauses.lean b/tests/lean/misc-loops/Loops/Clauses/Clauses.lean deleted file mode 100644 index 89a7ce34..00000000 --- a/tests/lean/misc-loops/Loops/Clauses/Clauses.lean +++ /dev/null @@ -1,205 +0,0 @@ --- [loops]: decreases clauses -import Base.Primitives -import Loops.Types - -/- [loops::sum]: termination measure -/ -@[simp] -def sum_loop_terminates (max : U32) (i : U32) (s : U32) := (max, i, s) - -syntax "sum_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| sum_loop_decreases $max $i $s) =>`(tactic| sorry) - -/- [loops::sum_with_mut_borrows]: termination measure -/ -@[simp] -def sum_with_mut_borrows_loop_terminates (max : U32) (mi : U32) (ms : U32) := - (max, mi, ms) - -syntax "sum_with_mut_borrows_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| sum_with_mut_borrows_loop_decreases $max $mi $ms) =>`(tactic| sorry) - -/- [loops::sum_with_shared_borrows]: termination measure -/ -@[simp] -def sum_with_shared_borrows_loop_terminates (max : U32) (i : U32) (s : U32) := - (max, i, s) - -syntax "sum_with_shared_borrows_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| sum_with_shared_borrows_loop_decreases $max $i $s) =>`(tactic| sorry) - -/- [loops::clear]: termination measure -/ -@[simp] def clear_loop_terminates (v : Vec U32) (i : Usize) := (v, i) - -syntax "clear_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| clear_loop_decreases $v $i) =>`(tactic| sorry) - -/- [loops::list_mem]: termination measure -/ -@[simp] -def list_mem_loop_terminates (x : U32) (ls : list_t U32) := (x, ls) - -syntax "list_mem_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_mem_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop]: termination measure -/ -@[simp] -def list_nth_mut_loop_loop_terminates (T : Type) (ls : list_t T) (i : U32) := - (ls, i) - -syntax "list_nth_mut_loop_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_loop_loop_decreases $ls $i) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop]: termination measure -/ -@[simp] -def list_nth_shared_loop_loop_terminates (T : Type) (ls : list_t T) (i : U32) := - (ls, i) - -syntax "list_nth_shared_loop_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_loop_loop_decreases $ls $i) =>`(tactic| sorry) - -/- [loops::get_elem_mut]: termination measure -/ -@[simp] -def get_elem_mut_loop_terminates (x : Usize) (ls : list_t Usize) := (x, ls) - -syntax "get_elem_mut_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| get_elem_mut_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::get_elem_shared]: termination measure -/ -@[simp] -def get_elem_shared_loop_terminates (x : Usize) (ls : list_t Usize) := (x, ls) - -syntax "get_elem_shared_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| get_elem_shared_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop_with_id]: termination measure -/ -@[simp] -def list_nth_mut_loop_with_id_loop_terminates (T : Type) (i : U32) - (ls : list_t T) := - (i, ls) - -syntax "list_nth_mut_loop_with_id_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_loop_with_id_loop_decreases $i $ls) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop_with_id]: termination measure -/ -@[simp] -def list_nth_shared_loop_with_id_loop_terminates (T : Type) (i : U32) - (ls : list_t T) := - (i, ls) - -syntax "list_nth_shared_loop_with_id_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_loop_with_id_loop_decreases $i $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop_pair]: termination measure -/ -@[simp] -def list_nth_mut_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_mut_loop_pair_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_loop_pair_loop_decreases $ls0 $ls1 $i) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop_pair]: termination measure -/ -@[simp] -def list_nth_shared_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_shared_loop_pair_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_mut_loop_pair_merge_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_mut_loop_pair_merge_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_shared_loop_pair_merge_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_shared_loop_pair_merge_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_shared_loop_pair]: termination measure -/ -@[simp] -def list_nth_mut_shared_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_mut_shared_loop_pair_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_shared_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_shared_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_mut_shared_loop_pair_merge_loop_terminates (T : Type) - (ls0 : list_t T) (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_mut_shared_loop_pair_merge_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_mut_shared_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_mut_loop_pair]: termination measure -/ -@[simp] -def list_nth_shared_mut_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_shared_mut_loop_pair_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_mut_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_mut_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_shared_mut_loop_pair_merge_loop_terminates (T : Type) - (ls0 : list_t T) (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -syntax "list_nth_shared_mut_loop_pair_merge_loop_decreases" term+ : tactic - -macro_rules -| `(tactic| list_nth_shared_mut_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - diff --git a/tests/lean/misc-loops/Loops/Clauses/Template.lean b/tests/lean/misc-loops/Loops/Clauses/Template.lean deleted file mode 100644 index 2e28a6c0..00000000 --- a/tests/lean/misc-loops/Loops/Clauses/Template.lean +++ /dev/null @@ -1,205 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [loops]: templates for the decreases clauses -import Base.Primitives -import Loops.Types - -/- [loops::sum]: termination measure -/ -@[simp] def sum_loop_terminates (max : U32) (i : U32) (s : U32) := (max, i, s) - -/- [loops::sum]: decreases_by tactic -/ -syntax "sum_loop_decreases" term+ : tactic -macro_rules -| `(tactic| sum_loop_decreases $max $i $s) =>`(tactic| sorry) - -/- [loops::sum_with_mut_borrows]: termination measure -/ -@[simp] -def sum_with_mut_borrows_loop_terminates (max : U32) (mi : U32) (ms : U32) := - (max, mi, ms) - -/- [loops::sum_with_mut_borrows]: decreases_by tactic -/ -syntax "sum_with_mut_borrows_loop_decreases" term+ : tactic -macro_rules -| `(tactic| sum_with_mut_borrows_loop_decreases $max $mi $ms) =>`(tactic| sorry) - -/- [loops::sum_with_shared_borrows]: termination measure -/ -@[simp] -def sum_with_shared_borrows_loop_terminates (max : U32) (i : U32) (s : U32) := - (max, i, s) - -/- [loops::sum_with_shared_borrows]: decreases_by tactic -/ -syntax "sum_with_shared_borrows_loop_decreases" term+ : tactic -macro_rules -| `(tactic| sum_with_shared_borrows_loop_decreases $max $i $s) =>`(tactic| sorry) - -/- [loops::clear]: termination measure -/ -@[simp] def clear_loop_terminates (v : Vec U32) (i : Usize) := (v, i) - -/- [loops::clear]: decreases_by tactic -/ -syntax "clear_loop_decreases" term+ : tactic -macro_rules -| `(tactic| clear_loop_decreases $v $i) =>`(tactic| sorry) - -/- [loops::list_mem]: termination measure -/ -@[simp] def list_mem_loop_terminates (x : U32) (ls : list_t U32) := (x, ls) - -/- [loops::list_mem]: decreases_by tactic -/ -syntax "list_mem_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_mem_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop]: termination measure -/ -@[simp] -def list_nth_mut_loop_loop_terminates (T : Type) (ls : list_t T) (i : U32) := - (ls, i) - -/- [loops::list_nth_mut_loop]: decreases_by tactic -/ -syntax "list_nth_mut_loop_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_loop_loop_decreases $ls $i) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop]: termination measure -/ -@[simp] -def list_nth_shared_loop_loop_terminates (T : Type) (ls : list_t T) (i : U32) - := - (ls, i) - -/- [loops::list_nth_shared_loop]: decreases_by tactic -/ -syntax "list_nth_shared_loop_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_loop_loop_decreases $ls $i) =>`(tactic| sorry) - -/- [loops::get_elem_mut]: termination measure -/ -@[simp] -def get_elem_mut_loop_terminates (x : Usize) (ls : list_t Usize) := (x, ls) - -/- [loops::get_elem_mut]: decreases_by tactic -/ -syntax "get_elem_mut_loop_decreases" term+ : tactic -macro_rules -| `(tactic| get_elem_mut_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::get_elem_shared]: termination measure -/ -@[simp] -def get_elem_shared_loop_terminates (x : Usize) (ls : list_t Usize) := (x, ls) - -/- [loops::get_elem_shared]: decreases_by tactic -/ -syntax "get_elem_shared_loop_decreases" term+ : tactic -macro_rules -| `(tactic| get_elem_shared_loop_decreases $x $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop_with_id]: termination measure -/ -@[simp] -def list_nth_mut_loop_with_id_loop_terminates (T : Type) (i : U32) - (ls : list_t T) := - (i, ls) - -/- [loops::list_nth_mut_loop_with_id]: decreases_by tactic -/ -syntax "list_nth_mut_loop_with_id_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_loop_with_id_loop_decreases $i $ls) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop_with_id]: termination measure -/ -@[simp] -def list_nth_shared_loop_with_id_loop_terminates (T : Type) (i : U32) - (ls : list_t T) := - (i, ls) - -/- [loops::list_nth_shared_loop_with_id]: decreases_by tactic -/ -syntax "list_nth_shared_loop_with_id_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_loop_with_id_loop_decreases $i $ls) =>`(tactic| sorry) - -/- [loops::list_nth_mut_loop_pair]: termination measure -/ -@[simp] -def list_nth_mut_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_mut_loop_pair]: decreases_by tactic -/ -syntax "list_nth_mut_loop_pair_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_loop_pair_loop_decreases $ls0 $ls1 $i) =>`(tactic| sorry) - -/- [loops::list_nth_shared_loop_pair]: termination measure -/ -@[simp] -def list_nth_shared_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_shared_loop_pair]: decreases_by tactic -/ -syntax "list_nth_shared_loop_pair_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_mut_loop_pair_merge_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_mut_loop_pair_merge]: decreases_by tactic -/ -syntax "list_nth_mut_loop_pair_merge_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_shared_loop_pair_merge_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_shared_loop_pair_merge]: decreases_by tactic -/ -syntax "list_nth_shared_loop_pair_merge_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_shared_loop_pair]: termination measure -/ -@[simp] -def list_nth_mut_shared_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_mut_shared_loop_pair]: decreases_by tactic -/ -syntax "list_nth_mut_shared_loop_pair_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_shared_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_mut_shared_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_mut_shared_loop_pair_merge_loop_terminates (T : Type) - (ls0 : list_t T) (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_mut_shared_loop_pair_merge]: decreases_by tactic -/ -syntax "list_nth_mut_shared_loop_pair_merge_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_mut_shared_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_mut_loop_pair]: termination measure -/ -@[simp] -def list_nth_shared_mut_loop_pair_loop_terminates (T : Type) (ls0 : list_t T) - (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_shared_mut_loop_pair]: decreases_by tactic -/ -syntax "list_nth_shared_mut_loop_pair_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_mut_loop_pair_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - -/- [loops::list_nth_shared_mut_loop_pair_merge]: termination measure -/ -@[simp] -def list_nth_shared_mut_loop_pair_merge_loop_terminates (T : Type) - (ls0 : list_t T) (ls1 : list_t T) (i : U32) := - (ls0, ls1, i) - -/- [loops::list_nth_shared_mut_loop_pair_merge]: decreases_by tactic -/ -syntax "list_nth_shared_mut_loop_pair_merge_loop_decreases" term+ : tactic -macro_rules -| `(tactic| list_nth_shared_mut_loop_pair_merge_loop_decreases $ls0 $ls1 $i) => - `(tactic| sorry) - diff --git a/tests/lean/misc-loops/Loops/Funs.lean b/tests/lean/misc-loops/Loops/Funs.lean deleted file mode 100644 index fd8d62d7..00000000 --- a/tests/lean/misc-loops/Loops/Funs.lean +++ /dev/null @@ -1,705 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [loops]: function definitions -import Base.Primitives -import Loops.Types -import Loops.Clauses.Clauses - -/- [loops::sum] -/ -def sum_loop_fwd (max : U32) (i : U32) (s : U32) : (Result U32) := - if h: i < max - then - do - let s0 ← s + i - let i0 ← i + (U32.ofInt 1 (by intlit)) - sum_loop_fwd max i0 s0 - else s * (U32.ofInt 2 (by intlit)) -termination_by sum_loop_fwd max i s => sum_loop_terminates max i s -decreasing_by sum_loop_decreases max i s - -/- [loops::sum] -/ -def sum_fwd (max : U32) : Result U32 := - sum_loop_fwd max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) - -/- [loops::sum_with_mut_borrows] -/ -def sum_with_mut_borrows_loop_fwd - (max : U32) (mi : U32) (ms : U32) : (Result U32) := - if h: mi < max - then - do - let ms0 ← ms + mi - let mi0 ← mi + (U32.ofInt 1 (by intlit)) - sum_with_mut_borrows_loop_fwd max mi0 ms0 - else ms * (U32.ofInt 2 (by intlit)) -termination_by sum_with_mut_borrows_loop_fwd max mi ms => - sum_with_mut_borrows_loop_terminates max mi ms -decreasing_by sum_with_mut_borrows_loop_decreases max mi ms - -/- [loops::sum_with_mut_borrows] -/ -def sum_with_mut_borrows_fwd (max : U32) : Result U32 := - sum_with_mut_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) - (U32.ofInt 0 (by intlit)) - -/- [loops::sum_with_shared_borrows] -/ -def sum_with_shared_borrows_loop_fwd - (max : U32) (i : U32) (s : U32) : (Result U32) := - if h: i < max - then - do - let i0 ← i + (U32.ofInt 1 (by intlit)) - let s0 ← s + i0 - sum_with_shared_borrows_loop_fwd max i0 s0 - else s * (U32.ofInt 2 (by intlit)) -termination_by sum_with_shared_borrows_loop_fwd max i s => - sum_with_shared_borrows_loop_terminates max i s -decreasing_by sum_with_shared_borrows_loop_decreases max i s - -/- [loops::sum_with_shared_borrows] -/ -def sum_with_shared_borrows_fwd (max : U32) : Result U32 := - sum_with_shared_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) - (U32.ofInt 0 (by intlit)) - -/- [loops::clear] -/ -def clear_loop_fwd_back (v : Vec U32) (i : Usize) : (Result (Vec U32)) := - let i0 := vec_len U32 v - if h: i < i0 - then - do - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let v0 ← vec_index_mut_back U32 v i (U32.ofInt 0 (by intlit)) - clear_loop_fwd_back v0 i1 - else Result.ret v -termination_by clear_loop_fwd_back v i => clear_loop_terminates v i -decreasing_by clear_loop_decreases v i - -/- [loops::clear] -/ -def clear_fwd_back (v : Vec U32) : Result (Vec U32) := - clear_loop_fwd_back v (Usize.ofInt 0 (by intlit)) - -/- [loops::list_mem] -/ -def list_mem_loop_fwd (x : U32) (ls : list_t U32) : (Result Bool) := - match h: ls with - | list_t.Cons y tl => - if h: y = x - then Result.ret true - else list_mem_loop_fwd x tl - | list_t.Nil => Result.ret false -termination_by list_mem_loop_fwd x ls => list_mem_loop_terminates x ls -decreasing_by list_mem_loop_decreases x ls - -/- [loops::list_mem] -/ -def list_mem_fwd (x : U32) (ls : list_t U32) : Result Bool := - list_mem_loop_fwd x ls - -/- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_loop_fwd - (T : Type) (ls : list_t T) (i : U32) : (Result T) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_loop_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_loop_fwd ls i => - list_nth_mut_loop_loop_terminates T ls i -decreasing_by list_nth_mut_loop_loop_decreases ls i - -/- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := - list_nth_mut_loop_loop_fwd T ls i - -/- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_loop_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : (Result (list_t T)) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl0 ← list_nth_mut_loop_loop_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_loop_back ls i ret0 => - list_nth_mut_loop_loop_terminates T ls i -decreasing_by list_nth_mut_loop_loop_decreases ls i - -/- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - list_nth_mut_loop_loop_back T ls i ret0 - -/- [loops::list_nth_shared_loop] -/ -def list_nth_shared_loop_loop_fwd - (T : Type) (ls : list_t T) (i : U32) : (Result T) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_loop_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_loop_loop_fwd ls i => - list_nth_shared_loop_loop_terminates T ls i -decreasing_by list_nth_shared_loop_loop_decreases ls i - -/- [loops::list_nth_shared_loop] -/ -def list_nth_shared_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := - list_nth_shared_loop_loop_fwd T ls i - -/- [loops::get_elem_mut] -/ -def get_elem_mut_loop_fwd (x : Usize) (ls : list_t Usize) : (Result Usize) := - match h: ls with - | list_t.Cons y tl => - if h: y = x - then Result.ret y - else get_elem_mut_loop_fwd x tl - | list_t.Nil => Result.fail Error.panic -termination_by get_elem_mut_loop_fwd x ls => get_elem_mut_loop_terminates x ls -decreasing_by get_elem_mut_loop_decreases x ls - -/- [loops::get_elem_mut] -/ -def get_elem_mut_fwd (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := - do - let l ← - vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) - get_elem_mut_loop_fwd x l - -/- [loops::get_elem_mut] -/ -def get_elem_mut_loop_back - (x : Usize) (ls : list_t Usize) (ret0 : Usize) : (Result (list_t Usize)) := - match h: ls with - | list_t.Cons y tl => - if h: y = x - then Result.ret (list_t.Cons ret0 tl) - else - do - let tl0 ← get_elem_mut_loop_back x tl ret0 - Result.ret (list_t.Cons y tl0) - | list_t.Nil => Result.fail Error.panic -termination_by get_elem_mut_loop_back x ls ret0 => - get_elem_mut_loop_terminates x ls -decreasing_by get_elem_mut_loop_decreases x ls - -/- [loops::get_elem_mut] -/ -def get_elem_mut_back - (slots : Vec (list_t Usize)) (x : Usize) (ret0 : Usize) : - Result (Vec (list_t Usize)) - := - do - let l ← - vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) - let l0 ← get_elem_mut_loop_back x l ret0 - vec_index_mut_back (list_t Usize) slots (Usize.ofInt 0 (by intlit)) l0 - -/- [loops::get_elem_shared] -/ -def get_elem_shared_loop_fwd - (x : Usize) (ls : list_t Usize) : (Result Usize) := - match h: ls with - | list_t.Cons y tl => - if h: y = x - then Result.ret y - else get_elem_shared_loop_fwd x tl - | list_t.Nil => Result.fail Error.panic -termination_by get_elem_shared_loop_fwd x ls => - get_elem_shared_loop_terminates x ls -decreasing_by get_elem_shared_loop_decreases x ls - -/- [loops::get_elem_shared] -/ -def get_elem_shared_fwd - (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := - do - let l ← vec_index_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) - get_elem_shared_loop_fwd x l - -/- [loops::id_mut] -/ -def id_mut_fwd (T : Type) (ls : list_t T) : Result (list_t T) := - Result.ret ls - -/- [loops::id_mut] -/ -def id_mut_back - (T : Type) (ls : list_t T) (ret0 : list_t T) : Result (list_t T) := - Result.ret ret0 - -/- [loops::id_shared] -/ -def id_shared_fwd (T : Type) (ls : list_t T) : Result (list_t T) := - Result.ret ls - -/- [loops::list_nth_mut_loop_with_id] -/ -def list_nth_mut_loop_with_id_loop_fwd - (T : Type) (i : U32) (ls : list_t T) : (Result T) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_with_id_loop_fwd T i0 tl - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_with_id_loop_fwd i ls => - list_nth_mut_loop_with_id_loop_terminates T i ls -decreasing_by list_nth_mut_loop_with_id_loop_decreases i ls - -/- [loops::list_nth_mut_loop_with_id] -/ -def list_nth_mut_loop_with_id_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := - do - let ls0 ← id_mut_fwd T ls - list_nth_mut_loop_with_id_loop_fwd T i ls0 - -/- [loops::list_nth_mut_loop_with_id] -/ -def list_nth_mut_loop_with_id_loop_back - (T : Type) (i : U32) (ls : list_t T) (ret0 : T) : (Result (list_t T)) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl0 ← list_nth_mut_loop_with_id_loop_back T i0 tl ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_with_id_loop_back i ls ret0 => - list_nth_mut_loop_with_id_loop_terminates T i ls -decreasing_by list_nth_mut_loop_with_id_loop_decreases i ls - -/- [loops::list_nth_mut_loop_with_id] -/ -def list_nth_mut_loop_with_id_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - do - let ls0 ← id_mut_fwd T ls - let l ← list_nth_mut_loop_with_id_loop_back T i ls0 ret0 - id_mut_back T ls l - -/- [loops::list_nth_shared_loop_with_id] -/ -def list_nth_shared_loop_with_id_loop_fwd - (T : Type) (i : U32) (ls : list_t T) : (Result T) := - match h: ls with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_with_id_loop_fwd T i0 tl - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_loop_with_id_loop_fwd i ls => - list_nth_shared_loop_with_id_loop_terminates T i ls -decreasing_by list_nth_shared_loop_with_id_loop_decreases i ls - -/- [loops::list_nth_shared_loop_with_id] -/ -def list_nth_shared_loop_with_id_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := - do - let ls0 ← id_shared_fwd T ls - list_nth_shared_loop_with_id_loop_fwd T i ls0 - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_pair_loop_fwd ls0 ls1 i => - list_nth_mut_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_mut_loop_pair_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_loop_back'a - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl00 ← list_nth_mut_loop_pair_loop_back'a T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_pair_loop_back'a ls0 ls1 i ret0 => - list_nth_mut_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_back'a - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_mut_loop_pair_loop_back'a T ls0 ls1 i ret0 - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_loop_back'b - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl10 ← list_nth_mut_loop_pair_loop_back'b T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_pair_loop_back'b ls0 ls1 i ret0 => - list_nth_mut_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_back'b - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_mut_loop_pair_loop_back'b T ls0 ls1 i ret0 - -/- [loops::list_nth_shared_loop_pair] -/ -def list_nth_shared_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_loop_pair_loop_fwd ls0 ls1 i => - list_nth_shared_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_loop_pair] -/ -def list_nth_shared_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_shared_loop_pair_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair_merge] -/ -def list_nth_mut_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_pair_merge_loop_fwd ls0 ls1 i => - list_nth_mut_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair_merge] -/ -def list_nth_mut_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_mut_loop_pair_merge_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair_merge] -/ -def list_nth_mut_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : - (Result ((list_t T) × (list_t T))) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then - let (t, t0) := ret0 - Result.ret (list_t.Cons t tl0, list_t.Cons t0 tl1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let (tl00, tl10) ← - list_nth_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00, list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_loop_pair_merge_loop_back ls0 ls1 i ret0 => - list_nth_mut_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_loop_pair_merge] -/ -def list_nth_mut_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : - Result ((list_t T) × (list_t T)) - := - list_nth_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 - -/- [loops::list_nth_shared_loop_pair_merge] -/ -def list_nth_shared_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_loop_pair_merge_loop_fwd ls0 ls1 i => - list_nth_shared_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_loop_pair_merge] -/ -def list_nth_shared_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_shared_loop_pair_merge_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair] -/ -def list_nth_mut_shared_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_shared_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_shared_loop_pair_loop_fwd ls0 ls1 i => - list_nth_mut_shared_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_shared_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair] -/ -def list_nth_mut_shared_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_mut_shared_loop_pair_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair] -/ -def list_nth_mut_shared_loop_pair_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl00 ← - list_nth_mut_shared_loop_pair_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_shared_loop_pair_loop_back ls0 ls1 i ret0 => - list_nth_mut_shared_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_shared_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair] -/ -def list_nth_mut_shared_loop_pair_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_mut_shared_loop_pair_loop_back T ls0 ls1 i ret0 - -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -def list_nth_mut_shared_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_shared_loop_pair_merge_loop_fwd ls0 ls1 i => - list_nth_mut_shared_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_shared_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -def list_nth_mut_shared_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_mut_shared_loop_pair_merge_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -def list_nth_mut_shared_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl00 ← - list_nth_mut_shared_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_mut_shared_loop_pair_merge_loop_back ls0 ls1 i ret0 => - list_nth_mut_shared_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_mut_shared_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -def list_nth_mut_shared_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_mut_shared_loop_pair_merge_loop_back T ls0 ls1 i ret0 - -/- [loops::list_nth_shared_mut_loop_pair] -/ -def list_nth_shared_mut_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_mut_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_mut_loop_pair_loop_fwd ls0 ls1 i => - list_nth_shared_mut_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_mut_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair] -/ -def list_nth_shared_mut_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_shared_mut_loop_pair_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair] -/ -def list_nth_shared_mut_loop_pair_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl10 ← - list_nth_shared_mut_loop_pair_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_mut_loop_pair_loop_back ls0 ls1 i ret0 => - list_nth_shared_mut_loop_pair_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_mut_loop_pair_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair] -/ -def list_nth_shared_mut_loop_pair_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_shared_mut_loop_pair_loop_back T ls0 ls1 i ret0 - -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -def list_nth_shared_mut_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : (Result (T × T)) := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (x0, x1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_mut_loop_pair_merge_loop_fwd ls0 ls1 i => - list_nth_shared_mut_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_mut_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -def list_nth_shared_mut_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - list_nth_shared_mut_loop_pair_merge_loop_fwd T ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -def list_nth_shared_mut_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - (Result (list_t T)) - := - match h: ls0 with - | list_t.Cons x0 tl0 => - match h: ls1 with - | list_t.Cons x1 tl1 => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl10 ← - list_nth_shared_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic -termination_by list_nth_shared_mut_loop_pair_merge_loop_back ls0 ls1 i ret0 => - list_nth_shared_mut_loop_pair_merge_loop_terminates T ls0 ls1 i -decreasing_by list_nth_shared_mut_loop_pair_merge_loop_decreases ls0 ls1 i - -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -def list_nth_shared_mut_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) - := - list_nth_shared_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 - diff --git a/tests/lean/misc-loops/Loops/Types.lean b/tests/lean/misc-loops/Loops/Types.lean deleted file mode 100644 index ca43f4c8..00000000 --- a/tests/lean/misc-loops/Loops/Types.lean +++ /dev/null @@ -1,9 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [loops]: type definitions -import Base.Primitives - -/- [loops::List] -/ -inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T -| Nil : list_t T - diff --git a/tests/lean/misc-loops/lake-manifest.json b/tests/lean/misc-loops/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-loops/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-loops/lakefile.lean b/tests/lean/misc-loops/lakefile.lean deleted file mode 100644 index 097c0a7d..00000000 --- a/tests/lean/misc-loops/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «loops» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «Loops» {} diff --git a/tests/lean/misc-loops/lean-toolchain b/tests/lean/misc-loops/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-loops/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/misc-no_nested_borrows/Base/Primitives.lean b/tests/lean/misc-no_nested_borrows/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-no_nested_borrows/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-no_nested_borrows/NoNestedBorrows.lean b/tests/lean/misc-no_nested_borrows/NoNestedBorrows.lean deleted file mode 100644 index 12c7d8f7..00000000 --- a/tests/lean/misc-no_nested_borrows/NoNestedBorrows.lean +++ /dev/null @@ -1,538 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [no_nested_borrows] -import Base.Primitives - -/- [no_nested_borrows::Pair] -/ -structure pair_t (T1 T2 : Type) where - pair_x : T1 - pair_y : T2 - -/- [no_nested_borrows::List] -/ -inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T -| Nil : list_t T - -/- [no_nested_borrows::One] -/ -inductive one_t (T1 : Type) := -| One : T1 -> one_t T1 - -/- [no_nested_borrows::EmptyEnum] -/ -inductive empty_enum_t := -| Empty : empty_enum_t - -/- [no_nested_borrows::Enum] -/ -inductive enum_t := -| Variant1 : enum_t -| Variant2 : enum_t - -/- [no_nested_borrows::EmptyStruct] -/ -structure empty_struct_t where - -/- [no_nested_borrows::Sum] -/ -inductive sum_t (T1 T2 : Type) := -| Left : T1 -> sum_t T1 T2 -| Right : T2 -> sum_t T1 T2 - -/- [no_nested_borrows::neg_test] -/ -def neg_test_fwd (x : I32) : Result I32 := - - x - -/- [no_nested_borrows::add_test] -/ -def add_test_fwd (x : U32) (y : U32) : Result U32 := - x + y - -/- [no_nested_borrows::subs_test] -/ -def subs_test_fwd (x : U32) (y : U32) : Result U32 := - x - y - -/- [no_nested_borrows::div_test] -/ -def div_test_fwd (x : U32) (y : U32) : Result U32 := - x / y - -/- [no_nested_borrows::div_test1] -/ -def div_test1_fwd (x : U32) : Result U32 := - x / (U32.ofInt 2 (by intlit)) - -/- [no_nested_borrows::rem_test] -/ -def rem_test_fwd (x : U32) (y : U32) : Result U32 := - x % y - -/- [no_nested_borrows::cast_test] -/ -def cast_test_fwd (x : U32) : Result I32 := - Scalar.cast .I32 x - -/- [no_nested_borrows::test2] -/ -def test2_fwd : Result Unit := - do - let _ ← (U32.ofInt 23 (by intlit)) + (U32.ofInt 44 (by intlit)) - Result.ret () - -/- Unit test for [no_nested_borrows::test2] -/ -#assert (test2_fwd == .ret ()) - -/- [no_nested_borrows::get_max] -/ -def get_max_fwd (x : U32) (y : U32) : Result U32 := - if h: x >= y - then Result.ret x - else Result.ret y - -/- [no_nested_borrows::test3] -/ -def test3_fwd : Result Unit := - do - let x ← get_max_fwd (U32.ofInt 4 (by intlit)) (U32.ofInt 3 (by intlit)) - let y ← get_max_fwd (U32.ofInt 10 (by intlit)) (U32.ofInt 11 (by intlit)) - let z ← x + y - if h: not (z = (U32.ofInt 15 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test3] -/ -#assert (test3_fwd == .ret ()) - -/- [no_nested_borrows::test_neg1] -/ -def test_neg1_fwd : Result Unit := - do - let y ← - (I32.ofInt 3 (by intlit)) - if h: not (y = (I32.ofInt (-(3:Int)) (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_neg1] -/ -#assert (test_neg1_fwd == .ret ()) - -/- [no_nested_borrows::refs_test1] -/ -def refs_test1_fwd : Result Unit := - if h: not ((I32.ofInt 1 (by intlit)) = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::refs_test1] -/ -#assert (refs_test1_fwd == .ret ()) - -/- [no_nested_borrows::refs_test2] -/ -def refs_test2_fwd : Result Unit := - if h: not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) - then Result.fail Error.panic - else - if h: not ((I32.ofInt 0 (by intlit)) = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else - if h: not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) - then Result.fail Error.panic - else - if h: not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::refs_test2] -/ -#assert (refs_test2_fwd == .ret ()) - -/- [no_nested_borrows::test_list1] -/ -def test_list1_fwd : Result Unit := - Result.ret () - -/- Unit test for [no_nested_borrows::test_list1] -/ -#assert (test_list1_fwd == .ret ()) - -/- [no_nested_borrows::test_box1] -/ -def test_box1_fwd : Result Unit := - let b := (I32.ofInt 1 (by intlit)) - let x := b - if h: not (x = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_box1] -/ -#assert (test_box1_fwd == .ret ()) - -/- [no_nested_borrows::copy_int] -/ -def copy_int_fwd (x : I32) : Result I32 := - Result.ret x - -/- [no_nested_borrows::test_unreachable] -/ -def test_unreachable_fwd (b : Bool) : Result Unit := - if h: b - then Result.fail Error.panic - else Result.ret () - -/- [no_nested_borrows::test_panic] -/ -def test_panic_fwd (b : Bool) : Result Unit := - if h: b - then Result.fail Error.panic - else Result.ret () - -/- [no_nested_borrows::test_copy_int] -/ -def test_copy_int_fwd : Result Unit := - do - let y ← copy_int_fwd (I32.ofInt 0 (by intlit)) - if h: not ((I32.ofInt 0 (by intlit)) = y) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_copy_int] -/ -#assert (test_copy_int_fwd == .ret ()) - -/- [no_nested_borrows::is_cons] -/ -def is_cons_fwd (T : Type) (l : list_t T) : Result Bool := - match h: l with - | list_t.Cons t l0 => Result.ret true - | list_t.Nil => Result.ret false - -/- [no_nested_borrows::test_is_cons] -/ -def test_is_cons_fwd : Result Unit := - do - let l := list_t.Nil - let b ← is_cons_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) - if h: not b - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_is_cons] -/ -#assert (test_is_cons_fwd == .ret ()) - -/- [no_nested_borrows::split_list] -/ -def split_list_fwd (T : Type) (l : list_t T) : Result (T × (list_t T)) := - match h: l with - | list_t.Cons hd tl => Result.ret (hd, tl) - | list_t.Nil => Result.fail Error.panic - -/- [no_nested_borrows::test_split_list] -/ -def test_split_list_fwd : Result Unit := - do - let l := list_t.Nil - let p ← split_list_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) - let (hd, _) := p - if h: not (hd = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_split_list] -/ -#assert (test_split_list_fwd == .ret ()) - -/- [no_nested_borrows::choose] -/ -def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := - if h: b - then Result.ret x - else Result.ret y - -/- [no_nested_borrows::choose] -/ -def choose_back - (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := - if h: b - then Result.ret (ret0, y) - else Result.ret (x, ret0) - -/- [no_nested_borrows::choose_test] -/ -def choose_test_fwd : Result Unit := - do - let z ← - choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) - let z0 ← z + (I32.ofInt 1 (by intlit)) - if h: not (z0 = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let (x, y) ← - choose_back I32 true (I32.ofInt 0 (by intlit)) - (I32.ofInt 0 (by intlit)) z0 - if h: not (x = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - if h: not (y = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::choose_test] -/ -#assert (choose_test_fwd == .ret ()) - -/- [no_nested_borrows::test_char] -/ -def test_char_fwd : Result Char := - Result.ret 'a' - -mutual - -/- [no_nested_borrows::NodeElem] -/ -inductive node_elem_t (T : Type) := -| Cons : tree_t T -> node_elem_t T -> node_elem_t T -| Nil : node_elem_t T - -/- [no_nested_borrows::Tree] -/ -inductive tree_t (T : Type) := -| Leaf : T -> tree_t T -| Node : T -> node_elem_t T -> tree_t T -> tree_t T - -end - -/- [no_nested_borrows::list_length] -/ -def list_length_fwd (T : Type) (l : list_t T) : Result U32 := - match h: l with - | list_t.Cons t l1 => - do - let i ← list_length_fwd T l1 - (U32.ofInt 1 (by intlit)) + i - | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) - -/- [no_nested_borrows::list_nth_shared] -/ -def list_nth_shared_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic - -/- [no_nested_borrows::list_nth_mut] -/ -def list_nth_mut_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic - -/- [no_nested_borrows::list_nth_mut] -/ -def list_nth_mut_back - (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: l with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl0 ← list_nth_mut_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic - -/- [no_nested_borrows::list_rev_aux] -/ -def list_rev_aux_fwd - (T : Type) (li : list_t T) (lo : list_t T) : Result (list_t T) := - match h: li with - | list_t.Cons hd tl => list_rev_aux_fwd T tl (list_t.Cons hd lo) - | list_t.Nil => Result.ret lo - -/- [no_nested_borrows::list_rev] -/ -def list_rev_fwd_back (T : Type) (l : list_t T) : Result (list_t T) := - let li := mem_replace_fwd (list_t T) l list_t.Nil - list_rev_aux_fwd T li list_t.Nil - -/- [no_nested_borrows::test_list_functions] -/ -def test_list_functions_fwd : Result Unit := - do - let l := list_t.Nil - let l0 := list_t.Cons (I32.ofInt 2 (by intlit)) l - let l1 := list_t.Cons (I32.ofInt 1 (by intlit)) l0 - let i ← list_length_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) - if h: not (i = (U32.ofInt 3 (by intlit))) - then Result.fail Error.panic - else - do - let i0 ← - list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) - (U32.ofInt 0 (by intlit)) - if h: not (i0 = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else - do - let i1 ← - list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) - l1) (U32.ofInt 1 (by intlit)) - if h: not (i1 = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let i2 ← - list_nth_shared_fwd I32 (list_t.Cons - (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 2 (by intlit)) - if h: not (i2 = (I32.ofInt 2 (by intlit))) - then Result.fail Error.panic - else - do - let ls ← - list_nth_mut_back I32 (list_t.Cons - (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) - (I32.ofInt 3 (by intlit)) - let i3 ← - list_nth_shared_fwd I32 ls (U32.ofInt 0 (by intlit)) - if h: not (i3 = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else - do - let i4 ← - list_nth_shared_fwd I32 ls (U32.ofInt 1 (by intlit)) - if h: not (i4 = (I32.ofInt 3 (by intlit))) - then Result.fail Error.panic - else - do - let i5 ← - list_nth_shared_fwd I32 ls - (U32.ofInt 2 (by intlit)) - if h: not (i5 = (I32.ofInt 2 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_list_functions] -/ -#assert (test_list_functions_fwd == .ret ()) - -/- [no_nested_borrows::id_mut_pair1] -/ -def id_mut_pair1_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := - Result.ret (x, y) - -/- [no_nested_borrows::id_mut_pair1] -/ -def id_mut_pair1_back - (T1 T2 : Type) (x : T1) (y : T2) (ret0 : (T1 × T2)) : Result (T1 × T2) := - let (t, t0) := ret0 - Result.ret (t, t0) - -/- [no_nested_borrows::id_mut_pair2] -/ -def id_mut_pair2_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := - let (t, t0) := p - Result.ret (t, t0) - -/- [no_nested_borrows::id_mut_pair2] -/ -def id_mut_pair2_back - (T1 T2 : Type) (p : (T1 × T2)) (ret0 : (T1 × T2)) : Result (T1 × T2) := - let (t, t0) := ret0 - Result.ret (t, t0) - -/- [no_nested_borrows::id_mut_pair3] -/ -def id_mut_pair3_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := - Result.ret (x, y) - -/- [no_nested_borrows::id_mut_pair3] -/ -def id_mut_pair3_back'a - (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T1) : Result T1 := - Result.ret ret0 - -/- [no_nested_borrows::id_mut_pair3] -/ -def id_mut_pair3_back'b - (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T2) : Result T2 := - Result.ret ret0 - -/- [no_nested_borrows::id_mut_pair4] -/ -def id_mut_pair4_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := - let (t, t0) := p - Result.ret (t, t0) - -/- [no_nested_borrows::id_mut_pair4] -/ -def id_mut_pair4_back'a - (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T1) : Result T1 := - Result.ret ret0 - -/- [no_nested_borrows::id_mut_pair4] -/ -def id_mut_pair4_back'b - (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T2) : Result T2 := - Result.ret ret0 - -/- [no_nested_borrows::StructWithTuple] -/ -structure struct_with_tuple_t (T1 T2 : Type) where - struct_with_tuple_p : (T1 × T2) - -/- [no_nested_borrows::new_tuple1] -/ -def new_tuple1_fwd : Result (struct_with_tuple_t U32 U32) := - Result.ret - { - struct_with_tuple_p := - ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) - } - -/- [no_nested_borrows::new_tuple2] -/ -def new_tuple2_fwd : Result (struct_with_tuple_t I16 I16) := - Result.ret - { - struct_with_tuple_p := - ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) - } - -/- [no_nested_borrows::new_tuple3] -/ -def new_tuple3_fwd : Result (struct_with_tuple_t U64 I64) := - Result.ret - { - struct_with_tuple_p := - ((U64.ofInt 1 (by intlit)), (I64.ofInt 2 (by intlit))) - } - -/- [no_nested_borrows::StructWithPair] -/ -structure struct_with_pair_t (T1 T2 : Type) where - struct_with_pair_p : pair_t T1 T2 - -/- [no_nested_borrows::new_pair1] -/ -def new_pair1_fwd : Result (struct_with_pair_t U32 U32) := - Result.ret - { - struct_with_pair_p := - { - pair_x := (U32.ofInt 1 (by intlit)), - pair_y := (U32.ofInt 2 (by intlit)) - } - } - -/- [no_nested_borrows::test_constants] -/ -def test_constants_fwd : Result Unit := - do - let swt ← new_tuple1_fwd - let (i, _) := swt.struct_with_tuple_p - if h: not (i = (U32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let swt0 ← new_tuple2_fwd - let (i0, _) := swt0.struct_with_tuple_p - if h: not (i0 = (I16.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let swt1 ← new_tuple3_fwd - let (i1, _) := swt1.struct_with_tuple_p - if h: not (i1 = (U64.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let swp ← new_pair1_fwd - if h: not (swp.struct_with_pair_p.pair_x = - (U32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [no_nested_borrows::test_constants] -/ -#assert (test_constants_fwd == .ret ()) - -/- [no_nested_borrows::test_weird_borrows1] -/ -def test_weird_borrows1_fwd : Result Unit := - Result.ret () - -/- Unit test for [no_nested_borrows::test_weird_borrows1] -/ -#assert (test_weird_borrows1_fwd == .ret ()) - -/- [no_nested_borrows::test_mem_replace] -/ -def test_mem_replace_fwd_back (px : U32) : Result U32 := - let y := mem_replace_fwd U32 px (U32.ofInt 1 (by intlit)) - if h: not (y = (U32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else Result.ret (U32.ofInt 2 (by intlit)) - -/- [no_nested_borrows::test_shared_borrow_bool1] -/ -def test_shared_borrow_bool1_fwd (b : Bool) : Result U32 := - if h: b - then Result.ret (U32.ofInt 0 (by intlit)) - else Result.ret (U32.ofInt 1 (by intlit)) - -/- [no_nested_borrows::test_shared_borrow_bool2] -/ -def test_shared_borrow_bool2_fwd : Result U32 := - Result.ret (U32.ofInt 0 (by intlit)) - -/- [no_nested_borrows::test_shared_borrow_enum1] -/ -def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := - match h: l with - | list_t.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) - | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) - -/- [no_nested_borrows::test_shared_borrow_enum2] -/ -def test_shared_borrow_enum2_fwd : Result U32 := - Result.ret (U32.ofInt 0 (by intlit)) - diff --git a/tests/lean/misc-no_nested_borrows/lake-manifest.json b/tests/lean/misc-no_nested_borrows/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-no_nested_borrows/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-no_nested_borrows/lakefile.lean b/tests/lean/misc-no_nested_borrows/lakefile.lean deleted file mode 100644 index 58619110..00000000 --- a/tests/lean/misc-no_nested_borrows/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «no_nested_borrows» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «NoNestedBorrows» {} diff --git a/tests/lean/misc-no_nested_borrows/lean-toolchain b/tests/lean/misc-no_nested_borrows/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-no_nested_borrows/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/misc-paper/Base/Primitives.lean b/tests/lean/misc-paper/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-paper/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-paper/Paper.lean b/tests/lean/misc-paper/Paper.lean deleted file mode 100644 index 0b16fb8e..00000000 --- a/tests/lean/misc-paper/Paper.lean +++ /dev/null @@ -1,123 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [paper] -import Base.Primitives - -/- [paper::ref_incr] -/ -def ref_incr_fwd_back (x : I32) : Result I32 := - x + (I32.ofInt 1 (by intlit)) - -/- [paper::test_incr] -/ -def test_incr_fwd : Result Unit := - do - let x ← ref_incr_fwd_back (I32.ofInt 0 (by intlit)) - if h: not (x = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [paper::test_incr] -/ -#assert (test_incr_fwd == .ret ()) - -/- [paper::choose] -/ -def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := - if h: b - then Result.ret x - else Result.ret y - -/- [paper::choose] -/ -def choose_back - (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := - if h: b - then Result.ret (ret0, y) - else Result.ret (x, ret0) - -/- [paper::test_choose] -/ -def test_choose_fwd : Result Unit := - do - let z ← - choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) - let z0 ← z + (I32.ofInt 1 (by intlit)) - if h: not (z0 = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - do - let (x, y) ← - choose_back I32 true (I32.ofInt 0 (by intlit)) - (I32.ofInt 0 (by intlit)) z0 - if h: not (x = (I32.ofInt 1 (by intlit))) - then Result.fail Error.panic - else - if h: not (y = (I32.ofInt 0 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [paper::test_choose] -/ -#assert (test_choose_fwd == .ret ()) - -/- [paper::List] -/ -inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T -| Nil : list_t T - -/- [paper::list_nth_mut] -/ -def list_nth_mut_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret x - else do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic - -/- [paper::list_nth_mut] -/ -def list_nth_mut_back - (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: l with - | list_t.Cons x tl => - if h: i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - let tl0 ← list_nth_mut_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic - -/- [paper::sum] -/ -def sum_fwd (l : list_t I32) : Result I32 := - match h: l with - | list_t.Cons x tl => do - let i ← sum_fwd tl - x + i - | list_t.Nil => Result.ret (I32.ofInt 0 (by intlit)) - -/- [paper::test_nth] -/ -def test_nth_fwd : Result Unit := - do - let l := list_t.Nil - let l0 := list_t.Cons (I32.ofInt 3 (by intlit)) l - let l1 := list_t.Cons (I32.ofInt 2 (by intlit)) l0 - let x ← - list_nth_mut_fwd I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) - (U32.ofInt 2 (by intlit)) - let x0 ← x + (I32.ofInt 1 (by intlit)) - let l2 ← - list_nth_mut_back I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) - (U32.ofInt 2 (by intlit)) x0 - let i ← sum_fwd l2 - if h: not (i = (I32.ofInt 7 (by intlit))) - then Result.fail Error.panic - else Result.ret () - -/- Unit test for [paper::test_nth] -/ -#assert (test_nth_fwd == .ret ()) - -/- [paper::call_choose] -/ -def call_choose_fwd (p : (U32 × U32)) : Result U32 := - do - let (px, py) := p - let pz ← choose_fwd U32 true px py - let pz0 ← pz + (U32.ofInt 1 (by intlit)) - let (px0, _) ← choose_back U32 true px py pz0 - Result.ret px0 - diff --git a/tests/lean/misc-paper/lake-manifest.json b/tests/lean/misc-paper/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-paper/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-paper/lakefile.lean b/tests/lean/misc-paper/lakefile.lean deleted file mode 100644 index 75d7208e..00000000 --- a/tests/lean/misc-paper/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «paper» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «Paper» {} diff --git a/tests/lean/misc-paper/lean-toolchain b/tests/lean/misc-paper/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-paper/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 diff --git a/tests/lean/misc-polonius_list/Base/Primitives.lean b/tests/lean/misc-polonius_list/Base/Primitives.lean deleted file mode 100644 index 4a66a453..00000000 --- a/tests/lean/misc-polonius_list/Base/Primitives.lean +++ /dev/null @@ -1,583 +0,0 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd - --------------------- --- ASSERT COMMAND -- --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo "Assertion failed for: " - logInfo _stx[1] - logError "Expression reduced to false" - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -/- HELPERS -/ - -def ret? {α: Type} (r: Result α): Bool := - match r with - | Result.ret _ => true - | Result.fail _ => false - -def massert (b:Bool) : Result Unit := - if b then .ret () else fail assertionFailure - -def eval_global {α: Type} (x: Result α) (_: ret? x): α := - match x with - | Result.fail _ => by contradiction - | Result.ret x => x - -/- DO-DSL SUPPORT -/ - -def bind (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | .ret x => .ret ⟨x, rfl⟩ - | .fail e => .fail e - -macro "let" e:term " ⟵ " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- TODO: any way to factorize both definitions? -macro "let" e:term " <-- " f:term : doElem => - `(doElem| let ⟨$e, h⟩ ← Result.attach $f) - --- We call the hypothesis `h`, in effect making it unavailable to the user --- (because too much shadowing). But in practice, once can use the French single --- quote notation (input with f< and f>), where `‹ h ›` finds a suitable --- hypothesis in the context, this is equivalent to `have x: h := by assumption in x` -#eval do - let y <-- .ret (0: Nat) - let _: y = 0 := by cases ‹ ret 0 = ret y › ; decide - let r: { x: Nat // x = 0 } := ⟨ y, by assumption ⟩ - .ret r - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.min - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => I32.max - | .Usize => U32.max - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry -theorem Scalar.cMax_bound ty : Scalar.min ty <= Scalar.cMin ty := by sorry - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty <= val - hmax : val <= Scalar.max ty - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty <= x && x <= Scalar.cMax ty -> - (decide (Scalar.min ty ≤ x) && decide (x ≤ Scalar.max ty)) = true - := by sorry - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty <= x) (hmax : x <= Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty <= x && x <= Scalar.max ty) : Scalar ty := - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - Scalar.ofIntCore x hmin hmax - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - -- TODO: write this with only one if then else - if hmin_cons: Scalar.cMin ty <= x || Scalar.min ty <= x then - if hmax_cons: x <= Scalar.cMax ty || x <= Scalar.max ty then - let hmin: Scalar.min ty <= x := by sorry - let hmax: x <= Scalar.max ty := by sorry - return Scalar.ofIntCore x hmin hmax - else fail integerOverflow - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Checking that the % operation in Lean computes the same as the remainder operation in Rust -#assert 1 % 2 = (1:Int) -#assert (-1) % 2 = -1 -#assert 1 % (-2) = 1 -#assert (-1) % (-2) = -1 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- Tactic to prove that integers are in bounds -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l <= Usize.max } - -def vec_new (α : Type u): Vec α := ⟨ [], by sorry ⟩ - -def vec_len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by sorry) l - -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - if h : List.length v.val <= U32.max || List.length v.val <= Usize.max then - return ⟨ List.concat v.val x, by sorry ⟩ - else - fail maximumSizeExceeded - -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - let h: i < List.length v.val := by sorry - .ret (List.get v.val ⟨i.val, h⟩) - else - .fail arrayOutOfBounds - -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - let i : Nat := - match i.val with - | .ofNat n => n - | .negSucc n => by sorry -- TODO: we can't get here - let isLt: i < USize.size := by sorry - let i : Fin USize.size := { val := i, isLt := isLt } - .ret ⟨ List.set v.val i.val x, by - have h: List.length v.val <= Usize.max := v.property - rewrite [ List.length_set v.val i.val x ] - assumption - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := - x - -def mem_replace_back (a : Type) (_ : a) (y : a) : a := - y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas diff --git a/tests/lean/misc-polonius_list/PoloniusList.lean b/tests/lean/misc-polonius_list/PoloniusList.lean deleted file mode 100644 index 79696996..00000000 --- a/tests/lean/misc-polonius_list/PoloniusList.lean +++ /dev/null @@ -1,31 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [polonius_list] -import Base.Primitives - -/- [polonius_list::List] -/ -inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T -| Nil : list_t T - -/- [polonius_list::get_list_at_x] -/ -def get_list_at_x_fwd (ls : list_t U32) (x : U32) : Result (list_t U32) := - match h: ls with - | list_t.Cons hd tl => - if h: hd = x - then Result.ret (list_t.Cons hd tl) - else get_list_at_x_fwd tl x - | list_t.Nil => Result.ret list_t.Nil - -/- [polonius_list::get_list_at_x] -/ -def get_list_at_x_back - (ls : list_t U32) (x : U32) (ret0 : list_t U32) : Result (list_t U32) := - match h: ls with - | list_t.Cons hd tl => - if h: hd = x - then Result.ret ret0 - else - do - let tl0 ← get_list_at_x_back tl x ret0 - Result.ret (list_t.Cons hd tl0) - | list_t.Nil => Result.ret ret0 - diff --git a/tests/lean/misc-polonius_list/lake-manifest.json b/tests/lean/misc-polonius_list/lake-manifest.json deleted file mode 100644 index 57b071ca..00000000 --- a/tests/lean/misc-polonius_list/lake-manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{"version": 4, - "packagesDir": "./lake-packages", - "packages": - [{"git": - {"url": "https://github.com/leanprover-community/mathlib4.git", - "subDir?": null, - "rev": "4037792ead804d7bfa8868e2c4684d4223c15ece", - "name": "mathlib", - "inputRev?": null}}, - {"git": - {"url": "https://github.com/gebner/quote4", - "subDir?": null, - "rev": "2412c4fdf4a8b689f4467618e5e7b371ae5014aa", - "name": "Qq", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/JLimperg/aesop", - "subDir?": null, - "rev": "7fe9ecd9339b0e1796e89d243b776849c305c690", - "name": "aesop", - "inputRev?": "master"}}, - {"git": - {"url": "https://github.com/leanprover/std4", - "subDir?": null, - "rev": "24897887905b3a1254b244369f5dd2cf6174b0ee", - "name": "std", - "inputRev?": "main"}}]} diff --git a/tests/lean/misc-polonius_list/lakefile.lean b/tests/lean/misc-polonius_list/lakefile.lean deleted file mode 100644 index e89d4259..00000000 --- a/tests/lean/misc-polonius_list/lakefile.lean +++ /dev/null @@ -1,12 +0,0 @@ -import Lake -open Lake DSL - -require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" - -package «polonius_list» {} - -lean_lib «Base» {} - -@[default_target] -lean_lib «PoloniusList» {} diff --git a/tests/lean/misc-polonius_list/lean-toolchain b/tests/lean/misc-polonius_list/lean-toolchain deleted file mode 100644 index bbf57f10..00000000 --- a/tests/lean/misc-polonius_list/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:nightly-2023-01-21 -- cgit v1.2.3 From bd873499f9a8d517cc948c6336a5c6ce856d846d Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 17:30:35 +0200 Subject: Fix some issues with the extraction to Lean --- backends/lean/Base/Diverge/Elab.lean | 63 +++++++++++----- compiler/Extract.ml | 134 ++++++++++++++++++++++------------- 2 files changed, 133 insertions(+), 64 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 41209021..4b08fe44 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -255,10 +255,11 @@ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) preDefs.mapM fun preDef => do -- Replace the recursive calls let body ← mapVisit visit_e preDef.value + trace[Diverge.def.genBody] "Body after replacement of the recursive calls: {body}" -- Currify the function by grouping the arguments into a dependent tuple -- (over which we match to retrieve the individual arguments). - lambdaLetTelescope body fun args body => do + lambdaTelescope body fun args body => do let body ← mkSigmasMatch args.toList body 0 -- Add the declaration @@ -376,15 +377,18 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do | .sort _ => throwError "Unreachable" | .lam .. => throwError "Unimplemented" | .forallE .. => throwError "Unreachable" -- Shouldn't get there - | .letE dName dTy dValue body _nonDep => do - -- Introduce a local declaration for the let-binding - withLetDecl dName dTy dValue fun decl => do + | .letE .. => do + -- Telescope all the let-bindings (remark: this also telescopes the lambdas) + lambdaLetTelescope e fun xs body => do + -- Note that we don't visit the bound values: there shouldn't be + -- recursive calls, lambda expressions, etc. inside + -- Prove that the body is valid let isValid ← proveExprIsValid k_var kk_var body - -- Add the let-binding around. + -- Add the let-bindings around. -- Rem.: the let-binding should be *inside* the `is_valid_p`, not outside, -- but because it reduces in the end it doesn't matter. More precisely: -- `P (let x := v in y)` and `let x := v in P y` reduce to the same expression. - mkLetFVars #[decl] isValid + mkLambdaFVars xs isValid (usedLetOnly := false) | .mdata _ b => proveExprIsValid k_var kk_var b | .proj _ _ _ => -- The projection shouldn't use the continuation @@ -410,7 +414,7 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do if isIte then proveExprIsValid k_var kk_var br else do -- There is a lambda -- TODO: how do we remove exacly *one* lambda? - lambdaLetTelescope br fun xs br => do + lambdaTelescope br fun xs br => do let x := xs.get! 0 let xs := xs.extract 1 xs.size let br ← mkLambdaFVars xs br @@ -518,7 +522,7 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do trace[Diverge.def.valid] "bind: xValid:\n{xValid}:\n{← inferType xValid}" let yValid ← do -- This is a lambda expression -- TODO: how do we remove exacly *one* lambda? - lambdaLetTelescope y fun xs y => do + lambdaTelescope y fun xs y => do let x := xs.get! 0 let xs := xs.extract 1 xs.size let y ← mkLambdaFVars xs y @@ -555,7 +559,7 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp -- binders might come from the match, and some of the binders might come -- from the fact that the expression in the match is a lambda expression: -- we use the branchesNumParams field for this reason - lambdaLetTelescope br fun xs br => do + lambdaTelescope br fun xs br => do let numParams := me.branchesNumParams.get! idx let xs_beg := xs.extract 0 numParams let xs_end := xs.extract numParams xs.size @@ -622,7 +626,7 @@ partial def proveSingleBodyIsValid let env ← getEnv let body := (env.constants.find! name).value! trace[Diverge.def.valid] "body: {body}" - lambdaLetTelescope body fun xs body => do + lambdaTelescope body fun xs body => do assert! xs.size = 2 let kk_var := xs.get! 0 let x_var := xs.get! 1 @@ -695,8 +699,10 @@ def proveMutRecIsValid let bodiesValid ← bodies.mapIdxM fun idx body => do let preDef := preDefs.get! idx + trace[Diverge.def.valid] "## Proving that the body {body} is valid" proveSingleBodyIsValid k_var preDef body -- Then prove that the mut rec body is valid + trace[Diverge.def.valid] "## Proving that the 'Funs' body is valid" let isValid ← proveFunsBodyIsValid inOutTys bodyFuns k_var bodiesValid -- Save the theorem let thmTy ← mkAppM ``FixI.is_valid #[mutRecBodyConst] @@ -724,7 +730,7 @@ def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : TermElabM (Array Name) := do let grSize := preDefs.size let defs ← preDefs.mapIdxM fun idx preDef => do - lambdaLetTelescope preDef.value fun xs _ => do + lambdaTelescope preDef.value fun xs _ => do -- Create the index let idx ← mkFinVal grSize idx.val -- Group the inputs into a dependent tuple @@ -755,7 +761,7 @@ partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinitio let preDef := preDefs.get! i let defName := decls.get! i -- Retrieve the arguments - lambdaLetTelescope preDef.value fun xs body => do + lambdaTelescope preDef.value fun xs body => do trace[Diverge.def.unfold] "proveUnfoldingThms: xs: {xs}" trace[Diverge.def.unfold] "proveUnfoldingThms: body: {body}" -- The theorem statement @@ -799,7 +805,7 @@ partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinitio def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do let msg := toMessageData <| preDefs.map fun pd => (pd.declName, pd.levelParams, pd.type, pd.value) - trace[Diverge.def] ("divRecursion: defs: " ++ msg) + trace[Diverge.def] ("divRecursion: defs:\n" ++ msg) -- TODO: what is this? for preDef in preDefs do @@ -880,8 +886,11 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- Replace the recursive calls in all the function bodies by calls to the -- continuation `k` and and generate for those bodies declarations + trace[Diverge.def] "# Generating the unary bodies" let bodies ← mkDeclareUnaryBodies grLvlParams kk_var preDefs + trace[Diverge.def] "Unary bodies (after decl): {bodies}" -- Generate the mutually recursive body + trace[Diverge.def] "# Generating the mut rec body" let (bodyFuns, mutRecBody) ← mkDeclareMutRecBody grName grLvlParams kk_var i_var in_ty out_ty inOutTys.toList bodies trace[Diverge.def] "mut rec body (after decl): {mutRecBody}" @@ -889,15 +898,18 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- our fixed-point let k_var_ty ← mkAppM ``FixI.k_ty #[i_var_ty, in_ty, out_ty] withLocalDeclD (mkAnonymous "k" 3) k_var_ty fun k_var => do + trace[Diverge.def] "# Proving that the mut rec body is valid" let isValidThm ← proveMutRecIsValid grName grLvlParams inOutTysExpr bodyFuns mutRecBody k_var preDefs bodies -- Generate the final definitions + trace[Diverge.def] "# Generating the final definitions" let decls ← mkDeclareFixDefs mutRecBody preDefs -- Prove the unfolding theorems + trace[Diverge.def] "# Proving the unfolding theorems" proveUnfoldingThms isValidThm preDefs decls - -- Process the definitions - TODO + -- Generating code -- TODO addAndCompilePartialRec preDefs -- The following function is copy&pasted from Lean.Elab.PreDefinition.Main @@ -1064,13 +1076,32 @@ namespace Tests -- Testing dependent branching and let-bindings -- TODO: why the linter warning? - divergent def is_non_zero (i : Int) : Result Bool := + divergent def isNonZero (i : Int) : Result Bool := if _h:i = 0 then return false else let b := true return b - #check is_non_zero.unfold + #check isNonZero.unfold + + -- Testing let-bindings + divergent def iInBounds {a : Type} (ls : List a) (i : Int) : Result Bool := + let i0 := ls.length + if i < i0 + then Result.ret True + else Result.ret False + + #check iInBounds.unfold + + divergent def isCons + {a : Type} (ls : List a) : Result Bool := + let ls1 := ls + match ls1 with + | [] => Result.ret False + | x :: tl => Result.ret True + + #check isCons.unfold + end Tests end Diverge diff --git a/compiler/Extract.ml b/compiler/Extract.ml index a54a2299..b18d4743 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -618,9 +618,12 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) let struct_constructor (basename : name) : string = let tname = type_name basename in let prefix = - match !backend with FStar -> "Mk" | Lean | Coq | HOL4 -> "mk" + match !backend with FStar -> "Mk" | Coq | HOL4 -> "mk" | Lean -> "" in - prefix ^ tname + let suffix = + match !backend with FStar | Coq | HOL4 -> "" | Lean -> ".mk" + in + prefix ^ tname ^ suffix in let get_fun_name = get_name in let fun_name_to_snake_case (fname : fun_name) : string = @@ -1326,7 +1329,8 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt (unit_name ())) else if !backend = Lean && fields = [] then () (* If the definition is recursive, we may need to extract it as an inductive - (instead of a record) *) + (instead of a record). We start with the "normal" case: we extract it + as a record. *) else if (not is_rec) || (!backend <> Coq && !backend <> Lean) then ( if !backend <> Lean then F.pp_print_space fmt (); (* If Coq: print the constructor name *) @@ -1379,7 +1383,14 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) a group of mutually recursive types: we extract it as an inductive type *) assert (is_rec && (!backend = Coq || !backend = Lean)); let with_opaque_pre = false in - let cons_name = ctx_get_struct with_opaque_pre (AdtId def.def_id) ctx in + (* Small trick: in Lean we use namespaces, meaning we don't need to prefix + the constructor name with the name of the type at definition site, + i.e., instead of generating `inductive Foo := | MkFoo ...` like in Coq + we generate `inductive Foo := | mk ... *) + let cons_name = + if !backend = Lean then "mk" + else ctx_get_struct with_opaque_pre (AdtId def.def_id) ctx + in let def_name = ctx_get_local_type with_opaque_pre def.def_id ctx in extract_type_decl_variant ctx fmt type_decl_group def_name type_params cons_name fields) @@ -1950,14 +1961,17 @@ let extract_global_decl_register_names (ctx : extraction_ctx) Note that patterns can introduce new variables: we thus return an extraction context updated with new bindings. + [is_single_pat]: are we extracting a single pattern (a pattern for a let-binding + or a lambda). + TODO: we don't need something very generic anymore (some definitions used to be polymorphic). *) let extract_adt_g_value (extract_value : extraction_ctx -> bool -> 'v -> extraction_ctx) - (fmt : F.formatter) (ctx : extraction_ctx) (inside : bool) - (variant_id : VariantId.id option) (field_values : 'v list) (ty : ty) : - extraction_ctx = + (fmt : F.formatter) (ctx : extraction_ctx) (is_single_pat : bool) + (inside : bool) (variant_id : VariantId.id option) (field_values : 'v list) + (ty : ty) : extraction_ctx = match ty with | Adt (Tuple, type_args) -> (* Tuple *) @@ -1982,36 +1996,57 @@ let extract_adt_g_value ctx) | Adt (adt_id, _) -> (* "Regular" ADT *) - (* We print something of the form: [Cons field0 ... fieldn]. - * We could update the code to print something of the form: - * [{ field0=...; ...; fieldn=...; }] in case of structures. - *) - let cons = - (* The ADT shouldn't be opaque *) - let with_opaque_pre = false in - match variant_id with - | Some vid -> ( - (* In the case of Lean, we might have to add the type name as a prefix *) - match (!backend, adt_id) with - | Lean, Assumed _ -> - ctx_get_type with_opaque_pre adt_id ctx - ^ "." - ^ ctx_get_variant adt_id vid ctx - | _ -> ctx_get_variant adt_id vid ctx) - | None -> ctx_get_struct with_opaque_pre adt_id ctx - in - let use_parentheses = inside && field_values <> [] in - if use_parentheses then F.pp_print_string fmt "("; - F.pp_print_string fmt cons; - let ctx = - Collections.List.fold_left - (fun ctx v -> - F.pp_print_space fmt (); - extract_value ctx true v) - ctx field_values - in - if use_parentheses then F.pp_print_string fmt ")"; - ctx + + (* If we are generating a pattern for a let-binding and we target Lean, + the syntax is: `let ⟨ x0, ..., xn ⟩ := ...`. + + Otherwise, it is: `let Cons x0 ... xn = ...` + *) + if is_single_pat && !Config.backend = Lean then ( + F.pp_print_string fmt "⟨"; + F.pp_print_space fmt (); + let ctx = + Collections.List.fold_left_link + (fun _ -> + F.pp_print_string fmt ","; + F.pp_print_space fmt ()) + (fun ctx v -> extract_value ctx true v) + ctx field_values + in + F.pp_print_space fmt (); + F.pp_print_string fmt "⟩"; + ctx) + else + (* We print something of the form: [Cons field0 ... fieldn]. + * We could update the code to print something of the form: + * [{ field0=...; ...; fieldn=...; }] in case of structures. + *) + let cons = + (* The ADT shouldn't be opaque *) + let with_opaque_pre = false in + match variant_id with + | Some vid -> ( + (* In the case of Lean, we might have to add the type name as a prefix *) + match (!backend, adt_id) with + | Lean, Assumed _ -> + ctx_get_type with_opaque_pre adt_id ctx + ^ "." + ^ ctx_get_variant adt_id vid ctx + | _ -> ctx_get_variant adt_id vid ctx) + | None -> ctx_get_struct with_opaque_pre adt_id ctx + in + let use_parentheses = inside && field_values <> [] in + if use_parentheses then F.pp_print_string fmt "("; + F.pp_print_string fmt cons; + let ctx = + Collections.List.fold_left + (fun ctx v -> + F.pp_print_space fmt (); + extract_value ctx true v) + ctx field_values + in + if use_parentheses then F.pp_print_string fmt ")"; + ctx | _ -> raise (Failure "Inconsistent typed value") (* Extract globals in the same way as variables *) @@ -2026,7 +2061,7 @@ let extract_global (ctx : extraction_ctx) (fmt : F.formatter) updated with new bindings. *) let rec extract_typed_pattern (ctx : extraction_ctx) (fmt : F.formatter) - (inside : bool) (v : typed_pattern) : extraction_ctx = + (is_let : bool) (inside : bool) (v : typed_pattern) : extraction_ctx = match v.value with | PatConstant cv -> ctx.fmt.extract_primitive_value fmt inside cv; @@ -2042,8 +2077,10 @@ let rec extract_typed_pattern (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_string fmt "_"; ctx | PatAdt av -> - let extract_value ctx inside v = extract_typed_pattern ctx fmt inside v in - extract_adt_g_value extract_value fmt ctx inside av.variant_id + let extract_value ctx inside v = + extract_typed_pattern ctx fmt is_let inside v + in + extract_adt_g_value extract_value fmt ctx is_let inside av.variant_id av.field_values v.ty (** [inside]: controls the introduction of parentheses. See [extract_ty] @@ -2173,12 +2210,13 @@ and extract_adt_cons (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) (adt_cons : adt_cons_id) (type_args : ty list) (args : texpression list) : unit = let e_ty = Adt (adt_cons.adt_id, type_args) in + let is_single_pat = false in let _ = extract_adt_g_value (fun ctx inside e -> extract_texpression ctx fmt inside e; ctx) - fmt ctx inside adt_cons.variant_id args e_ty + fmt ctx is_single_pat inside adt_cons.variant_id args e_ty in () @@ -2226,7 +2264,7 @@ and extract_Abs (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) List.fold_left (fun ctx x -> F.pp_print_space fmt (); - extract_typed_pattern ctx fmt true x) + extract_typed_pattern ctx fmt true true x) ctx xl in F.pp_print_space fmt (); @@ -2295,7 +2333,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) * TODO: cleanup * *) if monadic && (!backend = Coq || !backend = HOL4) then ( - let ctx = extract_typed_pattern ctx fmt true lv in + let ctx = extract_typed_pattern ctx fmt true true lv in F.pp_print_space fmt (); let arrow = match !backend with @@ -2321,7 +2359,7 @@ and extract_lets (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) else ( F.pp_print_string fmt "let"; F.pp_print_space fmt ()); - let ctx = extract_typed_pattern ctx fmt true lv in + let ctx = extract_typed_pattern ctx fmt true true lv in F.pp_print_space fmt (); let eq = match !backend with @@ -2468,7 +2506,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) match !backend with | FStar -> "begin match" | Coq -> "match" - | Lean -> "match h:" + | Lean -> if ctx.use_dep_ite then "match h:" else "match" | HOL4 -> (* We're being extra safe in the case of HOL4 *) "(case" @@ -2495,7 +2533,7 @@ and extract_Switch (ctx : extraction_ctx) (fmt : F.formatter) (_inside : bool) (* Print the pattern *) F.pp_print_string fmt "|"; F.pp_print_space fmt (); - let ctx = extract_typed_pattern ctx fmt false br.pat in + let ctx = extract_typed_pattern ctx fmt false false br.pat in F.pp_print_space fmt (); let arrow = match !backend with FStar -> "->" | Coq | Lean | HOL4 -> "=>" @@ -2687,7 +2725,7 @@ let extract_fun_parameters (space : bool ref) (ctx : extraction_ctx) (* Open a box for the input parameter *) F.pp_open_hovbox fmt 0; F.pp_print_string fmt "("; - let ctx = extract_typed_pattern ctx fmt false lv in + let ctx = extract_typed_pattern ctx fmt true false lv in F.pp_print_space fmt (); F.pp_print_string fmt ":"; F.pp_print_space fmt (); @@ -3032,7 +3070,7 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) List.fold_left (fun ctx (lv : typed_pattern) -> F.pp_print_space fmt (); - let ctx = extract_typed_pattern ctx fmt false lv in + let ctx = extract_typed_pattern ctx fmt true false lv in ctx) ctx inputs_lvs in -- cgit v1.2.3 From 74b3ce71b0e3794853aa1413afaaaa05c8cc5a84 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 18:08:40 +0200 Subject: Fix minor issues --- compiler/Extract.ml | 14 +++-- compiler/Translate.ml | 166 ++++++++++++++++++++++++++++++++++---------------- 2 files changed, 125 insertions(+), 55 deletions(-) diff --git a/compiler/Extract.ml b/compiler/Extract.ml index b18d4743..7d00dd73 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -1010,6 +1010,11 @@ let end_type_decl_group (fmt : F.formatter) (is_rec : bool) let unit_name () = match !backend with Lean -> "Unit" | Coq | FStar | HOL4 -> "unit" +(** Small helper *) +let extract_arrow (fmt : F.formatter) () : unit = + if !Config.backend = Lean then F.pp_print_string fmt "→" + else F.pp_print_string fmt "->" + (** [inside] constrols whether we should add parentheses or not around type applications (if [true] we add parentheses). @@ -1103,7 +1108,7 @@ let rec extract_ty (ctx : extraction_ctx) (fmt : F.formatter) if inside then F.pp_print_string fmt "("; extract_rec false arg_ty; F.pp_print_space fmt (); - F.pp_print_string fmt "->"; + extract_arrow fmt (); F.pp_print_space fmt (); extract_rec false ret_ty; if inside then F.pp_print_string fmt ")" @@ -1191,7 +1196,7 @@ let extract_type_decl_variant (ctx : extraction_ctx) (fmt : F.formatter) (* Print the arrow [->] *) if !backend <> HOL4 then ( F.pp_print_space fmt (); - F.pp_print_string fmt "->"); + extract_arrow fmt ()); (* Close the field box *) F.pp_close_box fmt (); (* Return *) @@ -2268,7 +2273,8 @@ and extract_Abs (ctx : extraction_ctx) (fmt : F.formatter) (inside : bool) ctx xl in F.pp_print_space fmt (); - F.pp_print_string fmt "->"; + if !backend = Lean then F.pp_print_string fmt "=>" + else F.pp_print_string fmt "->"; F.pp_print_space fmt (); (* Print the body *) extract_texpression ctx fmt false e; @@ -2750,7 +2756,7 @@ let extract_fun_input_parameters_types (ctx : extraction_ctx) let inside = false in extract_ty ctx fmt TypeDeclId.Set.empty inside ty; F.pp_print_space fmt (); - F.pp_print_string fmt "->"; + extract_arrow fmt (); F.pp_print_space fmt () in List.iter extract_param def.signature.inputs diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 39b169c9..5827b4a8 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -783,11 +783,20 @@ let extract_definitions (fmt : Format.formatter) (config : gen_config) if wrap_in_sig then Format.pp_close_box fmt () -let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) - (rust_module_name : string) (module_name : string) (custom_msg : string) - (custom_imports : string list) (custom_includes : string list) : unit = +type extract_file_info = { + filename : string; + crate_name : string; + rust_module_name : string; + module_name : string; + custom_msg : string; + custom_imports : string list; + custom_includes : string list; +} + +let extract_file (config : gen_config) (ctx : gen_ctx) (fi : extract_file_info) + : unit = (* Open the file and create the formatter *) - let out = open_out filename in + let out = open_out fi.filename in let fmt = Format.formatter_of_out_channel out in (* Print the headers. @@ -801,19 +810,22 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) (match !Config.backend with | Lean -> Printf.fprintf out "-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS\n"; - Printf.fprintf out "-- [%s]%s\n" rust_module_name custom_msg + Printf.fprintf out "-- [%s]%s\n" fi.rust_module_name fi.custom_msg | Coq | FStar | HOL4 -> Printf.fprintf out "(** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *)\n"; - Printf.fprintf out "(** [%s]%s *)\n" rust_module_name custom_msg); + Printf.fprintf out "(** [%s]%s *)\n" fi.rust_module_name fi.custom_msg); + (* Generate the imports *) (match !Config.backend with | FStar -> - Printf.fprintf out "module %s\n" module_name; + Printf.fprintf out "module %s\n" fi.module_name; Printf.fprintf out "open Primitives\n"; (* Add the custom imports *) - List.iter (fun m -> Printf.fprintf out "open %s\n" m) custom_imports; + List.iter (fun m -> Printf.fprintf out "open %s\n" m) fi.custom_imports; (* Add the custom includes *) - List.iter (fun m -> Printf.fprintf out "include %s\n" m) custom_includes; + List.iter + (fun m -> Printf.fprintf out "include %s\n" m) + fi.custom_includes; (* Z3 options - note that we use fuel 1 because it its useful for the decrease clauses *) Printf.fprintf out "\n#set-options \"--z3rlimit 50 --fuel 1 --ifuel 1\"\n" | Coq -> @@ -825,26 +837,28 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) (* Add the custom imports *) List.iter (fun m -> Printf.fprintf out "Require Import %s.\n" m) - custom_imports; + fi.custom_imports; (* Add the custom includes *) List.iter (fun m -> Printf.fprintf out "Require Export %s.\n" m; Printf.fprintf out "Import %s.\n" m) - custom_includes; - Printf.fprintf out "Module %s.\n" module_name + fi.custom_includes; + Printf.fprintf out "Module %s.\n" fi.module_name | Lean -> Printf.fprintf out "import Base\n"; (* Add the custom imports *) - List.iter (fun m -> Printf.fprintf out "import %s\n" m) custom_imports; + List.iter (fun m -> Printf.fprintf out "import %s\n" m) fi.custom_imports; (* Add the custom includes *) - List.iter (fun m -> Printf.fprintf out "import %s\n" m) custom_includes; + List.iter (fun m -> Printf.fprintf out "import %s\n" m) fi.custom_includes; (* Always open the Primitives namespace *) - Printf.fprintf out "open Primitives\n" + Printf.fprintf out "open Primitives\n\n"; + (* Open the namespace *) + Printf.fprintf out "namespace %s\n" fi.crate_name | HOL4 -> Printf.fprintf out "open primitivesLib divDefLib\n"; (* Add the custom imports and includes *) - let imports = custom_imports @ custom_includes in + let imports = fi.custom_imports @ fi.custom_includes in (* The imports are a list of module names: we need to add a "Theory" suffix *) let imports = List.map (fun s -> s ^ "Theory") imports in if imports <> [] then @@ -852,7 +866,7 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) Printf.fprintf out "open %s\n\n" imports else Printf.fprintf out "\n"; (* Initialize the theory *) - Printf.fprintf out "val _ = new_theory \"%s\"\n\n" module_name); + Printf.fprintf out "val _ = new_theory \"%s\"\n\n" fi.module_name); (* From now onwards, we use the formatter *) (* Set the margin *) Format.pp_set_margin fmt 80; @@ -869,12 +883,13 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (filename : string) (* Close the module *) (match !Config.backend with - | FStar | Lean -> () + | FStar -> () + | Lean -> Printf.fprintf out "end %s\n" fi.crate_name | HOL4 -> Printf.fprintf out "val _ = export_theory ()\n" - | Coq -> Printf.fprintf out "End %s .\n" module_name); + | Coq -> Printf.fprintf out "End %s .\n" fi.module_name); (* Some logging *) - log#linfo (lazy ("Generated: " ^ filename)); + log#linfo (lazy ("Generated: " ^ fi.filename)); (* Flush and close the file *) close_out out @@ -971,7 +986,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : (* Open the output file *) (* First compute the filename by replacing the extension and converting the * case (rust module names are snake case) *) - let module_name, extract_filebasename = + let crate_name, extract_filebasename = match Filename.chop_suffix_opt ~suffix:".llbc" filename with | None -> (* Note that we already checked the suffix upon opening the file *) @@ -980,14 +995,14 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : (* Retrieve the file basename *) let basename = Filename.basename filename in (* Convert the case *) - let module_name = StringUtils.to_camel_case basename in - let module_name = + let crate_name = StringUtils.to_camel_case basename in + let crate_name = if !Config.backend = HOL4 then - StringUtils.lowercase_first_letter module_name - else module_name + StringUtils.lowercase_first_letter crate_name + else crate_name in (* Concatenate *) - (module_name, Filename.concat dest_dir module_name) + (crate_name, Filename.concat dest_dir crate_name) in (* Put the translated definitions in maps *) @@ -1022,10 +1037,10 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : create more directories *) if !Config.backend = Lean then ( let ( ^^ ) = Filename.concat in - if !Config.split_files then mkdir_if (dest_dir ^^ module_name); + if !Config.split_files then mkdir_if (dest_dir ^^ crate_name); if needs_clauses_module then ( assert !Config.split_files; - mkdir_if (dest_dir ^^ module_name ^^ "Clauses"))); + mkdir_if (dest_dir ^^ crate_name ^^ "Clauses"))); (* Copy the "Primitives" file, if necessary *) let _ = @@ -1129,7 +1144,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let types_filename = extract_filebasename ^ file_delimiter ^ "Types" ^ types_filename_ext in - let types_module = module_name ^ module_delimiter ^ "Types" in + let types_module = crate_name ^ module_delimiter ^ "Types" in let types_config = { base_gen_config with @@ -1139,8 +1154,18 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : interface = has_opaque_types; } in - extract_file types_config gen_ctx types_filename crate.A.name types_module - ": type definitions" [] []; + let file_info = + { + filename = types_filename; + crate_name; + rust_module_name = crate.A.name; + module_name = types_module; + custom_msg = ": type definitions"; + custom_imports = []; + custom_includes = []; + } + in + extract_file types_config gen_ctx file_info; (* Extract the template clauses *) (if needs_clauses_module && !Config.extract_template_decreases_clauses then @@ -1149,15 +1174,24 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : ^ "Template" ^ ext in let template_clauses_module = - module_name ^ module_delimiter ^ "Clauses" ^ module_delimiter + crate_name ^ module_delimiter ^ "Clauses" ^ module_delimiter ^ "Template" in let template_clauses_config = { base_gen_config with extract_template_decreases_clauses = true } in - extract_file template_clauses_config gen_ctx template_clauses_filename - crate.A.name template_clauses_module - ": templates for the decreases clauses" [ types_module ] []); + let file_info = + { + filename = template_clauses_filename; + crate_name; + rust_module_name = crate.A.name; + module_name = template_clauses_module; + custom_msg = ": templates for the decreases clauses"; + custom_imports = [ types_module ]; + custom_includes = []; + } + in + extract_file template_clauses_config gen_ctx file_info); (* Extract the opaque functions, if needed *) let opaque_funs_module = @@ -1165,7 +1199,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let opaque_filename = extract_filebasename ^ file_delimiter ^ "Opaque" ^ opaque_ext in - let opaque_module = module_name ^ module_delimiter ^ "Opaque" in + let opaque_module = crate_name ^ module_delimiter ^ "Opaque" in let opaque_imported_module = (* In the case of Lean, we declare an interface (a record) containing the opaque definitions, and we leave it to the user to provide an @@ -1175,7 +1209,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : TODO: do the same for the type definitions. *) if !Config.backend = Lean then - module_name ^ module_delimiter ^ "ExternalFuns" + crate_name ^ module_delimiter ^ "ExternalFuns" else opaque_module in let opaque_config = @@ -1193,15 +1227,26 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : extract_ctx = { gen_ctx.extract_ctx with use_opaque_pre = false }; } in - extract_file opaque_config gen_ctx opaque_filename crate.A.name - opaque_module ": opaque function definitions" [] [ types_module ]; + let file_info = + { + filename = opaque_filename; + crate_name; + rust_module_name = crate.A.name; + module_name = opaque_module; + custom_msg = ": opaque function definitions"; + custom_imports = []; + custom_includes = [ types_module ]; + } + in + extract_file opaque_config gen_ctx file_info; + (* Return the additional dependencies *) [ opaque_imported_module ]) else [] in (* Extract the functions *) let fun_filename = extract_filebasename ^ file_delimiter ^ "Funs" ^ ext in - let fun_module = module_name ^ module_delimiter ^ "Funs" in + let fun_module = crate_name ^ module_delimiter ^ "Funs" in let fun_config = { base_gen_config with @@ -1215,12 +1260,22 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let clauses_submodule = if !Config.backend = Lean then module_delimiter ^ "Clauses" else "" in - [ module_name ^ clauses_submodule ^ module_delimiter ^ "Clauses" ] + [ crate_name ^ clauses_submodule ^ module_delimiter ^ "Clauses" ] else [] in - extract_file fun_config gen_ctx fun_filename crate.A.name fun_module - ": function definitions" [] - ([ types_module ] @ opaque_funs_module @ clauses_module)) + let file_info = + { + filename = fun_filename; + crate_name; + rust_module_name = crate.A.name; + module_name = fun_module; + custom_msg = ": function definitions"; + custom_imports = []; + custom_includes = + [ types_module ] @ opaque_funs_module @ clauses_module; + } + in + extract_file fun_config gen_ctx file_info) else let gen_config = { @@ -1237,10 +1292,19 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : test_trans_unit_functions = !Config.test_trans_unit_functions; } in + let file_info = + { + filename = extract_filebasename ^ ext; + crate_name; + rust_module_name = crate.A.name; + module_name = crate_name; + custom_msg = ""; + custom_imports = []; + custom_includes = []; + } + in (* Add the extension for F* *) - let extract_filename = extract_filebasename ^ ext in - extract_file gen_config gen_ctx extract_filename crate.A.name module_name - "" [] []); + extract_file gen_config gen_ctx file_info); (* Generate the build file *) match !Config.backend with @@ -1258,10 +1322,10 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : * different files. *) if !Config.split_files then ( - let filename = Filename.concat dest_dir (module_name ^ ".lean") in + let filename = Filename.concat dest_dir (crate_name ^ ".lean") in let out = open_out filename in (* Write *) - Printf.fprintf out "import %s.Funs\n" module_name; + Printf.fprintf out "import %s.Funs\n" crate_name; (* Flush and close the file, log *) close_out out; log#linfo (lazy ("Generated: " ^ filename))); @@ -1280,10 +1344,10 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : Printf.fprintf out " \"https://github.com/leanprover-community/mathlib4.git\"\n\n"; - let package_name = StringUtils.to_snake_case module_name in + let package_name = StringUtils.to_snake_case crate_name in Printf.fprintf out "package «%s» {}\n\n" package_name; - Printf.fprintf out "@[default_target]\nlean_lib «%s» {}\n" module_name; + Printf.fprintf out "@[default_target]\nlean_lib «%s» {}\n" crate_name; (* No default target for now. Format would be: -- cgit v1.2.3 From b643bd00747e75d69b6066c55a1798b61277c4b6 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 18:09:36 +0200 Subject: Regenerate the Lean test files --- tests/lean/BetreeMain/ExternalFuns.lean | 9 ++ tests/lean/BetreeMain/Funs.lean | 147 ++++++++++++++++--------------- tests/lean/BetreeMain/Opaque.lean | 16 ++-- tests/lean/BetreeMain/Types.lean | 24 +++-- tests/lean/Constants.lean | 3 + tests/lean/External/ExternalFuns.lean | 9 ++ tests/lean/External/Funs.lean | 3 + tests/lean/External/Opaque.lean | 14 +-- tests/lean/External/Types.lean | 3 + tests/lean/Hashmap/Funs.lean | 31 ++++--- tests/lean/Hashmap/Types.lean | 5 +- tests/lean/HashmapMain/ExternalFuns.lean | 9 ++ tests/lean/HashmapMain/Funs.lean | 31 ++++--- tests/lean/HashmapMain/Opaque.lean | 7 +- tests/lean/HashmapMain/Types.lean | 5 +- tests/lean/Loops/Funs.lean | 83 ++++++++--------- tests/lean/Loops/Types.lean | 5 +- tests/lean/NoNestedBorrows.lean | 33 +++---- tests/lean/Paper.lean | 11 ++- tests/lean/PoloniusList.lean | 9 +- tests/lean/lake-manifest.json | 2 +- tests/lean/lakefile.lean | 8 ++ 22 files changed, 275 insertions(+), 192 deletions(-) create mode 100644 tests/lean/BetreeMain/ExternalFuns.lean create mode 100644 tests/lean/External/ExternalFuns.lean create mode 100644 tests/lean/HashmapMain/ExternalFuns.lean diff --git a/tests/lean/BetreeMain/ExternalFuns.lean b/tests/lean/BetreeMain/ExternalFuns.lean new file mode 100644 index 00000000..59beb514 --- /dev/null +++ b/tests/lean/BetreeMain/ExternalFuns.lean @@ -0,0 +1,9 @@ +import Base +import BetreeMain.Types +import BetreeMain.Opaque + +namespace BetreeMain + +def opaque_defs : OpaqueDefs := by sorry + +end BetreeMain diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index fb48b3a6..2eb7fa1f 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -5,6 +5,8 @@ import BetreeMain.Types import BetreeMain.ExternalFuns open Primitives +namespace BetreeMain + /- [betree_main::betree::load_internal_node] -/ def betree_load_internal_node_fwd (id : U64) (st : State) : @@ -75,13 +77,13 @@ def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) /- [betree_main::betree::upsert_update] -/ def betree_upsert_update_fwd (prev : Option U64) (st : betree_upsert_fun_state_t) : Result U64 := - match h: prev with + match prev with | Option.none => - match h: st with + match st with | betree_upsert_fun_state_t.Add v => Result.ret v | betree_upsert_fun_state_t.Sub i => Result.ret (U64.ofInt 0 (by intlit)) | Option.some prev0 => - match h: st with + match st with | betree_upsert_fun_state_t.Add v => do let margin ← core_num_u64_max_c - prev0 @@ -96,7 +98,7 @@ def betree_upsert_update_fwd /- [betree_main::betree::List::{1}::len] -/ divergent def betree_list_len_fwd (T : Type) (self : betree_list_t T) : Result U64 := - match h: self with + match self with | betree_list_t.Cons t tl => do let i ← betree_list_len_fwd T tl @@ -111,7 +113,7 @@ divergent def betree_list_split_at_fwd if n = (U64.ofInt 0 (by intlit)) then Result.ret (betree_list_t.Nil, self) else - match h: self with + match self with | betree_list_t.Cons hd tl => do let i ← n - (U64.ofInt 1 (by intlit)) @@ -131,7 +133,7 @@ def betree_list_push_front_fwd_back /- [betree_main::betree::List::{1}::pop_front] -/ def betree_list_pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil - match h: ls with + match ls with | betree_list_t.Cons x tl => Result.ret x | betree_list_t.Nil => Result.fail Error.panic @@ -139,20 +141,20 @@ def betree_list_pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := def betree_list_pop_front_back (T : Type) (self : betree_list_t T) : Result (betree_list_t T) := let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil - match h: ls with + match ls with | betree_list_t.Cons x tl => Result.ret tl | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::hd] -/ def betree_list_hd_fwd (T : Type) (self : betree_list_t T) : Result T := - match h: self with + match self with | betree_list_t.Cons hd l => Result.ret hd | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{2}::head_has_key] -/ def betree_list_head_has_key_fwd (T : Type) (self : betree_list_t (U64 × T)) (key : U64) : Result Bool := - match h: self with + match self with | betree_list_t.Cons hd l => let (i, _) := hd Result.ret (i = key) | betree_list_t.Nil => Result.ret false @@ -162,7 +164,7 @@ divergent def betree_list_partition_at_pivot_fwd (T : Type) (self : betree_list_t (U64 × T)) (pivot : U64) : Result ((betree_list_t (U64 × T)) × (betree_list_t (U64 × T))) := - match h: self with + match self with | betree_list_t.Cons hd tl => let (i, t) := hd if i >= pivot @@ -204,7 +206,7 @@ def betree_leaf_split_fwd betree_leaf_id := id1, betree_leaf_size := params.betree_params_split_size } - Result.ret (st1, mkbetree_internal_t self.betree_leaf_id pivot n n0) + Result.ret (st1, betree_internal_t.mk self.betree_leaf_id pivot n n0) /- [betree_main::betree::Leaf::{3}::split] -/ def betree_leaf_split_back @@ -229,7 +231,7 @@ def betree_leaf_split_back /- [betree_main::betree::Node::{5}::lookup_in_bindings] -/ divergent def betree_node_lookup_in_bindings_fwd (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (Option U64) := - match h: bindings with + match bindings with | betree_list_t.Cons hd tl => let (i, i0) := hd if i = key @@ -245,7 +247,7 @@ divergent def betree_node_lookup_first_message_for_key_fwd (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: msgs with + match msgs with | betree_list_t.Cons x next_msgs => let (i, m) := x if i >= key @@ -259,7 +261,7 @@ divergent def betree_node_lookup_first_message_for_key_back (ret0 : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: msgs with + match msgs with | betree_list_t.Cons x next_msgs => let (i, m) := x if i >= key @@ -284,7 +286,7 @@ divergent def betree_node_apply_upserts_fwd do let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs let (_, m) := msg - match h: m with + match m with | betree_message_t.Insert i => Result.fail Error.panic | betree_message_t.Delete => Result.fail Error.panic | betree_message_t.Upsert s => @@ -314,7 +316,7 @@ divergent def betree_node_apply_upserts_back do let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs let (_, m) := msg - match h: m with + match m with | betree_message_t.Insert i => Result.fail Error.panic | betree_message_t.Delete => Result.fail Error.panic | betree_message_t.Upsert s => @@ -334,27 +336,27 @@ mutual divergent def betree_node_lookup_fwd (self : betree_node_t) (key : U64) (st : State) : Result (State × (Option U64)) := - match h: self with + match self with | betree_node_t.Internal node => do - let (mkbetree_internal_t i i0 n n0) := node + let ⟨ i, i0, n, n0 ⟩ := node let (st0, msgs) ← betree_load_internal_node_fwd i st let pending ← betree_node_lookup_first_message_for_key_fwd key msgs - match h: pending with + match pending with | betree_list_t.Cons p l => let (k, msg) := p if k != key then do let (st1, opt) ← - betree_internal_lookup_in_children_fwd (mkbetree_internal_t i i0 + betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let _ ← betree_node_lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, msg) l) Result.ret (st1, opt) else - match h: msg with + match msg with | betree_message_t.Insert v => do let _ ← @@ -370,15 +372,15 @@ mutual divergent def betree_node_lookup_fwd | betree_message_t.Upsert ufs => do let (st1, v) ← - betree_internal_lookup_in_children_fwd (mkbetree_internal_t i + betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let (st2, v0) ← betree_node_apply_upserts_fwd (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let node0 ← - betree_internal_lookup_in_children_back (mkbetree_internal_t i + betree_internal_lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 - let (mkbetree_internal_t i1 _ _ _) := node0 + let ⟨ i1, _, _, _ ⟩ := node0 let pending0 ← betree_node_apply_upserts_back (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 @@ -389,7 +391,7 @@ mutual divergent def betree_node_lookup_fwd | betree_list_t.Nil => do let (st1, opt) ← - betree_internal_lookup_in_children_fwd (mkbetree_internal_t i i0 n + betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let _ ← betree_node_lookup_first_message_for_key_back key msgs @@ -404,13 +406,13 @@ mutual divergent def betree_node_lookup_fwd /- [betree_main::betree::Node::{5}::lookup] -/ divergent def betree_node_lookup_back (self : betree_node_t) (key : U64) (st : State) : Result betree_node_t := - match h: self with + match self with | betree_node_t.Internal node => do - let (mkbetree_internal_t i i0 n n0) := node + let ⟨ i, i0, n, n0 ⟩ := node let (st0, msgs) ← betree_load_internal_node_fwd i st let pending ← betree_node_lookup_first_message_for_key_fwd key msgs - match h: pending with + match pending with | betree_list_t.Cons p l => let (k, msg) := p if k != key @@ -420,44 +422,44 @@ divergent def betree_node_lookup_back betree_node_lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, msg) l) let node0 ← - betree_internal_lookup_in_children_back (mkbetree_internal_t i i0 - n n0) key st0 + betree_internal_lookup_in_children_back (betree_internal_t.mk i + i0 n n0) key st0 Result.ret (betree_node_t.Internal node0) else - match h: msg with + match msg with | betree_message_t.Insert v => do let _ ← betree_node_lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Insert v) l) - Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n + Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0)) | betree_message_t.Delete => do let _ ← betree_node_lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Delete) l) - Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n + Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0)) | betree_message_t.Upsert ufs => do let (st1, v) ← - betree_internal_lookup_in_children_fwd (mkbetree_internal_t i + betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let (st2, _) ← betree_node_apply_upserts_fwd (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let node0 ← - betree_internal_lookup_in_children_back (mkbetree_internal_t i + betree_internal_lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 - let (mkbetree_internal_t i1 i2 n1 n2) := node0 + let ⟨ i1, i2, n1, n2 ⟩ := node0 let pending0 ← betree_node_apply_upserts_back (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let msgs0 ← betree_node_lookup_first_message_for_key_back key msgs pending0 let _ ← betree_store_internal_node_fwd i1 msgs0 st2 - Result.ret (betree_node_t.Internal (mkbetree_internal_t i1 i2 n1 + Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 n2)) | betree_list_t.Nil => do @@ -465,8 +467,8 @@ divergent def betree_node_lookup_back betree_node_lookup_first_message_for_key_back key msgs betree_list_t.Nil let node0 ← - betree_internal_lookup_in_children_back (mkbetree_internal_t i i0 n - n0) key st0 + betree_internal_lookup_in_children_back (betree_internal_t.mk i i0 + n n0) key st0 Result.ret (betree_node_t.Internal node0) | betree_node_t.Leaf node => do @@ -479,7 +481,7 @@ divergent def betree_internal_lookup_in_children_fwd (self : betree_internal_t) (key : U64) (st : State) : Result (State × (Option U64)) := - let (mkbetree_internal_t _ i n n0) := self + let ⟨ _, i, n, n0 ⟩ := self if key < i then betree_node_lookup_fwd n key st else betree_node_lookup_fwd n0 key st @@ -489,16 +491,16 @@ divergent def betree_internal_lookup_in_children_back (self : betree_internal_t) (key : U64) (st : State) : Result betree_internal_t := - let (mkbetree_internal_t i i0 n n0) := self + let ⟨ i, i0, n, n0 ⟩ := self if key < i0 then do let n1 ← betree_node_lookup_back n key st - Result.ret (mkbetree_internal_t i i0 n1 n0) + Result.ret (betree_internal_t.mk i i0 n1 n0) else do let n1 ← betree_node_lookup_back n0 key st - Result.ret (mkbetree_internal_t i i0 n n1) + Result.ret (betree_internal_t.mk i i0 n n1) end @@ -507,7 +509,7 @@ divergent def betree_node_lookup_mut_in_bindings_fwd (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (betree_list_t (U64 × U64)) := - match h: bindings with + match bindings with | betree_list_t.Cons hd tl => let (i, i0) := hd if i >= key @@ -521,7 +523,7 @@ divergent def betree_node_lookup_mut_in_bindings_back (ret0 : betree_list_t (U64 × U64)) : Result (betree_list_t (U64 × U64)) := - match h: bindings with + match bindings with | betree_list_t.Cons hd tl => let (i, i0) := hd if i >= key @@ -545,7 +547,7 @@ def betree_node_apply_to_leaf_fwd_back then do let hd ← betree_list_pop_front_fwd (U64 × U64) bindings0 - match h: new_msg with + match new_msg with | betree_message_t.Insert v => do let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 @@ -565,7 +567,7 @@ def betree_node_apply_to_leaf_fwd_back betree_list_push_front_fwd_back (U64 × U64) bindings1 (key, v) betree_node_lookup_mut_in_bindings_back key bindings bindings2 else - match h: new_msg with + match new_msg with | betree_message_t.Insert v => do let bindings1 ← @@ -586,7 +588,7 @@ divergent def betree_node_apply_messages_to_leaf_fwd_back (new_msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × U64)) := - match h: new_msgs with + match new_msgs with | betree_list_t.Cons new_msg new_msgs_tl => do let (i, m) := new_msg @@ -599,7 +601,7 @@ divergent def betree_node_filter_messages_for_key_fwd_back (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: msgs with + match msgs with | betree_list_t.Cons p l => let (k, m) := p if k = key @@ -617,7 +619,7 @@ divergent def betree_node_lookup_first_message_after_key_fwd (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: msgs with + match msgs with | betree_list_t.Cons p next_msgs => let (k, m) := p if k = key @@ -631,7 +633,7 @@ divergent def betree_node_lookup_first_message_after_key_back (ret0 : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: msgs with + match msgs with | betree_list_t.Cons p next_msgs => let (k, m) := p if k = key @@ -654,7 +656,7 @@ def betree_node_apply_to_internal_fwd_back let b ← betree_list_head_has_key_fwd betree_message_t msgs0 key if b then - match h: new_msg with + match new_msg with | betree_message_t.Insert i => do let msgs1 ← betree_node_filter_messages_for_key_fwd_back key msgs0 @@ -673,7 +675,7 @@ def betree_node_apply_to_internal_fwd_back do let p ← betree_list_hd_fwd (U64 × betree_message_t) msgs0 let (_, m) := p - match h: m with + match m with | betree_message_t.Insert prev => do let v ← betree_upsert_update_fwd (Option.some prev) s @@ -715,7 +717,7 @@ divergent def betree_node_apply_messages_to_internal_fwd_back (new_msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := - match h: new_msgs with + match new_msgs with | betree_list_t.Cons new_msg new_msgs_tl => do let (i, m) := new_msg @@ -730,10 +732,10 @@ mutual divergent def betree_node_apply_messages_fwd (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : Result (State × Unit) := - match h: self with + match self with | betree_node_t.Internal node => do - let (mkbetree_internal_t i i0 n n0) := node + let ⟨ i, i0, n, n0 ⟩ := node let (st0, content) ← betree_load_internal_node_fwd i st let content0 ← betree_node_apply_messages_to_internal_fwd_back content msgs @@ -742,12 +744,12 @@ mutual divergent def betree_node_apply_messages_fwd then do let (st1, content1) ← - betree_internal_flush_fwd (mkbetree_internal_t i i0 n n0) params + betree_internal_flush_fwd (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, _) ← - betree_internal_flush_back (mkbetree_internal_t i i0 n n0) params + betree_internal_flush_back (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 - let (mkbetree_internal_t i1 _ _ _) := node0 + let ⟨ i1, _, _, _ ⟩ := node0 let (st2, _) ← betree_store_internal_node_fwd i1 content1 st1 Result.ret (st2, ()) else @@ -782,10 +784,10 @@ divergent def betree_node_apply_messages_back (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : Result (betree_node_t × betree_node_id_counter_t) := - match h: self with + match self with | betree_node_t.Internal node => do - let (mkbetree_internal_t i i0 n n0) := node + let ⟨ i, i0, n, n0 ⟩ := node let (st0, content) ← betree_load_internal_node_fwd i st let content0 ← betree_node_apply_messages_to_internal_fwd_back content msgs @@ -794,19 +796,19 @@ divergent def betree_node_apply_messages_back then do let (st1, content1) ← - betree_internal_flush_fwd (mkbetree_internal_t i i0 n n0) params + betree_internal_flush_fwd (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, node_id_cnt0) ← - betree_internal_flush_back (mkbetree_internal_t i i0 n n0) params + betree_internal_flush_back (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 - let (mkbetree_internal_t i1 i2 n1 n2) := node0 + let ⟨ i1, i2, n1, n2 ⟩ := node0 let _ ← betree_store_internal_node_fwd i1 content1 st1 - Result.ret (betree_node_t.Internal (mkbetree_internal_t i1 i2 n1 n2), - node_id_cnt0) + Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 + n2), node_id_cnt0) else do let _ ← betree_store_internal_node_fwd i content0 st0 - Result.ret (betree_node_t.Internal (mkbetree_internal_t i i0 n n0), + Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0), node_id_cnt) | betree_node_t.Leaf node => do @@ -839,7 +841,7 @@ divergent def betree_internal_flush_fwd Result (State × (betree_list_t (U64 × betree_message_t))) := do - let (mkbetree_internal_t _ i n n0) := self + let ⟨ _, i, n, n0 ⟩ := self let p ← betree_list_partition_at_pivot_fwd betree_message_t content i let (msgs_left, msgs_right) := p let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left @@ -879,7 +881,7 @@ divergent def betree_internal_flush_back Result (betree_internal_t × betree_node_id_counter_t) := do - let (mkbetree_internal_t i i0 n n0) := self + let ⟨ i, i0, n, n0 ⟩ := self let p ← betree_list_partition_at_pivot_fwd betree_message_t content i0 let (msgs_left, msgs_right) := p let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left @@ -898,13 +900,13 @@ divergent def betree_internal_flush_back let (n2, node_id_cnt1) ← betree_node_apply_messages_back n0 params node_id_cnt0 msgs_right st0 - Result.ret (mkbetree_internal_t i i0 n1 n2, node_id_cnt1) - else Result.ret (mkbetree_internal_t i i0 n1 n0, node_id_cnt0) + Result.ret (betree_internal_t.mk i i0 n1 n2, node_id_cnt1) + else Result.ret (betree_internal_t.mk i i0 n1 n0, node_id_cnt0) else do let (n1, node_id_cnt0) ← betree_node_apply_messages_back n0 params node_id_cnt msgs_right st - Result.ret (mkbetree_internal_t i i0 n n1, node_id_cnt0) + Result.ret (betree_internal_t.mk i i0 n n1, node_id_cnt0) end @@ -1069,3 +1071,4 @@ def main_fwd : Result Unit := /- Unit test for [betree_main::main] -/ #assert (main_fwd == .ret ()) +end BetreeMain diff --git a/tests/lean/BetreeMain/Opaque.lean b/tests/lean/BetreeMain/Opaque.lean index c8226d4e..d043186b 100644 --- a/tests/lean/BetreeMain/Opaque.lean +++ b/tests/lean/BetreeMain/Opaque.lean @@ -4,28 +4,32 @@ import Base import BetreeMain.Types open Primitives +namespace BetreeMain + structure OpaqueDefs where /- [betree_main::betree_utils::load_internal_node] -/ betree_utils_load_internal_node_fwd : - U64 -> State -> Result (State × (betree_list_t (U64 × betree_message_t))) + U64 → State → Result (State × (betree_list_t (U64 × + betree_message_t))) /- [betree_main::betree_utils::store_internal_node] -/ betree_utils_store_internal_node_fwd : - U64 -> betree_list_t (U64 × betree_message_t) -> State -> Result (State × - Unit) + U64 → betree_list_t (U64 × betree_message_t) → State → Result (State + × Unit) /- [betree_main::betree_utils::load_leaf_node] -/ betree_utils_load_leaf_node_fwd - : U64 -> State -> Result (State × (betree_list_t (U64 × U64))) + : U64 → State → Result (State × (betree_list_t (U64 × U64))) /- [betree_main::betree_utils::store_leaf_node] -/ betree_utils_store_leaf_node_fwd - : U64 -> betree_list_t (U64 × U64) -> State -> Result (State × Unit) + : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) /- [core::option::Option::{0}::unwrap] -/ core_option_option_unwrap_fwd - (T : Type) : Option T -> State -> Result (State × T) + (T : Type) : Option T → State → Result (State × T) +end BetreeMain diff --git a/tests/lean/BetreeMain/Types.lean b/tests/lean/BetreeMain/Types.lean index 4875a8ba..cfed6a28 100644 --- a/tests/lean/BetreeMain/Types.lean +++ b/tests/lean/BetreeMain/Types.lean @@ -3,21 +3,23 @@ import Base open Primitives +namespace BetreeMain + /- [betree_main::betree::List] -/ inductive betree_list_t (T : Type) := -| Cons : T -> betree_list_t T -> betree_list_t T +| Cons : T → betree_list_t T → betree_list_t T | Nil : betree_list_t T /- [betree_main::betree::UpsertFunState] -/ inductive betree_upsert_fun_state_t := -| Add : U64 -> betree_upsert_fun_state_t -| Sub : U64 -> betree_upsert_fun_state_t +| Add : U64 → betree_upsert_fun_state_t +| Sub : U64 → betree_upsert_fun_state_t /- [betree_main::betree::Message] -/ inductive betree_message_t := -| Insert : U64 -> betree_message_t +| Insert : U64 → betree_message_t | Delete : betree_message_t -| Upsert : betree_upsert_fun_state_t -> betree_message_t +| Upsert : betree_upsert_fun_state_t → betree_message_t /- [betree_main::betree::Leaf] -/ structure betree_leaf_t where @@ -28,17 +30,12 @@ mutual /- [betree_main::betree::Node] -/ inductive betree_node_t := -| Internal : betree_internal_t -> betree_node_t -| Leaf : betree_leaf_t -> betree_node_t +| Internal : betree_internal_t → betree_node_t +| Leaf : betree_leaf_t → betree_node_t /- [betree_main::betree::Internal] -/ inductive betree_internal_t := -| mkbetree_internal_t : - U64 -> - U64 -> - betree_node_t -> - betree_node_t -> - betree_internal_t +| mk : U64 → U64 → betree_node_t → betree_node_t → betree_internal_t end @@ -60,3 +57,4 @@ structure betree_be_tree_t where /- The state type used in the state-error monad -/ axiom State : Type +end BetreeMain diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index cd2f88f5..9f6a47de 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -3,6 +3,8 @@ import Base open Primitives +namespace Constants + /- [constants::X0] -/ def x0_body : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) def x0_c : U32 := eval_global x0_body (by simp) @@ -130,3 +132,4 @@ def s4_body : Result (pair_t U32 U32) := mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) def s4_c : pair_t U32 U32 := eval_global s4_body (by simp) +end Constants diff --git a/tests/lean/External/ExternalFuns.lean b/tests/lean/External/ExternalFuns.lean new file mode 100644 index 00000000..d63db2ac --- /dev/null +++ b/tests/lean/External/ExternalFuns.lean @@ -0,0 +1,9 @@ +import Base +import External.Types +import External.Opaque + +namespace External + +def opaque_defs : OpaqueDefs := sorry + +end External diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index 73e45938..e36987e0 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -5,6 +5,8 @@ import External.Types import External.ExternalFuns open Primitives +namespace External + /- [external::swap] -/ def swap_fwd (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := @@ -86,3 +88,4 @@ def test_swap_non_zero_fwd (x : U32) (st : State) : Result (State × U32) := then Result.fail Error.panic else Result.ret (st1, x0) +end External diff --git a/tests/lean/External/Opaque.lean b/tests/lean/External/Opaque.lean index 5483c3a9..1c0db095 100644 --- a/tests/lean/External/Opaque.lean +++ b/tests/lean/External/Opaque.lean @@ -4,25 +4,29 @@ import Base import External.Types open Primitives +namespace External + structure OpaqueDefs where /- [core::mem::swap] -/ - core_mem_swap_fwd (T : Type) : T -> T -> State -> Result (State × Unit) + core_mem_swap_fwd (T : Type) : T → T → State → Result (State × Unit) /- [core::mem::swap] -/ core_mem_swap_back0 - (T : Type) : T -> T -> State -> State -> Result (State × T) + (T : Type) : T → T → State → State → Result (State × T) /- [core::mem::swap] -/ core_mem_swap_back1 - (T : Type) : T -> T -> State -> State -> Result (State × T) + (T : Type) : T → T → State → State → Result (State × T) /- [core::num::nonzero::NonZeroU32::{14}::new] -/ core_num_nonzero_non_zero_u32_new_fwd : - U32 -> State -> Result (State × (Option core_num_nonzero_non_zero_u32_t)) + U32 → State → Result (State × (Option + core_num_nonzero_non_zero_u32_t)) /- [core::option::Option::{0}::unwrap] -/ core_option_option_unwrap_fwd - (T : Type) : Option T -> State -> Result (State × T) + (T : Type) : Option T → State → Result (State × T) +end External diff --git a/tests/lean/External/Types.lean b/tests/lean/External/Types.lean index 25907da2..fda0670e 100644 --- a/tests/lean/External/Types.lean +++ b/tests/lean/External/Types.lean @@ -3,9 +3,12 @@ import Base open Primitives +namespace External + /- [core::num::nonzero::NonZeroU32] -/ axiom core_num_nonzero_non_zero_u32_t : Type /- The state type used in the state-error monad -/ axiom State : Type +end External diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 26742d5d..b4254726 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -4,6 +4,8 @@ import Base import Hashmap.Types open Primitives +namespace Hashmap + /- [hashmap::hash_key] -/ def hash_key_fwd (k : Usize) : Result Usize := Result.ret k @@ -82,7 +84,7 @@ def hash_map_len_fwd (T : Type) (self : hash_map_t T) : Result Usize := /- [hashmap::HashMap::{0}::insert_in_list] -/ divergent def hash_map_insert_in_list_loop_fwd (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := - match h: ls with + match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret false @@ -97,7 +99,7 @@ def hash_map_insert_in_list_fwd /- [hashmap::HashMap::{0}::insert_in_list] -/ divergent def hash_map_insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := - match h: ls with + match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret (list_t.Cons ckey value tl) @@ -146,7 +148,7 @@ def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap::HashMap::{0}::move_elements_from_list] -/ divergent def hash_map_move_elements_from_list_loop_fwd_back (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := - match h: ls with + match ls with | list_t.Cons k v tl => do let ntable0 ← hash_map_insert_no_resize_fwd_back T ntable k v @@ -224,7 +226,7 @@ def hash_map_insert_fwd_back /- [hashmap::HashMap::{0}::contains_key_in_list] -/ divergent def hash_map_contains_key_in_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result Bool := - match h: ls with + match ls with | list_t.Cons ckey t tl => if ckey = key then Result.ret true @@ -249,7 +251,7 @@ def hash_map_contains_key_fwd /- [hashmap::HashMap::{0}::get_in_list] -/ divergent def hash_map_get_in_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result T := - match h: ls with + match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue @@ -274,7 +276,7 @@ def hash_map_get_fwd /- [hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def hash_map_get_mut_in_list_loop_fwd (T : Type) (ls : list_t T) (key : Usize) : Result T := - match h: ls with + match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue @@ -289,7 +291,7 @@ def hash_map_get_mut_in_list_fwd /- [hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def hash_map_get_mut_in_list_loop_back (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := - match h: ls with + match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret (list_t.Cons ckey ret0 tl) @@ -331,13 +333,13 @@ def hash_map_get_mut_back /- [hashmap::HashMap::{0}::remove_from_list] -/ divergent def hash_map_remove_from_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := - match h: ls with + match ls with | list_t.Cons ckey t tl => if ckey = key then let mv_ls := mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil - match h: mv_ls with + match mv_ls with | list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | list_t.Nil => Result.fail Error.panic else hash_map_remove_from_list_loop_fwd T key tl @@ -351,13 +353,13 @@ def hash_map_remove_from_list_fwd /- [hashmap::HashMap::{0}::remove_from_list] -/ divergent def hash_map_remove_from_list_loop_back (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := - match h: ls with + match ls with | list_t.Cons ckey t tl => if ckey = key then let mv_ls := mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil - match h: mv_ls with + match mv_ls with | list_t.Cons i cvalue tl0 => Result.ret tl0 | list_t.Nil => Result.fail Error.panic else @@ -380,7 +382,7 @@ def hash_map_remove_fwd let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod let x ← hash_map_remove_from_list_fwd T key l - match h: x with + match x with | Option.none => Result.ret Option.none | Option.some x0 => do @@ -396,7 +398,7 @@ def hash_map_remove_back let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod let x ← hash_map_remove_from_list_fwd T key l - match h: x with + match x with | Option.none => do let l0 ← hash_map_remove_from_list_back T key l @@ -441,7 +443,7 @@ def test1_fwd : Result Unit := do let x ← hash_map_remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) - match h: x with + match x with | Option.none => Result.fail Error.panic | Option.some x0 => if not (x0 = (U64.ofInt 56 (by intlit))) @@ -472,3 +474,4 @@ def test1_fwd : Result Unit := /- Unit test for [hashmap::test1] -/ #assert (test1_fwd == .ret ()) +end Hashmap diff --git a/tests/lean/Hashmap/Types.lean b/tests/lean/Hashmap/Types.lean index af26f363..0aec6acf 100644 --- a/tests/lean/Hashmap/Types.lean +++ b/tests/lean/Hashmap/Types.lean @@ -3,9 +3,11 @@ import Base open Primitives +namespace Hashmap + /- [hashmap::List] -/ inductive list_t (T : Type) := -| Cons : Usize -> T -> list_t T -> list_t T +| Cons : Usize → T → list_t T → list_t T | Nil : list_t T /- [hashmap::HashMap] -/ @@ -15,3 +17,4 @@ structure hash_map_t (T : Type) where hash_map_max_load : Usize hash_map_slots : Vec (list_t T) +end Hashmap diff --git a/tests/lean/HashmapMain/ExternalFuns.lean b/tests/lean/HashmapMain/ExternalFuns.lean new file mode 100644 index 00000000..bc831158 --- /dev/null +++ b/tests/lean/HashmapMain/ExternalFuns.lean @@ -0,0 +1,9 @@ +import Base +import HashmapMain.Types +import HashmapMain.Opaque + +namespace HashmapMain + +def opaque_defs : OpaqueDefs := by sorry + +end HashmapMain diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index a59a9f26..34a0eca1 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -5,6 +5,8 @@ import HashmapMain.Types import HashmapMain.ExternalFuns open Primitives +namespace HashmapMain + /- [hashmap_main::hashmap::hash_key] -/ def hashmap_hash_key_fwd (k : Usize) : Result Usize := Result.ret k @@ -92,7 +94,7 @@ def hashmap_hash_map_len_fwd /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ divergent def hashmap_hash_map_insert_in_list_loop_fwd (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := - match h: ls with + match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret false @@ -109,7 +111,7 @@ divergent def hashmap_hash_map_insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := - match h: ls with + match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret (hashmap_list_t.Cons ckey value tl) @@ -173,7 +175,7 @@ divergent def hashmap_hash_map_move_elements_from_list_loop_fwd_back (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : Result (hashmap_hash_map_t T) := - match h: ls with + match ls with | hashmap_list_t.Cons k v tl => do let ntable0 ← hashmap_hash_map_insert_no_resize_fwd_back T ntable k v @@ -256,7 +258,7 @@ def hashmap_hash_map_insert_fwd_back /- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ divergent def hashmap_hash_map_contains_key_in_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := - match h: ls with + match ls with | hashmap_list_t.Cons ckey t tl => if ckey = key then Result.ret true @@ -282,7 +284,7 @@ def hashmap_hash_map_contains_key_fwd /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ divergent def hashmap_hash_map_get_in_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := - match h: ls with + match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue @@ -308,7 +310,7 @@ def hashmap_hash_map_get_fwd /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def hashmap_hash_map_get_mut_in_list_loop_fwd (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := - match h: ls with + match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue @@ -325,7 +327,7 @@ divergent def hashmap_hash_map_get_mut_in_list_loop_back (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : Result (hashmap_list_t T) := - match h: ls with + match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret (hashmap_list_t.Cons ckey ret0 tl) @@ -373,14 +375,14 @@ def hashmap_hash_map_get_mut_back /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ divergent def hashmap_hash_map_remove_from_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := - match h: ls with + match ls with | hashmap_list_t.Cons ckey t tl => if ckey = key then let mv_ls := mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) hashmap_list_t.Nil - match h: mv_ls with + match mv_ls with | hashmap_list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | hashmap_list_t.Nil => Result.fail Error.panic else hashmap_hash_map_remove_from_list_loop_fwd T key tl @@ -396,14 +398,14 @@ divergent def hashmap_hash_map_remove_from_list_loop_back (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := - match h: ls with + match ls with | hashmap_list_t.Cons ckey t tl => if ckey = key then let mv_ls := mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) hashmap_list_t.Nil - match h: mv_ls with + match mv_ls with | hashmap_list_t.Cons i cvalue tl0 => Result.ret tl0 | hashmap_list_t.Nil => Result.fail Error.panic else @@ -429,7 +431,7 @@ def hashmap_hash_map_remove_fwd let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod let x ← hashmap_hash_map_remove_from_list_fwd T key l - match h: x with + match x with | Option.none => Result.ret Option.none | Option.some x0 => do @@ -449,7 +451,7 @@ def hashmap_hash_map_remove_back let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod let x ← hashmap_hash_map_remove_from_list_fwd T key l - match h: x with + match x with | Option.none => do let l0 ← hashmap_hash_map_remove_from_list_back T key l @@ -505,7 +507,7 @@ def hashmap_test1_fwd : Result Unit := let x ← hashmap_hash_map_remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) - match h: x with + match x with | Option.none => Result.fail Error.panic | Option.some x0 => if not (x0 = (U64.ofInt 56 (by intlit))) @@ -555,3 +557,4 @@ def main_fwd : Result Unit := /- Unit test for [hashmap_main::main] -/ #assert (main_fwd == .ret ()) +end HashmapMain diff --git a/tests/lean/HashmapMain/Opaque.lean b/tests/lean/HashmapMain/Opaque.lean index bef4f3fb..10e4d8bd 100644 --- a/tests/lean/HashmapMain/Opaque.lean +++ b/tests/lean/HashmapMain/Opaque.lean @@ -4,13 +4,16 @@ import Base import HashmapMain.Types open Primitives +namespace HashmapMain + structure OpaqueDefs where /- [hashmap_main::hashmap_utils::deserialize] -/ hashmap_utils_deserialize_fwd - : State -> Result (State × (hashmap_hash_map_t U64)) + : State → Result (State × (hashmap_hash_map_t U64)) /- [hashmap_main::hashmap_utils::serialize] -/ hashmap_utils_serialize_fwd - : hashmap_hash_map_t U64 -> State -> Result (State × Unit) + : hashmap_hash_map_t U64 → State → Result (State × Unit) +end HashmapMain diff --git a/tests/lean/HashmapMain/Types.lean b/tests/lean/HashmapMain/Types.lean index 858e1c51..b91ff3a7 100644 --- a/tests/lean/HashmapMain/Types.lean +++ b/tests/lean/HashmapMain/Types.lean @@ -3,9 +3,11 @@ import Base open Primitives +namespace HashmapMain + /- [hashmap_main::hashmap::List] -/ inductive hashmap_list_t (T : Type) := -| Cons : Usize -> T -> hashmap_list_t T -> hashmap_list_t T +| Cons : Usize → T → hashmap_list_t T → hashmap_list_t T | Nil : hashmap_list_t T /- [hashmap_main::hashmap::HashMap] -/ @@ -18,3 +20,4 @@ structure hashmap_hash_map_t (T : Type) where /- The state type used in the state-error monad -/ axiom State : Type +end HashmapMain diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 7d5f7595..9e084327 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -4,6 +4,8 @@ import Base import Loops.Types open Primitives +namespace Loops + /- [loops::sum] -/ divergent def sum_loop_fwd (max : U32) (i : U32) (s : U32) : Result U32 := if i < max @@ -68,7 +70,7 @@ def clear_fwd_back (v : Vec U32) : Result (Vec U32) := /- [loops::list_mem] -/ divergent def list_mem_loop_fwd (x : U32) (ls : list_t U32) : Result Bool := - match h: ls with + match ls with | list_t.Cons y tl => if y = x then Result.ret true @@ -82,7 +84,7 @@ def list_mem_fwd (x : U32) (ls : list_t U32) : Result Bool := /- [loops::list_nth_mut_loop] -/ divergent def list_nth_mut_loop_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -99,7 +101,7 @@ def list_nth_mut_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := /- [loops::list_nth_mut_loop] -/ divergent def list_nth_mut_loop_loop_back (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl) @@ -118,7 +120,7 @@ def list_nth_mut_loop_back /- [loops::list_nth_shared_loop] -/ divergent def list_nth_shared_loop_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -135,7 +137,7 @@ def list_nth_shared_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := /- [loops::get_elem_mut] -/ divergent def get_elem_mut_loop_fwd (x : Usize) (ls : list_t Usize) : Result Usize := - match h: ls with + match ls with | list_t.Cons y tl => if y = x then Result.ret y @@ -152,7 +154,7 @@ def get_elem_mut_fwd (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := /- [loops::get_elem_mut] -/ divergent def get_elem_mut_loop_back (x : Usize) (ls : list_t Usize) (ret0 : Usize) : Result (list_t Usize) := - match h: ls with + match ls with | list_t.Cons y tl => if y = x then Result.ret (list_t.Cons ret0 tl) @@ -176,7 +178,7 @@ def get_elem_mut_back /- [loops::get_elem_shared] -/ divergent def get_elem_shared_loop_fwd (x : Usize) (ls : list_t Usize) : Result Usize := - match h: ls with + match ls with | list_t.Cons y tl => if y = x then Result.ret y @@ -206,7 +208,7 @@ def id_shared_fwd (T : Type) (ls : list_t T) : Result (list_t T) := /- [loops::list_nth_mut_loop_with_id] -/ divergent def list_nth_mut_loop_with_id_loop_fwd (T : Type) (i : U32) (ls : list_t T) : Result T := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -226,7 +228,7 @@ def list_nth_mut_loop_with_id_fwd /- [loops::list_nth_mut_loop_with_id] -/ divergent def list_nth_mut_loop_with_id_loop_back (T : Type) (i : U32) (ls : list_t T) (ret0 : T) : Result (list_t T) := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl) @@ -248,7 +250,7 @@ def list_nth_mut_loop_with_id_back /- [loops::list_nth_shared_loop_with_id] -/ divergent def list_nth_shared_loop_with_id_loop_fwd (T : Type) (i : U32) (ls : list_t T) : Result T := - match h: ls with + match ls with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -268,9 +270,9 @@ def list_nth_shared_loop_with_id_fwd /- [loops::list_nth_mut_loop_pair] -/ divergent def list_nth_mut_loop_pair_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -291,9 +293,9 @@ divergent def list_nth_mut_loop_pair_loop_back'a (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl0) @@ -317,9 +319,9 @@ divergent def list_nth_mut_loop_pair_loop_back'b (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl1) @@ -341,9 +343,9 @@ def list_nth_mut_loop_pair_back'b /- [loops::list_nth_shared_loop_pair] -/ divergent def list_nth_shared_loop_pair_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -362,9 +364,9 @@ def list_nth_shared_loop_pair_fwd /- [loops::list_nth_mut_loop_pair_merge] -/ divergent def list_nth_mut_loop_pair_merge_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -385,9 +387,9 @@ divergent def list_nth_mut_loop_pair_merge_loop_back (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : Result ((list_t T) × (list_t T)) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then @@ -412,9 +414,9 @@ def list_nth_mut_loop_pair_merge_back /- [loops::list_nth_shared_loop_pair_merge] -/ divergent def list_nth_shared_loop_pair_merge_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -433,9 +435,9 @@ def list_nth_shared_loop_pair_merge_fwd /- [loops::list_nth_mut_shared_loop_pair] -/ divergent def list_nth_mut_shared_loop_pair_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -456,9 +458,9 @@ divergent def list_nth_mut_shared_loop_pair_loop_back (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl0) @@ -481,9 +483,9 @@ def list_nth_mut_shared_loop_pair_back /- [loops::list_nth_mut_shared_loop_pair_merge] -/ divergent def list_nth_mut_shared_loop_pair_merge_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -504,9 +506,9 @@ divergent def list_nth_mut_shared_loop_pair_merge_loop_back (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl0) @@ -529,9 +531,9 @@ def list_nth_mut_shared_loop_pair_merge_back /- [loops::list_nth_shared_mut_loop_pair] -/ divergent def list_nth_shared_mut_loop_pair_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -552,9 +554,9 @@ divergent def list_nth_shared_mut_loop_pair_loop_back (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl1) @@ -577,9 +579,9 @@ def list_nth_shared_mut_loop_pair_back /- [loops::list_nth_shared_mut_loop_pair_merge] -/ divergent def list_nth_shared_mut_loop_pair_merge_loop_fwd (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) @@ -600,9 +602,9 @@ divergent def list_nth_shared_mut_loop_pair_merge_loop_back (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: ls0 with + match ls0 with | list_t.Cons x0 tl0 => - match h: ls1 with + match ls1 with | list_t.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl1) @@ -622,3 +624,4 @@ def list_nth_shared_mut_loop_pair_merge_back := list_nth_shared_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 +end Loops diff --git a/tests/lean/Loops/Types.lean b/tests/lean/Loops/Types.lean index e14f9766..ca0403e9 100644 --- a/tests/lean/Loops/Types.lean +++ b/tests/lean/Loops/Types.lean @@ -3,8 +3,11 @@ import Base open Primitives +namespace Loops + /- [loops::List] -/ inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T +| Cons : T → list_t T → list_t T | Nil : list_t T +end Loops diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index 67ef4b20..769bb311 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -3,6 +3,8 @@ import Base open Primitives +namespace NoNestedBorrows + /- [no_nested_borrows::Pair] -/ structure pair_t (T1 T2 : Type) where pair_x : T1 @@ -10,12 +12,12 @@ structure pair_t (T1 T2 : Type) where /- [no_nested_borrows::List] -/ inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T +| Cons : T → list_t T → list_t T | Nil : list_t T /- [no_nested_borrows::One] -/ inductive one_t (T1 : Type) := -| One : T1 -> one_t T1 +| One : T1 → one_t T1 /- [no_nested_borrows::EmptyEnum] -/ inductive empty_enum_t := @@ -31,8 +33,8 @@ structure empty_struct_t where /- [no_nested_borrows::Sum] -/ inductive sum_t (T1 T2 : Type) := -| Left : T1 -> sum_t T1 T2 -| Right : T2 -> sum_t T1 T2 +| Left : T1 → sum_t T1 T2 +| Right : T2 → sum_t T1 T2 /- [no_nested_borrows::neg_test] -/ def neg_test_fwd (x : I32) : Result I32 := @@ -175,7 +177,7 @@ def test_copy_int_fwd : Result Unit := /- [no_nested_borrows::is_cons] -/ def is_cons_fwd (T : Type) (l : list_t T) : Result Bool := - match h: l with + match l with | list_t.Cons t l0 => Result.ret true | list_t.Nil => Result.ret false @@ -193,7 +195,7 @@ def test_is_cons_fwd : Result Unit := /- [no_nested_borrows::split_list] -/ def split_list_fwd (T : Type) (l : list_t T) : Result (T × (list_t T)) := - match h: l with + match l with | list_t.Cons hd tl => Result.ret (hd, tl) | list_t.Nil => Result.fail Error.panic @@ -254,19 +256,19 @@ mutual /- [no_nested_borrows::NodeElem] -/ inductive node_elem_t (T : Type) := -| Cons : tree_t T -> node_elem_t T -> node_elem_t T +| Cons : tree_t T → node_elem_t T → node_elem_t T | Nil : node_elem_t T /- [no_nested_borrows::Tree] -/ inductive tree_t (T : Type) := -| Leaf : T -> tree_t T -| Node : T -> node_elem_t T -> tree_t T -> tree_t T +| Leaf : T → tree_t T +| Node : T → node_elem_t T → tree_t T → tree_t T end /- [no_nested_borrows::list_length] -/ divergent def list_length_fwd (T : Type) (l : list_t T) : Result U32 := - match h: l with + match l with | list_t.Cons t l1 => do let i ← list_length_fwd T l1 @@ -276,7 +278,7 @@ divergent def list_length_fwd (T : Type) (l : list_t T) : Result U32 := /- [no_nested_borrows::list_nth_shared] -/ divergent def list_nth_shared_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with + match l with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -289,7 +291,7 @@ divergent def list_nth_shared_fwd /- [no_nested_borrows::list_nth_mut] -/ divergent def list_nth_mut_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with + match l with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -301,7 +303,7 @@ divergent def list_nth_mut_fwd /- [no_nested_borrows::list_nth_mut] -/ divergent def list_nth_mut_back (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: l with + match l with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl) @@ -315,7 +317,7 @@ divergent def list_nth_mut_back /- [no_nested_borrows::list_rev_aux] -/ divergent def list_rev_aux_fwd (T : Type) (li : list_t T) (lo : list_t T) : Result (list_t T) := - match h: li with + match li with | list_t.Cons hd tl => list_rev_aux_fwd T tl (list_t.Cons hd lo) | list_t.Nil => Result.ret lo @@ -531,7 +533,7 @@ def test_shared_borrow_bool2_fwd : Result U32 := /- [no_nested_borrows::test_shared_borrow_enum1] -/ def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := - match h: l with + match l with | list_t.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) @@ -539,3 +541,4 @@ def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := def test_shared_borrow_enum2_fwd : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) +end NoNestedBorrows diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean index 9019b694..edcb5c1b 100644 --- a/tests/lean/Paper.lean +++ b/tests/lean/Paper.lean @@ -3,6 +3,8 @@ import Base open Primitives +namespace Paper + /- [paper::ref_incr] -/ def ref_incr_fwd_back (x : I32) : Result I32 := x + (I32.ofInt 1 (by intlit)) @@ -56,13 +58,13 @@ def test_choose_fwd : Result Unit := /- [paper::List] -/ inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T +| Cons : T → list_t T → list_t T | Nil : list_t T /- [paper::list_nth_mut] -/ divergent def list_nth_mut_fwd (T : Type) (l : list_t T) (i : U32) : Result T := - match h: l with + match l with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x @@ -74,7 +76,7 @@ divergent def list_nth_mut_fwd /- [paper::list_nth_mut] -/ divergent def list_nth_mut_back (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := - match h: l with + match l with | list_t.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret (list_t.Cons ret0 tl) @@ -87,7 +89,7 @@ divergent def list_nth_mut_back /- [paper::sum] -/ divergent def sum_fwd (l : list_t I32) : Result I32 := - match h: l with + match l with | list_t.Cons x tl => do let i ← sum_fwd tl x + i @@ -123,3 +125,4 @@ def call_choose_fwd (p : (U32 × U32)) : Result U32 := let (px0, _) ← choose_back U32 true px py pz0 Result.ret px0 +end Paper diff --git a/tests/lean/PoloniusList.lean b/tests/lean/PoloniusList.lean index 671f54ea..0f2a05e3 100644 --- a/tests/lean/PoloniusList.lean +++ b/tests/lean/PoloniusList.lean @@ -3,15 +3,17 @@ import Base open Primitives +namespace PoloniusList + /- [polonius_list::List] -/ inductive list_t (T : Type) := -| Cons : T -> list_t T -> list_t T +| Cons : T → list_t T → list_t T | Nil : list_t T /- [polonius_list::get_list_at_x] -/ divergent def get_list_at_x_fwd (ls : list_t U32) (x : U32) : Result (list_t U32) := - match h: ls with + match ls with | list_t.Cons hd tl => if hd = x then Result.ret (list_t.Cons hd tl) @@ -21,7 +23,7 @@ divergent def get_list_at_x_fwd /- [polonius_list::get_list_at_x] -/ divergent def get_list_at_x_back (ls : list_t U32) (x : U32) (ret0 : list_t U32) : Result (list_t U32) := - match h: ls with + match ls with | list_t.Cons hd tl => if hd = x then Result.ret ret0 @@ -31,3 +33,4 @@ divergent def get_list_at_x_back Result.ret (list_t.Cons hd tl0) | list_t.Nil => Result.ret ret0 +end PoloniusList diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json index 1397c6f0..ccd6d61a 100644 --- a/tests/lean/lake-manifest.json +++ b/tests/lean/lake-manifest.json @@ -11,7 +11,7 @@ {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "cb02d09e1d5611d22efc2b406e7893f246b2f51e", + "rev": "409bee4eabf8072c4569950c3c2f310afd203abf", "name": "mathlib", "inputRev?": null}}, {"git": diff --git a/tests/lean/lakefile.lean b/tests/lean/lakefile.lean index da4293dd..217e533f 100644 --- a/tests/lean/lakefile.lean +++ b/tests/lean/lakefile.lean @@ -11,4 +11,12 @@ package «tests» {} @[default_target] lean_lib «Tests» {} +lean_lib betreeMain +lean_lib constants +lean_lib external lean_lib hashmap +lean_lib hashmapMain +lean_lib loops +lean_lib noNestedBorrows +lean_lib paper +lean_lib poloniusList -- cgit v1.2.3 From 442caaf62e4a217b9a10116c4e529c49f83c4efd Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 4 Jul 2023 22:45:02 +0200 Subject: Fix an issue with mkSigmasVal --- backends/lean/Base/Diverge/Elab.lean | 228 +++++++++++++++++++------------ backends/lean/Base/Diverge/ElabBase.lean | 47 ++++--- backends/lean/lake-manifest.json | 2 +- tests/lean/lake-manifest.json | 2 +- 4 files changed, 171 insertions(+), 108 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 4b08fe44..1af06fea 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -26,38 +26,42 @@ def mkInOutTy (x y : Expr) : MetaM Expr := mkAppM ``FixI.mk_in_out_ty #[x, y] -- Return the `a` in `Return a` -def get_result_ty (ty : Expr) : MetaM Expr := +def getResultTy (ty : Expr) : MetaM Expr := ty.withApp fun f args => do if ¬ f.isConstOf ``Result ∨ args.size ≠ 1 then - throwError "Invalid argument to get_result_ty: {ty}" + throwError "Invalid argument to getResultTy: {ty}" else pure (args.get! 0) -/- Group a list of expressions into a dependent tuple. +/- Deconstruct a sigma type. - Example: - xl = [`a : Type`, `ls : List a`] - returns: - `⟨ (a:Type), (ls: List a) ⟩` + For instance, deconstructs `(a : Type) × List a` into + `Type` and `λ a => List a`. -/ -def mkSigmasVal (xl : List Expr) : MetaM Expr := - match xl with - | [] => do - trace[Diverge.def.sigmas] "mkSigmasVal: []" - pure (Expr.const ``PUnit.unit []) - | [x] => do - trace[Diverge.def.sigmas] "mkSigmasVal: [{x}]" - pure x - | fst :: xl => do - trace[Diverge.def.sigmas] "mkSigmasVal: [{fst}::{xl}]" - let alpha ← Lean.Meta.inferType fst - let snd ← mkSigmasVal xl - let snd_ty ← inferType snd - let beta ← mkLambdaFVars #[fst] snd_ty - trace[Diverge.def.sigmas] "mkSigmasVal:\n{alpha}\n{beta}\n{fst}\n{snd}" - mkAppOptM ``Sigma.mk #[some alpha, some beta, some fst, some snd] - -/- Generate a Sigma type from a list of expressions. +def getSigmaTypes (ty : Expr) : MetaM (Expr × Expr) := do + ty.withApp fun f args => do + if ¬ f.isConstOf ``Sigma ∨ args.size ≠ 2 then + throwError "Invalid argument to getSigmaTypes: {ty}" + else + pure (args.get! 0, args.get! 1) + +/- Like `lambdaTelescopeN` but only destructs a fixed number of lambdas -/ +def lambdaTelescopeN (e : Expr) (n : Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := + lambdaTelescope e fun xs body => do + if xs.size < n then throwError "lambdaTelescopeN: not enough lambdas"; + let xs := xs.extract 0 n + let ys := xs.extract n xs.size + let body ← mkLambdaFVars ys body + k xs body + +/- Like `lambdaTelescope`, but only destructs one lambda + TODO: is there an equivalent of this function somewhere in the + standard library? -/ +def lambdaOne (e : Expr) (k : Expr → Expr → MetaM α) : MetaM α := + lambdaTelescopeN e 1 λ xs b => k (xs.get! 0) b + +/- Generate a Sigma type from a list of *variables* (all the expressions + must be variables). Example: - xl = [(a:Type), (ls:List a), (i:Int)] @@ -84,6 +88,53 @@ def mkSigmasType (xl : List Expr) : MetaM Expr := trace[Diverge.def.sigmas] "mkSigmasOfTypes: ({alpha}) ({beta})" mkAppOptM ``Sigma #[some alpha, some beta] +/- Apply a lambda expression to some arguments, simplifying the lambdas -/ +def applyLambdaToArgs (e : Expr) (xs : Array Expr) : MetaM Expr := do + lambdaTelescopeN e xs.size fun vars body => + -- Create the substitution + let s : HashMap FVarId Expr := HashMap.ofList (List.zip (vars.toList.map Expr.fvarId!) xs.toList) + -- Substitute in the body + pure (body.replace fun e => + match e with + | Expr.fvar fvarId => match s.find? fvarId with + | none => e + | some v => v + | _ => none) + +/- Group a list of expressions into a dependent tuple. + + Example: + xl = [`a : Type`, `ls : List a`] + returns: + `⟨ (a:Type), (ls: List a) ⟩` + + We need the type argument because as the elements in the tuple are + "concrete", we can't in all generality figure out the type of the tuple. + + Example: + `⟨ True, 3 ⟩ : (x : Bool) × (if x then Int else Unit)` + -/ +def mkSigmasVal (ty : Expr) (xl : List Expr) : MetaM Expr := + match xl with + | [] => do + trace[Diverge.def.sigmas] "mkSigmasVal: []" + pure (Expr.const ``PUnit.unit []) + | [x] => do + trace[Diverge.def.sigmas] "mkSigmasVal: [{x}]" + pure x + | fst :: xl => do + trace[Diverge.def.sigmas] "mkSigmasVal: [{fst}::{xl}]" + -- Deconstruct the type + let (alpha, beta) ← getSigmaTypes ty + -- Compute the "second" field + -- Specialize beta for fst + let nty ← applyLambdaToArgs beta #[fst] + -- Recursive call + let snd ← mkSigmasVal nty xl + -- Put everything together + trace[Diverge.def.sigmas] "mkSigmasVal:\n{alpha}\n{beta}\n{fst}\n{snd}" + mkAppOptM ``Sigma.mk #[some alpha, some beta, some fst, some snd] + def mkAnonymous (s : String) (i : Nat) : Name := .num (.str .anonymous s) i @@ -208,52 +259,57 @@ def mkFinVal (n i : Nat) : MetaM Expr := do We return the new declarations. -/ def mkDeclareUnaryBodies (grLvlParams : List Name) (kk_var : Expr) - (preDefs : Array PreDefinition) : + (inOutTys : Array (Expr × Expr)) (preDefs : Array PreDefinition) : MetaM (Array Expr) := do let grSize := preDefs.size - -- Compute the map from name to index - the continuation has an indexed type: - -- we use the index (a finite number of type `Fin`) to control which function - -- we call at the recursive call site. - let nameToId : HashMap Name Nat := - let namesIds := preDefs.mapIdx (fun i d => (d.declName, i.val)) - HashMap.ofList namesIds.toList + -- Compute the map from name to (index × input type). + -- Remark: the continuation has an indexed type; we use the index (a finite number of + -- type `Fin`) to control which function we call at the recursive call site. + let nameToInfo : HashMap Name (Nat × Expr) := + let bl := preDefs.mapIdx fun i d => (d.declName, (i.val, (inOutTys.get! i.val).fst)) + HashMap.ofList bl.toList - trace[Diverge.def.genBody] "nameToId: {nameToId.toList}" + trace[Diverge.def.genBody] "nameToId: {nameToInfo.toList}" -- Auxiliary function to explore the function bodies and replace the -- recursive calls - let visit_e (e : Expr) : MetaM Expr := do - trace[Diverge.def.genBody] "visiting expression: {e}" - match e with - | .app .. => do - e.withApp fun f args => do - trace[Diverge.def.genBody] "this is an app: {f} {args}" - -- Check if this is a recursive call - if f.isConst then - let name := f.constName! - match nameToId.find? name with - | none => pure e - | some id => - -- This is a recursive call: replace it - -- Compute the index - let i ← mkFinVal grSize id - -- Put the arguments in one big dependent tuple - let args ← mkSigmasVal args.toList - mkAppM' kk_var #[i, args] - else - -- Not a recursive call: do nothing - pure e - | .const name _ => - -- Sanity check: we eliminated all the recursive calls - if (nameToId.find? name).isSome then - throwError "mkUnaryBodies: a recursive call was not eliminated" - else pure e - | _ => pure e + let visit_e (i : Nat) (e : Expr) : MetaM Expr := do + trace[Diverge.def.genBody] "visiting expression (dept: {i}): {e}" + let ne ← do + match e with + | .app .. => do + e.withApp fun f args => do + trace[Diverge.def.genBody] "this is an app: {f} {args}" + -- Check if this is a recursive call + if f.isConst then + let name := f.constName! + match nameToInfo.find? name with + | none => pure e + | some (id, in_ty) => + trace[Diverge.def.genBody] "this is a recursive call" + -- This is a recursive call: replace it + -- Compute the index + let i ← mkFinVal grSize id + -- Put the arguments in one big dependent tuple + let args ← mkSigmasVal in_ty args.toList + mkAppM' kk_var #[i, args] + else + -- Not a recursive call: do nothing + pure e + | .const name _ => + -- Sanity check: we eliminated all the recursive calls + if (nameToInfo.find? name).isSome then + throwError "mkUnaryBodies: a recursive call was not eliminated" + else pure e + | _ => pure e + trace[Diverge.def.genBody] "done with expression (depth: {i}): {e}" + pure ne -- Explore the bodies preDefs.mapM fun preDef => do -- Replace the recursive calls + trace[Diverge.def.genBody] "About to replace recursive calls in {preDef.declName}" let body ← mapVisit visit_e preDef.value trace[Diverge.def.genBody] "Body after replacement of the recursive calls: {body}" @@ -413,11 +469,8 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do let proveBranchValid (br : Expr) : MetaM Expr := if isIte then proveExprIsValid k_var kk_var br else do - -- There is a lambda -- TODO: how do we remove exacly *one* lambda? - lambdaTelescope br fun xs br => do - let x := xs.get! 0 - let xs := xs.extract 1 xs.size - let br ← mkLambdaFVars xs br + -- There is a lambda + lambdaOne br fun x br => do let brValid ← proveExprIsValid k_var kk_var br mkLambdaFVars #[x] brValid let br0Valid ← proveBranchValid br0 @@ -521,11 +574,8 @@ partial def proveExprIsValid (k_var kk_var : Expr) (e : Expr) : MetaM Expr := do let xValid ← proveExprIsValid k_var kk_var x trace[Diverge.def.valid] "bind: xValid:\n{xValid}:\n{← inferType xValid}" let yValid ← do - -- This is a lambda expression -- TODO: how do we remove exacly *one* lambda? - lambdaTelescope y fun xs y => do - let x := xs.get! 0 - let xs := xs.extract 1 xs.size - let y ← mkLambdaFVars xs y + -- This is a lambda expression + lambdaOne y fun x y => do trace[Diverge.def.valid] "bind: y: {y}" let yValid ← proveExprIsValid k_var kk_var y trace[Diverge.def.valid] "bind: yValid (no forall): {yValid}" @@ -559,15 +609,12 @@ partial def proveMatchIsValid (k_var kk_var : Expr) (me : MatchInfo) : MetaM Exp -- binders might come from the match, and some of the binders might come -- from the fact that the expression in the match is a lambda expression: -- we use the branchesNumParams field for this reason - lambdaTelescope br fun xs br => do let numParams := me.branchesNumParams.get! idx - let xs_beg := xs.extract 0 numParams - let xs_end := xs.extract numParams xs.size - let br ← mkLambdaFVars xs_end br + lambdaTelescopeN br numParams fun xs br => do -- Prove that the branch expression is valid let brValid ← proveExprIsValid k_var kk_var br -- Reconstruct the lambda expression - mkLambdaFVars xs_beg brValid + mkLambdaFVars xs brValid trace[Diverge.def.valid] "branchesValid:\n{branchesValid}" -- Compute the motive, which has the following shape: -- ``` @@ -726,15 +773,17 @@ def proveMutRecIsValid -- def is_even (i : Int) : Result Bool := mut_rec_body 0 i -- def is_odd (i : Int) : Result Bool := mut_rec_body 1 i -- ``` -def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : +def mkDeclareFixDefs (mutRecBody : Expr) (inOutTys : Array (Expr × Expr)) (preDefs : Array PreDefinition) : TermElabM (Array Name) := do let grSize := preDefs.size let defs ← preDefs.mapIdxM fun idx preDef => do lambdaTelescope preDef.value fun xs _ => do + -- Retrieve the input type + let in_ty := (inOutTys.get! idx.val).fst -- Create the index let idx ← mkFinVal grSize idx.val -- Group the inputs into a dependent tuple - let input ← mkSigmasVal xs.toList + let input ← mkSigmasVal in_ty xs.toList -- Apply the fixed point let fixedBody ← mkAppM ``FixI.fix #[mutRecBody, idx, input] let fixedBody ← mkLambdaFVars xs fixedBody @@ -754,8 +803,8 @@ def mkDeclareFixDefs (mutRecBody : Expr) (preDefs : Array PreDefinition) : pure defs -- Prove the equations that we will use as unfolding theorems -partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinition) - (decls : Array Name) : MetaM Unit := do +partial def proveUnfoldingThms (isValidThm : Expr) (inOutTys : Array (Expr × Expr)) + (preDefs : Array PreDefinition) (decls : Array Name) : MetaM Unit := do let grSize := preDefs.size let proveIdx (i : Nat) : MetaM Unit := do let preDef := preDefs.get! i @@ -779,7 +828,7 @@ partial def proveUnfoldingThms (isValidThm : Expr) (preDefs : Array PreDefinitio let idx ← mkFinVal grSize i let proof ← mkAppM ``congr_fun #[proof, idx] -- Add the input argument - let arg ← mkSigmasVal xs.toList + let arg ← mkSigmasVal (inOutTys.get! i).fst xs.toList let proof ← mkAppM ``congr_fun #[proof, arg] -- Abstract the arguments away let proof ← mkLambdaFVars xs proof @@ -833,7 +882,7 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do forallTelescope preDef.type (fun in_tys out_ty => do let in_ty ← liftM (mkSigmasType in_tys.toList) -- Retrieve the type in the "Result" - let out_ty ← get_result_ty out_ty + let out_ty ← getResultTy out_ty let out_ty ← liftM (mkSigmasMatch in_tys.toList out_ty) pure (in_ty, out_ty) ) @@ -886,8 +935,8 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- Replace the recursive calls in all the function bodies by calls to the -- continuation `k` and and generate for those bodies declarations - trace[Diverge.def] "# Generating the unary bodies" - let bodies ← mkDeclareUnaryBodies grLvlParams kk_var preDefs + trace[Diverge.def] "# Generating the unary bodies" + let bodies ← mkDeclareUnaryBodies grLvlParams kk_var inOutTys preDefs trace[Diverge.def] "Unary bodies (after decl): {bodies}" -- Generate the mutually recursive body trace[Diverge.def] "# Generating the mut rec body" @@ -903,11 +952,11 @@ def divRecursion (preDefs : Array PreDefinition) : TermElabM Unit := do -- Generate the final definitions trace[Diverge.def] "# Generating the final definitions" - let decls ← mkDeclareFixDefs mutRecBody preDefs + let decls ← mkDeclareFixDefs mutRecBody inOutTys preDefs -- Prove the unfolding theorems trace[Diverge.def] "# Proving the unfolding theorems" - proveUnfoldingThms isValidThm preDefs decls + proveUnfoldingThms isValidThm inOutTys preDefs decls -- Generating code -- TODO addAndCompilePartialRec preDefs @@ -1102,6 +1151,15 @@ namespace Tests #check isCons.unfold + -- Testing what happens when we use concrete arguments in dependent tuples + divergent def test1 + (_ : Option Bool) (_ : Unit) : + Result Unit + := + test1 Option.none () + + #check test1.unfold + end Tests end Diverge diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index 1c1062c0..aaaea6f7 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -83,7 +83,10 @@ print_decl test1 print_decl test2 -- A map visitor function for expressions (adapted from `AbstractNestedProofs.visit`) -partial def mapVisit (k : Expr → MetaM Expr) (e : Expr) : MetaM Expr := do +-- The continuation takes as parameters: +-- - the current depth of the expression (useful for printing/debugging) +-- - the expression to explore +partial def mapVisit (k : Nat → Expr → MetaM Expr) (e : Expr) : MetaM Expr := do let mapVisitBinders (xs : Array Expr) (k2 : MetaM Expr) : MetaM Expr := do let localInstances ← getLocalInstances let mut lctx ← getLCtx @@ -98,25 +101,27 @@ partial def mapVisit (k : Expr → MetaM Expr) (e : Expr) : MetaM Expr := do lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl withLCtx lctx localInstances k2 -- TODO: use a cache? (Lean.checkCache) - -- Explore - let e ← k e - match e with - | .bvar _ - | .fvar _ - | .mvar _ - | .sort _ - | .lit _ - | .const _ _ => pure e - | .app .. => do e.withApp fun f args => return mkAppN f (← args.mapM (mapVisit k)) - | .lam .. => - lambdaLetTelescope e fun xs b => - mapVisitBinders xs do mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) - | .forallE .. => do - forallTelescope e fun xs b => mapVisitBinders xs do mkForallFVars xs (← mapVisit k b) - | .letE .. => do - lambdaLetTelescope e fun xs b => mapVisitBinders xs do - mkLambdaFVars xs (← mapVisit k b) (usedLetOnly := false) - | .mdata _ b => return e.updateMData! (← mapVisit k b) - | .proj _ _ b => return e.updateProj! (← mapVisit k b) + let rec visit (i : Nat) (e : Expr) : MetaM Expr := do + -- Explore + let e ← k i e + match e with + | .bvar _ + | .fvar _ + | .mvar _ + | .sort _ + | .lit _ + | .const _ _ => pure e + | .app .. => do e.withApp fun f args => return mkAppN f (← args.mapM (visit (i + 1))) + | .lam .. => + lambdaLetTelescope e fun xs b => + mapVisitBinders xs do mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) + | .forallE .. => do + forallTelescope e fun xs b => mapVisitBinders xs do mkForallFVars xs (← visit (i + 1) b) + | .letE .. => do + lambdaLetTelescope e fun xs b => mapVisitBinders xs do + mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) + | .mdata _ b => return e.updateMData! (← visit (i + 1) b) + | .proj _ _ b => return e.updateProj! (← visit (i + 1) b) + visit 0 e end Diverge diff --git a/backends/lean/lake-manifest.json b/backends/lean/lake-manifest.json index 40eb1682..f4759ad3 100644 --- a/backends/lean/lake-manifest.json +++ b/backends/lean/lake-manifest.json @@ -10,7 +10,7 @@ {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "4f103b3696795c62e76fb89d177efb91c29afdf5", + "rev": "cc5d11f24e1b92db65ec3389bb5142f4b2d7670e", "name": "mathlib", "inputRev?": null}}, {"git": diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json index ccd6d61a..637bda23 100644 --- a/tests/lean/lake-manifest.json +++ b/tests/lean/lake-manifest.json @@ -11,7 +11,7 @@ {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "409bee4eabf8072c4569950c3c2f310afd203abf", + "rev": "cc5d11f24e1b92db65ec3389bb5142f4b2d7670e", "name": "mathlib", "inputRev?": null}}, {"git": -- cgit v1.2.3 From 0a0445c72e005c328b4764f5fb0f8f38e7a55d60 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 5 Jul 2023 14:52:23 +0200 Subject: Start using namespaces in the Lean backend --- compiler/Config.ml | 7 + compiler/Extract.ml | 28 +- compiler/ExtractBase.ml | 4 +- compiler/Pure.ml | 10 +- compiler/Translate.ml | 80 ++-- tests/coq/betree/BetreeMain_Opaque.v | 2 +- tests/coq/hashmap_on_disk/HashmapMain_Opaque.v | 2 +- tests/coq/misc/External_Opaque.v | 2 +- tests/fstar/betree/BetreeMain.Opaque.fsti | 2 +- .../betree_back_stateful/BetreeMain.Opaque.fsti | 2 +- .../fstar/hashmap_on_disk/HashmapMain.Opaque.fsti | 2 +- tests/fstar/misc/External.Opaque.fsti | 2 +- tests/hol4/betree/betreeMain_OpaqueScript.sml | 2 +- .../hashmap_on_disk/hashmapMain_OpaqueScript.sml | 2 +- tests/hol4/misc-external/external_OpaqueScript.sml | 2 +- tests/lean/BetreeMain/ExternalFuns.lean | 9 - tests/lean/BetreeMain/Funs.lean | 498 ++++++++++----------- tests/lean/BetreeMain/FunsExternal.lean | 35 ++ tests/lean/BetreeMain/FunsExternal_Template.lean | 31 ++ tests/lean/BetreeMain/Opaque.lean | 35 -- tests/lean/BetreeMain/Types.lean | 5 +- tests/lean/Constants.lean | 9 +- tests/lean/External/ExternalFuns.lean | 9 - tests/lean/External/Funs.lean | 36 +- tests/lean/External/FunsExternal.lean | 33 ++ tests/lean/External/FunsExternal_Template.lean | 29 ++ tests/lean/External/Opaque.lean | 14 +- tests/lean/External/Types.lean | 5 +- tests/lean/Hashmap/Funs.lean | 192 ++++---- tests/lean/Hashmap/Types.lean | 5 +- tests/lean/HashmapMain/ExternalFuns.lean | 9 - tests/lean/HashmapMain/Funs.lean | 221 +++++---- tests/lean/HashmapMain/FunsExternal.lean | 17 + tests/lean/HashmapMain/FunsExternal_Template.lean | 16 + tests/lean/HashmapMain/Opaque.lean | 8 +- tests/lean/HashmapMain/Types.lean | 5 +- tests/lean/Loops/Funs.lean | 5 +- tests/lean/Loops/Types.lean | 5 +- tests/lean/NoNestedBorrows.lean | 5 +- tests/lean/Paper.lean | 5 +- tests/lean/PoloniusList.lean | 5 +- tests/lean/Tests.lean | 9 - tests/lean/lakefile.lean | 21 +- 43 files changed, 766 insertions(+), 659 deletions(-) delete mode 100644 tests/lean/BetreeMain/ExternalFuns.lean create mode 100644 tests/lean/BetreeMain/FunsExternal.lean create mode 100644 tests/lean/BetreeMain/FunsExternal_Template.lean delete mode 100644 tests/lean/BetreeMain/Opaque.lean delete mode 100644 tests/lean/External/ExternalFuns.lean create mode 100644 tests/lean/External/FunsExternal.lean create mode 100644 tests/lean/External/FunsExternal_Template.lean delete mode 100644 tests/lean/HashmapMain/ExternalFuns.lean create mode 100644 tests/lean/HashmapMain/FunsExternal.lean create mode 100644 tests/lean/HashmapMain/FunsExternal_Template.lean delete mode 100644 tests/lean/Tests.lean diff --git a/compiler/Config.ml b/compiler/Config.ml index bfb9d161..f58ba89b 100644 --- a/compiler/Config.ml +++ b/compiler/Config.ml @@ -297,3 +297,10 @@ let filter_useless_monadic_calls = ref true dynamically check for that). *) let filter_useless_functions = ref true + +(** Obsolete. TODO: remove. + + For Lean we used to parameterize the entire development by a section variable + called opaque_defs, of type OpaqueDefs. + *) +let wrap_opaque_in_sig = ref false diff --git a/compiler/Extract.ml b/compiler/Extract.ml index 7d00dd73..50215dac 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -625,13 +625,12 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) in prefix ^ tname ^ suffix in - let get_fun_name = get_name in - let fun_name_to_snake_case (fname : fun_name) : string = - let fname = get_fun_name fname in - (* Converting to snake case should be a no-op, but it doesn't cost much *) - let fname = List.map to_snake_case fname in - (* Concatenate the elements *) - String.concat "_" fname + let get_fun_name fname = + let fname = get_name fname in + (* TODO: don't convert to snake case for Coq, HOL4, F* *) + match !backend with + | FStar | Coq | HOL4 -> String.concat "_" (List.map to_snake_case fname) + | Lean -> String.concat "." fname in let global_name (name : global_name) : string = (* Converting to snake case also lowercases the letters (in Rust, global @@ -642,7 +641,7 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) let fun_name (fname : fun_name) (num_loops : int) (loop_id : LoopId.id option) (num_rgs : int) (rg : region_group_info option) (filter_info : bool * int) : string = - let fname = fun_name_to_snake_case fname in + let fname = get_fun_name fname in (* Compute the suffix *) let suffix = default_fun_suffix num_loops loop_id num_rgs rg filter_info in (* Concatenate *) @@ -651,7 +650,7 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) let termination_measure_name (_fid : A.FunDeclId.id) (fname : fun_name) (num_loops : int) (loop_id : LoopId.id option) : string = - let fname = fun_name_to_snake_case fname in + let fname = get_fun_name fname in let lp_suffix = default_fun_loop_suffix num_loops loop_id in (* Compute the suffix *) let suffix = @@ -666,7 +665,7 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) let decreases_proof_name (_fid : A.FunDeclId.id) (fname : fun_name) (num_loops : int) (loop_id : LoopId.id option) : string = - let fname = fun_name_to_snake_case fname in + let fname = get_fun_name fname in let lp_suffix = default_fun_loop_suffix num_loops loop_id in (* Compute the suffix *) let suffix = @@ -681,7 +680,7 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) let opaque_pre () = match !Config.backend with | FStar | Coq | HOL4 -> "" - | Lean -> "opaque_defs." + | Lean -> if !Config.wrap_opaque_in_sig then "opaque_defs." else "" in let var_basename (_varset : StringSet.t) (basename : string option) (ty : ty) @@ -2981,8 +2980,11 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) let use_forall = is_opaque_coq && def.signature.type_params <> [] in (* Print the qualifier ("assume", etc.). - For Lean: we generate a record of assumed functions *) - (if not (!backend = Lean && (kind = Assumed || kind = Declared)) then + if `wrap_opaque_in_sig`: we generate a record of assumed funcions. + TODO: this is obsolete. + *) + (if not (!Config.wrap_opaque_in_sig && (kind = Assumed || kind = Declared)) + then let qualif = ctx.fmt.fun_decl_kind_to_qualif kind in match qualif with | Some qualif -> diff --git a/compiler/ExtractBase.ml b/compiler/ExtractBase.ml index 14ce4119..feab7706 100644 --- a/compiler/ExtractBase.ml +++ b/compiler/ExtractBase.ml @@ -240,7 +240,9 @@ type formatter = { - loop identifier, if this is for a loop *) opaque_pre : unit -> string; - (** The prefix to use for opaque definitions. + (** TODO: obsolete, remove. + + The prefix to use for opaque definitions. We need this because for some backends like Lean and Coq, we group opaque definitions in module signatures, meaning that using those diff --git a/compiler/Pure.ml b/compiler/Pure.ml index 4a00dfb2..b251a005 100644 --- a/compiler/Pure.ml +++ b/compiler/Pure.ml @@ -18,16 +18,19 @@ module GlobalDeclId = A.GlobalDeclId (they monotonically increase across functions) while in {!module:Pure} we want the indices to start at 0 for every function. *) -module LoopId = IdGen () +module LoopId = +IdGen () type loop_id = LoopId.id [@@deriving show, ord] (** We give an identifier to every phase of the synthesis (forward, backward for group of regions 0, etc.) *) -module SynthPhaseId = IdGen () +module SynthPhaseId = +IdGen () (** Pay attention to the fact that we also define a {!E.VarId} module in Values *) -module VarId = IdGen () +module VarId = +IdGen () type integer_type = T.integer_type [@@deriving show, ord] @@ -723,6 +726,7 @@ type fun_sig_info = { *) type fun_sig = { type_params : type_var list; + (** TODO: we should analyse the signature to make the type parameters implicit whenever possible *) inputs : ty list; (** The input types. diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 5827b4a8..795674b4 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -750,18 +750,17 @@ let extract_definitions (fmt : Format.formatter) (config : gen_config) if config.extract_state_type && config.extract_fun_decls then export_state_type (); - (* For Lean, we parameterize the entire development by a section variable - called opaque_defs, of type OpaqueDefs. The code below emits the type - definition for OpaqueDefs, which is a structure, in which each field is one - of the functions marked as Opaque. We emit the `structure ...` bit here, - then rely on `extract_fun_decl` to be aware of this, and skip the keyword - (e.g. "axiom" or "val") so as to generate valid syntax for records. - - We also generate such a structure only if there actually are opaque - definitions. - *) + (* Obsolete: (TODO: remove) For Lean we parameterize the entire development by a section + variable called opaque_defs, of type OpaqueDefs. The code below emits the type + definition for OpaqueDefs, which is a structure, in which each field is one of the + functions marked as Opaque. We emit the `structure ...` bit here, then rely on + `extract_fun_decl` to be aware of this, and skip the keyword (e.g. "axiom" or "val") + so as to generate valid syntax for records. + + We also generate such a structure only if there actually are opaque definitions. *) let wrap_in_sig = - config.extract_opaque && config.extract_fun_decls && !Config.backend = Lean + config.extract_opaque && config.extract_fun_decls + && !Config.wrap_opaque_in_sig && let _, opaque_funs = module_has_opaque_decls ctx in opaque_funs @@ -785,6 +784,8 @@ let extract_definitions (fmt : Format.formatter) (config : gen_config) type extract_file_info = { filename : string; + namespace : string; + in_namespace : bool; crate_name : string; rust_module_name : string; module_name : string; @@ -852,9 +853,10 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (fi : extract_file_info) (* Add the custom includes *) List.iter (fun m -> Printf.fprintf out "import %s\n" m) fi.custom_includes; (* Always open the Primitives namespace *) - Printf.fprintf out "open Primitives\n\n"; - (* Open the namespace *) - Printf.fprintf out "namespace %s\n" fi.crate_name + Printf.fprintf out "open Primitives\n"; + (* If we are inside the namespace: declare it, otherwise: open it *) + if fi.in_namespace then Printf.fprintf out "namespace %s\n" fi.namespace + else Printf.fprintf out "open %s\n" fi.namespace | HOL4 -> Printf.fprintf out "open primitivesLib divDefLib\n"; (* Add the custom imports and includes *) @@ -884,7 +886,7 @@ let extract_file (config : gen_config) (ctx : gen_ctx) (fi : extract_file_info) (* Close the module *) (match !Config.backend with | FStar -> () - | Lean -> Printf.fprintf out "end %s\n" fi.crate_name + | Lean -> if fi.in_namespace then Printf.fprintf out "end %s\n" fi.namespace | HOL4 -> Printf.fprintf out "val _ = export_theory ()\n" | Coq -> Printf.fprintf out "End %s .\n" fi.module_name); @@ -986,7 +988,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : (* Open the output file *) (* First compute the filename by replacing the extension and converting the * case (rust module names are snake case) *) - let crate_name, extract_filebasename = + let namespace, crate_name, extract_filebasename = match Filename.chop_suffix_opt ~suffix:".llbc" filename with | None -> (* Note that we already checked the suffix upon opening the file *) @@ -1001,8 +1003,14 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : StringUtils.lowercase_first_letter crate_name else crate_name in + (* We use the raw crate name for the namespaces *) + let namespace = + match !Config.backend with + | FStar | Coq | HOL4 -> crate.name + | Lean -> crate.name + in (* Concatenate *) - (crate_name, Filename.concat dest_dir crate_name) + (namespace, crate_name, Filename.concat dest_dir crate_name) in (* Put the translated definitions in maps *) @@ -1134,6 +1142,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : (* Extract the types *) (* If there are opaque types, we extract in an interface *) + (* TODO: for Lean and Coq: generate a template file *) let types_filename_ext = match !Config.backend with | FStar -> if has_opaque_types then ".fsti" else ".fst" @@ -1157,6 +1166,8 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let file_info = { filename = types_filename; + namespace; + in_namespace = true; crate_name; rust_module_name = crate.A.name; module_name = types_module; @@ -1183,6 +1194,8 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let file_info = { filename = template_clauses_filename; + namespace; + in_namespace = true; crate_name; rust_module_name = crate.A.name; module_name = template_clauses_module; @@ -1196,20 +1209,25 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : (* Extract the opaque functions, if needed *) let opaque_funs_module = if has_opaque_funs then ( + (* In the case of Lean we generate a template file *) + let module_suffix, opaque_imported_suffix, custom_msg = + match !Config.backend with + | FStar | Coq | HOL4 -> + ("Opaque", "Opaque", ": external function declarations") + | Lean -> + ( "FunsExternal_Template", + "FunsExternal", + ": external functions.\n\ + -- This is a template file: rename it to \ + \"FunsExternal.lean\" and fill the holes." ) + in let opaque_filename = - extract_filebasename ^ file_delimiter ^ "Opaque" ^ opaque_ext + extract_filebasename ^ file_delimiter ^ module_suffix ^ opaque_ext in - let opaque_module = crate_name ^ module_delimiter ^ "Opaque" in + let opaque_module = crate_name ^ module_delimiter ^ module_suffix in let opaque_imported_module = - (* In the case of Lean, we declare an interface (a record) containing - the opaque definitions, and we leave it to the user to provide an - instance of this module. - - TODO: do the same for Coq. - TODO: do the same for the type definitions. - *) if !Config.backend = Lean then - crate_name ^ module_delimiter ^ "ExternalFuns" + crate_name ^ module_delimiter ^ opaque_imported_suffix else opaque_module in let opaque_config = @@ -1230,10 +1248,12 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let file_info = { filename = opaque_filename; + namespace; + in_namespace = false; crate_name; rust_module_name = crate.A.name; module_name = opaque_module; - custom_msg = ": opaque function definitions"; + custom_msg; custom_imports = []; custom_includes = [ types_module ]; } @@ -1266,6 +1286,8 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let file_info = { filename = fun_filename; + namespace; + in_namespace = true; crate_name; rust_module_name = crate.A.name; module_name = fun_module; @@ -1295,6 +1317,8 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : let file_info = { filename = extract_filebasename ^ ext; + namespace; + in_namespace = true; crate_name; rust_module_name = crate.A.name; module_name = crate_name; diff --git a/tests/coq/betree/BetreeMain_Opaque.v b/tests/coq/betree/BetreeMain_Opaque.v index 08ab530a..51321f56 100644 --- a/tests/coq/betree/BetreeMain_Opaque.v +++ b/tests/coq/betree/BetreeMain_Opaque.v @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [betree_main]: opaque function definitions *) +(** [betree_main]: external function declarations *) Require Import Primitives. Import Primitives. Require Import Coq.ZArith.ZArith. diff --git a/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v b/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v index 6152b94b..e1e7fe2b 100644 --- a/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v +++ b/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [hashmap_main]: opaque function definitions *) +(** [hashmap_main]: external function declarations *) Require Import Primitives. Import Primitives. Require Import Coq.ZArith.ZArith. diff --git a/tests/coq/misc/External_Opaque.v b/tests/coq/misc/External_Opaque.v index d60251e0..5ee65277 100644 --- a/tests/coq/misc/External_Opaque.v +++ b/tests/coq/misc/External_Opaque.v @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [external]: opaque function definitions *) +(** [external]: external function declarations *) Require Import Primitives. Import Primitives. Require Import Coq.ZArith.ZArith. diff --git a/tests/fstar/betree/BetreeMain.Opaque.fsti b/tests/fstar/betree/BetreeMain.Opaque.fsti index dc49601a..dfbd73d6 100644 --- a/tests/fstar/betree/BetreeMain.Opaque.fsti +++ b/tests/fstar/betree/BetreeMain.Opaque.fsti @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [betree_main]: opaque function definitions *) +(** [betree_main]: external function declarations *) module BetreeMain.Opaque open Primitives include BetreeMain.Types diff --git a/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti b/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti index dc49601a..dfbd73d6 100644 --- a/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti +++ b/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [betree_main]: opaque function definitions *) +(** [betree_main]: external function declarations *) module BetreeMain.Opaque open Primitives include BetreeMain.Types diff --git a/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti b/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti index 6e54ea10..6e6a0e2b 100644 --- a/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti +++ b/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [hashmap_main]: opaque function definitions *) +(** [hashmap_main]: external function declarations *) module HashmapMain.Opaque open Primitives include HashmapMain.Types diff --git a/tests/fstar/misc/External.Opaque.fsti b/tests/fstar/misc/External.Opaque.fsti index 7d86405a..356d5fc4 100644 --- a/tests/fstar/misc/External.Opaque.fsti +++ b/tests/fstar/misc/External.Opaque.fsti @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [external]: opaque function definitions *) +(** [external]: external function declarations *) module External.Opaque open Primitives include External.Types diff --git a/tests/hol4/betree/betreeMain_OpaqueScript.sml b/tests/hol4/betree/betreeMain_OpaqueScript.sml index a6f0cf15..10d67cca 100644 --- a/tests/hol4/betree/betreeMain_OpaqueScript.sml +++ b/tests/hol4/betree/betreeMain_OpaqueScript.sml @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [betree_main]: opaque function definitions *) +(** [betree_main]: external function declarations *) open primitivesLib divDefLib open betreeMain_TypesTheory diff --git a/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml b/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml index 5f6bcbb4..c38eca01 100644 --- a/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml +++ b/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [hashmap_main]: opaque function definitions *) +(** [hashmap_main]: external function declarations *) open primitivesLib divDefLib open hashmapMain_TypesTheory diff --git a/tests/hol4/misc-external/external_OpaqueScript.sml b/tests/hol4/misc-external/external_OpaqueScript.sml index e2fd281d..02efc2be 100644 --- a/tests/hol4/misc-external/external_OpaqueScript.sml +++ b/tests/hol4/misc-external/external_OpaqueScript.sml @@ -1,5 +1,5 @@ (** THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS *) -(** [external]: opaque function definitions *) +(** [external]: external function declarations *) open primitivesLib divDefLib open external_TypesTheory diff --git a/tests/lean/BetreeMain/ExternalFuns.lean b/tests/lean/BetreeMain/ExternalFuns.lean deleted file mode 100644 index 59beb514..00000000 --- a/tests/lean/BetreeMain/ExternalFuns.lean +++ /dev/null @@ -1,9 +0,0 @@ -import Base -import BetreeMain.Types -import BetreeMain.Opaque - -namespace BetreeMain - -def opaque_defs : OpaqueDefs := by sorry - -end BetreeMain diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index 2eb7fa1f..78e14146 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -2,59 +2,57 @@ -- [betree_main]: function definitions import Base import BetreeMain.Types -import BetreeMain.ExternalFuns +import BetreeMain.FunsExternal open Primitives - -namespace BetreeMain +namespace betree_main /- [betree_main::betree::load_internal_node] -/ -def betree_load_internal_node_fwd +def betree.load_internal_node_fwd (id : U64) (st : State) : Result (State × (betree_list_t (U64 × betree_message_t))) := - opaque_defs.betree_utils_load_internal_node_fwd id st + betree_utils.load_internal_node_fwd id st /- [betree_main::betree::store_internal_node] -/ -def betree_store_internal_node_fwd +def betree.store_internal_node_fwd (id : U64) (content : betree_list_t (U64 × betree_message_t)) (st : State) : Result (State × Unit) := do - let (st0, _) ← - opaque_defs.betree_utils_store_internal_node_fwd id content st + let (st0, _) ← betree_utils.store_internal_node_fwd id content st Result.ret (st0, ()) /- [betree_main::betree::load_leaf_node] -/ -def betree_load_leaf_node_fwd +def betree.load_leaf_node_fwd (id : U64) (st : State) : Result (State × (betree_list_t (U64 × U64))) := - opaque_defs.betree_utils_load_leaf_node_fwd id st + betree_utils.load_leaf_node_fwd id st /- [betree_main::betree::store_leaf_node] -/ -def betree_store_leaf_node_fwd +def betree.store_leaf_node_fwd (id : U64) (content : betree_list_t (U64 × U64)) (st : State) : Result (State × Unit) := do - let (st0, _) ← opaque_defs.betree_utils_store_leaf_node_fwd id content st + let (st0, _) ← betree_utils.store_leaf_node_fwd id content st Result.ret (st0, ()) /- [betree_main::betree::fresh_node_id] -/ -def betree_fresh_node_id_fwd (counter : U64) : Result U64 := +def betree.fresh_node_id_fwd (counter : U64) : Result U64 := do let _ ← counter + (U64.ofInt 1 (by intlit)) Result.ret counter /- [betree_main::betree::fresh_node_id] -/ -def betree_fresh_node_id_back (counter : U64) : Result U64 := +def betree.fresh_node_id_back (counter : U64) : Result U64 := counter + (U64.ofInt 1 (by intlit)) /- [betree_main::betree::NodeIdCounter::{0}::new] -/ -def betree_node_id_counter_new_fwd : Result betree_node_id_counter_t := +def betree.NodeIdCounter.new_fwd : Result betree_node_id_counter_t := Result.ret { betree_node_id_counter_next_node_id := (U64.ofInt 0 (by intlit)) } /- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ -def betree_node_id_counter_fresh_id_fwd +def betree.NodeIdCounter.fresh_id_fwd (self : betree_node_id_counter_t) : Result U64 := do let _ ← self.betree_node_id_counter_next_node_id + @@ -62,7 +60,7 @@ def betree_node_id_counter_fresh_id_fwd Result.ret self.betree_node_id_counter_next_node_id /- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ -def betree_node_id_counter_fresh_id_back +def betree.NodeIdCounter.fresh_id_back (self : betree_node_id_counter_t) : Result betree_node_id_counter_t := do let i ← self.betree_node_id_counter_next_node_id + @@ -75,7 +73,7 @@ def core_num_u64_max_body : Result U64 := def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) /- [betree_main::betree::upsert_update] -/ -def betree_upsert_update_fwd +def betree.upsert_update_fwd (prev : Option U64) (st : betree_upsert_fun_state_t) : Result U64 := match prev with | Option.none => @@ -96,17 +94,17 @@ def betree_upsert_update_fwd else Result.ret (U64.ofInt 0 (by intlit)) /- [betree_main::betree::List::{1}::len] -/ -divergent def betree_list_len_fwd +divergent def betree.List.len_fwd (T : Type) (self : betree_list_t T) : Result U64 := match self with | betree_list_t.Cons t tl => do - let i ← betree_list_len_fwd T tl + let i ← betree.List.len_fwd T tl (U64.ofInt 1 (by intlit)) + i | betree_list_t.Nil => Result.ret (U64.ofInt 0 (by intlit)) /- [betree_main::betree::List::{1}::split_at] -/ -divergent def betree_list_split_at_fwd +divergent def betree.List.split_at_fwd (T : Type) (self : betree_list_t T) (n : U64) : Result ((betree_list_t T) × (betree_list_t T)) := @@ -117,28 +115,28 @@ divergent def betree_list_split_at_fwd | betree_list_t.Cons hd tl => do let i ← n - (U64.ofInt 1 (by intlit)) - let p ← betree_list_split_at_fwd T tl i + let p ← betree.List.split_at_fwd T tl i let (ls0, ls1) := p let l := ls0 Result.ret (betree_list_t.Cons hd l, ls1) | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::push_front] -/ -def betree_list_push_front_fwd_back +def betree.List.push_front_fwd_back (T : Type) (self : betree_list_t T) (x : T) : Result (betree_list_t T) := let tl := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil let l := tl Result.ret (betree_list_t.Cons x l) /- [betree_main::betree::List::{1}::pop_front] -/ -def betree_list_pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := +def betree.List.pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil match ls with | betree_list_t.Cons x tl => Result.ret x | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::pop_front] -/ -def betree_list_pop_front_back +def betree.List.pop_front_back (T : Type) (self : betree_list_t T) : Result (betree_list_t T) := let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil match ls with @@ -146,13 +144,13 @@ def betree_list_pop_front_back | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::hd] -/ -def betree_list_hd_fwd (T : Type) (self : betree_list_t T) : Result T := +def betree.List.hd_fwd (T : Type) (self : betree_list_t T) : Result T := match self with | betree_list_t.Cons hd l => Result.ret hd | betree_list_t.Nil => Result.fail Error.panic /- [betree_main::betree::List::{2}::head_has_key] -/ -def betree_list_head_has_key_fwd +def betree.List.head_has_key_fwd (T : Type) (self : betree_list_t (U64 × T)) (key : U64) : Result Bool := match self with | betree_list_t.Cons hd l => let (i, _) := hd @@ -160,7 +158,7 @@ def betree_list_head_has_key_fwd | betree_list_t.Nil => Result.ret false /- [betree_main::betree::List::{2}::partition_at_pivot] -/ -divergent def betree_list_partition_at_pivot_fwd +divergent def betree.List.partition_at_pivot_fwd (T : Type) (self : betree_list_t (U64 × T)) (pivot : U64) : Result ((betree_list_t (U64 × T)) × (betree_list_t (U64 × T))) := @@ -171,14 +169,14 @@ divergent def betree_list_partition_at_pivot_fwd then Result.ret (betree_list_t.Nil, betree_list_t.Cons (i, t) tl) else do - let p ← betree_list_partition_at_pivot_fwd T tl pivot + let p ← betree.List.partition_at_pivot_fwd T tl pivot let (ls0, ls1) := p let l := ls0 Result.ret (betree_list_t.Cons (i, t) l, ls1) | betree_list_t.Nil => Result.ret (betree_list_t.Nil, betree_list_t.Nil) /- [betree_main::betree::Leaf::{3}::split] -/ -def betree_leaf_split_fwd +def betree.Leaf.split_fwd (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (st : State) : @@ -186,16 +184,16 @@ def betree_leaf_split_fwd := do let p ← - betree_list_split_at_fwd (U64 × U64) content + betree.List.split_at_fwd (U64 × U64) content params.betree_params_split_size let (content0, content1) := p - let p0 ← betree_list_hd_fwd (U64 × U64) content1 + let p0 ← betree.List.hd_fwd (U64 × U64) content1 let (pivot, _) := p0 - let id0 ← betree_node_id_counter_fresh_id_fwd node_id_cnt - let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt - let id1 ← betree_node_id_counter_fresh_id_fwd node_id_cnt0 - let (st0, _) ← betree_store_leaf_node_fwd id0 content0 st - let (st1, _) ← betree_store_leaf_node_fwd id1 content1 st0 + let id0 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt + let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt + let id1 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt0 + let (st0, _) ← betree.store_leaf_node_fwd id0 content0 st + let (st1, _) ← betree.store_leaf_node_fwd id1 content1 st0 let n := betree_node_t.Leaf { betree_leaf_id := id0, @@ -209,7 +207,7 @@ def betree_leaf_split_fwd Result.ret (st1, betree_internal_t.mk self.betree_leaf_id pivot n n0) /- [betree_main::betree::Leaf::{3}::split] -/ -def betree_leaf_split_back +def betree.Leaf.split_back (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (st : State) : @@ -217,19 +215,19 @@ def betree_leaf_split_back := do let p ← - betree_list_split_at_fwd (U64 × U64) content + betree.List.split_at_fwd (U64 × U64) content params.betree_params_split_size let (content0, content1) := p - let _ ← betree_list_hd_fwd (U64 × U64) content1 - let id0 ← betree_node_id_counter_fresh_id_fwd node_id_cnt - let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt - let id1 ← betree_node_id_counter_fresh_id_fwd node_id_cnt0 - let (st0, _) ← betree_store_leaf_node_fwd id0 content0 st - let _ ← betree_store_leaf_node_fwd id1 content1 st0 - betree_node_id_counter_fresh_id_back node_id_cnt0 + let _ ← betree.List.hd_fwd (U64 × U64) content1 + let id0 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt + let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt + let id1 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt0 + let (st0, _) ← betree.store_leaf_node_fwd id0 content0 st + let _ ← betree.store_leaf_node_fwd id1 content1 st0 + betree.NodeIdCounter.fresh_id_back node_id_cnt0 /- [betree_main::betree::Node::{5}::lookup_in_bindings] -/ -divergent def betree_node_lookup_in_bindings_fwd +divergent def betree.Node.lookup_in_bindings_fwd (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (Option U64) := match bindings with | betree_list_t.Cons hd tl => @@ -239,11 +237,11 @@ divergent def betree_node_lookup_in_bindings_fwd else if i > key then Result.ret Option.none - else betree_node_lookup_in_bindings_fwd key tl + else betree.Node.lookup_in_bindings_fwd key tl | betree_list_t.Nil => Result.ret Option.none /- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ -divergent def betree_node_lookup_first_message_for_key_fwd +divergent def betree.Node.lookup_first_message_for_key_fwd (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := @@ -252,11 +250,11 @@ divergent def betree_node_lookup_first_message_for_key_fwd let (i, m) := x if i >= key then Result.ret (betree_list_t.Cons (i, m) next_msgs) - else betree_node_lookup_first_message_for_key_fwd key next_msgs + else betree.Node.lookup_first_message_for_key_fwd key next_msgs | betree_list_t.Nil => Result.ret betree_list_t.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ -divergent def betree_node_lookup_first_message_for_key_back +divergent def betree.Node.lookup_first_message_for_key_back (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) (ret0 : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) @@ -269,70 +267,70 @@ divergent def betree_node_lookup_first_message_for_key_back else do let next_msgs0 ← - betree_node_lookup_first_message_for_key_back key next_msgs ret0 + betree.Node.lookup_first_message_for_key_back key next_msgs ret0 Result.ret (betree_list_t.Cons (i, m) next_msgs0) | betree_list_t.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_upserts] -/ -divergent def betree_node_apply_upserts_fwd +divergent def betree.Node.apply_upserts_fwd (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) (key : U64) (st : State) : Result (State × U64) := do - let b ← betree_list_head_has_key_fwd betree_message_t msgs key + let b ← betree.List.head_has_key_fwd betree_message_t msgs key if b then do - let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs + let msg ← betree.List.pop_front_fwd (U64 × betree_message_t) msgs let (_, m) := msg match m with | betree_message_t.Insert i => Result.fail Error.panic | betree_message_t.Delete => Result.fail Error.panic | betree_message_t.Upsert s => do - let v ← betree_upsert_update_fwd prev s + let v ← betree.upsert_update_fwd prev s let msgs0 ← - betree_list_pop_front_back (U64 × betree_message_t) msgs - betree_node_apply_upserts_fwd msgs0 (Option.some v) key st + betree.List.pop_front_back (U64 × betree_message_t) msgs + betree.Node.apply_upserts_fwd msgs0 (Option.some v) key st else do - let (st0, v) ← opaque_defs.core_option_option_unwrap_fwd U64 prev st + let (st0, v) ← core.option.Option.unwrap_fwd U64 prev st let _ ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs (key, + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs (key, betree_message_t.Insert v) Result.ret (st0, v) /- [betree_main::betree::Node::{5}::apply_upserts] -/ -divergent def betree_node_apply_upserts_back +divergent def betree.Node.apply_upserts_back (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) (key : U64) (st : State) : Result (betree_list_t (U64 × betree_message_t)) := do - let b ← betree_list_head_has_key_fwd betree_message_t msgs key + let b ← betree.List.head_has_key_fwd betree_message_t msgs key if b then do - let msg ← betree_list_pop_front_fwd (U64 × betree_message_t) msgs + let msg ← betree.List.pop_front_fwd (U64 × betree_message_t) msgs let (_, m) := msg match m with | betree_message_t.Insert i => Result.fail Error.panic | betree_message_t.Delete => Result.fail Error.panic | betree_message_t.Upsert s => do - let v ← betree_upsert_update_fwd prev s + let v ← betree.upsert_update_fwd prev s let msgs0 ← - betree_list_pop_front_back (U64 × betree_message_t) msgs - betree_node_apply_upserts_back msgs0 (Option.some v) key st + betree.List.pop_front_back (U64 × betree_message_t) msgs + betree.Node.apply_upserts_back msgs0 (Option.some v) key st else do - let (_, v) ← opaque_defs.core_option_option_unwrap_fwd U64 prev st - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs (key, + let (_, v) ← core.option.Option.unwrap_fwd U64 prev st + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs (key, betree_message_t.Insert v) /- [betree_main::betree::Node::{5}::lookup] -/ -mutual divergent def betree_node_lookup_fwd +mutual divergent def betree.Node.lookup_fwd (self : betree_node_t) (key : U64) (st : State) : Result (State × (Option U64)) := @@ -340,8 +338,8 @@ mutual divergent def betree_node_lookup_fwd | betree_node_t.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, msgs) ← betree_load_internal_node_fwd i st - let pending ← betree_node_lookup_first_message_for_key_fwd key msgs + let (st0, msgs) ← betree.load_internal_node_fwd i st + let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs match pending with | betree_list_t.Cons p l => let (k, msg) := p @@ -349,10 +347,10 @@ mutual divergent def betree_node_lookup_fwd then do let (st1, opt) ← - betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 + betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, msg) l) Result.ret (st1, opt) else @@ -360,58 +358,58 @@ mutual divergent def betree_node_lookup_fwd | betree_message_t.Insert v => do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Insert v) l) Result.ret (st0, Option.some v) | betree_message_t.Delete => do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Delete) l) Result.ret (st0, Option.none) | betree_message_t.Upsert ufs => do let (st1, v) ← - betree_internal_lookup_in_children_fwd (betree_internal_t.mk i + betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let (st2, v0) ← - betree_node_apply_upserts_fwd (betree_list_t.Cons (k, + betree.Node.apply_upserts_fwd (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let node0 ← - betree_internal_lookup_in_children_back (betree_internal_t.mk i + betree.Internal.lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 let ⟨ i1, _, _, _ ⟩ := node0 let pending0 ← - betree_node_apply_upserts_back (betree_list_t.Cons (k, + betree.Node.apply_upserts_back (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let msgs0 ← - betree_node_lookup_first_message_for_key_back key msgs pending0 - let (st3, _) ← betree_store_internal_node_fwd i1 msgs0 st2 + betree.Node.lookup_first_message_for_key_back key msgs pending0 + let (st3, _) ← betree.store_internal_node_fwd i1 msgs0 st2 Result.ret (st3, Option.some v0) | betree_list_t.Nil => do let (st1, opt) ← - betree_internal_lookup_in_children_fwd (betree_internal_t.mk i i0 n + betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs betree_list_t.Nil Result.ret (st1, opt) | betree_node_t.Leaf node => do - let (st0, bindings) ← betree_load_leaf_node_fwd node.betree_leaf_id st - let opt ← betree_node_lookup_in_bindings_fwd key bindings + let (st0, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st + let opt ← betree.Node.lookup_in_bindings_fwd key bindings Result.ret (st0, opt) /- [betree_main::betree::Node::{5}::lookup] -/ -divergent def betree_node_lookup_back +divergent def betree.Node.lookup_back (self : betree_node_t) (key : U64) (st : State) : Result betree_node_t := match self with | betree_node_t.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, msgs) ← betree_load_internal_node_fwd i st - let pending ← betree_node_lookup_first_message_for_key_fwd key msgs + let (st0, msgs) ← betree.load_internal_node_fwd i st + let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs match pending with | betree_list_t.Cons p l => let (k, msg) := p @@ -419,10 +417,10 @@ divergent def betree_node_lookup_back then do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, msg) l) let node0 ← - betree_internal_lookup_in_children_back (betree_internal_t.mk i + betree.Internal.lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 Result.ret (betree_node_t.Internal node0) else @@ -430,64 +428,64 @@ divergent def betree_node_lookup_back | betree_message_t.Insert v => do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Insert v) l) Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0)) | betree_message_t.Delete => do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs (betree_list_t.Cons (k, betree_message_t.Delete) l) Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0)) | betree_message_t.Upsert ufs => do let (st1, v) ← - betree_internal_lookup_in_children_fwd (betree_internal_t.mk i + betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 n n0) key st0 let (st2, _) ← - betree_node_apply_upserts_fwd (betree_list_t.Cons (k, + betree.Node.apply_upserts_fwd (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let node0 ← - betree_internal_lookup_in_children_back (betree_internal_t.mk i + betree.Internal.lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 let ⟨ i1, i2, n1, n2 ⟩ := node0 let pending0 ← - betree_node_apply_upserts_back (betree_list_t.Cons (k, + betree.Node.apply_upserts_back (betree_list_t.Cons (k, betree_message_t.Upsert ufs) l) v key st1 let msgs0 ← - betree_node_lookup_first_message_for_key_back key msgs pending0 - let _ ← betree_store_internal_node_fwd i1 msgs0 st2 + betree.Node.lookup_first_message_for_key_back key msgs pending0 + let _ ← betree.store_internal_node_fwd i1 msgs0 st2 Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 n2)) | betree_list_t.Nil => do let _ ← - betree_node_lookup_first_message_for_key_back key msgs + betree.Node.lookup_first_message_for_key_back key msgs betree_list_t.Nil let node0 ← - betree_internal_lookup_in_children_back (betree_internal_t.mk i i0 + betree.Internal.lookup_in_children_back (betree_internal_t.mk i i0 n n0) key st0 Result.ret (betree_node_t.Internal node0) | betree_node_t.Leaf node => do - let (_, bindings) ← betree_load_leaf_node_fwd node.betree_leaf_id st - let _ ← betree_node_lookup_in_bindings_fwd key bindings + let (_, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st + let _ ← betree.Node.lookup_in_bindings_fwd key bindings Result.ret (betree_node_t.Leaf node) /- [betree_main::betree::Internal::{4}::lookup_in_children] -/ -divergent def betree_internal_lookup_in_children_fwd +divergent def betree.Internal.lookup_in_children_fwd (self : betree_internal_t) (key : U64) (st : State) : Result (State × (Option U64)) := let ⟨ _, i, n, n0 ⟩ := self if key < i - then betree_node_lookup_fwd n key st - else betree_node_lookup_fwd n0 key st + then betree.Node.lookup_fwd n key st + else betree.Node.lookup_fwd n0 key st /- [betree_main::betree::Internal::{4}::lookup_in_children] -/ -divergent def betree_internal_lookup_in_children_back +divergent def betree.Internal.lookup_in_children_back (self : betree_internal_t) (key : U64) (st : State) : Result betree_internal_t := @@ -495,17 +493,17 @@ divergent def betree_internal_lookup_in_children_back if key < i0 then do - let n1 ← betree_node_lookup_back n key st + let n1 ← betree.Node.lookup_back n key st Result.ret (betree_internal_t.mk i i0 n1 n0) else do - let n1 ← betree_node_lookup_back n0 key st + let n1 ← betree.Node.lookup_back n0 key st Result.ret (betree_internal_t.mk i i0 n n1) end /- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ -divergent def betree_node_lookup_mut_in_bindings_fwd +divergent def betree.Node.lookup_mut_in_bindings_fwd (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (betree_list_t (U64 × U64)) := @@ -514,11 +512,11 @@ divergent def betree_node_lookup_mut_in_bindings_fwd let (i, i0) := hd if i >= key then Result.ret (betree_list_t.Cons (i, i0) tl) - else betree_node_lookup_mut_in_bindings_fwd key tl + else betree.Node.lookup_mut_in_bindings_fwd key tl | betree_list_t.Nil => Result.ret betree_list_t.Nil /- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ -divergent def betree_node_lookup_mut_in_bindings_back +divergent def betree.Node.lookup_mut_in_bindings_back (key : U64) (bindings : betree_list_t (U64 × U64)) (ret0 : betree_list_t (U64 × U64)) : Result (betree_list_t (U64 × U64)) @@ -530,60 +528,60 @@ divergent def betree_node_lookup_mut_in_bindings_back then Result.ret ret0 else do - let tl0 ← betree_node_lookup_mut_in_bindings_back key tl ret0 + let tl0 ← betree.Node.lookup_mut_in_bindings_back key tl ret0 Result.ret (betree_list_t.Cons (i, i0) tl0) | betree_list_t.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_to_leaf] -/ -def betree_node_apply_to_leaf_fwd_back +def betree.Node.apply_to_leaf_fwd_back (bindings : betree_list_t (U64 × U64)) (key : U64) (new_msg : betree_message_t) : Result (betree_list_t (U64 × U64)) := do - let bindings0 ← betree_node_lookup_mut_in_bindings_fwd key bindings - let b ← betree_list_head_has_key_fwd U64 bindings0 key + let bindings0 ← betree.Node.lookup_mut_in_bindings_fwd key bindings + let b ← betree.List.head_has_key_fwd U64 bindings0 key if b then do - let hd ← betree_list_pop_front_fwd (U64 × U64) bindings0 + let hd ← betree.List.pop_front_fwd (U64 × U64) bindings0 match new_msg with | betree_message_t.Insert v => do - let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 + let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 let bindings2 ← - betree_list_push_front_fwd_back (U64 × U64) bindings1 (key, v) - betree_node_lookup_mut_in_bindings_back key bindings bindings2 + betree.List.push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree.Node.lookup_mut_in_bindings_back key bindings bindings2 | betree_message_t.Delete => do - let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 - betree_node_lookup_mut_in_bindings_back key bindings bindings1 + let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 + betree.Node.lookup_mut_in_bindings_back key bindings bindings1 | betree_message_t.Upsert s => do let (_, i) := hd - let v ← betree_upsert_update_fwd (Option.some i) s - let bindings1 ← betree_list_pop_front_back (U64 × U64) bindings0 + let v ← betree.upsert_update_fwd (Option.some i) s + let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 let bindings2 ← - betree_list_push_front_fwd_back (U64 × U64) bindings1 (key, v) - betree_node_lookup_mut_in_bindings_back key bindings bindings2 + betree.List.push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree.Node.lookup_mut_in_bindings_back key bindings bindings2 else match new_msg with | betree_message_t.Insert v => do let bindings1 ← - betree_list_push_front_fwd_back (U64 × U64) bindings0 (key, v) - betree_node_lookup_mut_in_bindings_back key bindings bindings1 + betree.List.push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree.Node.lookup_mut_in_bindings_back key bindings bindings1 | betree_message_t.Delete => - betree_node_lookup_mut_in_bindings_back key bindings bindings0 + betree.Node.lookup_mut_in_bindings_back key bindings bindings0 | betree_message_t.Upsert s => do - let v ← betree_upsert_update_fwd Option.none s + let v ← betree.upsert_update_fwd Option.none s let bindings1 ← - betree_list_push_front_fwd_back (U64 × U64) bindings0 (key, v) - betree_node_lookup_mut_in_bindings_back key bindings bindings1 + betree.List.push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree.Node.lookup_mut_in_bindings_back key bindings bindings1 /- [betree_main::betree::Node::{5}::apply_messages_to_leaf] -/ -divergent def betree_node_apply_messages_to_leaf_fwd_back +divergent def betree.Node.apply_messages_to_leaf_fwd_back (bindings : betree_list_t (U64 × U64)) (new_msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × U64)) @@ -592,12 +590,12 @@ divergent def betree_node_apply_messages_to_leaf_fwd_back | betree_list_t.Cons new_msg new_msgs_tl => do let (i, m) := new_msg - let bindings0 ← betree_node_apply_to_leaf_fwd_back bindings i m - betree_node_apply_messages_to_leaf_fwd_back bindings0 new_msgs_tl + let bindings0 ← betree.Node.apply_to_leaf_fwd_back bindings i m + betree.Node.apply_messages_to_leaf_fwd_back bindings0 new_msgs_tl | betree_list_t.Nil => Result.ret bindings /- [betree_main::betree::Node::{5}::filter_messages_for_key] -/ -divergent def betree_node_filter_messages_for_key_fwd_back +divergent def betree.Node.filter_messages_for_key_fwd_back (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := @@ -608,14 +606,14 @@ divergent def betree_node_filter_messages_for_key_fwd_back then do let msgs0 ← - betree_list_pop_front_back (U64 × betree_message_t) + betree.List.pop_front_back (U64 × betree_message_t) (betree_list_t.Cons (k, m) l) - betree_node_filter_messages_for_key_fwd_back key msgs0 + betree.Node.filter_messages_for_key_fwd_back key msgs0 else Result.ret (betree_list_t.Cons (k, m) l) | betree_list_t.Nil => Result.ret betree_list_t.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ -divergent def betree_node_lookup_first_message_after_key_fwd +divergent def betree.Node.lookup_first_message_after_key_fwd (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) := @@ -623,12 +621,12 @@ divergent def betree_node_lookup_first_message_after_key_fwd | betree_list_t.Cons p next_msgs => let (k, m) := p if k = key - then betree_node_lookup_first_message_after_key_fwd key next_msgs + then betree.Node.lookup_first_message_after_key_fwd key next_msgs else Result.ret (betree_list_t.Cons (k, m) next_msgs) | betree_list_t.Nil => Result.ret betree_list_t.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ -divergent def betree_node_lookup_first_message_after_key_back +divergent def betree.Node.lookup_first_message_after_key_back (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) (ret0 : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) @@ -640,79 +638,79 @@ divergent def betree_node_lookup_first_message_after_key_back then do let next_msgs0 ← - betree_node_lookup_first_message_after_key_back key next_msgs ret0 + betree.Node.lookup_first_message_after_key_back key next_msgs ret0 Result.ret (betree_list_t.Cons (k, m) next_msgs0) else Result.ret ret0 | betree_list_t.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_to_internal] -/ -def betree_node_apply_to_internal_fwd_back +def betree.Node.apply_to_internal_fwd_back (msgs : betree_list_t (U64 × betree_message_t)) (key : U64) (new_msg : betree_message_t) : Result (betree_list_t (U64 × betree_message_t)) := do - let msgs0 ← betree_node_lookup_first_message_for_key_fwd key msgs - let b ← betree_list_head_has_key_fwd betree_message_t msgs0 key + let msgs0 ← betree.Node.lookup_first_message_for_key_fwd key msgs + let b ← betree.List.head_has_key_fwd betree_message_t msgs0 key if b then match new_msg with | betree_message_t.Insert i => do - let msgs1 ← betree_node_filter_messages_for_key_fwd_back key msgs0 + let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 let msgs2 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 (key, betree_message_t.Insert i) - betree_node_lookup_first_message_for_key_back key msgs msgs2 + betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree_message_t.Delete => do - let msgs1 ← betree_node_filter_messages_for_key_fwd_back key msgs0 + let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 let msgs2 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 (key, betree_message_t.Delete) - betree_node_lookup_first_message_for_key_back key msgs msgs2 + betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree_message_t.Upsert s => do - let p ← betree_list_hd_fwd (U64 × betree_message_t) msgs0 + let p ← betree.List.hd_fwd (U64 × betree_message_t) msgs0 let (_, m) := p match m with | betree_message_t.Insert prev => do - let v ← betree_upsert_update_fwd (Option.some prev) s + let v ← betree.upsert_update_fwd (Option.some prev) s let msgs1 ← - betree_list_pop_front_back (U64 × betree_message_t) msgs0 + betree.List.pop_front_back (U64 × betree_message_t) msgs0 let msgs2 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 (key, betree_message_t.Insert v) - betree_node_lookup_first_message_for_key_back key msgs msgs2 + betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree_message_t.Delete => do - let v ← betree_upsert_update_fwd Option.none s + let v ← betree.upsert_update_fwd Option.none s let msgs1 ← - betree_list_pop_front_back (U64 × betree_message_t) msgs0 + betree.List.pop_front_back (U64 × betree_message_t) msgs0 let msgs2 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 (key, betree_message_t.Insert v) - betree_node_lookup_first_message_for_key_back key msgs msgs2 + betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree_message_t.Upsert ufs => do let msgs1 ← - betree_node_lookup_first_message_after_key_fwd key msgs0 + betree.Node.lookup_first_message_after_key_fwd key msgs0 let msgs2 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs1 + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 (key, betree_message_t.Upsert s) let msgs3 ← - betree_node_lookup_first_message_after_key_back key msgs0 msgs2 - betree_node_lookup_first_message_for_key_back key msgs msgs3 + betree.Node.lookup_first_message_after_key_back key msgs0 msgs2 + betree.Node.lookup_first_message_for_key_back key msgs msgs3 else do let msgs1 ← - betree_list_push_front_fwd_back (U64 × betree_message_t) msgs0 (key, + betree.List.push_front_fwd_back (U64 × betree_message_t) msgs0 (key, new_msg) - betree_node_lookup_first_message_for_key_back key msgs msgs1 + betree.Node.lookup_first_message_for_key_back key msgs msgs1 /- [betree_main::betree::Node::{5}::apply_messages_to_internal] -/ -divergent def betree_node_apply_messages_to_internal_fwd_back +divergent def betree.Node.apply_messages_to_internal_fwd_back (msgs : betree_list_t (U64 × betree_message_t)) (new_msgs : betree_list_t (U64 × betree_message_t)) : Result (betree_list_t (U64 × betree_message_t)) @@ -721,12 +719,12 @@ divergent def betree_node_apply_messages_to_internal_fwd_back | betree_list_t.Cons new_msg new_msgs_tl => do let (i, m) := new_msg - let msgs0 ← betree_node_apply_to_internal_fwd_back msgs i m - betree_node_apply_messages_to_internal_fwd_back msgs0 new_msgs_tl + let msgs0 ← betree.Node.apply_to_internal_fwd_back msgs i m + betree.Node.apply_messages_to_internal_fwd_back msgs0 new_msgs_tl | betree_list_t.Nil => Result.ret msgs /- [betree_main::betree::Node::{5}::apply_messages] -/ -mutual divergent def betree_node_apply_messages_fwd +mutual divergent def betree.Node.apply_messages_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : @@ -736,49 +734,49 @@ mutual divergent def betree_node_apply_messages_fwd | betree_node_t.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, content) ← betree_load_internal_node_fwd i st + let (st0, content) ← betree.load_internal_node_fwd i st let content0 ← - betree_node_apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree_list_len_fwd (U64 × betree_message_t) content0 + betree.Node.apply_messages_to_internal_fwd_back content msgs + let num_msgs ← betree.List.len_fwd (U64 × betree_message_t) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree_internal_flush_fwd (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_fwd (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, _) ← - betree_internal_flush_back (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_back (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, _, _, _ ⟩ := node0 - let (st2, _) ← betree_store_internal_node_fwd i1 content1 st1 + let (st2, _) ← betree.store_internal_node_fwd i1 content1 st1 Result.ret (st2, ()) else do - let (st1, _) ← betree_store_internal_node_fwd i content0 st0 + let (st1, _) ← betree.store_internal_node_fwd i content0 st0 Result.ret (st1, ()) | betree_node_t.Leaf node => do - let (st0, content) ← betree_load_leaf_node_fwd node.betree_leaf_id st - let content0 ← betree_node_apply_messages_to_leaf_fwd_back content msgs - let len ← betree_list_len_fwd (U64 × U64) content0 + let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st + let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs + let len ← betree.List.len_fwd (U64 × U64) content0 let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size if len >= i then do let (st1, _) ← - betree_leaf_split_fwd node content0 params node_id_cnt st0 + betree.Leaf.split_fwd node content0 params node_id_cnt st0 let (st2, _) ← - betree_store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil + betree.store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil st1 Result.ret (st2, ()) else do let (st1, _) ← - betree_store_leaf_node_fwd node.betree_leaf_id content0 st0 + betree.store_leaf_node_fwd node.betree_leaf_id content0 st0 Result.ret (st1, ()) /- [betree_main::betree::Node::{5}::apply_messages] -/ -divergent def betree_node_apply_messages_back +divergent def betree.Node.apply_messages_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : @@ -788,53 +786,53 @@ divergent def betree_node_apply_messages_back | betree_node_t.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, content) ← betree_load_internal_node_fwd i st + let (st0, content) ← betree.load_internal_node_fwd i st let content0 ← - betree_node_apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree_list_len_fwd (U64 × betree_message_t) content0 + betree.Node.apply_messages_to_internal_fwd_back content msgs + let num_msgs ← betree.List.len_fwd (U64 × betree_message_t) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree_internal_flush_fwd (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_fwd (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, node_id_cnt0) ← - betree_internal_flush_back (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_back (betree_internal_t.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, i2, n1, n2 ⟩ := node0 - let _ ← betree_store_internal_node_fwd i1 content1 st1 + let _ ← betree.store_internal_node_fwd i1 content1 st1 Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 n2), node_id_cnt0) else do - let _ ← betree_store_internal_node_fwd i content0 st0 + let _ ← betree.store_internal_node_fwd i content0 st0 Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0), node_id_cnt) | betree_node_t.Leaf node => do - let (st0, content) ← betree_load_leaf_node_fwd node.betree_leaf_id st - let content0 ← betree_node_apply_messages_to_leaf_fwd_back content msgs - let len ← betree_list_len_fwd (U64 × U64) content0 + let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st + let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs + let len ← betree.List.len_fwd (U64 × U64) content0 let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size if len >= i then do let (st1, new_node) ← - betree_leaf_split_fwd node content0 params node_id_cnt st0 + betree.Leaf.split_fwd node content0 params node_id_cnt st0 let _ ← - betree_store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil + betree.store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil st1 let node_id_cnt0 ← - betree_leaf_split_back node content0 params node_id_cnt st0 + betree.Leaf.split_back node content0 params node_id_cnt st0 Result.ret (betree_node_t.Internal new_node, node_id_cnt0) else do - let _ ← betree_store_leaf_node_fwd node.betree_leaf_id content0 st0 + let _ ← betree.store_leaf_node_fwd node.betree_leaf_id content0 st0 Result.ret (betree_node_t.Leaf { node with betree_leaf_size := len }, node_id_cnt) /- [betree_main::betree::Internal::{4}::flush] -/ -divergent def betree_internal_flush_fwd +divergent def betree.Internal.flush_fwd (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (content : betree_list_t (U64 × betree_message_t)) (st : State) : @@ -842,39 +840,39 @@ divergent def betree_internal_flush_fwd := do let ⟨ _, i, n, n0 ⟩ := self - let p ← betree_list_partition_at_pivot_fwd betree_message_t content i + let p ← betree.List.partition_at_pivot_fwd betree_message_t content i let (msgs_left, msgs_right) := p - let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left + let len_left ← betree.List.len_fwd (U64 × betree_message_t) msgs_left if len_left >= params.betree_params_min_flush_size then do let (st0, _) ← - betree_node_apply_messages_fwd n params node_id_cnt msgs_left st + betree.Node.apply_messages_fwd n params node_id_cnt msgs_left st let (_, node_id_cnt0) ← - betree_node_apply_messages_back n params node_id_cnt msgs_left st + betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← - betree_list_len_fwd (U64 × betree_message_t) msgs_right + betree.List.len_fwd (U64 × betree_message_t) msgs_right if len_right >= params.betree_params_min_flush_size then do let (st1, _) ← - betree_node_apply_messages_fwd n0 params node_id_cnt0 msgs_right + betree.Node.apply_messages_fwd n0 params node_id_cnt0 msgs_right st0 let _ ← - betree_node_apply_messages_back n0 params node_id_cnt0 msgs_right + betree.Node.apply_messages_back n0 params node_id_cnt0 msgs_right st0 Result.ret (st1, betree_list_t.Nil) else Result.ret (st0, msgs_right) else do let (st0, _) ← - betree_node_apply_messages_fwd n0 params node_id_cnt msgs_right st + betree.Node.apply_messages_fwd n0 params node_id_cnt msgs_right st let _ ← - betree_node_apply_messages_back n0 params node_id_cnt msgs_right st + betree.Node.apply_messages_back n0 params node_id_cnt msgs_right st Result.ret (st0, msgs_left) /- [betree_main::betree::Internal::{4}::flush] -/ -divergent def betree_internal_flush_back +divergent def betree.Internal.flush_back (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (content : betree_list_t (U64 × betree_message_t)) (st : State) : @@ -882,36 +880,36 @@ divergent def betree_internal_flush_back := do let ⟨ i, i0, n, n0 ⟩ := self - let p ← betree_list_partition_at_pivot_fwd betree_message_t content i0 + let p ← betree.List.partition_at_pivot_fwd betree_message_t content i0 let (msgs_left, msgs_right) := p - let len_left ← betree_list_len_fwd (U64 × betree_message_t) msgs_left + let len_left ← betree.List.len_fwd (U64 × betree_message_t) msgs_left if len_left >= params.betree_params_min_flush_size then do let (st0, _) ← - betree_node_apply_messages_fwd n params node_id_cnt msgs_left st + betree.Node.apply_messages_fwd n params node_id_cnt msgs_left st let (n1, node_id_cnt0) ← - betree_node_apply_messages_back n params node_id_cnt msgs_left st + betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← - betree_list_len_fwd (U64 × betree_message_t) msgs_right + betree.List.len_fwd (U64 × betree_message_t) msgs_right if len_right >= params.betree_params_min_flush_size then do let (n2, node_id_cnt1) ← - betree_node_apply_messages_back n0 params node_id_cnt0 msgs_right + betree.Node.apply_messages_back n0 params node_id_cnt0 msgs_right st0 Result.ret (betree_internal_t.mk i i0 n1 n2, node_id_cnt1) else Result.ret (betree_internal_t.mk i i0 n1 n0, node_id_cnt0) else do let (n1, node_id_cnt0) ← - betree_node_apply_messages_back n0 params node_id_cnt msgs_right st + betree.Node.apply_messages_back n0 params node_id_cnt msgs_right st Result.ret (betree_internal_t.mk i i0 n n1, node_id_cnt0) end /- [betree_main::betree::Node::{5}::apply] -/ -def betree_node_apply_fwd +def betree.Node.apply_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : U64) (new_msg : betree_message_t) (st : State) : @@ -920,34 +918,34 @@ def betree_node_apply_fwd do let l := betree_list_t.Nil let (st0, _) ← - betree_node_apply_messages_fwd self params node_id_cnt + betree.Node.apply_messages_fwd self params node_id_cnt (betree_list_t.Cons (key, new_msg) l) st let _ ← - betree_node_apply_messages_back self params node_id_cnt + betree.Node.apply_messages_back self params node_id_cnt (betree_list_t.Cons (key, new_msg) l) st Result.ret (st0, ()) /- [betree_main::betree::Node::{5}::apply] -/ -def betree_node_apply_back +def betree.Node.apply_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : U64) (new_msg : betree_message_t) (st : State) : Result (betree_node_t × betree_node_id_counter_t) := let l := betree_list_t.Nil - betree_node_apply_messages_back self params node_id_cnt (betree_list_t.Cons + betree.Node.apply_messages_back self params node_id_cnt (betree_list_t.Cons (key, new_msg) l) st /- [betree_main::betree::BeTree::{6}::new] -/ -def betree_be_tree_new_fwd +def betree.BeTree.new_fwd (min_flush_size : U64) (split_size : U64) (st : State) : Result (State × betree_be_tree_t) := do - let node_id_cnt ← betree_node_id_counter_new_fwd - let id ← betree_node_id_counter_fresh_id_fwd node_id_cnt - let (st0, _) ← betree_store_leaf_node_fwd id betree_list_t.Nil st - let node_id_cnt0 ← betree_node_id_counter_fresh_id_back node_id_cnt + let node_id_cnt ← betree.NodeIdCounter.new_fwd + let id ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt + let (st0, _) ← betree.store_leaf_node_fwd id betree_list_t.Nil st + let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt Result.ret (st0, { betree_be_tree_params := @@ -965,103 +963,103 @@ def betree_be_tree_new_fwd }) /- [betree_main::betree::BeTree::{6}::apply] -/ -def betree_be_tree_apply_fwd +def betree.BeTree.apply_fwd (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree_node_apply_fwd self.betree_be_tree_root self.betree_be_tree_params + betree.Node.apply_fwd self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st let _ ← - betree_node_apply_back self.betree_be_tree_root + betree.Node.apply_back self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::apply] -/ -def betree_be_tree_apply_back +def betree.BeTree.apply_back (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : Result betree_be_tree_t := do let (n, nic) ← - betree_node_apply_back self.betree_be_tree_root + betree.Node.apply_back self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st Result.ret { self with betree_be_tree_node_id_cnt := nic, betree_be_tree_root := n } /- [betree_main::betree::BeTree::{6}::insert] -/ -def betree_be_tree_insert_fwd +def betree.BeTree.insert_fwd (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree_be_tree_apply_fwd self key (betree_message_t.Insert value) st + betree.BeTree.apply_fwd self key (betree_message_t.Insert value) st let _ ← - betree_be_tree_apply_back self key (betree_message_t.Insert value) st + betree.BeTree.apply_back self key (betree_message_t.Insert value) st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::insert] -/ -def betree_be_tree_insert_back +def betree.BeTree.insert_back (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : Result betree_be_tree_t := - betree_be_tree_apply_back self key (betree_message_t.Insert value) st + betree.BeTree.apply_back self key (betree_message_t.Insert value) st /- [betree_main::betree::BeTree::{6}::delete] -/ -def betree_be_tree_delete_fwd +def betree.BeTree.delete_fwd (self : betree_be_tree_t) (key : U64) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree_be_tree_apply_fwd self key betree_message_t.Delete st - let _ ← betree_be_tree_apply_back self key betree_message_t.Delete st + betree.BeTree.apply_fwd self key betree_message_t.Delete st + let _ ← betree.BeTree.apply_back self key betree_message_t.Delete st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::delete] -/ -def betree_be_tree_delete_back +def betree.BeTree.delete_back (self : betree_be_tree_t) (key : U64) (st : State) : Result betree_be_tree_t := - betree_be_tree_apply_back self key betree_message_t.Delete st + betree.BeTree.apply_back self key betree_message_t.Delete st /- [betree_main::betree::BeTree::{6}::upsert] -/ -def betree_be_tree_upsert_fwd +def betree.BeTree.upsert_fwd (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree_be_tree_apply_fwd self key (betree_message_t.Upsert upd) st + betree.BeTree.apply_fwd self key (betree_message_t.Upsert upd) st let _ ← - betree_be_tree_apply_back self key (betree_message_t.Upsert upd) st + betree.BeTree.apply_back self key (betree_message_t.Upsert upd) st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::upsert] -/ -def betree_be_tree_upsert_back +def betree.BeTree.upsert_back (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) (st : State) : Result betree_be_tree_t := - betree_be_tree_apply_back self key (betree_message_t.Upsert upd) st + betree.BeTree.apply_back self key (betree_message_t.Upsert upd) st /- [betree_main::betree::BeTree::{6}::lookup] -/ -def betree_be_tree_lookup_fwd +def betree.BeTree.lookup_fwd (self : betree_be_tree_t) (key : U64) (st : State) : Result (State × (Option U64)) := - betree_node_lookup_fwd self.betree_be_tree_root key st + betree.Node.lookup_fwd self.betree_be_tree_root key st /- [betree_main::betree::BeTree::{6}::lookup] -/ -def betree_be_tree_lookup_back +def betree.BeTree.lookup_back (self : betree_be_tree_t) (key : U64) (st : State) : Result betree_be_tree_t := do - let n ← betree_node_lookup_back self.betree_be_tree_root key st + let n ← betree.Node.lookup_back self.betree_be_tree_root key st Result.ret { self with betree_be_tree_root := n } /- [betree_main::main] -/ @@ -1071,4 +1069,4 @@ def main_fwd : Result Unit := /- Unit test for [betree_main::main] -/ #assert (main_fwd == .ret ()) -end BetreeMain +end betree_main diff --git a/tests/lean/BetreeMain/FunsExternal.lean b/tests/lean/BetreeMain/FunsExternal.lean new file mode 100644 index 00000000..0c715ef9 --- /dev/null +++ b/tests/lean/BetreeMain/FunsExternal.lean @@ -0,0 +1,35 @@ +-- [betree_main]: external functions. +import Base +import BetreeMain.Types +open Primitives +open betree_main + +-- TODO: fill those bodies + +/- [betree_main::betree_utils::load_internal_node] -/ +def betree_utils.load_internal_node_fwd + : + U64 → State → Result (State × (betree_list_t (U64 × betree_message_t))) := + fun _ _ => .fail .panic + +/- [betree_main::betree_utils::store_internal_node] -/ +def betree_utils.store_internal_node_fwd + : + U64 → betree_list_t (U64 × betree_message_t) → State → Result (State + × Unit) := + fun _ _ _ => .fail .panic + +/- [betree_main::betree_utils::load_leaf_node] -/ +def betree_utils.load_leaf_node_fwd + : U64 → State → Result (State × (betree_list_t (U64 × U64))) := + fun _ _ => .fail .panic + +/- [betree_main::betree_utils::store_leaf_node] -/ +def betree_utils.store_leaf_node_fwd + : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) := + fun _ _ _ => .fail .panic + +/- [core::option::Option::{0}::unwrap] -/ +def core.option.Option.unwrap_fwd + (T : Type) : Option T → State → Result (State × T) := + fun _ _ => .fail .panic diff --git a/tests/lean/BetreeMain/FunsExternal_Template.lean b/tests/lean/BetreeMain/FunsExternal_Template.lean new file mode 100644 index 00000000..9b5a54e5 --- /dev/null +++ b/tests/lean/BetreeMain/FunsExternal_Template.lean @@ -0,0 +1,31 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [betree_main]: external functions. +-- This is a template file: rename it to "FunsExternal.lean" and fill the holes. +import Base +import BetreeMain.Types +open Primitives +open betree_main + +/- [betree_main::betree_utils::load_internal_node] -/ +axiom betree_utils.load_internal_node_fwd + : + U64 → State → Result (State × (betree_list_t (U64 × betree_message_t))) + +/- [betree_main::betree_utils::store_internal_node] -/ +axiom betree_utils.store_internal_node_fwd + : + U64 → betree_list_t (U64 × betree_message_t) → State → Result (State + × Unit) + +/- [betree_main::betree_utils::load_leaf_node] -/ +axiom betree_utils.load_leaf_node_fwd + : U64 → State → Result (State × (betree_list_t (U64 × U64))) + +/- [betree_main::betree_utils::store_leaf_node] -/ +axiom betree_utils.store_leaf_node_fwd + : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) + +/- [core::option::Option::{0}::unwrap] -/ +axiom core.option.Option.unwrap_fwd + (T : Type) : Option T → State → Result (State × T) + diff --git a/tests/lean/BetreeMain/Opaque.lean b/tests/lean/BetreeMain/Opaque.lean deleted file mode 100644 index d043186b..00000000 --- a/tests/lean/BetreeMain/Opaque.lean +++ /dev/null @@ -1,35 +0,0 @@ --- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS --- [betree_main]: opaque function definitions -import Base -import BetreeMain.Types -open Primitives - -namespace BetreeMain - -structure OpaqueDefs where - - /- [betree_main::betree_utils::load_internal_node] -/ - betree_utils_load_internal_node_fwd - : - U64 → State → Result (State × (betree_list_t (U64 × - betree_message_t))) - - /- [betree_main::betree_utils::store_internal_node] -/ - betree_utils_store_internal_node_fwd - : - U64 → betree_list_t (U64 × betree_message_t) → State → Result (State - × Unit) - - /- [betree_main::betree_utils::load_leaf_node] -/ - betree_utils_load_leaf_node_fwd - : U64 → State → Result (State × (betree_list_t (U64 × U64))) - - /- [betree_main::betree_utils::store_leaf_node] -/ - betree_utils_store_leaf_node_fwd - : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) - - /- [core::option::Option::{0}::unwrap] -/ - core_option_option_unwrap_fwd - (T : Type) : Option T → State → Result (State × T) - -end BetreeMain diff --git a/tests/lean/BetreeMain/Types.lean b/tests/lean/BetreeMain/Types.lean index cfed6a28..3ecbd668 100644 --- a/tests/lean/BetreeMain/Types.lean +++ b/tests/lean/BetreeMain/Types.lean @@ -2,8 +2,7 @@ -- [betree_main]: type definitions import Base open Primitives - -namespace BetreeMain +namespace betree_main /- [betree_main::betree::List] -/ inductive betree_list_t (T : Type) := @@ -57,4 +56,4 @@ structure betree_be_tree_t where /- The state type used in the state-error monad -/ axiom State : Type -end BetreeMain +end betree_main diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index 9f6a47de..39c270be 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -2,8 +2,7 @@ -- [constants] import Base open Primitives - -namespace Constants +namespace constants /- [constants::X0] -/ def x0_body : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) @@ -69,11 +68,11 @@ structure wrap_t (T : Type) where wrap_val : T /- [constants::Wrap::{0}::new] -/ -def wrap_new_fwd (T : Type) (val : T) : Result (wrap_t T) := +def Wrap.new_fwd (T : Type) (val : T) : Result (wrap_t T) := Result.ret { wrap_val := val } /- [constants::Y] -/ -def y_body : Result (wrap_t I32) := wrap_new_fwd I32 (I32.ofInt 2 (by intlit)) +def y_body : Result (wrap_t I32) := Wrap.new_fwd I32 (I32.ofInt 2 (by intlit)) def y_c : wrap_t I32 := eval_global y_body (by simp) /- [constants::unwrap_y] -/ @@ -132,4 +131,4 @@ def s4_body : Result (pair_t U32 U32) := mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) def s4_c : pair_t U32 U32 := eval_global s4_body (by simp) -end Constants +end constants diff --git a/tests/lean/External/ExternalFuns.lean b/tests/lean/External/ExternalFuns.lean deleted file mode 100644 index d63db2ac..00000000 --- a/tests/lean/External/ExternalFuns.lean +++ /dev/null @@ -1,9 +0,0 @@ -import Base -import External.Types -import External.Opaque - -namespace External - -def opaque_defs : OpaqueDefs := sorry - -end External diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index e36987e0..6bfffc33 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -2,18 +2,17 @@ -- [external]: function definitions import Base import External.Types -import External.ExternalFuns +import External.FunsExternal open Primitives - -namespace External +namespace external /- [external::swap] -/ def swap_fwd (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := do - let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st1, _) ← opaque_defs.core_mem_swap_back0 T x y st st0 - let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 + let (st0, _) ← core.mem.swap_fwd T x y st + let (st1, _) ← core.mem.swap_back0 T x y st st0 + let (st2, _) ← core.mem.swap_back1 T x y st st1 Result.ret (st2, ()) /- [external::swap] -/ @@ -22,18 +21,17 @@ def swap_back Result (State × (T × T)) := do - let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st2, x0) ← opaque_defs.core_mem_swap_back0 T x y st st1 - let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 + let (st1, _) ← core.mem.swap_fwd T x y st + let (st2, x0) ← core.mem.swap_back0 T x y st st1 + let (_, y0) ← core.mem.swap_back1 T x y st st2 Result.ret (st0, (x0, y0)) /- [external::test_new_non_zero_u32] -/ def test_new_non_zero_u32_fwd (x : U32) (st : State) : Result (State × core_num_nonzero_non_zero_u32_t) := do - let (st0, opt) ← opaque_defs.core_num_nonzero_non_zero_u32_new_fwd x st - opaque_defs.core_option_option_unwrap_fwd core_num_nonzero_non_zero_u32_t - opt st0 + let (st0, opt) ← core.num.nonzero.NonZeroU32.new_fwd x st + core.option.Option.unwrap_fwd core_num_nonzero_non_zero_u32_t opt st0 /- [external::test_vec] -/ def test_vec_fwd : Result Unit := @@ -49,9 +47,9 @@ def test_vec_fwd : Result Unit := def custom_swap_fwd (T : Type) (x : T) (y : T) (st : State) : Result (State × T) := do - let (st0, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st1, x0) ← opaque_defs.core_mem_swap_back0 T x y st st0 - let (st2, _) ← opaque_defs.core_mem_swap_back1 T x y st st1 + let (st0, _) ← core.mem.swap_fwd T x y st + let (st1, x0) ← core.mem.swap_back0 T x y st st0 + let (st2, _) ← core.mem.swap_back1 T x y st st1 Result.ret (st2, x0) /- [external::custom_swap] -/ @@ -60,9 +58,9 @@ def custom_swap_back Result (State × (T × T)) := do - let (st1, _) ← opaque_defs.core_mem_swap_fwd T x y st - let (st2, _) ← opaque_defs.core_mem_swap_back0 T x y st st1 - let (_, y0) ← opaque_defs.core_mem_swap_back1 T x y st st2 + let (st1, _) ← core.mem.swap_fwd T x y st + let (st2, _) ← core.mem.swap_back0 T x y st st1 + let (_, y0) ← core.mem.swap_back1 T x y st st2 Result.ret (st0, (ret0, y0)) /- [external::test_custom_swap] -/ @@ -88,4 +86,4 @@ def test_swap_non_zero_fwd (x : U32) (st : State) : Result (State × U32) := then Result.fail Error.panic else Result.ret (st1, x0) -end External +end external diff --git a/tests/lean/External/FunsExternal.lean b/tests/lean/External/FunsExternal.lean new file mode 100644 index 00000000..5326dd77 --- /dev/null +++ b/tests/lean/External/FunsExternal.lean @@ -0,0 +1,33 @@ +-- [external]: templates for the external functions. +import Base +import External.Types +open Primitives +open external + +-- TODO: fill those bodies + +/- [core::mem::swap] -/ +def core.mem.swap_fwd + (T : Type) : T → T → State → Result (State × Unit) := + fun _x _y s => .ret (s, ()) + +/- [core::mem::swap] -/ +def core.mem.swap_back0 + (T : Type) : T → T → State → State → Result (State × T) := + fun _x y _s0 s1 => .ret (s1, y) + +/- [core::mem::swap] -/ +def core.mem.swap_back1 + (T : Type) : T → T → State → State → Result (State × T) := + fun x _y _s0 s1 => .ret (s1, x) + +/- [core::num::nonzero::NonZeroU32::{14}::new] -/ +def core.num.nonzero.NonZeroU32.new_fwd + : + U32 → State → Result (State × (Option core_num_nonzero_non_zero_u32_t)) := + fun _ _ => .fail .panic + +/- [core::option::Option::{0}::unwrap] -/ +def core.option.Option.unwrap_fwd + (T : Type) : Option T → State → Result (State × T) := + fun _ _ => .fail .panic diff --git a/tests/lean/External/FunsExternal_Template.lean b/tests/lean/External/FunsExternal_Template.lean new file mode 100644 index 00000000..d6c0eb1d --- /dev/null +++ b/tests/lean/External/FunsExternal_Template.lean @@ -0,0 +1,29 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [external]: external functions. +-- This is a template file: rename it to "FunsExternal.lean" and fill the holes. +import Base +import External.Types +open Primitives +open external + +/- [core::mem::swap] -/ +axiom core.mem.swap_fwd + (T : Type) : T → T → State → Result (State × Unit) + +/- [core::mem::swap] -/ +axiom core.mem.swap_back0 + (T : Type) : T → T → State → State → Result (State × T) + +/- [core::mem::swap] -/ +axiom core.mem.swap_back1 + (T : Type) : T → T → State → State → Result (State × T) + +/- [core::num::nonzero::NonZeroU32::{14}::new] -/ +axiom core.num.nonzero.NonZeroU32.new_fwd + : + U32 → State → Result (State × (Option core_num_nonzero_non_zero_u32_t)) + +/- [core::option::Option::{0}::unwrap] -/ +axiom core.option.Option.unwrap_fwd + (T : Type) : Option T → State → Result (State × T) + diff --git a/tests/lean/External/Opaque.lean b/tests/lean/External/Opaque.lean index 1c0db095..d0297523 100644 --- a/tests/lean/External/Opaque.lean +++ b/tests/lean/External/Opaque.lean @@ -4,29 +4,29 @@ import Base import External.Types open Primitives -namespace External +namespace external structure OpaqueDefs where /- [core::mem::swap] -/ - core_mem_swap_fwd (T : Type) : T → T → State → Result (State × Unit) + core.mem.swap_fwd (T : Type) : T → T → State → Result (State × Unit) /- [core::mem::swap] -/ - core_mem_swap_back0 + core.mem.swap_back0 (T : Type) : T → T → State → State → Result (State × T) /- [core::mem::swap] -/ - core_mem_swap_back1 + core.mem.swap_back1 (T : Type) : T → T → State → State → Result (State × T) /- [core::num::nonzero::NonZeroU32::{14}::new] -/ - core_num_nonzero_non_zero_u32_new_fwd + core.num.nonzero.NonZeroU32.new_fwd : U32 → State → Result (State × (Option core_num_nonzero_non_zero_u32_t)) /- [core::option::Option::{0}::unwrap] -/ - core_option_option_unwrap_fwd + core.option.Option.unwrap_fwd (T : Type) : Option T → State → Result (State × T) -end External +end external diff --git a/tests/lean/External/Types.lean b/tests/lean/External/Types.lean index fda0670e..316f6474 100644 --- a/tests/lean/External/Types.lean +++ b/tests/lean/External/Types.lean @@ -2,8 +2,7 @@ -- [external]: type definitions import Base open Primitives - -namespace External +namespace external /- [core::num::nonzero::NonZeroU32] -/ axiom core_num_nonzero_non_zero_u32_t : Type @@ -11,4 +10,4 @@ axiom core_num_nonzero_non_zero_u32_t : Type /- The state type used in the state-error monad -/ axiom State : Type -end External +end external diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index b4254726..8f54eca8 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -3,38 +3,37 @@ import Base import Hashmap.Types open Primitives - -namespace Hashmap +namespace hashmap /- [hashmap::hash_key] -/ def hash_key_fwd (k : Usize) : Result Usize := Result.ret k /- [hashmap::HashMap::{0}::allocate_slots] -/ -divergent def hash_map_allocate_slots_loop_fwd +divergent def HashMap.allocate_slots_loop_fwd (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := if n > (Usize.ofInt 0 (by intlit)) then do let slots0 ← vec_push_back (list_t T) slots list_t.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) - hash_map_allocate_slots_loop_fwd T slots0 n0 + HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots /- [hashmap::HashMap::{0}::allocate_slots] -/ -def hash_map_allocate_slots_fwd +def HashMap.allocate_slots_fwd (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := - hash_map_allocate_slots_loop_fwd T slots n + HashMap.allocate_slots_loop_fwd T slots n /- [hashmap::HashMap::{0}::new_with_capacity] -/ -def hash_map_new_with_capacity_fwd +def HashMap.new_with_capacity_fwd (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : Result (hash_map_t T) := do let v := vec_new (list_t T) - let slots ← hash_map_allocate_slots_fwd T v capacity + let slots ← HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor Result.ret @@ -46,12 +45,12 @@ def hash_map_new_with_capacity_fwd } /- [hashmap::HashMap::{0}::new] -/ -def hash_map_new_fwd (T : Type) : Result (hash_map_t T) := - hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) +def HashMap.new_fwd (T : Type) : Result (hash_map_t T) := + HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) /- [hashmap::HashMap::{0}::clear] -/ -divergent def hash_map_clear_loop_fwd_back +divergent def HashMap.clear_loop_fwd_back (T : Type) (slots : Vec (list_t T)) (i : Usize) : Result (Vec (list_t T)) := let i0 := vec_len (list_t T) slots if i < i0 @@ -59,15 +58,15 @@ divergent def hash_map_clear_loop_fwd_back do let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← vec_index_mut_back (list_t T) slots i list_t.Nil - hash_map_clear_loop_fwd_back T slots0 i1 + HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots /- [hashmap::HashMap::{0}::clear] -/ -def hash_map_clear_fwd_back +def HashMap.clear_fwd_back (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := do let v ← - hash_map_clear_loop_fwd_back T self.hash_map_slots + HashMap.clear_loop_fwd_back T self.hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -78,26 +77,26 @@ def hash_map_clear_fwd_back } /- [hashmap::HashMap::{0}::len] -/ -def hash_map_len_fwd (T : Type) (self : hash_map_t T) : Result Usize := +def HashMap.len_fwd (T : Type) (self : hash_map_t T) : Result Usize := Result.ret self.hash_map_num_entries /- [hashmap::HashMap::{0}::insert_in_list] -/ -divergent def hash_map_insert_in_list_loop_fwd +divergent def HashMap.insert_in_list_loop_fwd (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret false - else hash_map_insert_in_list_loop_fwd T key value tl + else HashMap.insert_in_list_loop_fwd T key value tl | list_t.Nil => Result.ret true /- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_fwd +def HashMap.insert_in_list_fwd (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := - hash_map_insert_in_list_loop_fwd T key value ls + HashMap.insert_in_list_loop_fwd T key value ls /- [hashmap::HashMap::{0}::insert_in_list] -/ -divergent def hash_map_insert_in_list_loop_back +divergent def HashMap.insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := match ls with | list_t.Cons ckey cvalue tl => @@ -105,18 +104,18 @@ divergent def hash_map_insert_in_list_loop_back then Result.ret (list_t.Cons ckey value tl) else do - let tl0 ← hash_map_insert_in_list_loop_back T key value tl + let tl0 ← HashMap.insert_in_list_loop_back T key value tl Result.ret (list_t.Cons ckey cvalue tl0) | list_t.Nil => let l := list_t.Nil Result.ret (list_t.Cons key value l) /- [hashmap::HashMap::{0}::insert_in_list] -/ -def hash_map_insert_in_list_back +def HashMap.insert_in_list_back (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := - hash_map_insert_in_list_loop_back T key value ls + HashMap.insert_in_list_loop_back T key value ls /- [hashmap::HashMap::{0}::insert_no_resize] -/ -def hash_map_insert_no_resize_fwd_back +def HashMap.insert_no_resize_fwd_back (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : Result (hash_map_t T) := @@ -125,18 +124,18 @@ def hash_map_insert_no_resize_fwd_back let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let inserted ← hash_map_insert_in_list_fwd T key value l + let inserted ← HashMap.insert_in_list_fwd T key value l if inserted then do let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) - let l0 ← hash_map_insert_in_list_back T key value l + let l0 ← HashMap.insert_in_list_back T key value l let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } else do - let l0 ← hash_map_insert_in_list_back T key value l + let l0 ← HashMap.insert_in_list_back T key value l let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } @@ -146,22 +145,22 @@ def core_num_u32_max_body : Result U32 := def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap::HashMap::{0}::move_elements_from_list] -/ -divergent def hash_map_move_elements_from_list_loop_fwd_back +divergent def HashMap.move_elements_from_list_loop_fwd_back (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := match ls with | list_t.Cons k v tl => do - let ntable0 ← hash_map_insert_no_resize_fwd_back T ntable k v - hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl + let ntable0 ← HashMap.insert_no_resize_fwd_back T ntable k v + HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl | list_t.Nil => Result.ret ntable /- [hashmap::HashMap::{0}::move_elements_from_list] -/ -def hash_map_move_elements_from_list_fwd_back +def HashMap.move_elements_from_list_fwd_back (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := - hash_map_move_elements_from_list_loop_fwd_back T ntable ls + HashMap.move_elements_from_list_loop_fwd_back T ntable ls /- [hashmap::HashMap::{0}::move_elements] -/ -divergent def hash_map_move_elements_loop_fwd_back +divergent def HashMap.move_elements_loop_fwd_back (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : Result ((hash_map_t T) × (Vec (list_t T))) := @@ -171,22 +170,22 @@ divergent def hash_map_move_elements_loop_fwd_back do let l ← vec_index_mut_fwd (list_t T) slots i let ls := mem_replace_fwd (list_t T) l list_t.Nil - let ntable0 ← hash_map_move_elements_from_list_fwd_back T ntable ls + let ntable0 ← HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) let l0 := mem_replace_back (list_t T) l list_t.Nil let slots0 ← vec_index_mut_back (list_t T) slots i l0 - hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 + HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) /- [hashmap::HashMap::{0}::move_elements] -/ -def hash_map_move_elements_fwd_back +def HashMap.move_elements_fwd_back (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : Result ((hash_map_t T) × (Vec (list_t T))) := - hash_map_move_elements_loop_fwd_back T ntable slots i + HashMap.move_elements_loop_fwd_back T ntable slots i /- [hashmap::HashMap::{0}::try_resize] -/ -def hash_map_try_resize_fwd_back +def HashMap.try_resize_fwd_back (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c @@ -198,9 +197,9 @@ def hash_map_try_resize_fwd_back then do let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← hash_map_new_with_capacity_fwd T i2 i i0 + let ntable ← HashMap.new_with_capacity_fwd T i2 i i0 let (ntable0, _) ← - hash_map_move_elements_fwd_back T ntable self.hash_map_slots + HashMap.move_elements_fwd_back T ntable self.hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -212,84 +211,84 @@ def hash_map_try_resize_fwd_back else Result.ret { self with hash_map_max_load_factor := (i, i0) } /- [hashmap::HashMap::{0}::insert] -/ -def hash_map_insert_fwd_back +def HashMap.insert_fwd_back (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : Result (hash_map_t T) := do - let self0 ← hash_map_insert_no_resize_fwd_back T self key value - let i ← hash_map_len_fwd T self0 + let self0 ← HashMap.insert_no_resize_fwd_back T self key value + let i ← HashMap.len_fwd T self0 if i > self0.hash_map_max_load - then hash_map_try_resize_fwd_back T self0 + then HashMap.try_resize_fwd_back T self0 else Result.ret self0 /- [hashmap::HashMap::{0}::contains_key_in_list] -/ -divergent def hash_map_contains_key_in_list_loop_fwd +divergent def HashMap.contains_key_in_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result Bool := match ls with | list_t.Cons ckey t tl => if ckey = key then Result.ret true - else hash_map_contains_key_in_list_loop_fwd T key tl + else HashMap.contains_key_in_list_loop_fwd T key tl | list_t.Nil => Result.ret false /- [hashmap::HashMap::{0}::contains_key_in_list] -/ -def hash_map_contains_key_in_list_fwd +def HashMap.contains_key_in_list_fwd (T : Type) (key : Usize) (ls : list_t T) : Result Bool := - hash_map_contains_key_in_list_loop_fwd T key ls + HashMap.contains_key_in_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::contains_key] -/ -def hash_map_contains_key_fwd +def HashMap.contains_key_fwd (T : Type) (self : hash_map_t T) (key : Usize) : Result Bool := do let hash ← hash_key_fwd key let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_contains_key_in_list_fwd T key l + HashMap.contains_key_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_in_list] -/ -divergent def hash_map_get_in_list_loop_fwd +divergent def HashMap.get_in_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result T := match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hash_map_get_in_list_loop_fwd T key tl + else HashMap.get_in_list_loop_fwd T key tl | list_t.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_in_list] -/ -def hash_map_get_in_list_fwd +def HashMap.get_in_list_fwd (T : Type) (key : Usize) (ls : list_t T) : Result T := - hash_map_get_in_list_loop_fwd T key ls + HashMap.get_in_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::get] -/ -def hash_map_get_fwd +def HashMap.get_fwd (T : Type) (self : hash_map_t T) (key : Usize) : Result T := do let hash ← hash_key_fwd key let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_get_in_list_fwd T key l + HashMap.get_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def hash_map_get_mut_in_list_loop_fwd +divergent def HashMap.get_mut_in_list_loop_fwd (T : Type) (ls : list_t T) (key : Usize) : Result T := match ls with | list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hash_map_get_mut_in_list_loop_fwd T tl key + else HashMap.get_mut_in_list_loop_fwd T tl key | list_t.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_fwd +def HashMap.get_mut_in_list_fwd (T : Type) (ls : list_t T) (key : Usize) : Result T := - hash_map_get_mut_in_list_loop_fwd T ls key + HashMap.get_mut_in_list_loop_fwd T ls key /- [hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def hash_map_get_mut_in_list_loop_back +divergent def HashMap.get_mut_in_list_loop_back (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := match ls with | list_t.Cons ckey cvalue tl => @@ -297,27 +296,27 @@ divergent def hash_map_get_mut_in_list_loop_back then Result.ret (list_t.Cons ckey ret0 tl) else do - let tl0 ← hash_map_get_mut_in_list_loop_back T tl key ret0 + let tl0 ← HashMap.get_mut_in_list_loop_back T tl key ret0 Result.ret (list_t.Cons ckey cvalue tl0) | list_t.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def hash_map_get_mut_in_list_back +def HashMap.get_mut_in_list_back (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := - hash_map_get_mut_in_list_loop_back T ls key ret0 + HashMap.get_mut_in_list_loop_back T ls key ret0 /- [hashmap::HashMap::{0}::get_mut] -/ -def hash_map_get_mut_fwd +def HashMap.get_mut_fwd (T : Type) (self : hash_map_t T) (key : Usize) : Result T := do let hash ← hash_key_fwd key let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - hash_map_get_mut_in_list_fwd T l key + HashMap.get_mut_in_list_fwd T l key /- [hashmap::HashMap::{0}::get_mut] -/ -def hash_map_get_mut_back +def HashMap.get_mut_back (T : Type) (self : hash_map_t T) (key : Usize) (ret0 : T) : Result (hash_map_t T) := @@ -326,12 +325,12 @@ def hash_map_get_mut_back let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let l0 ← hash_map_get_mut_in_list_back T l key ret0 + let l0 ← HashMap.get_mut_in_list_back T l key ret0 let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } /- [hashmap::HashMap::{0}::remove_from_list] -/ -divergent def hash_map_remove_from_list_loop_fwd +divergent def HashMap.remove_from_list_loop_fwd (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := match ls with | list_t.Cons ckey t tl => @@ -342,16 +341,16 @@ divergent def hash_map_remove_from_list_loop_fwd match mv_ls with | list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | list_t.Nil => Result.fail Error.panic - else hash_map_remove_from_list_loop_fwd T key tl + else HashMap.remove_from_list_loop_fwd T key tl | list_t.Nil => Result.ret Option.none /- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_fwd +def HashMap.remove_from_list_fwd (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := - hash_map_remove_from_list_loop_fwd T key ls + HashMap.remove_from_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::remove_from_list] -/ -divergent def hash_map_remove_from_list_loop_back +divergent def HashMap.remove_from_list_loop_back (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := match ls with | list_t.Cons ckey t tl => @@ -364,24 +363,24 @@ divergent def hash_map_remove_from_list_loop_back | list_t.Nil => Result.fail Error.panic else do - let tl0 ← hash_map_remove_from_list_loop_back T key tl + let tl0 ← HashMap.remove_from_list_loop_back T key tl Result.ret (list_t.Cons ckey t tl0) | list_t.Nil => Result.ret list_t.Nil /- [hashmap::HashMap::{0}::remove_from_list] -/ -def hash_map_remove_from_list_back +def HashMap.remove_from_list_back (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := - hash_map_remove_from_list_loop_back T key ls + HashMap.remove_from_list_loop_back T key ls /- [hashmap::HashMap::{0}::remove] -/ -def hash_map_remove_fwd +def HashMap.remove_fwd (T : Type) (self : hash_map_t T) (key : Usize) : Result (Option T) := do let hash ← hash_key_fwd key let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let x ← hash_map_remove_from_list_fwd T key l + let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => @@ -390,24 +389,24 @@ def hash_map_remove_fwd Result.ret (Option.some x0) /- [hashmap::HashMap::{0}::remove] -/ -def hash_map_remove_back +def HashMap.remove_back (T : Type) (self : hash_map_t T) (key : Usize) : Result (hash_map_t T) := do let hash ← hash_key_fwd key let i := vec_len (list_t T) self.hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod - let x ← hash_map_remove_from_list_fwd T key l + let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => do - let l0 ← hash_map_remove_from_list_back T key l + let l0 ← HashMap.remove_from_list_back T key l let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } | Option.some x0 => do let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) - let l0 ← hash_map_remove_from_list_back T key l + let l0 ← HashMap.remove_from_list_back T key l let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } @@ -415,34 +414,33 @@ def hash_map_remove_back /- [hashmap::test1] -/ def test1_fwd : Result Unit := do - let hm ← hash_map_new_fwd U64 + let hm ← HashMap.new_fwd U64 let hm0 ← - hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + HashMap.insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) (U64.ofInt 42 (by intlit)) let hm1 ← - hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + HashMap.insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) (U64.ofInt 18 (by intlit)) let hm2 ← - hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + HashMap.insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 138 (by intlit)) let hm3 ← - hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + HashMap.insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) (U64.ofInt 256 (by intlit)) - let i ← hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + let i ← HashMap.get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) if not (i = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let hm4 ← - hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) + HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 56 (by intlit)) - let i0 ← hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + let i0 ← HashMap.get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) if not (i0 = (U64.ofInt 56 (by intlit))) then Result.fail Error.panic else do - let x ← - hash_map_remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + let x ← HashMap.remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) match x with | Option.none => Result.fail Error.panic | Option.some x0 => @@ -451,21 +449,21 @@ def test1_fwd : Result Unit := else do let hm5 ← - hash_map_remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) + HashMap.remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) let i1 ← - hash_map_get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) + HashMap.get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) if not (i1 = (U64.ofInt 42 (by intlit))) then Result.fail Error.panic else do let i2 ← - hash_map_get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) + HashMap.get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) if not (i2 = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let i3 ← - hash_map_get_fwd U64 hm5 + HashMap.get_fwd U64 hm5 (Usize.ofInt 1056 (by intlit)) if not (i3 = (U64.ofInt 256 (by intlit))) then Result.fail Error.panic @@ -474,4 +472,4 @@ def test1_fwd : Result Unit := /- Unit test for [hashmap::test1] -/ #assert (test1_fwd == .ret ()) -end Hashmap +end hashmap diff --git a/tests/lean/Hashmap/Types.lean b/tests/lean/Hashmap/Types.lean index 0aec6acf..75a6500f 100644 --- a/tests/lean/Hashmap/Types.lean +++ b/tests/lean/Hashmap/Types.lean @@ -2,8 +2,7 @@ -- [hashmap]: type definitions import Base open Primitives - -namespace Hashmap +namespace hashmap /- [hashmap::List] -/ inductive list_t (T : Type) := @@ -17,4 +16,4 @@ structure hash_map_t (T : Type) where hash_map_max_load : Usize hash_map_slots : Vec (list_t T) -end Hashmap +end hashmap diff --git a/tests/lean/HashmapMain/ExternalFuns.lean b/tests/lean/HashmapMain/ExternalFuns.lean deleted file mode 100644 index bc831158..00000000 --- a/tests/lean/HashmapMain/ExternalFuns.lean +++ /dev/null @@ -1,9 +0,0 @@ -import Base -import HashmapMain.Types -import HashmapMain.Opaque - -namespace HashmapMain - -def opaque_defs : OpaqueDefs := by sorry - -end HashmapMain diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index 34a0eca1..06929431 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -2,17 +2,16 @@ -- [hashmap_main]: function definitions import Base import HashmapMain.Types -import HashmapMain.ExternalFuns +import HashmapMain.FunsExternal open Primitives - -namespace HashmapMain +namespace hashmap_main /- [hashmap_main::hashmap::hash_key] -/ -def hashmap_hash_key_fwd (k : Usize) : Result Usize := +def hashmap.hash_key_fwd (k : Usize) : Result Usize := Result.ret k /- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -divergent def hashmap_hash_map_allocate_slots_loop_fwd +divergent def hashmap.HashMap.allocate_slots_loop_fwd (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : Result (Vec (hashmap_list_t T)) := @@ -21,25 +20,25 @@ divergent def hashmap_hash_map_allocate_slots_loop_fwd do let slots0 ← vec_push_back (hashmap_list_t T) slots hashmap_list_t.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) - hashmap_hash_map_allocate_slots_loop_fwd T slots0 n0 + hashmap.HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots /- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -def hashmap_hash_map_allocate_slots_fwd +def hashmap.HashMap.allocate_slots_fwd (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : Result (Vec (hashmap_list_t T)) := - hashmap_hash_map_allocate_slots_loop_fwd T slots n + hashmap.HashMap.allocate_slots_loop_fwd T slots n /- [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] -/ -def hashmap_hash_map_new_with_capacity_fwd +def hashmap.HashMap.new_with_capacity_fwd (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : Result (hashmap_hash_map_t T) := do let v := vec_new (hashmap_list_t T) - let slots ← hashmap_hash_map_allocate_slots_fwd T v capacity + let slots ← hashmap.HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor Result.ret @@ -52,12 +51,12 @@ def hashmap_hash_map_new_with_capacity_fwd } /- [hashmap_main::hashmap::HashMap::{0}::new] -/ -def hashmap_hash_map_new_fwd (T : Type) : Result (hashmap_hash_map_t T) := - hashmap_hash_map_new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) +def hashmap.HashMap.new_fwd (T : Type) : Result (hashmap_hash_map_t T) := + hashmap.HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) /- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -divergent def hashmap_hash_map_clear_loop_fwd_back +divergent def hashmap.HashMap.clear_loop_fwd_back (T : Type) (slots : Vec (hashmap_list_t T)) (i : Usize) : Result (Vec (hashmap_list_t T)) := @@ -68,15 +67,15 @@ divergent def hashmap_hash_map_clear_loop_fwd_back let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← vec_index_mut_back (hashmap_list_t T) slots i hashmap_list_t.Nil - hashmap_hash_map_clear_loop_fwd_back T slots0 i1 + hashmap.HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots /- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -def hashmap_hash_map_clear_fwd_back +def hashmap.HashMap.clear_fwd_back (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := do let v ← - hashmap_hash_map_clear_loop_fwd_back T self.hashmap_hash_map_slots + hashmap.HashMap.clear_loop_fwd_back T self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -87,27 +86,27 @@ def hashmap_hash_map_clear_fwd_back } /- [hashmap_main::hashmap::HashMap::{0}::len] -/ -def hashmap_hash_map_len_fwd +def hashmap.HashMap.len_fwd (T : Type) (self : hashmap_hash_map_t T) : Result Usize := Result.ret self.hashmap_hash_map_num_entries /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -divergent def hashmap_hash_map_insert_in_list_loop_fwd +divergent def hashmap.HashMap.insert_in_list_loop_fwd (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret false - else hashmap_hash_map_insert_in_list_loop_fwd T key value tl + else hashmap.HashMap.insert_in_list_loop_fwd T key value tl | hashmap_list_t.Nil => Result.ret true /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_fwd +def hashmap.HashMap.insert_in_list_fwd (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := - hashmap_hash_map_insert_in_list_loop_fwd T key value ls + hashmap.HashMap.insert_in_list_loop_fwd T key value ls /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -divergent def hashmap_hash_map_insert_in_list_loop_back +divergent def hashmap.HashMap.insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := @@ -117,37 +116,37 @@ divergent def hashmap_hash_map_insert_in_list_loop_back then Result.ret (hashmap_list_t.Cons ckey value tl) else do - let tl0 ← hashmap_hash_map_insert_in_list_loop_back T key value tl + let tl0 ← hashmap.HashMap.insert_in_list_loop_back T key value tl Result.ret (hashmap_list_t.Cons ckey cvalue tl0) | hashmap_list_t.Nil => let l := hashmap_list_t.Nil Result.ret (hashmap_list_t.Cons key value l) /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap_hash_map_insert_in_list_back +def hashmap.HashMap.insert_in_list_back (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := - hashmap_hash_map_insert_in_list_loop_back T key value ls + hashmap.HashMap.insert_in_list_loop_back T key value ls /- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] -/ -def hashmap_hash_map_insert_no_resize_fwd_back +def hashmap.HashMap.insert_no_resize_fwd_back (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : Result (hashmap_hash_map_t T) := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let inserted ← hashmap_hash_map_insert_in_list_fwd T key value l + let inserted ← hashmap.HashMap.insert_in_list_fwd T key value l if inserted then do let i0 ← self.hashmap_hash_map_num_entries + (Usize.ofInt 1 (by intlit)) - let l0 ← hashmap_hash_map_insert_in_list_back T key value l + let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod l0 @@ -159,7 +158,7 @@ def hashmap_hash_map_insert_no_resize_fwd_back } else do - let l0 ← hashmap_hash_map_insert_in_list_back T key value l + let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod l0 @@ -171,26 +170,26 @@ def core_num_u32_max_body : Result U32 := def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -divergent def hashmap_hash_map_move_elements_from_list_loop_fwd_back +divergent def hashmap.HashMap.move_elements_from_list_loop_fwd_back (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : Result (hashmap_hash_map_t T) := match ls with | hashmap_list_t.Cons k v tl => do - let ntable0 ← hashmap_hash_map_insert_no_resize_fwd_back T ntable k v - hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable0 tl + let ntable0 ← hashmap.HashMap.insert_no_resize_fwd_back T ntable k v + hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl | hashmap_list_t.Nil => Result.ret ntable /- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -def hashmap_hash_map_move_elements_from_list_fwd_back +def hashmap.HashMap.move_elements_from_list_fwd_back (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : Result (hashmap_hash_map_t T) := - hashmap_hash_map_move_elements_from_list_loop_fwd_back T ntable ls + hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable ls /- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -divergent def hashmap_hash_map_move_elements_loop_fwd_back +divergent def hashmap.HashMap.move_elements_loop_fwd_back (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) (i : Usize) : Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) @@ -202,23 +201,23 @@ divergent def hashmap_hash_map_move_elements_loop_fwd_back let l ← vec_index_mut_fwd (hashmap_list_t T) slots i let ls := mem_replace_fwd (hashmap_list_t T) l hashmap_list_t.Nil let ntable0 ← - hashmap_hash_map_move_elements_from_list_fwd_back T ntable ls + hashmap.HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) let l0 := mem_replace_back (hashmap_list_t T) l hashmap_list_t.Nil let slots0 ← vec_index_mut_back (hashmap_list_t T) slots i l0 - hashmap_hash_map_move_elements_loop_fwd_back T ntable0 slots0 i1 + hashmap.HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) /- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -def hashmap_hash_map_move_elements_fwd_back +def hashmap.HashMap.move_elements_fwd_back (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) (i : Usize) : Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) := - hashmap_hash_map_move_elements_loop_fwd_back T ntable slots i + hashmap.HashMap.move_elements_loop_fwd_back T ntable slots i /- [hashmap_main::hashmap::HashMap::{0}::try_resize] -/ -def hashmap_hash_map_try_resize_fwd_back +def hashmap.HashMap.try_resize_fwd_back (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c @@ -230,9 +229,9 @@ def hashmap_hash_map_try_resize_fwd_back then do let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← hashmap_hash_map_new_with_capacity_fwd T i2 i i0 + let ntable ← hashmap.HashMap.new_with_capacity_fwd T i2 i i0 let (ntable0, _) ← - hashmap_hash_map_move_elements_fwd_back T ntable + hashmap.HashMap.move_elements_fwd_back T ntable self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -244,86 +243,86 @@ def hashmap_hash_map_try_resize_fwd_back else Result.ret { self with hashmap_hash_map_max_load_factor := (i, i0) } /- [hashmap_main::hashmap::HashMap::{0}::insert] -/ -def hashmap_hash_map_insert_fwd_back +def hashmap.HashMap.insert_fwd_back (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : Result (hashmap_hash_map_t T) := do - let self0 ← hashmap_hash_map_insert_no_resize_fwd_back T self key value - let i ← hashmap_hash_map_len_fwd T self0 + let self0 ← hashmap.HashMap.insert_no_resize_fwd_back T self key value + let i ← hashmap.HashMap.len_fwd T self0 if i > self0.hashmap_hash_map_max_load - then hashmap_hash_map_try_resize_fwd_back T self0 + then hashmap.HashMap.try_resize_fwd_back T self0 else Result.ret self0 /- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -divergent def hashmap_hash_map_contains_key_in_list_loop_fwd +divergent def hashmap.HashMap.contains_key_in_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := match ls with | hashmap_list_t.Cons ckey t tl => if ckey = key then Result.ret true - else hashmap_hash_map_contains_key_in_list_loop_fwd T key tl + else hashmap.HashMap.contains_key_in_list_loop_fwd T key tl | hashmap_list_t.Nil => Result.ret false /- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -def hashmap_hash_map_contains_key_in_list_fwd +def hashmap.HashMap.contains_key_in_list_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := - hashmap_hash_map_contains_key_in_list_loop_fwd T key ls + hashmap.HashMap.contains_key_in_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::contains_key] -/ -def hashmap_hash_map_contains_key_fwd +def hashmap.HashMap.contains_key_fwd (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result Bool := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_contains_key_in_list_fwd T key l + hashmap.HashMap.contains_key_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -divergent def hashmap_hash_map_get_in_list_loop_fwd +divergent def hashmap.HashMap.get_in_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hashmap_hash_map_get_in_list_loop_fwd T key tl + else hashmap.HashMap.get_in_list_loop_fwd T key tl | hashmap_list_t.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -def hashmap_hash_map_get_in_list_fwd +def hashmap.HashMap.get_in_list_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := - hashmap_hash_map_get_in_list_loop_fwd T key ls + hashmap.HashMap.get_in_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::get] -/ -def hashmap_hash_map_get_fwd +def hashmap.HashMap.get_fwd (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_get_in_list_fwd T key l + hashmap.HashMap.get_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def hashmap_hash_map_get_mut_in_list_loop_fwd +divergent def hashmap.HashMap.get_mut_in_list_loop_fwd (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := match ls with | hashmap_list_t.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hashmap_hash_map_get_mut_in_list_loop_fwd T tl key + else hashmap.HashMap.get_mut_in_list_loop_fwd T tl key | hashmap_list_t.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_fwd +def hashmap.HashMap.get_mut_in_list_fwd (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := - hashmap_hash_map_get_mut_in_list_loop_fwd T ls key + hashmap.HashMap.get_mut_in_list_loop_fwd T ls key /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def hashmap_hash_map_get_mut_in_list_loop_back +divergent def hashmap.HashMap.get_mut_in_list_loop_back (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : Result (hashmap_list_t T) := @@ -333,47 +332,47 @@ divergent def hashmap_hash_map_get_mut_in_list_loop_back then Result.ret (hashmap_list_t.Cons ckey ret0 tl) else do - let tl0 ← hashmap_hash_map_get_mut_in_list_loop_back T tl key ret0 + let tl0 ← hashmap.HashMap.get_mut_in_list_loop_back T tl key ret0 Result.ret (hashmap_list_t.Cons ckey cvalue tl0) | hashmap_list_t.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap_hash_map_get_mut_in_list_back +def hashmap.HashMap.get_mut_in_list_back (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : Result (hashmap_list_t T) := - hashmap_hash_map_get_mut_in_list_loop_back T ls key ret0 + hashmap.HashMap.get_mut_in_list_loop_back T ls key ret0 /- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ -def hashmap_hash_map_get_mut_fwd +def hashmap.HashMap.get_mut_fwd (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - hashmap_hash_map_get_mut_in_list_fwd T l key + hashmap.HashMap.get_mut_in_list_fwd T l key /- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ -def hashmap_hash_map_get_mut_back +def hashmap.HashMap.get_mut_back (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (ret0 : T) : Result (hashmap_hash_map_t T) := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let l0 ← hashmap_hash_map_get_mut_in_list_back T l key ret0 + let l0 ← hashmap.HashMap.get_mut_in_list_back T l key ret0 let v ← vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -divergent def hashmap_hash_map_remove_from_list_loop_fwd +divergent def hashmap.HashMap.remove_from_list_loop_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := match ls with | hashmap_list_t.Cons ckey t tl => @@ -385,16 +384,16 @@ divergent def hashmap_hash_map_remove_from_list_loop_fwd match mv_ls with | hashmap_list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | hashmap_list_t.Nil => Result.fail Error.panic - else hashmap_hash_map_remove_from_list_loop_fwd T key tl + else hashmap.HashMap.remove_from_list_loop_fwd T key tl | hashmap_list_t.Nil => Result.ret Option.none /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_fwd +def hashmap.HashMap.remove_from_list_fwd (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := - hashmap_hash_map_remove_from_list_loop_fwd T key ls + hashmap.HashMap.remove_from_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -divergent def hashmap_hash_map_remove_from_list_loop_back +divergent def hashmap.HashMap.remove_from_list_loop_back (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := @@ -410,27 +409,27 @@ divergent def hashmap_hash_map_remove_from_list_loop_back | hashmap_list_t.Nil => Result.fail Error.panic else do - let tl0 ← hashmap_hash_map_remove_from_list_loop_back T key tl + let tl0 ← hashmap.HashMap.remove_from_list_loop_back T key tl Result.ret (hashmap_list_t.Cons ckey t tl0) | hashmap_list_t.Nil => Result.ret hashmap_list_t.Nil /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap_hash_map_remove_from_list_back +def hashmap.HashMap.remove_from_list_back (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (hashmap_list_t T) := - hashmap_hash_map_remove_from_list_loop_back T key ls + hashmap.HashMap.remove_from_list_loop_back T key ls /- [hashmap_main::hashmap::HashMap::{0}::remove] -/ -def hashmap_hash_map_remove_fwd +def hashmap.HashMap.remove_fwd (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result (Option T) := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap_hash_map_remove_from_list_fwd T key l + let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => @@ -440,21 +439,21 @@ def hashmap_hash_map_remove_fwd Result.ret (Option.some x0) /- [hashmap_main::hashmap::HashMap::{0}::remove] -/ -def hashmap_hash_map_remove_back +def hashmap.HashMap.remove_back (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result (hashmap_hash_map_t T) := do - let hash ← hashmap_hash_key_fwd key + let hash ← hashmap.hash_key_fwd key let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap_hash_map_remove_from_list_fwd T key l + let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => do - let l0 ← hashmap_hash_map_remove_from_list_back T key l + let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod l0 @@ -463,7 +462,7 @@ def hashmap_hash_map_remove_back do let i0 ← self.hashmap_hash_map_num_entries - (Usize.ofInt 1 (by intlit)) - let l0 ← hashmap_hash_map_remove_from_list_back T key l + let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod l0 @@ -475,38 +474,37 @@ def hashmap_hash_map_remove_back } /- [hashmap_main::hashmap::test1] -/ -def hashmap_test1_fwd : Result Unit := +def hashmap.test1_fwd : Result Unit := do - let hm ← hashmap_hash_map_new_fwd U64 + let hm ← hashmap.HashMap.new_fwd U64 let hm0 ← - hashmap_hash_map_insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) (U64.ofInt 42 (by intlit)) let hm1 ← - hashmap_hash_map_insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + hashmap.HashMap.insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) (U64.ofInt 18 (by intlit)) let hm2 ← - hashmap_hash_map_insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 138 (by intlit)) let hm3 ← - hashmap_hash_map_insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + hashmap.HashMap.insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) (U64.ofInt 256 (by intlit)) - let i ← hashmap_hash_map_get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + let i ← hashmap.HashMap.get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) if not (i = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let hm4 ← - hashmap_hash_map_get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 56 (by intlit)) let i0 ← - hashmap_hash_map_get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) if not (i0 = (U64.ofInt 56 (by intlit))) then Result.fail Error.panic else do let x ← - hashmap_hash_map_remove_fwd U64 hm4 - (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) match x with | Option.none => Result.fail Error.panic | Option.some x0 => @@ -515,39 +513,38 @@ def hashmap_test1_fwd : Result Unit := else do let hm5 ← - hashmap_hash_map_remove_back U64 hm4 + hashmap.HashMap.remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) let i1 ← - hashmap_hash_map_get_fwd U64 hm5 - (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) if not (i1 = (U64.ofInt 42 (by intlit))) then Result.fail Error.panic else do let i2 ← - hashmap_hash_map_get_fwd U64 hm5 + hashmap.HashMap.get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) if not (i2 = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let i3 ← - hashmap_hash_map_get_fwd U64 hm5 + hashmap.HashMap.get_fwd U64 hm5 (Usize.ofInt 1056 (by intlit)) if not (i3 = (U64.ofInt 256 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [hashmap_main::hashmap::test1] -/ -#assert (hashmap_test1_fwd == .ret ()) +#assert (hashmap.test1_fwd == .ret ()) /- [hashmap_main::insert_on_disk] -/ def insert_on_disk_fwd (key : Usize) (value : U64) (st : State) : Result (State × Unit) := do - let (st0, hm) ← opaque_defs.hashmap_utils_deserialize_fwd st - let hm0 ← hashmap_hash_map_insert_fwd_back U64 hm key value - let (st1, _) ← opaque_defs.hashmap_utils_serialize_fwd hm0 st0 + let (st0, hm) ← hashmap_utils.deserialize_fwd st + let hm0 ← hashmap.HashMap.insert_fwd_back U64 hm key value + let (st1, _) ← hashmap_utils.serialize_fwd hm0 st0 Result.ret (st1, ()) /- [hashmap_main::main] -/ @@ -557,4 +554,4 @@ def main_fwd : Result Unit := /- Unit test for [hashmap_main::main] -/ #assert (main_fwd == .ret ()) -end HashmapMain +end hashmap_main diff --git a/tests/lean/HashmapMain/FunsExternal.lean b/tests/lean/HashmapMain/FunsExternal.lean new file mode 100644 index 00000000..d917b485 --- /dev/null +++ b/tests/lean/HashmapMain/FunsExternal.lean @@ -0,0 +1,17 @@ +-- [hashmap_main]: templates for the external functions. +import Base +import HashmapMain.Types +open Primitives +open hashmap_main + +-- TODO: fill those bodies + +/- [hashmap_main::hashmap_utils::deserialize] -/ +def hashmap_utils.deserialize_fwd + : State → Result (State × (hashmap_hash_map_t U64)) := + fun _ => .fail .panic + +/- [hashmap_main::hashmap_utils::serialize] -/ +def hashmap_utils.serialize_fwd + : hashmap_hash_map_t U64 → State → Result (State × Unit) := + fun _ _ => .fail .panic diff --git a/tests/lean/HashmapMain/FunsExternal_Template.lean b/tests/lean/HashmapMain/FunsExternal_Template.lean new file mode 100644 index 00000000..86286373 --- /dev/null +++ b/tests/lean/HashmapMain/FunsExternal_Template.lean @@ -0,0 +1,16 @@ +-- THIS FILE WAS AUTOMATICALLY GENERATED BY AENEAS +-- [hashmap_main]: external functions. +-- This is a template file: rename it to "FunsExternal.lean" and fill the holes. +import Base +import HashmapMain.Types +open Primitives +open hashmap_main + +/- [hashmap_main::hashmap_utils::deserialize] -/ +axiom hashmap_utils.deserialize_fwd + : State → Result (State × (hashmap_hash_map_t U64)) + +/- [hashmap_main::hashmap_utils::serialize] -/ +axiom hashmap_utils.serialize_fwd + : hashmap_hash_map_t U64 → State → Result (State × Unit) + diff --git a/tests/lean/HashmapMain/Opaque.lean b/tests/lean/HashmapMain/Opaque.lean index 10e4d8bd..abf04c94 100644 --- a/tests/lean/HashmapMain/Opaque.lean +++ b/tests/lean/HashmapMain/Opaque.lean @@ -4,16 +4,16 @@ import Base import HashmapMain.Types open Primitives -namespace HashmapMain +namespace hashmap_main structure OpaqueDefs where /- [hashmap_main::hashmap_utils::deserialize] -/ - hashmap_utils_deserialize_fwd + hashmap_utils.deserialize_fwd : State → Result (State × (hashmap_hash_map_t U64)) /- [hashmap_main::hashmap_utils::serialize] -/ - hashmap_utils_serialize_fwd + hashmap_utils.serialize_fwd : hashmap_hash_map_t U64 → State → Result (State × Unit) -end HashmapMain +end hashmap_main diff --git a/tests/lean/HashmapMain/Types.lean b/tests/lean/HashmapMain/Types.lean index b91ff3a7..16641146 100644 --- a/tests/lean/HashmapMain/Types.lean +++ b/tests/lean/HashmapMain/Types.lean @@ -2,8 +2,7 @@ -- [hashmap_main]: type definitions import Base open Primitives - -namespace HashmapMain +namespace hashmap_main /- [hashmap_main::hashmap::List] -/ inductive hashmap_list_t (T : Type) := @@ -20,4 +19,4 @@ structure hashmap_hash_map_t (T : Type) where /- The state type used in the state-error monad -/ axiom State : Type -end HashmapMain +end hashmap_main diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 9e084327..694f5450 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -3,8 +3,7 @@ import Base import Loops.Types open Primitives - -namespace Loops +namespace loops /- [loops::sum] -/ divergent def sum_loop_fwd (max : U32) (i : U32) (s : U32) : Result U32 := @@ -624,4 +623,4 @@ def list_nth_shared_mut_loop_pair_merge_back := list_nth_shared_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 -end Loops +end loops diff --git a/tests/lean/Loops/Types.lean b/tests/lean/Loops/Types.lean index ca0403e9..5b5ed31f 100644 --- a/tests/lean/Loops/Types.lean +++ b/tests/lean/Loops/Types.lean @@ -2,12 +2,11 @@ -- [loops]: type definitions import Base open Primitives - -namespace Loops +namespace loops /- [loops::List] -/ inductive list_t (T : Type) := | Cons : T → list_t T → list_t T | Nil : list_t T -end Loops +end loops diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index 769bb311..67abc8f6 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -2,8 +2,7 @@ -- [no_nested_borrows] import Base open Primitives - -namespace NoNestedBorrows +namespace no_nested_borrows /- [no_nested_borrows::Pair] -/ structure pair_t (T1 T2 : Type) where @@ -541,4 +540,4 @@ def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := def test_shared_borrow_enum2_fwd : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) -end NoNestedBorrows +end no_nested_borrows diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean index edcb5c1b..c34941ef 100644 --- a/tests/lean/Paper.lean +++ b/tests/lean/Paper.lean @@ -2,8 +2,7 @@ -- [paper] import Base open Primitives - -namespace Paper +namespace paper /- [paper::ref_incr] -/ def ref_incr_fwd_back (x : I32) : Result I32 := @@ -125,4 +124,4 @@ def call_choose_fwd (p : (U32 × U32)) : Result U32 := let (px0, _) ← choose_back U32 true px py pz0 Result.ret px0 -end Paper +end paper diff --git a/tests/lean/PoloniusList.lean b/tests/lean/PoloniusList.lean index 0f2a05e3..0ff01b47 100644 --- a/tests/lean/PoloniusList.lean +++ b/tests/lean/PoloniusList.lean @@ -2,8 +2,7 @@ -- [polonius_list] import Base open Primitives - -namespace PoloniusList +namespace polonius_list /- [polonius_list::List] -/ inductive list_t (T : Type) := @@ -33,4 +32,4 @@ divergent def get_list_at_x_back Result.ret (list_t.Cons hd tl0) | list_t.Nil => Result.ret ret0 -end PoloniusList +end polonius_list diff --git a/tests/lean/Tests.lean b/tests/lean/Tests.lean deleted file mode 100644 index 9b12270e..00000000 --- a/tests/lean/Tests.lean +++ /dev/null @@ -1,9 +0,0 @@ -import BetreeMain -import Constants -import External -import Hashmap -import HashmapMain -import Loops -import NoNestedBorrows -import Paper -import PoloniusList diff --git a/tests/lean/lakefile.lean b/tests/lean/lakefile.lean index 217e533f..ae63b129 100644 --- a/tests/lean/lakefile.lean +++ b/tests/lean/lakefile.lean @@ -8,15 +8,12 @@ require Base from "../../backends/lean" package «tests» {} -@[default_target] -lean_lib «Tests» {} - -lean_lib betreeMain -lean_lib constants -lean_lib external -lean_lib hashmap -lean_lib hashmapMain -lean_lib loops -lean_lib noNestedBorrows -lean_lib paper -lean_lib poloniusList +@[default_target] lean_lib betreeMain +@[default_target] lean_lib constants +@[default_target] lean_lib external +@[default_target] lean_lib hashmap +@[default_target] lean_lib hashmapMain +@[default_target] lean_lib loops +@[default_target] lean_lib noNestedBorrows +@[default_target] lean_lib paper +@[default_target] lean_lib poloniusList -- cgit v1.2.3 From c07721dedb2cfe4c726c42606e623395cdfe5b80 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 5 Jul 2023 15:09:07 +0200 Subject: Simplify the generated names for the types in Lean --- compiler/Extract.ml | 17 +- tests/lean/BetreeMain/Funs.lean | 614 +++++++++++----------- tests/lean/BetreeMain/FunsExternal.lean | 8 +- tests/lean/BetreeMain/FunsExternal_Template.lean | 11 +- tests/lean/BetreeMain/Types.lean | 44 +- tests/lean/Constants.lean | 28 +- tests/lean/External/Funs.lean | 4 +- tests/lean/External/FunsExternal_Template.lean | 3 +- tests/lean/External/Types.lean | 2 +- tests/lean/Hashmap/Funs.lean | 203 ++++--- tests/lean/Hashmap/Types.lean | 10 +- tests/lean/HashmapMain/Funs.lean | 232 ++++---- tests/lean/HashmapMain/FunsExternal.lean | 4 +- tests/lean/HashmapMain/FunsExternal_Template.lean | 4 +- tests/lean/HashmapMain/Types.lean | 10 +- tests/lean/Loops/Funs.lean | 355 ++++++------- tests/lean/Loops/Types.lean | 6 +- tests/lean/NoNestedBorrows.lean | 143 +++-- tests/lean/Paper.lean | 43 +- tests/lean/PoloniusList.lean | 22 +- 20 files changed, 869 insertions(+), 894 deletions(-) diff --git a/compiler/Extract.ml b/compiler/Extract.ml index 50215dac..821bf4f7 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -601,7 +601,11 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) | FStar | Lean | HOL4 -> name | Coq -> capitalize_first_letter name in - let type_name name = type_name_to_snake_case name ^ "_t" in + let type_name name = + match !backend with + | FStar | Coq | HOL4 -> type_name_to_snake_case name ^ "_t" + | Lean -> String.concat "." (get_type_name name) + in let field_name (def_name : name) (field_id : FieldId.id) (field_name : string option) : string = let def_name = type_name_to_snake_case def_name ^ "_" in @@ -610,10 +614,13 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) | None -> def_name ^ FieldId.to_string field_id in let variant_name (def_name : name) (variant : string) : string = - let variant = to_camel_case variant in - if variant_concatenate_type_name then - type_name_to_camel_case def_name ^ variant - else variant + match !backend with + | FStar | Coq | HOL4 -> + let variant = to_camel_case variant in + if variant_concatenate_type_name then + type_name_to_camel_case def_name ^ variant + else variant + | Lean -> variant in let struct_constructor (basename : name) : string = let tname = type_name basename in diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index 78e14146..3a678c71 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -9,13 +9,13 @@ namespace betree_main /- [betree_main::betree::load_internal_node] -/ def betree.load_internal_node_fwd (id : U64) (st : State) : - Result (State × (betree_list_t (U64 × betree_message_t))) + Result (State × (betree.List (U64 × betree.Message))) := betree_utils.load_internal_node_fwd id st /- [betree_main::betree::store_internal_node] -/ def betree.store_internal_node_fwd - (id : U64) (content : betree_list_t (U64 × betree_message_t)) (st : State) : + (id : U64) (content : betree.List (U64 × betree.Message)) (st : State) : Result (State × Unit) := do @@ -24,12 +24,12 @@ def betree.store_internal_node_fwd /- [betree_main::betree::load_leaf_node] -/ def betree.load_leaf_node_fwd - (id : U64) (st : State) : Result (State × (betree_list_t (U64 × U64))) := + (id : U64) (st : State) : Result (State × (betree.List (U64 × U64))) := betree_utils.load_leaf_node_fwd id st /- [betree_main::betree::store_leaf_node] -/ def betree.store_leaf_node_fwd - (id : U64) (content : betree_list_t (U64 × U64)) (st : State) : + (id : U64) (content : betree.List (U64 × U64)) (st : State) : Result (State × Unit) := do @@ -47,13 +47,13 @@ def betree.fresh_node_id_back (counter : U64) : Result U64 := counter + (U64.ofInt 1 (by intlit)) /- [betree_main::betree::NodeIdCounter::{0}::new] -/ -def betree.NodeIdCounter.new_fwd : Result betree_node_id_counter_t := +def betree.NodeIdCounter.new_fwd : Result betree.NodeIdCounter := Result.ret { betree_node_id_counter_next_node_id := (U64.ofInt 0 (by intlit)) } /- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ def betree.NodeIdCounter.fresh_id_fwd - (self : betree_node_id_counter_t) : Result U64 := + (self : betree.NodeIdCounter) : Result U64 := do let _ ← self.betree_node_id_counter_next_node_id + (U64.ofInt 1 (by intlit)) @@ -61,7 +61,7 @@ def betree.NodeIdCounter.fresh_id_fwd /- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ def betree.NodeIdCounter.fresh_id_back - (self : betree_node_id_counter_t) : Result betree_node_id_counter_t := + (self : betree.NodeIdCounter) : Result betree.NodeIdCounter := do let i ← self.betree_node_id_counter_next_node_id + (U64.ofInt 1 (by intlit)) @@ -74,113 +74,112 @@ def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) /- [betree_main::betree::upsert_update] -/ def betree.upsert_update_fwd - (prev : Option U64) (st : betree_upsert_fun_state_t) : Result U64 := + (prev : Option U64) (st : betree.UpsertFunState) : Result U64 := match prev with | Option.none => match st with - | betree_upsert_fun_state_t.Add v => Result.ret v - | betree_upsert_fun_state_t.Sub i => Result.ret (U64.ofInt 0 (by intlit)) + | betree.UpsertFunState.Add v => Result.ret v + | betree.UpsertFunState.Sub i => Result.ret (U64.ofInt 0 (by intlit)) | Option.some prev0 => match st with - | betree_upsert_fun_state_t.Add v => + | betree.UpsertFunState.Add v => do let margin ← core_num_u64_max_c - prev0 if margin >= v then prev0 + v else Result.ret core_num_u64_max_c - | betree_upsert_fun_state_t.Sub v => + | betree.UpsertFunState.Sub v => if prev0 >= v then prev0 - v else Result.ret (U64.ofInt 0 (by intlit)) /- [betree_main::betree::List::{1}::len] -/ divergent def betree.List.len_fwd - (T : Type) (self : betree_list_t T) : Result U64 := + (T : Type) (self : betree.List T) : Result U64 := match self with - | betree_list_t.Cons t tl => + | betree.List.Cons t tl => do let i ← betree.List.len_fwd T tl (U64.ofInt 1 (by intlit)) + i - | betree_list_t.Nil => Result.ret (U64.ofInt 0 (by intlit)) + | betree.List.Nil => Result.ret (U64.ofInt 0 (by intlit)) /- [betree_main::betree::List::{1}::split_at] -/ divergent def betree.List.split_at_fwd - (T : Type) (self : betree_list_t T) (n : U64) : - Result ((betree_list_t T) × (betree_list_t T)) + (T : Type) (self : betree.List T) (n : U64) : + Result ((betree.List T) × (betree.List T)) := if n = (U64.ofInt 0 (by intlit)) - then Result.ret (betree_list_t.Nil, self) + then Result.ret (betree.List.Nil, self) else match self with - | betree_list_t.Cons hd tl => + | betree.List.Cons hd tl => do let i ← n - (U64.ofInt 1 (by intlit)) let p ← betree.List.split_at_fwd T tl i let (ls0, ls1) := p let l := ls0 - Result.ret (betree_list_t.Cons hd l, ls1) - | betree_list_t.Nil => Result.fail Error.panic + Result.ret (betree.List.Cons hd l, ls1) + | betree.List.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::push_front] -/ def betree.List.push_front_fwd_back - (T : Type) (self : betree_list_t T) (x : T) : Result (betree_list_t T) := - let tl := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil + (T : Type) (self : betree.List T) (x : T) : Result (betree.List T) := + let tl := mem_replace_fwd (betree.List T) self betree.List.Nil let l := tl - Result.ret (betree_list_t.Cons x l) + Result.ret (betree.List.Cons x l) /- [betree_main::betree::List::{1}::pop_front] -/ -def betree.List.pop_front_fwd (T : Type) (self : betree_list_t T) : Result T := - let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil +def betree.List.pop_front_fwd (T : Type) (self : betree.List T) : Result T := + let ls := mem_replace_fwd (betree.List T) self betree.List.Nil match ls with - | betree_list_t.Cons x tl => Result.ret x - | betree_list_t.Nil => Result.fail Error.panic + | betree.List.Cons x tl => Result.ret x + | betree.List.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::pop_front] -/ def betree.List.pop_front_back - (T : Type) (self : betree_list_t T) : Result (betree_list_t T) := - let ls := mem_replace_fwd (betree_list_t T) self betree_list_t.Nil + (T : Type) (self : betree.List T) : Result (betree.List T) := + let ls := mem_replace_fwd (betree.List T) self betree.List.Nil match ls with - | betree_list_t.Cons x tl => Result.ret tl - | betree_list_t.Nil => Result.fail Error.panic + | betree.List.Cons x tl => Result.ret tl + | betree.List.Nil => Result.fail Error.panic /- [betree_main::betree::List::{1}::hd] -/ -def betree.List.hd_fwd (T : Type) (self : betree_list_t T) : Result T := +def betree.List.hd_fwd (T : Type) (self : betree.List T) : Result T := match self with - | betree_list_t.Cons hd l => Result.ret hd - | betree_list_t.Nil => Result.fail Error.panic + | betree.List.Cons hd l => Result.ret hd + | betree.List.Nil => Result.fail Error.panic /- [betree_main::betree::List::{2}::head_has_key] -/ def betree.List.head_has_key_fwd - (T : Type) (self : betree_list_t (U64 × T)) (key : U64) : Result Bool := + (T : Type) (self : betree.List (U64 × T)) (key : U64) : Result Bool := match self with - | betree_list_t.Cons hd l => let (i, _) := hd - Result.ret (i = key) - | betree_list_t.Nil => Result.ret false + | betree.List.Cons hd l => let (i, _) := hd + Result.ret (i = key) + | betree.List.Nil => Result.ret false /- [betree_main::betree::List::{2}::partition_at_pivot] -/ divergent def betree.List.partition_at_pivot_fwd - (T : Type) (self : betree_list_t (U64 × T)) (pivot : U64) : - Result ((betree_list_t (U64 × T)) × (betree_list_t (U64 × T))) + (T : Type) (self : betree.List (U64 × T)) (pivot : U64) : + Result ((betree.List (U64 × T)) × (betree.List (U64 × T))) := match self with - | betree_list_t.Cons hd tl => + | betree.List.Cons hd tl => let (i, t) := hd if i >= pivot - then Result.ret (betree_list_t.Nil, betree_list_t.Cons (i, t) tl) + then Result.ret (betree.List.Nil, betree.List.Cons (i, t) tl) else do let p ← betree.List.partition_at_pivot_fwd T tl pivot let (ls0, ls1) := p let l := ls0 - Result.ret (betree_list_t.Cons (i, t) l, ls1) - | betree_list_t.Nil => Result.ret (betree_list_t.Nil, betree_list_t.Nil) + Result.ret (betree.List.Cons (i, t) l, ls1) + | betree.List.Nil => Result.ret (betree.List.Nil, betree.List.Nil) /- [betree_main::betree::Leaf::{3}::split] -/ def betree.Leaf.split_fwd - (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) - (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) - (st : State) : - Result (State × betree_internal_t) + (self : betree.Leaf) (content : betree.List (U64 × U64)) + (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (st : State) : + Result (State × betree.Internal) := do let p ← @@ -194,24 +193,23 @@ def betree.Leaf.split_fwd let id1 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt0 let (st0, _) ← betree.store_leaf_node_fwd id0 content0 st let (st1, _) ← betree.store_leaf_node_fwd id1 content1 st0 - let n := betree_node_t.Leaf + let n := betree.Node.Leaf { betree_leaf_id := id0, betree_leaf_size := params.betree_params_split_size } - let n0 := betree_node_t.Leaf + let n0 := betree.Node.Leaf { betree_leaf_id := id1, betree_leaf_size := params.betree_params_split_size } - Result.ret (st1, betree_internal_t.mk self.betree_leaf_id pivot n n0) + Result.ret (st1, betree.Internal.mk self.betree_leaf_id pivot n n0) /- [betree_main::betree::Leaf::{3}::split] -/ def betree.Leaf.split_back - (self : betree_leaf_t) (content : betree_list_t (U64 × U64)) - (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) - (st : State) : - Result betree_node_id_counter_t + (self : betree.Leaf) (content : betree.List (U64 × U64)) + (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (st : State) : + Result betree.NodeIdCounter := do let p ← @@ -228,9 +226,9 @@ def betree.Leaf.split_back /- [betree_main::betree::Node::{5}::lookup_in_bindings] -/ divergent def betree.Node.lookup_in_bindings_fwd - (key : U64) (bindings : betree_list_t (U64 × U64)) : Result (Option U64) := + (key : U64) (bindings : betree.List (U64 × U64)) : Result (Option U64) := match bindings with - | betree_list_t.Cons hd tl => + | betree.List.Cons hd tl => let (i, i0) := hd if i = key then Result.ret (Option.some i0) @@ -238,29 +236,29 @@ divergent def betree.Node.lookup_in_bindings_fwd if i > key then Result.ret Option.none else betree.Node.lookup_in_bindings_fwd key tl - | betree_list_t.Nil => Result.ret Option.none + | betree.List.Nil => Result.ret Option.none /- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ divergent def betree.Node.lookup_first_message_for_key_fwd - (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (key : U64) (msgs : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match msgs with - | betree_list_t.Cons x next_msgs => + | betree.List.Cons x next_msgs => let (i, m) := x if i >= key - then Result.ret (betree_list_t.Cons (i, m) next_msgs) + then Result.ret (betree.List.Cons (i, m) next_msgs) else betree.Node.lookup_first_message_for_key_fwd key next_msgs - | betree_list_t.Nil => Result.ret betree_list_t.Nil + | betree.List.Nil => Result.ret betree.List.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ divergent def betree.Node.lookup_first_message_for_key_back - (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) - (ret0 : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (key : U64) (msgs : betree.List (U64 × betree.Message)) + (ret0 : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match msgs with - | betree_list_t.Cons x next_msgs => + | betree.List.Cons x next_msgs => let (i, m) := x if i >= key then Result.ret ret0 @@ -268,134 +266,134 @@ divergent def betree.Node.lookup_first_message_for_key_back do let next_msgs0 ← betree.Node.lookup_first_message_for_key_back key next_msgs ret0 - Result.ret (betree_list_t.Cons (i, m) next_msgs0) - | betree_list_t.Nil => Result.ret ret0 + Result.ret (betree.List.Cons (i, m) next_msgs0) + | betree.List.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_upserts] -/ divergent def betree.Node.apply_upserts_fwd - (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) - (key : U64) (st : State) : + (msgs : betree.List (U64 × betree.Message)) (prev : Option U64) (key : U64) + (st : State) : Result (State × U64) := do - let b ← betree.List.head_has_key_fwd betree_message_t msgs key + let b ← betree.List.head_has_key_fwd betree.Message msgs key if b then do - let msg ← betree.List.pop_front_fwd (U64 × betree_message_t) msgs + let msg ← betree.List.pop_front_fwd (U64 × betree.Message) msgs let (_, m) := msg match m with - | betree_message_t.Insert i => Result.fail Error.panic - | betree_message_t.Delete => Result.fail Error.panic - | betree_message_t.Upsert s => + | betree.Message.Insert i => Result.fail Error.panic + | betree.Message.Delete => Result.fail Error.panic + | betree.Message.Upsert s => do let v ← betree.upsert_update_fwd prev s let msgs0 ← - betree.List.pop_front_back (U64 × betree_message_t) msgs + betree.List.pop_front_back (U64 × betree.Message) msgs betree.Node.apply_upserts_fwd msgs0 (Option.some v) key st else do let (st0, v) ← core.option.Option.unwrap_fwd U64 prev st let _ ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs (key, - betree_message_t.Insert v) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs (key, + betree.Message.Insert v) Result.ret (st0, v) /- [betree_main::betree::Node::{5}::apply_upserts] -/ divergent def betree.Node.apply_upserts_back - (msgs : betree_list_t (U64 × betree_message_t)) (prev : Option U64) - (key : U64) (st : State) : - Result (betree_list_t (U64 × betree_message_t)) + (msgs : betree.List (U64 × betree.Message)) (prev : Option U64) (key : U64) + (st : State) : + Result (betree.List (U64 × betree.Message)) := do - let b ← betree.List.head_has_key_fwd betree_message_t msgs key + let b ← betree.List.head_has_key_fwd betree.Message msgs key if b then do - let msg ← betree.List.pop_front_fwd (U64 × betree_message_t) msgs + let msg ← betree.List.pop_front_fwd (U64 × betree.Message) msgs let (_, m) := msg match m with - | betree_message_t.Insert i => Result.fail Error.panic - | betree_message_t.Delete => Result.fail Error.panic - | betree_message_t.Upsert s => + | betree.Message.Insert i => Result.fail Error.panic + | betree.Message.Delete => Result.fail Error.panic + | betree.Message.Upsert s => do let v ← betree.upsert_update_fwd prev s let msgs0 ← - betree.List.pop_front_back (U64 × betree_message_t) msgs + betree.List.pop_front_back (U64 × betree.Message) msgs betree.Node.apply_upserts_back msgs0 (Option.some v) key st else do let (_, v) ← core.option.Option.unwrap_fwd U64 prev st - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs (key, - betree_message_t.Insert v) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs (key, + betree.Message.Insert v) /- [betree_main::betree::Node::{5}::lookup] -/ mutual divergent def betree.Node.lookup_fwd - (self : betree_node_t) (key : U64) (st : State) : + (self : betree.Node) (key : U64) (st : State) : Result (State × (Option U64)) := match self with - | betree_node_t.Internal node => + | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node let (st0, msgs) ← betree.load_internal_node_fwd i st let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs match pending with - | betree_list_t.Cons p l => + | betree.List.Cons p l => let (k, msg) := p if k != key then do let (st1, opt) ← - betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 - n n0) key st0 + betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 n + n0) key st0 let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, msg) l) + (betree.List.Cons (k, msg) l) Result.ret (st1, opt) else match msg with - | betree_message_t.Insert v => + | betree.Message.Insert v => do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, betree_message_t.Insert v) l) + (betree.List.Cons (k, betree.Message.Insert v) l) Result.ret (st0, Option.some v) - | betree_message_t.Delete => + | betree.Message.Delete => do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, betree_message_t.Delete) l) + (betree.List.Cons (k, betree.Message.Delete) l) Result.ret (st0, Option.none) - | betree_message_t.Upsert ufs => + | betree.Message.Upsert ufs => do let (st1, v) ← - betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i - i0 n n0) key st0 + betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 + n n0) key st0 let (st2, v0) ← - betree.Node.apply_upserts_fwd (betree_list_t.Cons (k, - betree_message_t.Upsert ufs) l) v key st1 + betree.Node.apply_upserts_fwd (betree.List.Cons (k, + betree.Message.Upsert ufs) l) v key st1 let node0 ← - betree.Internal.lookup_in_children_back (betree_internal_t.mk i + betree.Internal.lookup_in_children_back (betree.Internal.mk i i0 n n0) key st0 let ⟨ i1, _, _, _ ⟩ := node0 let pending0 ← - betree.Node.apply_upserts_back (betree_list_t.Cons (k, - betree_message_t.Upsert ufs) l) v key st1 + betree.Node.apply_upserts_back (betree.List.Cons (k, + betree.Message.Upsert ufs) l) v key st1 let msgs0 ← betree.Node.lookup_first_message_for_key_back key msgs pending0 let (st3, _) ← betree.store_internal_node_fwd i1 msgs0 st2 Result.ret (st3, Option.some v0) - | betree_list_t.Nil => + | betree.List.Nil => do let (st1, opt) ← - betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i i0 n + betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 n n0) key st0 let _ ← betree.Node.lookup_first_message_for_key_back key msgs - betree_list_t.Nil + betree.List.Nil Result.ret (st1, opt) - | betree_node_t.Leaf node => + | betree.Node.Leaf node => do let (st0, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st let opt ← betree.Node.lookup_in_bindings_fwd key bindings @@ -403,80 +401,78 @@ mutual divergent def betree.Node.lookup_fwd /- [betree_main::betree::Node::{5}::lookup] -/ divergent def betree.Node.lookup_back - (self : betree_node_t) (key : U64) (st : State) : Result betree_node_t := + (self : betree.Node) (key : U64) (st : State) : Result betree.Node := match self with - | betree_node_t.Internal node => + | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node let (st0, msgs) ← betree.load_internal_node_fwd i st let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs match pending with - | betree_list_t.Cons p l => + | betree.List.Cons p l => let (k, msg) := p if k != key then do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, msg) l) + (betree.List.Cons (k, msg) l) let node0 ← - betree.Internal.lookup_in_children_back (betree_internal_t.mk i - i0 n n0) key st0 - Result.ret (betree_node_t.Internal node0) + betree.Internal.lookup_in_children_back (betree.Internal.mk i i0 + n n0) key st0 + Result.ret (betree.Node.Internal node0) else match msg with - | betree_message_t.Insert v => + | betree.Message.Insert v => do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, betree_message_t.Insert v) l) - Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n - n0)) - | betree_message_t.Delete => + (betree.List.Cons (k, betree.Message.Insert v) l) + Result.ret (betree.Node.Internal (betree.Internal.mk i i0 n n0)) + | betree.Message.Delete => do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - (betree_list_t.Cons (k, betree_message_t.Delete) l) - Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n - n0)) - | betree_message_t.Upsert ufs => + (betree.List.Cons (k, betree.Message.Delete) l) + Result.ret (betree.Node.Internal (betree.Internal.mk i i0 n n0)) + | betree.Message.Upsert ufs => do let (st1, v) ← - betree.Internal.lookup_in_children_fwd (betree_internal_t.mk i - i0 n n0) key st0 + betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 + n n0) key st0 let (st2, _) ← - betree.Node.apply_upserts_fwd (betree_list_t.Cons (k, - betree_message_t.Upsert ufs) l) v key st1 + betree.Node.apply_upserts_fwd (betree.List.Cons (k, + betree.Message.Upsert ufs) l) v key st1 let node0 ← - betree.Internal.lookup_in_children_back (betree_internal_t.mk i + betree.Internal.lookup_in_children_back (betree.Internal.mk i i0 n n0) key st0 let ⟨ i1, i2, n1, n2 ⟩ := node0 let pending0 ← - betree.Node.apply_upserts_back (betree_list_t.Cons (k, - betree_message_t.Upsert ufs) l) v key st1 + betree.Node.apply_upserts_back (betree.List.Cons (k, + betree.Message.Upsert ufs) l) v key st1 let msgs0 ← betree.Node.lookup_first_message_for_key_back key msgs pending0 let _ ← betree.store_internal_node_fwd i1 msgs0 st2 - Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 + Result.ret (betree.Node.Internal (betree.Internal.mk i1 i2 n1 n2)) - | betree_list_t.Nil => + | betree.List.Nil => do let _ ← betree.Node.lookup_first_message_for_key_back key msgs - betree_list_t.Nil + betree.List.Nil let node0 ← - betree.Internal.lookup_in_children_back (betree_internal_t.mk i i0 - n n0) key st0 - Result.ret (betree_node_t.Internal node0) - | betree_node_t.Leaf node => + betree.Internal.lookup_in_children_back (betree.Internal.mk i i0 n + n0) key st0 + Result.ret (betree.Node.Internal node0) + | betree.Node.Leaf node => do let (_, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st let _ ← betree.Node.lookup_in_bindings_fwd key bindings - Result.ret (betree_node_t.Leaf node) + Result.ret (betree.Node.Leaf node) /- [betree_main::betree::Internal::{4}::lookup_in_children] -/ divergent def betree.Internal.lookup_in_children_fwd - (self : betree_internal_t) (key : U64) (st : State) : + (self : betree.Internal) (key : U64) (st : State) : Result (State × (Option U64)) := let ⟨ _, i, n, n0 ⟩ := self @@ -486,57 +482,55 @@ divergent def betree.Internal.lookup_in_children_fwd /- [betree_main::betree::Internal::{4}::lookup_in_children] -/ divergent def betree.Internal.lookup_in_children_back - (self : betree_internal_t) (key : U64) (st : State) : - Result betree_internal_t - := + (self : betree.Internal) (key : U64) (st : State) : Result betree.Internal := let ⟨ i, i0, n, n0 ⟩ := self if key < i0 then do let n1 ← betree.Node.lookup_back n key st - Result.ret (betree_internal_t.mk i i0 n1 n0) + Result.ret (betree.Internal.mk i i0 n1 n0) else do let n1 ← betree.Node.lookup_back n0 key st - Result.ret (betree_internal_t.mk i i0 n n1) + Result.ret (betree.Internal.mk i i0 n n1) end /- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ divergent def betree.Node.lookup_mut_in_bindings_fwd - (key : U64) (bindings : betree_list_t (U64 × U64)) : - Result (betree_list_t (U64 × U64)) + (key : U64) (bindings : betree.List (U64 × U64)) : + Result (betree.List (U64 × U64)) := match bindings with - | betree_list_t.Cons hd tl => + | betree.List.Cons hd tl => let (i, i0) := hd if i >= key - then Result.ret (betree_list_t.Cons (i, i0) tl) + then Result.ret (betree.List.Cons (i, i0) tl) else betree.Node.lookup_mut_in_bindings_fwd key tl - | betree_list_t.Nil => Result.ret betree_list_t.Nil + | betree.List.Nil => Result.ret betree.List.Nil /- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ divergent def betree.Node.lookup_mut_in_bindings_back - (key : U64) (bindings : betree_list_t (U64 × U64)) - (ret0 : betree_list_t (U64 × U64)) : - Result (betree_list_t (U64 × U64)) + (key : U64) (bindings : betree.List (U64 × U64)) + (ret0 : betree.List (U64 × U64)) : + Result (betree.List (U64 × U64)) := match bindings with - | betree_list_t.Cons hd tl => + | betree.List.Cons hd tl => let (i, i0) := hd if i >= key then Result.ret ret0 else do let tl0 ← betree.Node.lookup_mut_in_bindings_back key tl ret0 - Result.ret (betree_list_t.Cons (i, i0) tl0) - | betree_list_t.Nil => Result.ret ret0 + Result.ret (betree.List.Cons (i, i0) tl0) + | betree.List.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_to_leaf] -/ def betree.Node.apply_to_leaf_fwd_back - (bindings : betree_list_t (U64 × U64)) (key : U64) - (new_msg : betree_message_t) : - Result (betree_list_t (U64 × U64)) + (bindings : betree.List (U64 × U64)) (key : U64) (new_msg : betree.Message) + : + Result (betree.List (U64 × U64)) := do let bindings0 ← betree.Node.lookup_mut_in_bindings_fwd key bindings @@ -546,17 +540,17 @@ def betree.Node.apply_to_leaf_fwd_back do let hd ← betree.List.pop_front_fwd (U64 × U64) bindings0 match new_msg with - | betree_message_t.Insert v => + | betree.Message.Insert v => do let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 let bindings2 ← betree.List.push_front_fwd_back (U64 × U64) bindings1 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings2 - | betree_message_t.Delete => + | betree.Message.Delete => do let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 betree.Node.lookup_mut_in_bindings_back key bindings bindings1 - | betree_message_t.Upsert s => + | betree.Message.Upsert s => do let (_, i) := hd let v ← betree.upsert_update_fwd (Option.some i) s @@ -566,14 +560,14 @@ def betree.Node.apply_to_leaf_fwd_back betree.Node.lookup_mut_in_bindings_back key bindings bindings2 else match new_msg with - | betree_message_t.Insert v => + | betree.Message.Insert v => do let bindings1 ← betree.List.push_front_fwd_back (U64 × U64) bindings0 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings1 - | betree_message_t.Delete => + | betree.Message.Delete => betree.Node.lookup_mut_in_bindings_back key bindings bindings0 - | betree_message_t.Upsert s => + | betree.Message.Upsert s => do let v ← betree.upsert_update_fwd Option.none s let bindings1 ← @@ -582,170 +576,170 @@ def betree.Node.apply_to_leaf_fwd_back /- [betree_main::betree::Node::{5}::apply_messages_to_leaf] -/ divergent def betree.Node.apply_messages_to_leaf_fwd_back - (bindings : betree_list_t (U64 × U64)) - (new_msgs : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × U64)) + (bindings : betree.List (U64 × U64)) + (new_msgs : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × U64)) := match new_msgs with - | betree_list_t.Cons new_msg new_msgs_tl => + | betree.List.Cons new_msg new_msgs_tl => do let (i, m) := new_msg let bindings0 ← betree.Node.apply_to_leaf_fwd_back bindings i m betree.Node.apply_messages_to_leaf_fwd_back bindings0 new_msgs_tl - | betree_list_t.Nil => Result.ret bindings + | betree.List.Nil => Result.ret bindings /- [betree_main::betree::Node::{5}::filter_messages_for_key] -/ divergent def betree.Node.filter_messages_for_key_fwd_back - (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (key : U64) (msgs : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match msgs with - | betree_list_t.Cons p l => + | betree.List.Cons p l => let (k, m) := p if k = key then do let msgs0 ← - betree.List.pop_front_back (U64 × betree_message_t) - (betree_list_t.Cons (k, m) l) + betree.List.pop_front_back (U64 × betree.Message) (betree.List.Cons + (k, m) l) betree.Node.filter_messages_for_key_fwd_back key msgs0 - else Result.ret (betree_list_t.Cons (k, m) l) - | betree_list_t.Nil => Result.ret betree_list_t.Nil + else Result.ret (betree.List.Cons (k, m) l) + | betree.List.Nil => Result.ret betree.List.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ divergent def betree.Node.lookup_first_message_after_key_fwd - (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (key : U64) (msgs : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match msgs with - | betree_list_t.Cons p next_msgs => + | betree.List.Cons p next_msgs => let (k, m) := p if k = key then betree.Node.lookup_first_message_after_key_fwd key next_msgs - else Result.ret (betree_list_t.Cons (k, m) next_msgs) - | betree_list_t.Nil => Result.ret betree_list_t.Nil + else Result.ret (betree.List.Cons (k, m) next_msgs) + | betree.List.Nil => Result.ret betree.List.Nil /- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ divergent def betree.Node.lookup_first_message_after_key_back - (key : U64) (msgs : betree_list_t (U64 × betree_message_t)) - (ret0 : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (key : U64) (msgs : betree.List (U64 × betree.Message)) + (ret0 : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match msgs with - | betree_list_t.Cons p next_msgs => + | betree.List.Cons p next_msgs => let (k, m) := p if k = key then do let next_msgs0 ← betree.Node.lookup_first_message_after_key_back key next_msgs ret0 - Result.ret (betree_list_t.Cons (k, m) next_msgs0) + Result.ret (betree.List.Cons (k, m) next_msgs0) else Result.ret ret0 - | betree_list_t.Nil => Result.ret ret0 + | betree.List.Nil => Result.ret ret0 /- [betree_main::betree::Node::{5}::apply_to_internal] -/ def betree.Node.apply_to_internal_fwd_back - (msgs : betree_list_t (U64 × betree_message_t)) (key : U64) - (new_msg : betree_message_t) : - Result (betree_list_t (U64 × betree_message_t)) + (msgs : betree.List (U64 × betree.Message)) (key : U64) + (new_msg : betree.Message) : + Result (betree.List (U64 × betree.Message)) := do let msgs0 ← betree.Node.lookup_first_message_for_key_fwd key msgs - let b ← betree.List.head_has_key_fwd betree_message_t msgs0 key + let b ← betree.List.head_has_key_fwd betree.Message msgs0 key if b then match new_msg with - | betree_message_t.Insert i => + | betree.Message.Insert i => do let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 - (key, betree_message_t.Insert i) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 (key, + betree.Message.Insert i) betree.Node.lookup_first_message_for_key_back key msgs msgs2 - | betree_message_t.Delete => + | betree.Message.Delete => do let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 - (key, betree_message_t.Delete) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 (key, + betree.Message.Delete) betree.Node.lookup_first_message_for_key_back key msgs msgs2 - | betree_message_t.Upsert s => + | betree.Message.Upsert s => do - let p ← betree.List.hd_fwd (U64 × betree_message_t) msgs0 + let p ← betree.List.hd_fwd (U64 × betree.Message) msgs0 let (_, m) := p match m with - | betree_message_t.Insert prev => + | betree.Message.Insert prev => do let v ← betree.upsert_update_fwd (Option.some prev) s let msgs1 ← - betree.List.pop_front_back (U64 × betree_message_t) msgs0 + betree.List.pop_front_back (U64 × betree.Message) msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 - (key, betree_message_t.Insert v) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 + (key, betree.Message.Insert v) betree.Node.lookup_first_message_for_key_back key msgs msgs2 - | betree_message_t.Delete => + | betree.Message.Delete => do let v ← betree.upsert_update_fwd Option.none s let msgs1 ← - betree.List.pop_front_back (U64 × betree_message_t) msgs0 + betree.List.pop_front_back (U64 × betree.Message) msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 - (key, betree_message_t.Insert v) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 + (key, betree.Message.Insert v) betree.Node.lookup_first_message_for_key_back key msgs msgs2 - | betree_message_t.Upsert ufs => + | betree.Message.Upsert ufs => do let msgs1 ← betree.Node.lookup_first_message_after_key_fwd key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs1 - (key, betree_message_t.Upsert s) + betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 + (key, betree.Message.Upsert s) let msgs3 ← betree.Node.lookup_first_message_after_key_back key msgs0 msgs2 betree.Node.lookup_first_message_for_key_back key msgs msgs3 else do let msgs1 ← - betree.List.push_front_fwd_back (U64 × betree_message_t) msgs0 (key, + betree.List.push_front_fwd_back (U64 × betree.Message) msgs0 (key, new_msg) betree.Node.lookup_first_message_for_key_back key msgs msgs1 /- [betree_main::betree::Node::{5}::apply_messages_to_internal] -/ divergent def betree.Node.apply_messages_to_internal_fwd_back - (msgs : betree_list_t (U64 × betree_message_t)) - (new_msgs : betree_list_t (U64 × betree_message_t)) : - Result (betree_list_t (U64 × betree_message_t)) + (msgs : betree.List (U64 × betree.Message)) + (new_msgs : betree.List (U64 × betree.Message)) : + Result (betree.List (U64 × betree.Message)) := match new_msgs with - | betree_list_t.Cons new_msg new_msgs_tl => + | betree.List.Cons new_msg new_msgs_tl => do let (i, m) := new_msg let msgs0 ← betree.Node.apply_to_internal_fwd_back msgs i m betree.Node.apply_messages_to_internal_fwd_back msgs0 new_msgs_tl - | betree_list_t.Nil => Result.ret msgs + | betree.List.Nil => Result.ret msgs /- [betree_main::betree::Node::{5}::apply_messages] -/ mutual divergent def betree.Node.apply_messages_fwd - (self : betree_node_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) - (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : + (self : betree.Node) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) + (msgs : betree.List (U64 × betree.Message)) (st : State) : Result (State × Unit) := match self with - | betree_node_t.Internal node => + | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node let (st0, content) ← betree.load_internal_node_fwd i st let content0 ← betree.Node.apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree.List.len_fwd (U64 × betree_message_t) content0 + let num_msgs ← betree.List.len_fwd (U64 × betree.Message) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree.Internal.flush_fwd (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_fwd (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, _) ← - betree.Internal.flush_back (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_back (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, _, _, _ ⟩ := node0 let (st2, _) ← betree.store_internal_node_fwd i1 content1 st1 @@ -754,7 +748,7 @@ mutual divergent def betree.Node.apply_messages_fwd do let (st1, _) ← betree.store_internal_node_fwd i content0 st0 Result.ret (st1, ()) - | betree_node_t.Leaf node => + | betree.Node.Leaf node => do let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs @@ -766,8 +760,7 @@ mutual divergent def betree.Node.apply_messages_fwd let (st1, _) ← betree.Leaf.split_fwd node content0 params node_id_cnt st0 let (st2, _) ← - betree.store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil - st1 + betree.store_leaf_node_fwd node.betree_leaf_id betree.List.Nil st1 Result.ret (st2, ()) else do @@ -777,38 +770,38 @@ mutual divergent def betree.Node.apply_messages_fwd /- [betree_main::betree::Node::{5}::apply_messages] -/ divergent def betree.Node.apply_messages_back - (self : betree_node_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) - (msgs : betree_list_t (U64 × betree_message_t)) (st : State) : - Result (betree_node_t × betree_node_id_counter_t) + (self : betree.Node) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) + (msgs : betree.List (U64 × betree.Message)) (st : State) : + Result (betree.Node × betree.NodeIdCounter) := match self with - | betree_node_t.Internal node => + | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node let (st0, content) ← betree.load_internal_node_fwd i st let content0 ← betree.Node.apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree.List.len_fwd (U64 × betree_message_t) content0 + let num_msgs ← betree.List.len_fwd (U64 × betree.Message) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree.Internal.flush_fwd (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_fwd (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, node_id_cnt0) ← - betree.Internal.flush_back (betree_internal_t.mk i i0 n n0) params + betree.Internal.flush_back (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, i2, n1, n2 ⟩ := node0 let _ ← betree.store_internal_node_fwd i1 content1 st1 - Result.ret (betree_node_t.Internal (betree_internal_t.mk i1 i2 n1 - n2), node_id_cnt0) + Result.ret (betree.Node.Internal (betree.Internal.mk i1 i2 n1 n2), + node_id_cnt0) else do let _ ← betree.store_internal_node_fwd i content0 st0 - Result.ret (betree_node_t.Internal (betree_internal_t.mk i i0 n n0), + Result.ret (betree.Node.Internal (betree.Internal.mk i i0 n n0), node_id_cnt) - | betree_node_t.Leaf node => + | betree.Node.Leaf node => do let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs @@ -820,29 +813,28 @@ divergent def betree.Node.apply_messages_back let (st1, new_node) ← betree.Leaf.split_fwd node content0 params node_id_cnt st0 let _ ← - betree.store_leaf_node_fwd node.betree_leaf_id betree_list_t.Nil - st1 + betree.store_leaf_node_fwd node.betree_leaf_id betree.List.Nil st1 let node_id_cnt0 ← betree.Leaf.split_back node content0 params node_id_cnt st0 - Result.ret (betree_node_t.Internal new_node, node_id_cnt0) + Result.ret (betree.Node.Internal new_node, node_id_cnt0) else do let _ ← betree.store_leaf_node_fwd node.betree_leaf_id content0 st0 - Result.ret (betree_node_t.Leaf { node with betree_leaf_size := len }, + Result.ret (betree.Node.Leaf { node with betree_leaf_size := len }, node_id_cnt) /- [betree_main::betree::Internal::{4}::flush] -/ divergent def betree.Internal.flush_fwd - (self : betree_internal_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) - (content : betree_list_t (U64 × betree_message_t)) (st : State) : - Result (State × (betree_list_t (U64 × betree_message_t))) + (self : betree.Internal) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) + (content : betree.List (U64 × betree.Message)) (st : State) : + Result (State × (betree.List (U64 × betree.Message))) := do let ⟨ _, i, n, n0 ⟩ := self - let p ← betree.List.partition_at_pivot_fwd betree_message_t content i + let p ← betree.List.partition_at_pivot_fwd betree.Message content i let (msgs_left, msgs_right) := p - let len_left ← betree.List.len_fwd (U64 × betree_message_t) msgs_left + let len_left ← betree.List.len_fwd (U64 × betree.Message) msgs_left if len_left >= params.betree_params_min_flush_size then do @@ -851,7 +843,7 @@ divergent def betree.Internal.flush_fwd let (_, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← - betree.List.len_fwd (U64 × betree_message_t) msgs_right + betree.List.len_fwd (U64 × betree.Message) msgs_right if len_right >= params.betree_params_min_flush_size then do @@ -861,7 +853,7 @@ divergent def betree.Internal.flush_fwd let _ ← betree.Node.apply_messages_back n0 params node_id_cnt0 msgs_right st0 - Result.ret (st1, betree_list_t.Nil) + Result.ret (st1, betree.List.Nil) else Result.ret (st0, msgs_right) else do @@ -873,16 +865,16 @@ divergent def betree.Internal.flush_fwd /- [betree_main::betree::Internal::{4}::flush] -/ divergent def betree.Internal.flush_back - (self : betree_internal_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) - (content : betree_list_t (U64 × betree_message_t)) (st : State) : - Result (betree_internal_t × betree_node_id_counter_t) + (self : betree.Internal) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) + (content : betree.List (U64 × betree.Message)) (st : State) : + Result (betree.Internal × betree.NodeIdCounter) := do let ⟨ i, i0, n, n0 ⟩ := self - let p ← betree.List.partition_at_pivot_fwd betree_message_t content i0 + let p ← betree.List.partition_at_pivot_fwd betree.Message content i0 let (msgs_left, msgs_right) := p - let len_left ← betree.List.len_fwd (U64 × betree_message_t) msgs_left + let len_left ← betree.List.len_fwd (U64 × betree.Message) msgs_left if len_left >= params.betree_params_min_flush_size then do @@ -891,60 +883,60 @@ divergent def betree.Internal.flush_back let (n1, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← - betree.List.len_fwd (U64 × betree_message_t) msgs_right + betree.List.len_fwd (U64 × betree.Message) msgs_right if len_right >= params.betree_params_min_flush_size then do let (n2, node_id_cnt1) ← betree.Node.apply_messages_back n0 params node_id_cnt0 msgs_right st0 - Result.ret (betree_internal_t.mk i i0 n1 n2, node_id_cnt1) - else Result.ret (betree_internal_t.mk i i0 n1 n0, node_id_cnt0) + Result.ret (betree.Internal.mk i i0 n1 n2, node_id_cnt1) + else Result.ret (betree.Internal.mk i i0 n1 n0, node_id_cnt0) else do let (n1, node_id_cnt0) ← betree.Node.apply_messages_back n0 params node_id_cnt msgs_right st - Result.ret (betree_internal_t.mk i i0 n n1, node_id_cnt0) + Result.ret (betree.Internal.mk i i0 n n1, node_id_cnt0) end /- [betree_main::betree::Node::{5}::apply] -/ def betree.Node.apply_fwd - (self : betree_node_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) (key : U64) - (new_msg : betree_message_t) (st : State) : + (self : betree.Node) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) (key : U64) (new_msg : betree.Message) + (st : State) : Result (State × Unit) := do - let l := betree_list_t.Nil + let l := betree.List.Nil let (st0, _) ← - betree.Node.apply_messages_fwd self params node_id_cnt - (betree_list_t.Cons (key, new_msg) l) st + betree.Node.apply_messages_fwd self params node_id_cnt (betree.List.Cons + (key, new_msg) l) st let _ ← - betree.Node.apply_messages_back self params node_id_cnt - (betree_list_t.Cons (key, new_msg) l) st + betree.Node.apply_messages_back self params node_id_cnt (betree.List.Cons + (key, new_msg) l) st Result.ret (st0, ()) /- [betree_main::betree::Node::{5}::apply] -/ def betree.Node.apply_back - (self : betree_node_t) (params : betree_params_t) - (node_id_cnt : betree_node_id_counter_t) (key : U64) - (new_msg : betree_message_t) (st : State) : - Result (betree_node_t × betree_node_id_counter_t) + (self : betree.Node) (params : betree.Params) + (node_id_cnt : betree.NodeIdCounter) (key : U64) (new_msg : betree.Message) + (st : State) : + Result (betree.Node × betree.NodeIdCounter) := - let l := betree_list_t.Nil - betree.Node.apply_messages_back self params node_id_cnt (betree_list_t.Cons + let l := betree.List.Nil + betree.Node.apply_messages_back self params node_id_cnt (betree.List.Cons (key, new_msg) l) st /- [betree_main::betree::BeTree::{6}::new] -/ def betree.BeTree.new_fwd (min_flush_size : U64) (split_size : U64) (st : State) : - Result (State × betree_be_tree_t) + Result (State × betree.BeTree) := do let node_id_cnt ← betree.NodeIdCounter.new_fwd let id ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt - let (st0, _) ← betree.store_leaf_node_fwd id betree_list_t.Nil st + let (st0, _) ← betree.store_leaf_node_fwd id betree.List.Nil st let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt Result.ret (st0, { @@ -955,7 +947,7 @@ def betree.BeTree.new_fwd }, betree_be_tree_node_id_cnt := node_id_cnt0, betree_be_tree_root := - (betree_node_t.Leaf + (betree.Node.Leaf { betree_leaf_id := id, betree_leaf_size := (U64.ofInt 0 (by intlit)) @@ -964,7 +956,7 @@ def betree.BeTree.new_fwd /- [betree_main::betree::BeTree::{6}::apply] -/ def betree.BeTree.apply_fwd - (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : + (self : betree.BeTree) (key : U64) (msg : betree.Message) (st : State) : Result (State × Unit) := do @@ -978,8 +970,8 @@ def betree.BeTree.apply_fwd /- [betree_main::betree::BeTree::{6}::apply] -/ def betree.BeTree.apply_back - (self : betree_be_tree_t) (key : U64) (msg : betree_message_t) (st : State) : - Result betree_be_tree_t + (self : betree.BeTree) (key : U64) (msg : betree.Message) (st : State) : + Result betree.BeTree := do let (n, nic) ← @@ -990,74 +982,66 @@ def betree.BeTree.apply_back /- [betree_main::betree::BeTree::{6}::insert] -/ def betree.BeTree.insert_fwd - (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : + (self : betree.BeTree) (key : U64) (value : U64) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree.BeTree.apply_fwd self key (betree_message_t.Insert value) st + betree.BeTree.apply_fwd self key (betree.Message.Insert value) st let _ ← - betree.BeTree.apply_back self key (betree_message_t.Insert value) st + betree.BeTree.apply_back self key (betree.Message.Insert value) st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::insert] -/ def betree.BeTree.insert_back - (self : betree_be_tree_t) (key : U64) (value : U64) (st : State) : - Result betree_be_tree_t + (self : betree.BeTree) (key : U64) (value : U64) (st : State) : + Result betree.BeTree := - betree.BeTree.apply_back self key (betree_message_t.Insert value) st + betree.BeTree.apply_back self key (betree.Message.Insert value) st /- [betree_main::betree::BeTree::{6}::delete] -/ def betree.BeTree.delete_fwd - (self : betree_be_tree_t) (key : U64) (st : State) : - Result (State × Unit) - := + (self : betree.BeTree) (key : U64) (st : State) : Result (State × Unit) := do - let (st0, _) ← - betree.BeTree.apply_fwd self key betree_message_t.Delete st - let _ ← betree.BeTree.apply_back self key betree_message_t.Delete st + let (st0, _) ← betree.BeTree.apply_fwd self key betree.Message.Delete st + let _ ← betree.BeTree.apply_back self key betree.Message.Delete st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::delete] -/ def betree.BeTree.delete_back - (self : betree_be_tree_t) (key : U64) (st : State) : - Result betree_be_tree_t - := - betree.BeTree.apply_back self key betree_message_t.Delete st + (self : betree.BeTree) (key : U64) (st : State) : Result betree.BeTree := + betree.BeTree.apply_back self key betree.Message.Delete st /- [betree_main::betree::BeTree::{6}::upsert] -/ def betree.BeTree.upsert_fwd - (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) - (st : State) : + (self : betree.BeTree) (key : U64) (upd : betree.UpsertFunState) (st : State) + : Result (State × Unit) := do let (st0, _) ← - betree.BeTree.apply_fwd self key (betree_message_t.Upsert upd) st - let _ ← - betree.BeTree.apply_back self key (betree_message_t.Upsert upd) st + betree.BeTree.apply_fwd self key (betree.Message.Upsert upd) st + let _ ← betree.BeTree.apply_back self key (betree.Message.Upsert upd) st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::upsert] -/ def betree.BeTree.upsert_back - (self : betree_be_tree_t) (key : U64) (upd : betree_upsert_fun_state_t) - (st : State) : - Result betree_be_tree_t + (self : betree.BeTree) (key : U64) (upd : betree.UpsertFunState) (st : State) + : + Result betree.BeTree := - betree.BeTree.apply_back self key (betree_message_t.Upsert upd) st + betree.BeTree.apply_back self key (betree.Message.Upsert upd) st /- [betree_main::betree::BeTree::{6}::lookup] -/ def betree.BeTree.lookup_fwd - (self : betree_be_tree_t) (key : U64) (st : State) : + (self : betree.BeTree) (key : U64) (st : State) : Result (State × (Option U64)) := betree.Node.lookup_fwd self.betree_be_tree_root key st /- [betree_main::betree::BeTree::{6}::lookup] -/ def betree.BeTree.lookup_back - (self : betree_be_tree_t) (key : U64) (st : State) : - Result betree_be_tree_t - := + (self : betree.BeTree) (key : U64) (st : State) : Result betree.BeTree := do let n ← betree.Node.lookup_back self.betree_be_tree_root key st Result.ret { self with betree_be_tree_root := n } diff --git a/tests/lean/BetreeMain/FunsExternal.lean b/tests/lean/BetreeMain/FunsExternal.lean index 0c715ef9..7bcba380 100644 --- a/tests/lean/BetreeMain/FunsExternal.lean +++ b/tests/lean/BetreeMain/FunsExternal.lean @@ -9,24 +9,24 @@ open betree_main /- [betree_main::betree_utils::load_internal_node] -/ def betree_utils.load_internal_node_fwd : - U64 → State → Result (State × (betree_list_t (U64 × betree_message_t))) := + U64 → State → Result (State × (betree.List (U64 × betree.Message))) := fun _ _ => .fail .panic /- [betree_main::betree_utils::store_internal_node] -/ def betree_utils.store_internal_node_fwd : - U64 → betree_list_t (U64 × betree_message_t) → State → Result (State + U64 → betree.List (U64 × betree.Message) → State → Result (State × Unit) := fun _ _ _ => .fail .panic /- [betree_main::betree_utils::load_leaf_node] -/ def betree_utils.load_leaf_node_fwd - : U64 → State → Result (State × (betree_list_t (U64 × U64))) := + : U64 → State → Result (State × (betree.List (U64 × U64))) := fun _ _ => .fail .panic /- [betree_main::betree_utils::store_leaf_node] -/ def betree_utils.store_leaf_node_fwd - : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) := + : U64 → betree.List (U64 × U64) → State → Result (State × Unit) := fun _ _ _ => .fail .panic /- [core::option::Option::{0}::unwrap] -/ diff --git a/tests/lean/BetreeMain/FunsExternal_Template.lean b/tests/lean/BetreeMain/FunsExternal_Template.lean index 9b5a54e5..d768bb20 100644 --- a/tests/lean/BetreeMain/FunsExternal_Template.lean +++ b/tests/lean/BetreeMain/FunsExternal_Template.lean @@ -8,22 +8,21 @@ open betree_main /- [betree_main::betree_utils::load_internal_node] -/ axiom betree_utils.load_internal_node_fwd - : - U64 → State → Result (State × (betree_list_t (U64 × betree_message_t))) + : U64 → State → Result (State × (betree.List (U64 × betree.Message))) /- [betree_main::betree_utils::store_internal_node] -/ axiom betree_utils.store_internal_node_fwd : - U64 → betree_list_t (U64 × betree_message_t) → State → Result (State - × Unit) + U64 → betree.List (U64 × betree.Message) → State → Result (State × + Unit) /- [betree_main::betree_utils::load_leaf_node] -/ axiom betree_utils.load_leaf_node_fwd - : U64 → State → Result (State × (betree_list_t (U64 × U64))) + : U64 → State → Result (State × (betree.List (U64 × U64))) /- [betree_main::betree_utils::store_leaf_node] -/ axiom betree_utils.store_leaf_node_fwd - : U64 → betree_list_t (U64 × U64) → State → Result (State × Unit) + : U64 → betree.List (U64 × U64) → State → Result (State × Unit) /- [core::option::Option::{0}::unwrap] -/ axiom core.option.Option.unwrap_fwd diff --git a/tests/lean/BetreeMain/Types.lean b/tests/lean/BetreeMain/Types.lean index 3ecbd668..afbdac9a 100644 --- a/tests/lean/BetreeMain/Types.lean +++ b/tests/lean/BetreeMain/Types.lean @@ -5,53 +5,53 @@ open Primitives namespace betree_main /- [betree_main::betree::List] -/ -inductive betree_list_t (T : Type) := -| Cons : T → betree_list_t T → betree_list_t T -| Nil : betree_list_t T +inductive betree.List (T : Type) := +| Cons : T → betree.List T → betree.List T +| Nil : betree.List T /- [betree_main::betree::UpsertFunState] -/ -inductive betree_upsert_fun_state_t := -| Add : U64 → betree_upsert_fun_state_t -| Sub : U64 → betree_upsert_fun_state_t +inductive betree.UpsertFunState := +| Add : U64 → betree.UpsertFunState +| Sub : U64 → betree.UpsertFunState /- [betree_main::betree::Message] -/ -inductive betree_message_t := -| Insert : U64 → betree_message_t -| Delete : betree_message_t -| Upsert : betree_upsert_fun_state_t → betree_message_t +inductive betree.Message := +| Insert : U64 → betree.Message +| Delete : betree.Message +| Upsert : betree.UpsertFunState → betree.Message /- [betree_main::betree::Leaf] -/ -structure betree_leaf_t where +structure betree.Leaf where betree_leaf_id : U64 betree_leaf_size : U64 mutual /- [betree_main::betree::Node] -/ -inductive betree_node_t := -| Internal : betree_internal_t → betree_node_t -| Leaf : betree_leaf_t → betree_node_t +inductive betree.Node := +| Internal : betree.Internal → betree.Node +| Leaf : betree.Leaf → betree.Node /- [betree_main::betree::Internal] -/ -inductive betree_internal_t := -| mk : U64 → U64 → betree_node_t → betree_node_t → betree_internal_t +inductive betree.Internal := +| mk : U64 → U64 → betree.Node → betree.Node → betree.Internal end /- [betree_main::betree::Params] -/ -structure betree_params_t where +structure betree.Params where betree_params_min_flush_size : U64 betree_params_split_size : U64 /- [betree_main::betree::NodeIdCounter] -/ -structure betree_node_id_counter_t where +structure betree.NodeIdCounter where betree_node_id_counter_next_node_id : U64 /- [betree_main::betree::BeTree] -/ -structure betree_be_tree_t where - betree_be_tree_params : betree_params_t - betree_be_tree_node_id_cnt : betree_node_id_counter_t - betree_be_tree_root : betree_node_t +structure betree.BeTree where + betree_be_tree_params : betree.Params + betree_be_tree_node_id_cnt : betree.NodeIdCounter + betree_be_tree_root : betree.Node /- The state type used in the state-error monad -/ axiom State : Type diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index 39c270be..7014b0d8 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -34,12 +34,12 @@ def mk_pair0_fwd (x : U32) (y : U32) : Result (U32 × U32) := Result.ret (x, y) /- [constants::Pair] -/ -structure pair_t (T1 T2 : Type) where +structure Pair (T1 T2 : Type) where pair_x : T1 pair_y : T2 /- [constants::mk_pair1] -/ -def mk_pair1_fwd (x : U32) (y : U32) : Result (pair_t U32 U32) := +def mk_pair1_fwd (x : U32) (y : U32) : Result (Pair U32 U32) := Result.ret { pair_x := x, pair_y := y } /- [constants::P0] -/ @@ -48,9 +48,9 @@ def p0_body : Result (U32 × U32) := def p0_c : (U32 × U32) := eval_global p0_body (by simp) /- [constants::P1] -/ -def p1_body : Result (pair_t U32 U32) := +def p1_body : Result (Pair U32 U32) := mk_pair1_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) -def p1_c : pair_t U32 U32 := eval_global p1_body (by simp) +def p1_c : Pair U32 U32 := eval_global p1_body (by simp) /- [constants::P2] -/ def p2_body : Result (U32 × U32) := @@ -58,22 +58,22 @@ def p2_body : Result (U32 × U32) := def p2_c : (U32 × U32) := eval_global p2_body (by simp) /- [constants::P3] -/ -def p3_body : Result (pair_t U32 U32) := +def p3_body : Result (Pair U32 U32) := Result.ret { pair_x := (U32.ofInt 0 (by intlit)), pair_y := (U32.ofInt 1 (by intlit)) } -def p3_c : pair_t U32 U32 := eval_global p3_body (by simp) +def p3_c : Pair U32 U32 := eval_global p3_body (by simp) /- [constants::Wrap] -/ -structure wrap_t (T : Type) where +structure Wrap (T : Type) where wrap_val : T /- [constants::Wrap::{0}::new] -/ -def Wrap.new_fwd (T : Type) (val : T) : Result (wrap_t T) := +def Wrap.new_fwd (T : Type) (val : T) : Result (Wrap T) := Result.ret { wrap_val := val } /- [constants::Y] -/ -def y_body : Result (wrap_t I32) := Wrap.new_fwd I32 (I32.ofInt 2 (by intlit)) -def y_c : wrap_t I32 := eval_global y_body (by simp) +def y_body : Result (Wrap I32) := Wrap.new_fwd I32 (I32.ofInt 2 (by intlit)) +def y_c : Wrap I32 := eval_global y_body (by simp) /- [constants::unwrap_y] -/ def unwrap_y_fwd : Result I32 := @@ -123,12 +123,12 @@ def s2_body : Result U32 := incr_fwd s1_c def s2_c : U32 := eval_global s2_body (by simp) /- [constants::S3] -/ -def s3_body : Result (pair_t U32 U32) := Result.ret p3_c -def s3_c : pair_t U32 U32 := eval_global s3_body (by simp) +def s3_body : Result (Pair U32 U32) := Result.ret p3_c +def s3_c : Pair U32 U32 := eval_global s3_body (by simp) /- [constants::S4] -/ -def s4_body : Result (pair_t U32 U32) := +def s4_body : Result (Pair U32 U32) := mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) -def s4_c : pair_t U32 U32 := eval_global s4_body (by simp) +def s4_c : Pair U32 U32 := eval_global s4_body (by simp) end constants diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index 6bfffc33..10efc3db 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -28,10 +28,10 @@ def swap_back /- [external::test_new_non_zero_u32] -/ def test_new_non_zero_u32_fwd - (x : U32) (st : State) : Result (State × core_num_nonzero_non_zero_u32_t) := + (x : U32) (st : State) : Result (State × core.num.nonzero.NonZeroU32) := do let (st0, opt) ← core.num.nonzero.NonZeroU32.new_fwd x st - core.option.Option.unwrap_fwd core_num_nonzero_non_zero_u32_t opt st0 + core.option.Option.unwrap_fwd core.num.nonzero.NonZeroU32 opt st0 /- [external::test_vec] -/ def test_vec_fwd : Result Unit := diff --git a/tests/lean/External/FunsExternal_Template.lean b/tests/lean/External/FunsExternal_Template.lean index d6c0eb1d..669fe91b 100644 --- a/tests/lean/External/FunsExternal_Template.lean +++ b/tests/lean/External/FunsExternal_Template.lean @@ -20,8 +20,7 @@ axiom core.mem.swap_back1 /- [core::num::nonzero::NonZeroU32::{14}::new] -/ axiom core.num.nonzero.NonZeroU32.new_fwd - : - U32 → State → Result (State × (Option core_num_nonzero_non_zero_u32_t)) + : U32 → State → Result (State × (Option core.num.nonzero.NonZeroU32)) /- [core::option::Option::{0}::unwrap] -/ axiom core.option.Option.unwrap_fwd diff --git a/tests/lean/External/Types.lean b/tests/lean/External/Types.lean index 316f6474..ba984e2a 100644 --- a/tests/lean/External/Types.lean +++ b/tests/lean/External/Types.lean @@ -5,7 +5,7 @@ open Primitives namespace external /- [core::num::nonzero::NonZeroU32] -/ -axiom core_num_nonzero_non_zero_u32_t : Type +axiom core.num.nonzero.NonZeroU32 : Type /- The state type used in the state-error monad -/ axiom State : Type diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 8f54eca8..4f16688b 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -11,28 +11,28 @@ def hash_key_fwd (k : Usize) : Result Usize := /- [hashmap::HashMap::{0}::allocate_slots] -/ divergent def HashMap.allocate_slots_loop_fwd - (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := + (T : Type) (slots : Vec (List T)) (n : Usize) : Result (Vec (List T)) := if n > (Usize.ofInt 0 (by intlit)) then do - let slots0 ← vec_push_back (list_t T) slots list_t.Nil + let slots0 ← vec_push_back (List T) slots List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots /- [hashmap::HashMap::{0}::allocate_slots] -/ def HashMap.allocate_slots_fwd - (T : Type) (slots : Vec (list_t T)) (n : Usize) : Result (Vec (list_t T)) := + (T : Type) (slots : Vec (List T)) (n : Usize) : Result (Vec (List T)) := HashMap.allocate_slots_loop_fwd T slots n /- [hashmap::HashMap::{0}::new_with_capacity] -/ def HashMap.new_with_capacity_fwd (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : - Result (hash_map_t T) + Result (HashMap T) := do - let v := vec_new (list_t T) + let v := vec_new (List T) let slots ← HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor @@ -45,25 +45,25 @@ def HashMap.new_with_capacity_fwd } /- [hashmap::HashMap::{0}::new] -/ -def HashMap.new_fwd (T : Type) : Result (hash_map_t T) := +def HashMap.new_fwd (T : Type) : Result (HashMap T) := HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) /- [hashmap::HashMap::{0}::clear] -/ divergent def HashMap.clear_loop_fwd_back - (T : Type) (slots : Vec (list_t T)) (i : Usize) : Result (Vec (list_t T)) := - let i0 := vec_len (list_t T) slots + (T : Type) (slots : Vec (List T)) (i : Usize) : Result (Vec (List T)) := + let i0 := vec_len (List T) slots if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) - let slots0 ← vec_index_mut_back (list_t T) slots i list_t.Nil + let slots0 ← vec_index_mut_back (List T) slots i List.Nil HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots /- [hashmap::HashMap::{0}::clear] -/ def HashMap.clear_fwd_back - (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := + (T : Type) (self : HashMap T) : Result (HashMap T) := do let v ← HashMap.clear_loop_fwd_back T self.hash_map_slots @@ -77,66 +77,66 @@ def HashMap.clear_fwd_back } /- [hashmap::HashMap::{0}::len] -/ -def HashMap.len_fwd (T : Type) (self : hash_map_t T) : Result Usize := +def HashMap.len_fwd (T : Type) (self : HashMap T) : Result Usize := Result.ret self.hash_map_num_entries /- [hashmap::HashMap::{0}::insert_in_list] -/ divergent def HashMap.insert_in_list_loop_fwd - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := + (T : Type) (key : Usize) (value : T) (ls : List T) : Result Bool := match ls with - | list_t.Cons ckey cvalue tl => + | List.Cons ckey cvalue tl => if ckey = key then Result.ret false else HashMap.insert_in_list_loop_fwd T key value tl - | list_t.Nil => Result.ret true + | List.Nil => Result.ret true /- [hashmap::HashMap::{0}::insert_in_list] -/ def HashMap.insert_in_list_fwd - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result Bool := + (T : Type) (key : Usize) (value : T) (ls : List T) : Result Bool := HashMap.insert_in_list_loop_fwd T key value ls /- [hashmap::HashMap::{0}::insert_in_list] -/ divergent def HashMap.insert_in_list_loop_back - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := + (T : Type) (key : Usize) (value : T) (ls : List T) : Result (List T) := match ls with - | list_t.Cons ckey cvalue tl => + | List.Cons ckey cvalue tl => if ckey = key - then Result.ret (list_t.Cons ckey value tl) + then Result.ret (List.Cons ckey value tl) else do let tl0 ← HashMap.insert_in_list_loop_back T key value tl - Result.ret (list_t.Cons ckey cvalue tl0) - | list_t.Nil => let l := list_t.Nil - Result.ret (list_t.Cons key value l) + Result.ret (List.Cons ckey cvalue tl0) + | List.Nil => let l := List.Nil + Result.ret (List.Cons key value l) /- [hashmap::HashMap::{0}::insert_in_list] -/ def HashMap.insert_in_list_back - (T : Type) (key : Usize) (value : T) (ls : list_t T) : Result (list_t T) := + (T : Type) (key : Usize) (value : T) (ls : List T) : Result (List T) := HashMap.insert_in_list_loop_back T key value ls /- [hashmap::HashMap::{0}::insert_no_resize] -/ def HashMap.insert_no_resize_fwd_back - (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : - Result (hash_map_t T) + (T : Type) (self : HashMap T) (key : Usize) (value : T) : + Result (HashMap T) := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod let inserted ← HashMap.insert_in_list_fwd T key value l if inserted then do let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.insert_in_list_back T key value l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } else do let l0 ← HashMap.insert_in_list_back T key value l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } /- [core::num::u32::{9}::MAX] -/ @@ -146,50 +146,50 @@ def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap::HashMap::{0}::move_elements_from_list] -/ divergent def HashMap.move_elements_from_list_loop_fwd_back - (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := + (T : Type) (ntable : HashMap T) (ls : List T) : Result (HashMap T) := match ls with - | list_t.Cons k v tl => + | List.Cons k v tl => do let ntable0 ← HashMap.insert_no_resize_fwd_back T ntable k v HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl - | list_t.Nil => Result.ret ntable + | List.Nil => Result.ret ntable /- [hashmap::HashMap::{0}::move_elements_from_list] -/ def HashMap.move_elements_from_list_fwd_back - (T : Type) (ntable : hash_map_t T) (ls : list_t T) : Result (hash_map_t T) := + (T : Type) (ntable : HashMap T) (ls : List T) : Result (HashMap T) := HashMap.move_elements_from_list_loop_fwd_back T ntable ls /- [hashmap::HashMap::{0}::move_elements] -/ divergent def HashMap.move_elements_loop_fwd_back - (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : - Result ((hash_map_t T) × (Vec (list_t T))) + (T : Type) (ntable : HashMap T) (slots : Vec (List T)) (i : Usize) : + Result ((HashMap T) × (Vec (List T))) := - let i0 := vec_len (list_t T) slots + let i0 := vec_len (List T) slots if i < i0 then do - let l ← vec_index_mut_fwd (list_t T) slots i - let ls := mem_replace_fwd (list_t T) l list_t.Nil + let l ← vec_index_mut_fwd (List T) slots i + let ls := mem_replace_fwd (List T) l List.Nil let ntable0 ← HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (list_t T) l list_t.Nil - let slots0 ← vec_index_mut_back (list_t T) slots i l0 + let l0 := mem_replace_back (List T) l List.Nil + let slots0 ← vec_index_mut_back (List T) slots i l0 HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) /- [hashmap::HashMap::{0}::move_elements] -/ def HashMap.move_elements_fwd_back - (T : Type) (ntable : hash_map_t T) (slots : Vec (list_t T)) (i : Usize) : - Result ((hash_map_t T) × (Vec (list_t T))) + (T : Type) (ntable : HashMap T) (slots : Vec (List T)) (i : Usize) : + Result ((HashMap T) × (Vec (List T))) := HashMap.move_elements_loop_fwd_back T ntable slots i /- [hashmap::HashMap::{0}::try_resize] -/ def HashMap.try_resize_fwd_back - (T : Type) (self : hash_map_t T) : Result (hash_map_t T) := + (T : Type) (self : HashMap T) : Result (HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (list_t T) self.hash_map_slots + let capacity := vec_len (List T) self.hash_map_slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) let (i, i0) := self.hash_map_max_load_factor let i1 ← n1 / i @@ -212,8 +212,8 @@ def HashMap.try_resize_fwd_back /- [hashmap::HashMap::{0}::insert] -/ def HashMap.insert_fwd_back - (T : Type) (self : hash_map_t T) (key : Usize) (value : T) : - Result (hash_map_t T) + (T : Type) (self : HashMap T) (key : Usize) (value : T) : + Result (HashMap T) := do let self0 ← HashMap.insert_no_resize_fwd_back T self key value @@ -224,162 +224,159 @@ def HashMap.insert_fwd_back /- [hashmap::HashMap::{0}::contains_key_in_list] -/ divergent def HashMap.contains_key_in_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result Bool := + (T : Type) (key : Usize) (ls : List T) : Result Bool := match ls with - | list_t.Cons ckey t tl => + | List.Cons ckey t tl => if ckey = key then Result.ret true else HashMap.contains_key_in_list_loop_fwd T key tl - | list_t.Nil => Result.ret false + | List.Nil => Result.ret false /- [hashmap::HashMap::{0}::contains_key_in_list] -/ def HashMap.contains_key_in_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result Bool := + (T : Type) (key : Usize) (ls : List T) : Result Bool := HashMap.contains_key_in_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::contains_key] -/ def HashMap.contains_key_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result Bool := + (T : Type) (self : HashMap T) (key : Usize) : Result Bool := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_fwd (List T) self.hash_map_slots hash_mod HashMap.contains_key_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_in_list] -/ divergent def HashMap.get_in_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result T := + (T : Type) (key : Usize) (ls : List T) : Result T := match ls with - | list_t.Cons ckey cvalue tl => + | List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue else HashMap.get_in_list_loop_fwd T key tl - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_in_list] -/ def HashMap.get_in_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result T := + (T : Type) (key : Usize) (ls : List T) : Result T := HashMap.get_in_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::get] -/ -def HashMap.get_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result T := +def HashMap.get_fwd (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_fwd (List T) self.hash_map_slots hash_mod HashMap.get_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def HashMap.get_mut_in_list_loop_fwd - (T : Type) (ls : list_t T) (key : Usize) : Result T := + (T : Type) (ls : List T) (key : Usize) : Result T := match ls with - | list_t.Cons ckey cvalue tl => + | List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue else HashMap.get_mut_in_list_loop_fwd T tl key - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_mut_in_list] -/ def HashMap.get_mut_in_list_fwd - (T : Type) (ls : list_t T) (key : Usize) : Result T := + (T : Type) (ls : List T) (key : Usize) : Result T := HashMap.get_mut_in_list_loop_fwd T ls key /- [hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def HashMap.get_mut_in_list_loop_back - (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := + (T : Type) (ls : List T) (key : Usize) (ret0 : T) : Result (List T) := match ls with - | list_t.Cons ckey cvalue tl => + | List.Cons ckey cvalue tl => if ckey = key - then Result.ret (list_t.Cons ckey ret0 tl) + then Result.ret (List.Cons ckey ret0 tl) else do let tl0 ← HashMap.get_mut_in_list_loop_back T tl key ret0 - Result.ret (list_t.Cons ckey cvalue tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons ckey cvalue tl0) + | List.Nil => Result.fail Error.panic /- [hashmap::HashMap::{0}::get_mut_in_list] -/ def HashMap.get_mut_in_list_back - (T : Type) (ls : list_t T) (key : Usize) (ret0 : T) : Result (list_t T) := + (T : Type) (ls : List T) (key : Usize) (ret0 : T) : Result (List T) := HashMap.get_mut_in_list_loop_back T ls key ret0 /- [hashmap::HashMap::{0}::get_mut] -/ def HashMap.get_mut_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result T := + (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod HashMap.get_mut_in_list_fwd T l key /- [hashmap::HashMap::{0}::get_mut] -/ def HashMap.get_mut_back - (T : Type) (self : hash_map_t T) (key : Usize) (ret0 : T) : - Result (hash_map_t T) + (T : Type) (self : HashMap T) (key : Usize) (ret0 : T) : + Result (HashMap T) := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod let l0 ← HashMap.get_mut_in_list_back T l key ret0 - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } /- [hashmap::HashMap::{0}::remove_from_list] -/ divergent def HashMap.remove_from_list_loop_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := + (T : Type) (key : Usize) (ls : List T) : Result (Option T) := match ls with - | list_t.Cons ckey t tl => + | List.Cons ckey t tl => if ckey = key then - let mv_ls := - mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil + let mv_ls := mem_replace_fwd (List T) (List.Cons ckey t tl) List.Nil match mv_ls with - | list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) - | list_t.Nil => Result.fail Error.panic + | List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) + | List.Nil => Result.fail Error.panic else HashMap.remove_from_list_loop_fwd T key tl - | list_t.Nil => Result.ret Option.none + | List.Nil => Result.ret Option.none /- [hashmap::HashMap::{0}::remove_from_list] -/ def HashMap.remove_from_list_fwd - (T : Type) (key : Usize) (ls : list_t T) : Result (Option T) := + (T : Type) (key : Usize) (ls : List T) : Result (Option T) := HashMap.remove_from_list_loop_fwd T key ls /- [hashmap::HashMap::{0}::remove_from_list] -/ divergent def HashMap.remove_from_list_loop_back - (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := + (T : Type) (key : Usize) (ls : List T) : Result (List T) := match ls with - | list_t.Cons ckey t tl => + | List.Cons ckey t tl => if ckey = key then - let mv_ls := - mem_replace_fwd (list_t T) (list_t.Cons ckey t tl) list_t.Nil + let mv_ls := mem_replace_fwd (List T) (List.Cons ckey t tl) List.Nil match mv_ls with - | list_t.Cons i cvalue tl0 => Result.ret tl0 - | list_t.Nil => Result.fail Error.panic + | List.Cons i cvalue tl0 => Result.ret tl0 + | List.Nil => Result.fail Error.panic else do let tl0 ← HashMap.remove_from_list_loop_back T key tl - Result.ret (list_t.Cons ckey t tl0) - | list_t.Nil => Result.ret list_t.Nil + Result.ret (List.Cons ckey t tl0) + | List.Nil => Result.ret List.Nil /- [hashmap::HashMap::{0}::remove_from_list] -/ def HashMap.remove_from_list_back - (T : Type) (key : Usize) (ls : list_t T) : Result (list_t T) := + (T : Type) (key : Usize) (ls : List T) : Result (List T) := HashMap.remove_from_list_loop_back T key ls /- [hashmap::HashMap::{0}::remove] -/ def HashMap.remove_fwd - (T : Type) (self : hash_map_t T) (key : Usize) : Result (Option T) := + (T : Type) (self : HashMap T) (key : Usize) : Result (Option T) := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none @@ -390,24 +387,24 @@ def HashMap.remove_fwd /- [hashmap::HashMap::{0}::remove] -/ def HashMap.remove_back - (T : Type) (self : hash_map_t T) (key : Usize) : Result (hash_map_t T) := + (T : Type) (self : HashMap T) (key : Usize) : Result (HashMap T) := do let hash ← hash_key_fwd key - let i := vec_len (list_t T) self.hash_map_slots + let i := vec_len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (list_t T) self.hash_map_slots hash_mod + let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => do let l0 ← HashMap.remove_from_list_back T key l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } | Option.some x0 => do let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.remove_from_list_back T key l - let v ← vec_index_mut_back (list_t T) self.hash_map_slots hash_mod l0 + let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } diff --git a/tests/lean/Hashmap/Types.lean b/tests/lean/Hashmap/Types.lean index 75a6500f..7530f3b9 100644 --- a/tests/lean/Hashmap/Types.lean +++ b/tests/lean/Hashmap/Types.lean @@ -5,15 +5,15 @@ open Primitives namespace hashmap /- [hashmap::List] -/ -inductive list_t (T : Type) := -| Cons : Usize → T → list_t T → list_t T -| Nil : list_t T +inductive List (T : Type) := +| Cons : Usize → T → List T → List T +| Nil : List T /- [hashmap::HashMap] -/ -structure hash_map_t (T : Type) where +structure HashMap (T : Type) where hash_map_num_entries : Usize hash_map_max_load_factor : (Usize × Usize) hash_map_max_load : Usize - hash_map_slots : Vec (list_t T) + hash_map_slots : Vec (List T) end hashmap diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index 06929431..fd556878 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -12,21 +12,21 @@ def hashmap.hash_key_fwd (k : Usize) : Result Usize := /- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ divergent def hashmap.HashMap.allocate_slots_loop_fwd - (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : - Result (Vec (hashmap_list_t T)) + (T : Type) (slots : Vec (hashmap.List T)) (n : Usize) : + Result (Vec (hashmap.List T)) := if n > (Usize.ofInt 0 (by intlit)) then do - let slots0 ← vec_push_back (hashmap_list_t T) slots hashmap_list_t.Nil + let slots0 ← vec_push_back (hashmap.List T) slots hashmap.List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) hashmap.HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots /- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ def hashmap.HashMap.allocate_slots_fwd - (T : Type) (slots : Vec (hashmap_list_t T)) (n : Usize) : - Result (Vec (hashmap_list_t T)) + (T : Type) (slots : Vec (hashmap.List T)) (n : Usize) : + Result (Vec (hashmap.List T)) := hashmap.HashMap.allocate_slots_loop_fwd T slots n @@ -34,10 +34,10 @@ def hashmap.HashMap.allocate_slots_fwd def hashmap.HashMap.new_with_capacity_fwd (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : - Result (hashmap_hash_map_t T) + Result (hashmap.HashMap T) := do - let v := vec_new (hashmap_list_t T) + let v := vec_new (hashmap.List T) let slots ← hashmap.HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor @@ -51,28 +51,28 @@ def hashmap.HashMap.new_with_capacity_fwd } /- [hashmap_main::hashmap::HashMap::{0}::new] -/ -def hashmap.HashMap.new_fwd (T : Type) : Result (hashmap_hash_map_t T) := +def hashmap.HashMap.new_fwd (T : Type) : Result (hashmap.HashMap T) := hashmap.HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) /- [hashmap_main::hashmap::HashMap::{0}::clear] -/ divergent def hashmap.HashMap.clear_loop_fwd_back - (T : Type) (slots : Vec (hashmap_list_t T)) (i : Usize) : - Result (Vec (hashmap_list_t T)) + (T : Type) (slots : Vec (hashmap.List T)) (i : Usize) : + Result (Vec (hashmap.List T)) := - let i0 := vec_len (hashmap_list_t T) slots + let i0 := vec_len (hashmap.List T) slots if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← - vec_index_mut_back (hashmap_list_t T) slots i hashmap_list_t.Nil + vec_index_mut_back (hashmap.List T) slots i hashmap.List.Nil hashmap.HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots /- [hashmap_main::hashmap::HashMap::{0}::clear] -/ def hashmap.HashMap.clear_fwd_back - (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := + (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let v ← hashmap.HashMap.clear_loop_fwd_back T self.hashmap_hash_map_slots @@ -87,59 +87,59 @@ def hashmap.HashMap.clear_fwd_back /- [hashmap_main::hashmap::HashMap::{0}::len] -/ def hashmap.HashMap.len_fwd - (T : Type) (self : hashmap_hash_map_t T) : Result Usize := + (T : Type) (self : hashmap.HashMap T) : Result Usize := Result.ret self.hashmap_hash_map_num_entries /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ divergent def hashmap.HashMap.insert_in_list_loop_fwd - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := + (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result Bool := match ls with - | hashmap_list_t.Cons ckey cvalue tl => + | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret false else hashmap.HashMap.insert_in_list_loop_fwd T key value tl - | hashmap_list_t.Nil => Result.ret true + | hashmap.List.Nil => Result.ret true /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ def hashmap.HashMap.insert_in_list_fwd - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : Result Bool := + (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result Bool := hashmap.HashMap.insert_in_list_loop_fwd T key value ls /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ divergent def hashmap.HashMap.insert_in_list_loop_back - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) + (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : + Result (hashmap.List T) := match ls with - | hashmap_list_t.Cons ckey cvalue tl => + | hashmap.List.Cons ckey cvalue tl => if ckey = key - then Result.ret (hashmap_list_t.Cons ckey value tl) + then Result.ret (hashmap.List.Cons ckey value tl) else do let tl0 ← hashmap.HashMap.insert_in_list_loop_back T key value tl - Result.ret (hashmap_list_t.Cons ckey cvalue tl0) - | hashmap_list_t.Nil => - let l := hashmap_list_t.Nil - Result.ret (hashmap_list_t.Cons key value l) + Result.ret (hashmap.List.Cons ckey cvalue tl0) + | hashmap.List.Nil => + let l := hashmap.List.Nil + Result.ret (hashmap.List.Cons key value l) /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ def hashmap.HashMap.insert_in_list_back - (T : Type) (key : Usize) (value : T) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) + (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : + Result (hashmap.List T) := hashmap.HashMap.insert_in_list_loop_back T key value ls /- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] -/ def hashmap.HashMap.insert_no_resize_fwd_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : - Result (hashmap_hash_map_t T) + (T : Type) (self : hashmap.HashMap T) (key : Usize) (value : T) : + Result (hashmap.HashMap T) := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod let inserted ← hashmap.HashMap.insert_in_list_fwd T key value l if inserted then @@ -148,7 +148,7 @@ def hashmap.HashMap.insert_no_resize_fwd_back (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { @@ -160,7 +160,7 @@ def hashmap.HashMap.insert_no_resize_fwd_back do let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } @@ -171,57 +171,57 @@ def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ divergent def hashmap.HashMap.move_elements_from_list_loop_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : - Result (hashmap_hash_map_t T) + (T : Type) (ntable : hashmap.HashMap T) (ls : hashmap.List T) : + Result (hashmap.HashMap T) := match ls with - | hashmap_list_t.Cons k v tl => + | hashmap.List.Cons k v tl => do let ntable0 ← hashmap.HashMap.insert_no_resize_fwd_back T ntable k v hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl - | hashmap_list_t.Nil => Result.ret ntable + | hashmap.List.Nil => Result.ret ntable /- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ def hashmap.HashMap.move_elements_from_list_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (ls : hashmap_list_t T) : - Result (hashmap_hash_map_t T) + (T : Type) (ntable : hashmap.HashMap T) (ls : hashmap.List T) : + Result (hashmap.HashMap T) := hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable ls /- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ divergent def hashmap.HashMap.move_elements_loop_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) + (T : Type) (ntable : hashmap.HashMap T) (slots : Vec (hashmap.List T)) (i : Usize) : - Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) + Result ((hashmap.HashMap T) × (Vec (hashmap.List T))) := - let i0 := vec_len (hashmap_list_t T) slots + let i0 := vec_len (hashmap.List T) slots if i < i0 then do - let l ← vec_index_mut_fwd (hashmap_list_t T) slots i - let ls := mem_replace_fwd (hashmap_list_t T) l hashmap_list_t.Nil + let l ← vec_index_mut_fwd (hashmap.List T) slots i + let ls := mem_replace_fwd (hashmap.List T) l hashmap.List.Nil let ntable0 ← hashmap.HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (hashmap_list_t T) l hashmap_list_t.Nil - let slots0 ← vec_index_mut_back (hashmap_list_t T) slots i l0 + let l0 := mem_replace_back (hashmap.List T) l hashmap.List.Nil + let slots0 ← vec_index_mut_back (hashmap.List T) slots i l0 hashmap.HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) /- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ def hashmap.HashMap.move_elements_fwd_back - (T : Type) (ntable : hashmap_hash_map_t T) (slots : Vec (hashmap_list_t T)) + (T : Type) (ntable : hashmap.HashMap T) (slots : Vec (hashmap.List T)) (i : Usize) : - Result ((hashmap_hash_map_t T) × (Vec (hashmap_list_t T))) + Result ((hashmap.HashMap T) × (Vec (hashmap.List T))) := hashmap.HashMap.move_elements_loop_fwd_back T ntable slots i /- [hashmap_main::hashmap::HashMap::{0}::try_resize] -/ def hashmap.HashMap.try_resize_fwd_back - (T : Type) (self : hashmap_hash_map_t T) : Result (hashmap_hash_map_t T) := + (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let capacity := vec_len (hashmap.List T) self.hashmap_hash_map_slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) let (i, i0) := self.hashmap_hash_map_max_load_factor let i1 ← n1 / i @@ -244,8 +244,8 @@ def hashmap.HashMap.try_resize_fwd_back /- [hashmap_main::hashmap::HashMap::{0}::insert] -/ def hashmap.HashMap.insert_fwd_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (value : T) : - Result (hashmap_hash_map_t T) + (T : Type) (self : hashmap.HashMap T) (key : Usize) (value : T) : + Result (hashmap.HashMap T) := do let self0 ← hashmap.HashMap.insert_no_resize_fwd_back T self key value @@ -256,179 +256,175 @@ def hashmap.HashMap.insert_fwd_back /- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ divergent def hashmap.HashMap.contains_key_in_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result Bool := match ls with - | hashmap_list_t.Cons ckey t tl => + | hashmap.List.Cons ckey t tl => if ckey = key then Result.ret true else hashmap.HashMap.contains_key_in_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.ret false + | hashmap.List.Nil => Result.ret false /- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ def hashmap.HashMap.contains_key_in_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result Bool := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result Bool := hashmap.HashMap.contains_key_in_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::contains_key] -/ def hashmap.HashMap.contains_key_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result Bool := + (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result Bool := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.contains_key_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ divergent def hashmap.HashMap.get_in_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result T := match ls with - | hashmap_list_t.Cons ckey cvalue tl => + | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue else hashmap.HashMap.get_in_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.fail Error.panic + | hashmap.List.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ def hashmap.HashMap.get_in_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result T := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result T := hashmap.HashMap.get_in_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::get] -/ def hashmap.HashMap.get_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := + (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.get_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def hashmap.HashMap.get_mut_in_list_loop_fwd - (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := + (T : Type) (ls : hashmap.List T) (key : Usize) : Result T := match ls with - | hashmap_list_t.Cons ckey cvalue tl => + | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue else hashmap.HashMap.get_mut_in_list_loop_fwd T tl key - | hashmap_list_t.Nil => Result.fail Error.panic + | hashmap.List.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ def hashmap.HashMap.get_mut_in_list_fwd - (T : Type) (ls : hashmap_list_t T) (key : Usize) : Result T := + (T : Type) (ls : hashmap.List T) (key : Usize) : Result T := hashmap.HashMap.get_mut_in_list_loop_fwd T ls key /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ divergent def hashmap.HashMap.get_mut_in_list_loop_back - (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : - Result (hashmap_list_t T) + (T : Type) (ls : hashmap.List T) (key : Usize) (ret0 : T) : + Result (hashmap.List T) := match ls with - | hashmap_list_t.Cons ckey cvalue tl => + | hashmap.List.Cons ckey cvalue tl => if ckey = key - then Result.ret (hashmap_list_t.Cons ckey ret0 tl) + then Result.ret (hashmap.List.Cons ckey ret0 tl) else do let tl0 ← hashmap.HashMap.get_mut_in_list_loop_back T tl key ret0 - Result.ret (hashmap_list_t.Cons ckey cvalue tl0) - | hashmap_list_t.Nil => Result.fail Error.panic + Result.ret (hashmap.List.Cons ckey cvalue tl0) + | hashmap.List.Nil => Result.fail Error.panic /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ def hashmap.HashMap.get_mut_in_list_back - (T : Type) (ls : hashmap_list_t T) (key : Usize) (ret0 : T) : - Result (hashmap_list_t T) + (T : Type) (ls : hashmap.List T) (key : Usize) (ret0 : T) : + Result (hashmap.List T) := hashmap.HashMap.get_mut_in_list_loop_back T ls key ret0 /- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ def hashmap.HashMap.get_mut_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result T := + (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.get_mut_in_list_fwd T l key /- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ def hashmap.HashMap.get_mut_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) (ret0 : T) : - Result (hashmap_hash_map_t T) + (T : Type) (self : hashmap.HashMap T) (key : Usize) (ret0 : T) : + Result (hashmap.HashMap T) := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod let l0 ← hashmap.HashMap.get_mut_in_list_back T l key ret0 let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots - hash_mod l0 + vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod + l0 Result.ret { self with hashmap_hash_map_slots := v } /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ divergent def hashmap.HashMap.remove_from_list_loop_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result (Option T) := match ls with - | hashmap_list_t.Cons ckey t tl => + | hashmap.List.Cons ckey t tl => if ckey = key then let mv_ls := - mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) - hashmap_list_t.Nil + mem_replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + hashmap.List.Nil match mv_ls with - | hashmap_list_t.Cons i cvalue tl0 => Result.ret (Option.some cvalue) - | hashmap_list_t.Nil => Result.fail Error.panic + | hashmap.List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) + | hashmap.List.Nil => Result.fail Error.panic else hashmap.HashMap.remove_from_list_loop_fwd T key tl - | hashmap_list_t.Nil => Result.ret Option.none + | hashmap.List.Nil => Result.ret Option.none /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ def hashmap.HashMap.remove_from_list_fwd - (T : Type) (key : Usize) (ls : hashmap_list_t T) : Result (Option T) := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result (Option T) := hashmap.HashMap.remove_from_list_loop_fwd T key ls /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ divergent def hashmap.HashMap.remove_from_list_loop_back - (T : Type) (key : Usize) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) - := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result (hashmap.List T) := match ls with - | hashmap_list_t.Cons ckey t tl => + | hashmap.List.Cons ckey t tl => if ckey = key then let mv_ls := - mem_replace_fwd (hashmap_list_t T) (hashmap_list_t.Cons ckey t tl) - hashmap_list_t.Nil + mem_replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + hashmap.List.Nil match mv_ls with - | hashmap_list_t.Cons i cvalue tl0 => Result.ret tl0 - | hashmap_list_t.Nil => Result.fail Error.panic + | hashmap.List.Cons i cvalue tl0 => Result.ret tl0 + | hashmap.List.Nil => Result.fail Error.panic else do let tl0 ← hashmap.HashMap.remove_from_list_loop_back T key tl - Result.ret (hashmap_list_t.Cons ckey t tl0) - | hashmap_list_t.Nil => Result.ret hashmap_list_t.Nil + Result.ret (hashmap.List.Cons ckey t tl0) + | hashmap.List.Nil => Result.ret hashmap.List.Nil /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ def hashmap.HashMap.remove_from_list_back - (T : Type) (key : Usize) (ls : hashmap_list_t T) : - Result (hashmap_list_t T) - := + (T : Type) (key : Usize) (ls : hashmap.List T) : Result (hashmap.List T) := hashmap.HashMap.remove_from_list_loop_back T key ls /- [hashmap_main::hashmap::HashMap::{0}::remove] -/ def hashmap.HashMap.remove_fwd - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : Result (Option T) := + (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result (Option T) := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none @@ -440,22 +436,22 @@ def hashmap.HashMap.remove_fwd /- [hashmap_main::hashmap::HashMap::{0}::remove] -/ def hashmap.HashMap.remove_back - (T : Type) (self : hashmap_hash_map_t T) (key : Usize) : - Result (hashmap_hash_map_t T) + (T : Type) (self : hashmap.HashMap T) (key : Usize) : + Result (hashmap.HashMap T) := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap_list_t T) self.hashmap_hash_map_slots + let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap_list_t T) self.hashmap_hash_map_slots hash_mod + vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => do let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } | Option.some x0 => @@ -464,7 +460,7 @@ def hashmap.HashMap.remove_back (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← - vec_index_mut_back (hashmap_list_t T) self.hashmap_hash_map_slots + vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { diff --git a/tests/lean/HashmapMain/FunsExternal.lean b/tests/lean/HashmapMain/FunsExternal.lean index d917b485..3689dd45 100644 --- a/tests/lean/HashmapMain/FunsExternal.lean +++ b/tests/lean/HashmapMain/FunsExternal.lean @@ -8,10 +8,10 @@ open hashmap_main /- [hashmap_main::hashmap_utils::deserialize] -/ def hashmap_utils.deserialize_fwd - : State → Result (State × (hashmap_hash_map_t U64)) := + : State → Result (State × (hashmap.HashMap U64)) := fun _ => .fail .panic /- [hashmap_main::hashmap_utils::serialize] -/ def hashmap_utils.serialize_fwd - : hashmap_hash_map_t U64 → State → Result (State × Unit) := + : hashmap.HashMap U64 → State → Result (State × Unit) := fun _ _ => .fail .panic diff --git a/tests/lean/HashmapMain/FunsExternal_Template.lean b/tests/lean/HashmapMain/FunsExternal_Template.lean index 86286373..8853b7fc 100644 --- a/tests/lean/HashmapMain/FunsExternal_Template.lean +++ b/tests/lean/HashmapMain/FunsExternal_Template.lean @@ -8,9 +8,9 @@ open hashmap_main /- [hashmap_main::hashmap_utils::deserialize] -/ axiom hashmap_utils.deserialize_fwd - : State → Result (State × (hashmap_hash_map_t U64)) + : State → Result (State × (hashmap.HashMap U64)) /- [hashmap_main::hashmap_utils::serialize] -/ axiom hashmap_utils.serialize_fwd - : hashmap_hash_map_t U64 → State → Result (State × Unit) + : hashmap.HashMap U64 → State → Result (State × Unit) diff --git a/tests/lean/HashmapMain/Types.lean b/tests/lean/HashmapMain/Types.lean index 16641146..ac195e3d 100644 --- a/tests/lean/HashmapMain/Types.lean +++ b/tests/lean/HashmapMain/Types.lean @@ -5,16 +5,16 @@ open Primitives namespace hashmap_main /- [hashmap_main::hashmap::List] -/ -inductive hashmap_list_t (T : Type) := -| Cons : Usize → T → hashmap_list_t T → hashmap_list_t T -| Nil : hashmap_list_t T +inductive hashmap.List (T : Type) := +| Cons : Usize → T → hashmap.List T → hashmap.List T +| Nil : hashmap.List T /- [hashmap_main::hashmap::HashMap] -/ -structure hashmap_hash_map_t (T : Type) where +structure hashmap.HashMap (T : Type) where hashmap_hash_map_num_entries : Usize hashmap_hash_map_max_load_factor : (Usize × Usize) hashmap_hash_map_max_load : Usize - hashmap_hash_map_slots : Vec (hashmap_list_t T) + hashmap_hash_map_slots : Vec (hashmap.List T) /- The state type used in the state-error monad -/ axiom State : Type diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 694f5450..383bc819 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -68,179 +68,175 @@ def clear_fwd_back (v : Vec U32) : Result (Vec U32) := clear_loop_fwd_back v (Usize.ofInt 0 (by intlit)) /- [loops::list_mem] -/ -divergent def list_mem_loop_fwd (x : U32) (ls : list_t U32) : Result Bool := +divergent def list_mem_loop_fwd (x : U32) (ls : List U32) : Result Bool := match ls with - | list_t.Cons y tl => - if y = x - then Result.ret true - else list_mem_loop_fwd x tl - | list_t.Nil => Result.ret false + | List.Cons y tl => if y = x + then Result.ret true + else list_mem_loop_fwd x tl + | List.Nil => Result.ret false /- [loops::list_mem] -/ -def list_mem_fwd (x : U32) (ls : list_t U32) : Result Bool := +def list_mem_fwd (x : U32) (ls : List U32) : Result Bool := list_mem_loop_fwd x ls /- [loops::list_nth_mut_loop] -/ divergent def list_nth_mut_loop_loop_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := + (T : Type) (ls : List T) (i : U32) : Result T := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_loop_loop_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := +def list_nth_mut_loop_fwd (T : Type) (ls : List T) (i : U32) : Result T := list_nth_mut_loop_loop_fwd T ls i /- [loops::list_nth_mut_loop] -/ divergent def list_nth_mut_loop_loop_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) + then Result.ret (List.Cons ret0 tl) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl0 ← list_nth_mut_loop_loop_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x tl0) + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop] -/ def list_nth_mut_loop_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_loop_loop_back T ls i ret0 /- [loops::list_nth_shared_loop] -/ divergent def list_nth_shared_loop_loop_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := + (T : Type) (ls : List T) (i : U32) : Result T := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_loop_loop_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_loop] -/ -def list_nth_shared_loop_fwd (T : Type) (ls : list_t T) (i : U32) : Result T := +def list_nth_shared_loop_fwd (T : Type) (ls : List T) (i : U32) : Result T := list_nth_shared_loop_loop_fwd T ls i /- [loops::get_elem_mut] -/ divergent def get_elem_mut_loop_fwd - (x : Usize) (ls : list_t Usize) : Result Usize := + (x : Usize) (ls : List Usize) : Result Usize := match ls with - | list_t.Cons y tl => + | List.Cons y tl => if y = x then Result.ret y else get_elem_mut_loop_fwd x tl - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::get_elem_mut] -/ -def get_elem_mut_fwd (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := +def get_elem_mut_fwd (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← - vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← vec_index_mut_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) get_elem_mut_loop_fwd x l /- [loops::get_elem_mut] -/ divergent def get_elem_mut_loop_back - (x : Usize) (ls : list_t Usize) (ret0 : Usize) : Result (list_t Usize) := + (x : Usize) (ls : List Usize) (ret0 : Usize) : Result (List Usize) := match ls with - | list_t.Cons y tl => + | List.Cons y tl => if y = x - then Result.ret (list_t.Cons ret0 tl) + then Result.ret (List.Cons ret0 tl) else do let tl0 ← get_elem_mut_loop_back x tl ret0 - Result.ret (list_t.Cons y tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons y tl0) + | List.Nil => Result.fail Error.panic /- [loops::get_elem_mut] -/ def get_elem_mut_back - (slots : Vec (list_t Usize)) (x : Usize) (ret0 : Usize) : - Result (Vec (list_t Usize)) + (slots : Vec (List Usize)) (x : Usize) (ret0 : Usize) : + Result (Vec (List Usize)) := do - let l ← - vec_index_mut_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← vec_index_mut_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) let l0 ← get_elem_mut_loop_back x l ret0 - vec_index_mut_back (list_t Usize) slots (Usize.ofInt 0 (by intlit)) l0 + vec_index_mut_back (List Usize) slots (Usize.ofInt 0 (by intlit)) l0 /- [loops::get_elem_shared] -/ divergent def get_elem_shared_loop_fwd - (x : Usize) (ls : list_t Usize) : Result Usize := + (x : Usize) (ls : List Usize) : Result Usize := match ls with - | list_t.Cons y tl => + | List.Cons y tl => if y = x then Result.ret y else get_elem_shared_loop_fwd x tl - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::get_elem_shared] -/ def get_elem_shared_fwd - (slots : Vec (list_t Usize)) (x : Usize) : Result Usize := + (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← vec_index_fwd (list_t Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← vec_index_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) get_elem_shared_loop_fwd x l /- [loops::id_mut] -/ -def id_mut_fwd (T : Type) (ls : list_t T) : Result (list_t T) := +def id_mut_fwd (T : Type) (ls : List T) : Result (List T) := Result.ret ls /- [loops::id_mut] -/ -def id_mut_back - (T : Type) (ls : list_t T) (ret0 : list_t T) : Result (list_t T) := +def id_mut_back (T : Type) (ls : List T) (ret0 : List T) : Result (List T) := Result.ret ret0 /- [loops::id_shared] -/ -def id_shared_fwd (T : Type) (ls : list_t T) : Result (list_t T) := +def id_shared_fwd (T : Type) (ls : List T) : Result (List T) := Result.ret ls /- [loops::list_nth_mut_loop_with_id] -/ divergent def list_nth_mut_loop_with_id_loop_fwd - (T : Type) (i : U32) (ls : list_t T) : Result T := + (T : Type) (i : U32) (ls : List T) : Result T := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_loop_with_id_loop_fwd T i0 tl - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_with_id] -/ def list_nth_mut_loop_with_id_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := + (T : Type) (ls : List T) (i : U32) : Result T := do let ls0 ← id_mut_fwd T ls list_nth_mut_loop_with_id_loop_fwd T i ls0 /- [loops::list_nth_mut_loop_with_id] -/ divergent def list_nth_mut_loop_with_id_loop_back - (T : Type) (i : U32) (ls : list_t T) (ret0 : T) : Result (list_t T) := + (T : Type) (i : U32) (ls : List T) (ret0 : T) : Result (List T) := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) + then Result.ret (List.Cons ret0 tl) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl0 ← list_nth_mut_loop_with_id_loop_back T i0 tl ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x tl0) + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_with_id] -/ def list_nth_mut_loop_with_id_back - (T : Type) (ls : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := do let ls0 ← id_mut_fwd T ls let l ← list_nth_mut_loop_with_id_loop_back T i ls0 ret0 @@ -248,378 +244,377 @@ def list_nth_mut_loop_with_id_back /- [loops::list_nth_shared_loop_with_id] -/ divergent def list_nth_shared_loop_with_id_loop_fwd - (T : Type) (i : U32) (ls : list_t T) : Result T := + (T : Type) (i : U32) (ls : List T) : Result T := match ls with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_loop_with_id_loop_fwd T i0 tl - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_loop_with_id] -/ def list_nth_shared_loop_with_id_fwd - (T : Type) (ls : list_t T) (i : U32) : Result T := + (T : Type) (ls : List T) (i : U32) : Result T := do let ls0 ← id_shared_fwd T ls list_nth_shared_loop_with_id_loop_fwd T i ls0 /- [loops::list_nth_mut_loop_pair] -/ divergent def list_nth_mut_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_pair] -/ def list_nth_mut_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_mut_loop_pair_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_loop_pair] -/ divergent def list_nth_mut_loop_pair_loop_back'a - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) + then Result.ret (List.Cons ret0 tl0) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl00 ← list_nth_mut_loop_pair_loop_back'a T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x0 tl00) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_pair] -/ def list_nth_mut_loop_pair_back'a - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_mut_loop_pair_loop_back'a T ls0 ls1 i ret0 /- [loops::list_nth_mut_loop_pair] -/ divergent def list_nth_mut_loop_pair_loop_back'b - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) + then Result.ret (List.Cons ret0 tl1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl10 ← list_nth_mut_loop_pair_loop_back'b T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x1 tl10) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_pair] -/ def list_nth_mut_loop_pair_back'b - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_mut_loop_pair_loop_back'b T ls0 ls1 i ret0 /- [loops::list_nth_shared_loop_pair] -/ divergent def list_nth_shared_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_loop_pair] -/ def list_nth_shared_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_shared_loop_pair_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_loop_pair_merge] -/ divergent def list_nth_mut_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_pair_merge] -/ def list_nth_mut_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_mut_loop_pair_merge_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_loop_pair_merge] -/ divergent def list_nth_mut_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : - Result ((list_t T) × (list_t T)) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : (T × T)) : + Result ((List T) × (List T)) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then - let (t, t0) := ret0 - Result.ret (list_t.Cons t tl0, list_t.Cons t0 tl1) + then let (t, t0) := ret0 + Result.ret (List.Cons t tl0, List.Cons t0 tl1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let (tl00, tl10) ← list_nth_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00, list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x0 tl00, List.Cons x1 tl10) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_pair_merge] -/ def list_nth_mut_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : (T × T)) : - Result ((list_t T) × (list_t T)) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : (T × T)) : + Result ((List T) × (List T)) := list_nth_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 /- [loops::list_nth_shared_loop_pair_merge] -/ divergent def list_nth_shared_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_loop_pair_merge] -/ def list_nth_shared_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_shared_loop_pair_merge_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_shared_loop_pair] -/ divergent def list_nth_mut_shared_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_shared_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_shared_loop_pair] -/ def list_nth_mut_shared_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_mut_shared_loop_pair_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_shared_loop_pair] -/ divergent def list_nth_mut_shared_loop_pair_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) + then Result.ret (List.Cons ret0 tl0) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl00 ← list_nth_mut_shared_loop_pair_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x0 tl00) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_shared_loop_pair] -/ def list_nth_mut_shared_loop_pair_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_mut_shared_loop_pair_loop_back T ls0 ls1 i ret0 /- [loops::list_nth_mut_shared_loop_pair_merge] -/ divergent def list_nth_mut_shared_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_shared_loop_pair_merge] -/ def list_nth_mut_shared_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_mut_shared_loop_pair_merge_loop_fwd T ls0 ls1 i /- [loops::list_nth_mut_shared_loop_pair_merge] -/ divergent def list_nth_mut_shared_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl0) + then Result.ret (List.Cons ret0 tl0) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl00 ← list_nth_mut_shared_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x0 tl00) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x0 tl00) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_shared_loop_pair_merge] -/ def list_nth_mut_shared_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_mut_shared_loop_pair_merge_loop_back T ls0 ls1 i ret0 /- [loops::list_nth_shared_mut_loop_pair] -/ divergent def list_nth_shared_mut_loop_pair_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_mut_loop_pair_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_mut_loop_pair] -/ def list_nth_shared_mut_loop_pair_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_shared_mut_loop_pair_loop_fwd T ls0 ls1 i /- [loops::list_nth_shared_mut_loop_pair] -/ divergent def list_nth_shared_mut_loop_pair_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) + then Result.ret (List.Cons ret0 tl1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl10 ← list_nth_shared_mut_loop_pair_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x1 tl10) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_mut_loop_pair] -/ def list_nth_shared_mut_loop_pair_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_shared_mut_loop_pair_loop_back T ls0 ls1 i ret0 /- [loops::list_nth_shared_mut_loop_pair_merge] -/ divergent def list_nth_shared_mut_loop_pair_merge_loop_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) then Result.ret (x0, x1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_mut_loop_pair_merge] -/ def list_nth_shared_mut_loop_pair_merge_fwd - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) : Result (T × T) := + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := list_nth_shared_mut_loop_pair_merge_loop_fwd T ls0 ls1 i /- [loops::list_nth_shared_mut_loop_pair_merge] -/ divergent def list_nth_shared_mut_loop_pair_merge_loop_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := match ls0 with - | list_t.Cons x0 tl0 => + | List.Cons x0 tl0 => match ls1 with - | list_t.Cons x1 tl1 => + | List.Cons x1 tl1 => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl1) + then Result.ret (List.Cons ret0 tl1) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl10 ← list_nth_shared_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 - Result.ret (list_t.Cons x1 tl10) - | list_t.Nil => Result.fail Error.panic - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x1 tl10) + | List.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_mut_loop_pair_merge] -/ def list_nth_shared_mut_loop_pair_merge_back - (T : Type) (ls0 : list_t T) (ls1 : list_t T) (i : U32) (ret0 : T) : - Result (list_t T) + (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : + Result (List T) := list_nth_shared_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 diff --git a/tests/lean/Loops/Types.lean b/tests/lean/Loops/Types.lean index 5b5ed31f..f8bc193b 100644 --- a/tests/lean/Loops/Types.lean +++ b/tests/lean/Loops/Types.lean @@ -5,8 +5,8 @@ open Primitives namespace loops /- [loops::List] -/ -inductive list_t (T : Type) := -| Cons : T → list_t T → list_t T -| Nil : list_t T +inductive List (T : Type) := +| Cons : T → List T → List T +| Nil : List T end loops diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index 67abc8f6..cdbbcd67 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -5,35 +5,35 @@ open Primitives namespace no_nested_borrows /- [no_nested_borrows::Pair] -/ -structure pair_t (T1 T2 : Type) where +structure Pair (T1 T2 : Type) where pair_x : T1 pair_y : T2 /- [no_nested_borrows::List] -/ -inductive list_t (T : Type) := -| Cons : T → list_t T → list_t T -| Nil : list_t T +inductive List (T : Type) := +| Cons : T → List T → List T +| Nil : List T /- [no_nested_borrows::One] -/ -inductive one_t (T1 : Type) := -| One : T1 → one_t T1 +inductive One (T1 : Type) := +| One : T1 → One T1 /- [no_nested_borrows::EmptyEnum] -/ -inductive empty_enum_t := -| Empty : empty_enum_t +inductive EmptyEnum := +| Empty : EmptyEnum /- [no_nested_borrows::Enum] -/ -inductive enum_t := -| Variant1 : enum_t -| Variant2 : enum_t +inductive Enum := +| Variant1 : Enum +| Variant2 : Enum /- [no_nested_borrows::EmptyStruct] -/ -structure empty_struct_t where +structure EmptyStruct where /- [no_nested_borrows::Sum] -/ -inductive sum_t (T1 T2 : Type) := -| Left : T1 → sum_t T1 T2 -| Right : T2 → sum_t T1 T2 +inductive Sum (T1 T2 : Type) := +| Left : T1 → Sum T1 T2 +| Right : T2 → Sum T1 T2 /- [no_nested_borrows::neg_test] -/ def neg_test_fwd (x : I32) : Result I32 := @@ -175,16 +175,16 @@ def test_copy_int_fwd : Result Unit := #assert (test_copy_int_fwd == .ret ()) /- [no_nested_borrows::is_cons] -/ -def is_cons_fwd (T : Type) (l : list_t T) : Result Bool := +def is_cons_fwd (T : Type) (l : List T) : Result Bool := match l with - | list_t.Cons t l0 => Result.ret true - | list_t.Nil => Result.ret false + | List.Cons t l0 => Result.ret true + | List.Nil => Result.ret false /- [no_nested_borrows::test_is_cons] -/ def test_is_cons_fwd : Result Unit := do - let l := list_t.Nil - let b ← is_cons_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) + let l := List.Nil + let b ← is_cons_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l) if not b then Result.fail Error.panic else Result.ret () @@ -193,16 +193,16 @@ def test_is_cons_fwd : Result Unit := #assert (test_is_cons_fwd == .ret ()) /- [no_nested_borrows::split_list] -/ -def split_list_fwd (T : Type) (l : list_t T) : Result (T × (list_t T)) := +def split_list_fwd (T : Type) (l : List T) : Result (T × (List T)) := match l with - | list_t.Cons hd tl => Result.ret (hd, tl) - | list_t.Nil => Result.fail Error.panic + | List.Cons hd tl => Result.ret (hd, tl) + | List.Nil => Result.fail Error.panic /- [no_nested_borrows::test_split_list] -/ def test_split_list_fwd : Result Unit := do - let l := list_t.Nil - let p ← split_list_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l) + let l := List.Nil + let p ← split_list_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l) let (hd, _) := p if not (hd = (I32.ofInt 0 (by intlit))) then Result.fail Error.panic @@ -254,111 +254,110 @@ def test_char_fwd : Result Char := mutual /- [no_nested_borrows::NodeElem] -/ -inductive node_elem_t (T : Type) := -| Cons : tree_t T → node_elem_t T → node_elem_t T -| Nil : node_elem_t T +inductive NodeElem (T : Type) := +| Cons : Tree T → NodeElem T → NodeElem T +| Nil : NodeElem T /- [no_nested_borrows::Tree] -/ -inductive tree_t (T : Type) := -| Leaf : T → tree_t T -| Node : T → node_elem_t T → tree_t T → tree_t T +inductive Tree (T : Type) := +| Leaf : T → Tree T +| Node : T → NodeElem T → Tree T → Tree T end /- [no_nested_borrows::list_length] -/ -divergent def list_length_fwd (T : Type) (l : list_t T) : Result U32 := +divergent def list_length_fwd (T : Type) (l : List T) : Result U32 := match l with - | list_t.Cons t l1 => + | List.Cons t l1 => do let i ← list_length_fwd T l1 (U32.ofInt 1 (by intlit)) + i - | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) + | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) /- [no_nested_borrows::list_nth_shared] -/ divergent def list_nth_shared_fwd - (T : Type) (l : list_t T) (i : U32) : Result T := + (T : Type) (l : List T) (i : U32) : Result T := match l with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_shared_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [no_nested_borrows::list_nth_mut] -/ -divergent def list_nth_mut_fwd - (T : Type) (l : list_t T) (i : U32) : Result T := +divergent def list_nth_mut_fwd (T : Type) (l : List T) (i : U32) : Result T := match l with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [no_nested_borrows::list_nth_mut] -/ divergent def list_nth_mut_back - (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) + then Result.ret (List.Cons ret0 tl) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl0 ← list_nth_mut_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x tl0) + | List.Nil => Result.fail Error.panic /- [no_nested_borrows::list_rev_aux] -/ divergent def list_rev_aux_fwd - (T : Type) (li : list_t T) (lo : list_t T) : Result (list_t T) := + (T : Type) (li : List T) (lo : List T) : Result (List T) := match li with - | list_t.Cons hd tl => list_rev_aux_fwd T tl (list_t.Cons hd lo) - | list_t.Nil => Result.ret lo + | List.Cons hd tl => list_rev_aux_fwd T tl (List.Cons hd lo) + | List.Nil => Result.ret lo /- [no_nested_borrows::list_rev] -/ -def list_rev_fwd_back (T : Type) (l : list_t T) : Result (list_t T) := - let li := mem_replace_fwd (list_t T) l list_t.Nil - list_rev_aux_fwd T li list_t.Nil +def list_rev_fwd_back (T : Type) (l : List T) : Result (List T) := + let li := mem_replace_fwd (List T) l List.Nil + list_rev_aux_fwd T li List.Nil /- [no_nested_borrows::test_list_functions] -/ def test_list_functions_fwd : Result Unit := do - let l := list_t.Nil - let l0 := list_t.Cons (I32.ofInt 2 (by intlit)) l - let l1 := list_t.Cons (I32.ofInt 1 (by intlit)) l0 - let i ← list_length_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) + let l := List.Nil + let l0 := List.Cons (I32.ofInt 2 (by intlit)) l + let l1 := List.Cons (I32.ofInt 1 (by intlit)) l0 + let i ← list_length_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) if not (i = (U32.ofInt 3 (by intlit))) then Result.fail Error.panic else do let i0 ← - list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) l1) + list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 0 (by intlit)) if not (i0 = (I32.ofInt 0 (by intlit))) then Result.fail Error.panic else do let i1 ← - list_nth_shared_fwd I32 (list_t.Cons (I32.ofInt 0 (by intlit)) - l1) (U32.ofInt 1 (by intlit)) + list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) + (U32.ofInt 1 (by intlit)) if not (i1 = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic else do let i2 ← - list_nth_shared_fwd I32 (list_t.Cons - (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 2 (by intlit)) + list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) + l1) (U32.ofInt 2 (by intlit)) if not (i2 = (I32.ofInt 2 (by intlit))) then Result.fail Error.panic else do let ls ← - list_nth_mut_back I32 (list_t.Cons + list_nth_mut_back I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) (I32.ofInt 3 (by intlit)) let i3 ← @@ -434,11 +433,11 @@ def id_mut_pair4_back'b Result.ret ret0 /- [no_nested_borrows::StructWithTuple] -/ -structure struct_with_tuple_t (T1 T2 : Type) where +structure StructWithTuple (T1 T2 : Type) where struct_with_tuple_p : (T1 × T2) /- [no_nested_borrows::new_tuple1] -/ -def new_tuple1_fwd : Result (struct_with_tuple_t U32 U32) := +def new_tuple1_fwd : Result (StructWithTuple U32 U32) := Result.ret { struct_with_tuple_p := @@ -446,7 +445,7 @@ def new_tuple1_fwd : Result (struct_with_tuple_t U32 U32) := } /- [no_nested_borrows::new_tuple2] -/ -def new_tuple2_fwd : Result (struct_with_tuple_t I16 I16) := +def new_tuple2_fwd : Result (StructWithTuple I16 I16) := Result.ret { struct_with_tuple_p := @@ -454,7 +453,7 @@ def new_tuple2_fwd : Result (struct_with_tuple_t I16 I16) := } /- [no_nested_borrows::new_tuple3] -/ -def new_tuple3_fwd : Result (struct_with_tuple_t U64 I64) := +def new_tuple3_fwd : Result (StructWithTuple U64 I64) := Result.ret { struct_with_tuple_p := @@ -462,11 +461,11 @@ def new_tuple3_fwd : Result (struct_with_tuple_t U64 I64) := } /- [no_nested_borrows::StructWithPair] -/ -structure struct_with_pair_t (T1 T2 : Type) where - struct_with_pair_p : pair_t T1 T2 +structure StructWithPair (T1 T2 : Type) where + struct_with_pair_p : Pair T1 T2 /- [no_nested_borrows::new_pair1] -/ -def new_pair1_fwd : Result (struct_with_pair_t U32 U32) := +def new_pair1_fwd : Result (StructWithPair U32 U32) := Result.ret { struct_with_pair_p := @@ -531,10 +530,10 @@ def test_shared_borrow_bool2_fwd : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) /- [no_nested_borrows::test_shared_borrow_enum1] -/ -def test_shared_borrow_enum1_fwd (l : list_t U32) : Result U32 := +def test_shared_borrow_enum1_fwd (l : List U32) : Result U32 := match l with - | list_t.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) - | list_t.Nil => Result.ret (U32.ofInt 0 (by intlit)) + | List.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) + | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) /- [no_nested_borrows::test_shared_borrow_enum2] -/ def test_shared_borrow_enum2_fwd : Result U32 := diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean index c34941ef..9f63b460 100644 --- a/tests/lean/Paper.lean +++ b/tests/lean/Paper.lean @@ -56,56 +56,55 @@ def test_choose_fwd : Result Unit := #assert (test_choose_fwd == .ret ()) /- [paper::List] -/ -inductive list_t (T : Type) := -| Cons : T → list_t T → list_t T -| Nil : list_t T +inductive List (T : Type) := +| Cons : T → List T → List T +| Nil : List T /- [paper::list_nth_mut] -/ -divergent def list_nth_mut_fwd - (T : Type) (l : list_t T) (i : U32) : Result T := +divergent def list_nth_mut_fwd (T : Type) (l : List T) (i : U32) : Result T := match l with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) list_nth_mut_fwd T tl i0 - | list_t.Nil => Result.fail Error.panic + | List.Nil => Result.fail Error.panic /- [paper::list_nth_mut] -/ divergent def list_nth_mut_back - (T : Type) (l : list_t T) (i : U32) (ret0 : T) : Result (list_t T) := + (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with - | list_t.Cons x tl => + | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) - then Result.ret (list_t.Cons ret0 tl) + then Result.ret (List.Cons ret0 tl) else do let i0 ← i - (U32.ofInt 1 (by intlit)) let tl0 ← list_nth_mut_back T tl i0 ret0 - Result.ret (list_t.Cons x tl0) - | list_t.Nil => Result.fail Error.panic + Result.ret (List.Cons x tl0) + | List.Nil => Result.fail Error.panic /- [paper::sum] -/ -divergent def sum_fwd (l : list_t I32) : Result I32 := +divergent def sum_fwd (l : List I32) : Result I32 := match l with - | list_t.Cons x tl => do - let i ← sum_fwd tl - x + i - | list_t.Nil => Result.ret (I32.ofInt 0 (by intlit)) + | List.Cons x tl => do + let i ← sum_fwd tl + x + i + | List.Nil => Result.ret (I32.ofInt 0 (by intlit)) /- [paper::test_nth] -/ def test_nth_fwd : Result Unit := do - let l := list_t.Nil - let l0 := list_t.Cons (I32.ofInt 3 (by intlit)) l - let l1 := list_t.Cons (I32.ofInt 2 (by intlit)) l0 + let l := List.Nil + let l0 := List.Cons (I32.ofInt 3 (by intlit)) l + let l1 := List.Cons (I32.ofInt 2 (by intlit)) l0 let x ← - list_nth_mut_fwd I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) + list_nth_mut_fwd I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) (U32.ofInt 2 (by intlit)) let x0 ← x + (I32.ofInt 1 (by intlit)) let l2 ← - list_nth_mut_back I32 (list_t.Cons (I32.ofInt 1 (by intlit)) l1) + list_nth_mut_back I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) (U32.ofInt 2 (by intlit)) x0 let i ← sum_fwd l2 if not (i = (I32.ofInt 7 (by intlit))) diff --git a/tests/lean/PoloniusList.lean b/tests/lean/PoloniusList.lean index 0ff01b47..1d7ec99b 100644 --- a/tests/lean/PoloniusList.lean +++ b/tests/lean/PoloniusList.lean @@ -5,31 +5,31 @@ open Primitives namespace polonius_list /- [polonius_list::List] -/ -inductive list_t (T : Type) := -| Cons : T → list_t T → list_t T -| Nil : list_t T +inductive List (T : Type) := +| Cons : T → List T → List T +| Nil : List T /- [polonius_list::get_list_at_x] -/ divergent def get_list_at_x_fwd - (ls : list_t U32) (x : U32) : Result (list_t U32) := + (ls : List U32) (x : U32) : Result (List U32) := match ls with - | list_t.Cons hd tl => + | List.Cons hd tl => if hd = x - then Result.ret (list_t.Cons hd tl) + then Result.ret (List.Cons hd tl) else get_list_at_x_fwd tl x - | list_t.Nil => Result.ret list_t.Nil + | List.Nil => Result.ret List.Nil /- [polonius_list::get_list_at_x] -/ divergent def get_list_at_x_back - (ls : list_t U32) (x : U32) (ret0 : list_t U32) : Result (list_t U32) := + (ls : List U32) (x : U32) (ret0 : List U32) : Result (List U32) := match ls with - | list_t.Cons hd tl => + | List.Cons hd tl => if hd = x then Result.ret ret0 else do let tl0 ← get_list_at_x_back tl x ret0 - Result.ret (list_t.Cons hd tl0) - | list_t.Nil => Result.ret ret0 + Result.ret (List.Cons hd tl0) + | List.Nil => Result.ret ret0 end polonius_list -- cgit v1.2.3 From 5ca36bfc50083a01af2b7ae5f75993a520757ef5 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 5 Jul 2023 15:17:58 +0200 Subject: Simplify the names used in Primitives.lean --- backends/lean/Base/Primitives.lean | 37 ++++++++++++---------- compiler/Extract.ml | 49 +++++++++++++++++++---------- tests/lean/BetreeMain/Funs.lean | 6 ++-- tests/lean/External/Funs.lean | 4 +-- tests/lean/Hashmap/Funs.lean | 62 ++++++++++++++++++------------------ tests/lean/HashmapMain/Funs.lean | 64 ++++++++++++++++++-------------------- tests/lean/Loops/Funs.lean | 12 +++---- tests/lean/NoNestedBorrows.lean | 4 +-- tests/lean/lake-manifest.json | 2 +- 9 files changed, 130 insertions(+), 110 deletions(-) diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 117f76a2..808c1461 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -564,15 +564,17 @@ macro_rules def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } -def vec_new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ +def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ -def vec_len (α : Type u) (v : Vec α) : Usize := +def Vec.len (α : Type u) (v : Vec α) : Usize := let ⟨ v, l ⟩ := v Usize.ofIntCore (List.length v) (by simp [Scalar.min]) l -def vec_push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () +-- This shouldn't be used +def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () -def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) +-- This is actually the backward function +def Vec.push (α : Type u) (v : Vec α) (x : α) : Result (Vec α) := let nlen := List.length v.val + 1 if h : nlen ≤ U32.max || nlen ≤ Usize.max then @@ -588,13 +590,15 @@ def vec_push_back (α : Type u) (v : Vec α) (x : α) : Result (Vec α) else fail maximumSizeExceeded -def vec_insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := +-- This shouldn't be used +def Vec.insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := if i.val < List.length v.val then .ret () else .fail arrayOutOfBounds -def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := +-- This is actually the backward function +def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := if i.val < List.length v.val then -- TODO: maybe we should redefine a list library which uses integers -- (instead of natural numbers) @@ -607,7 +611,7 @@ def vec_insert_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α else .fail arrayOutOfBounds -def vec_index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : +def Vec.index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : Fin (List.length v.val) := let j := i.val.toNat let h: j < List.length v.val := by @@ -616,29 +620,30 @@ def vec_index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.leng assumption ⟨j, h⟩ -def vec_index_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := +def Vec.index (α : Type u) (v: Vec α) (i: Usize): Result α := if h: i.val < List.length v.val then - let i := vec_index_to_fin h + let i := Vec.index_to_fin h .ret (List.get v.val i) else .fail arrayOutOfBounds -def vec_index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := +-- This shouldn't be used +def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := if i.val < List.length v.val then .ret () else .fail arrayOutOfBounds -def vec_index_mut_fwd (α : Type u) (v: Vec α) (i: Usize): Result α := +def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize): Result α := if h: i.val < List.length v.val then - let i := vec_index_to_fin h + let i := Vec.index_to_fin h .ret (List.get v.val i) else .fail arrayOutOfBounds -def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := +def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := if h: i.val < List.length v.val then - let i := vec_index_to_fin h + let i := Vec.index_to_fin h .ret ⟨ List.set v.val i x, by have h: List.length v.val ≤ Usize.max := v.property simp [*] at * @@ -651,8 +656,8 @@ def vec_index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec -- MISC -- ---------- -@[simp] def mem_replace_fwd (a : Type) (x : a) (_ : a) : a := x -@[simp] def mem_replace_back (a : Type) (_ : a) (y : a) : a := y +@[simp] def mem.replace_fwd (a : Type) (x : a) (_ : a) : a := x +@[simp] def mem.replace_back (a : Type) (_ : a) (y : a) : a := y /-- Aeneas-translated function -- useful to reduce non-recursive definitions. Use with `simp [ aeneas ]` -/ diff --git a/compiler/Extract.ml b/compiler/Extract.ml index 821bf4f7..180ca7ca 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -300,23 +300,40 @@ let assumed_variants () : (assumed_ty * VariantId.id * string) list = (Option, option_none_id, "NONE"); ] -let assumed_llbc_functions : +let assumed_llbc_functions () : (A.assumed_fun_id * T.RegionGroupId.id option * string) list = let rg0 = Some T.RegionGroupId.zero in - [ - (Replace, None, "mem_replace_fwd"); - (Replace, rg0, "mem_replace_back"); - (VecNew, None, "vec_new"); - (VecPush, None, "vec_push_fwd") (* Shouldn't be used *); - (VecPush, rg0, "vec_push_back"); - (VecInsert, None, "vec_insert_fwd") (* Shouldn't be used *); - (VecInsert, rg0, "vec_insert_back"); - (VecLen, None, "vec_len"); - (VecIndex, None, "vec_index_fwd"); - (VecIndex, rg0, "vec_index_back") (* shouldn't be used *); - (VecIndexMut, None, "vec_index_mut_fwd"); - (VecIndexMut, rg0, "vec_index_mut_back"); - ] + match !backend with + | FStar | Coq | HOL4 -> + [ + (Replace, None, "mem_replace_fwd"); + (Replace, rg0, "mem_replace_back"); + (VecNew, None, "vec_new"); + (VecPush, None, "vec_push_fwd") (* Shouldn't be used *); + (VecPush, rg0, "vec_push_back"); + (VecInsert, None, "vec_insert_fwd") (* Shouldn't be used *); + (VecInsert, rg0, "vec_insert_back"); + (VecLen, None, "vec_len"); + (VecIndex, None, "vec_index_fwd"); + (VecIndex, rg0, "vec_index_back") (* shouldn't be used *); + (VecIndexMut, None, "vec_index_mut_fwd"); + (VecIndexMut, rg0, "vec_index_mut_back"); + ] + | Lean -> + [ + (Replace, None, "mem.replace_fwd"); + (Replace, rg0, "mem.replace_back"); + (VecNew, None, "Vec.new"); + (VecPush, None, "Vec.push_fwd") (* Shouldn't be used *); + (VecPush, rg0, "Vec.push"); + (VecInsert, None, "Vec.insert_fwd") (* Shouldn't be used *); + (VecInsert, rg0, "Vec.insert"); + (VecLen, None, "Vec.len"); + (VecIndex, None, "Vec.index"); + (VecIndex, rg0, "Vec.index_back") (* shouldn't be used *); + (VecIndexMut, None, "Vec.index_mut"); + (VecIndexMut, rg0, "Vec.index_mut_back"); + ] let assumed_pure_functions () : (pure_assumed_fun_id * string) list = match !backend with @@ -344,7 +361,7 @@ let names_map_init () : names_map_init = assumed_adts = assumed_adts (); assumed_structs; assumed_variants = assumed_variants (); - assumed_llbc_functions; + assumed_llbc_functions = assumed_llbc_functions (); assumed_pure_functions = assumed_pure_functions (); } diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index 3a678c71..074fff5e 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -124,13 +124,13 @@ divergent def betree.List.split_at_fwd /- [betree_main::betree::List::{1}::push_front] -/ def betree.List.push_front_fwd_back (T : Type) (self : betree.List T) (x : T) : Result (betree.List T) := - let tl := mem_replace_fwd (betree.List T) self betree.List.Nil + let tl := mem.replace_fwd (betree.List T) self betree.List.Nil let l := tl Result.ret (betree.List.Cons x l) /- [betree_main::betree::List::{1}::pop_front] -/ def betree.List.pop_front_fwd (T : Type) (self : betree.List T) : Result T := - let ls := mem_replace_fwd (betree.List T) self betree.List.Nil + let ls := mem.replace_fwd (betree.List T) self betree.List.Nil match ls with | betree.List.Cons x tl => Result.ret x | betree.List.Nil => Result.fail Error.panic @@ -138,7 +138,7 @@ def betree.List.pop_front_fwd (T : Type) (self : betree.List T) : Result T := /- [betree_main::betree::List::{1}::pop_front] -/ def betree.List.pop_front_back (T : Type) (self : betree.List T) : Result (betree.List T) := - let ls := mem_replace_fwd (betree.List T) self betree.List.Nil + let ls := mem.replace_fwd (betree.List T) self betree.List.Nil match ls with | betree.List.Cons x tl => Result.ret tl | betree.List.Nil => Result.fail Error.panic diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index 10efc3db..3fc21d91 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -36,8 +36,8 @@ def test_new_non_zero_u32_fwd /- [external::test_vec] -/ def test_vec_fwd : Result Unit := do - let v := vec_new U32 - let _ ← vec_push_back U32 v (U32.ofInt 0 (by intlit)) + let v := Vec.new U32 + let _ ← Vec.push U32 v (U32.ofInt 0 (by intlit)) Result.ret () /- Unit test for [external::test_vec] -/ diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 4f16688b..48038bfb 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -15,7 +15,7 @@ divergent def HashMap.allocate_slots_loop_fwd if n > (Usize.ofInt 0 (by intlit)) then do - let slots0 ← vec_push_back (List T) slots List.Nil + let slots0 ← Vec.push (List T) slots List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots @@ -32,7 +32,7 @@ def HashMap.new_with_capacity_fwd Result (HashMap T) := do - let v := vec_new (List T) + let v := Vec.new (List T) let slots ← HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor @@ -52,12 +52,12 @@ def HashMap.new_fwd (T : Type) : Result (HashMap T) := /- [hashmap::HashMap::{0}::clear] -/ divergent def HashMap.clear_loop_fwd_back (T : Type) (slots : Vec (List T)) (i : Usize) : Result (Vec (List T)) := - let i0 := vec_len (List T) slots + let i0 := Vec.len (List T) slots if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) - let slots0 ← vec_index_mut_back (List T) slots i List.Nil + let slots0 ← Vec.index_mut_back (List T) slots i List.Nil HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots @@ -121,22 +121,22 @@ def HashMap.insert_no_resize_fwd_back := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod let inserted ← HashMap.insert_in_list_fwd T key value l if inserted then do let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.insert_in_list_back T key value l - let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 + let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } else do let l0 ← HashMap.insert_in_list_back T key value l - let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 + let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } /- [core::num::u32::{9}::MAX] -/ @@ -164,16 +164,16 @@ divergent def HashMap.move_elements_loop_fwd_back (T : Type) (ntable : HashMap T) (slots : Vec (List T)) (i : Usize) : Result ((HashMap T) × (Vec (List T))) := - let i0 := vec_len (List T) slots + let i0 := Vec.len (List T) slots if i < i0 then do - let l ← vec_index_mut_fwd (List T) slots i - let ls := mem_replace_fwd (List T) l List.Nil + let l ← Vec.index_mut (List T) slots i + let ls := mem.replace_fwd (List T) l List.Nil let ntable0 ← HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (List T) l List.Nil - let slots0 ← vec_index_mut_back (List T) slots i l0 + let l0 := mem.replace_back (List T) l List.Nil + let slots0 ← Vec.index_mut_back (List T) slots i l0 HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) @@ -189,7 +189,7 @@ def HashMap.try_resize_fwd_back (T : Type) (self : HashMap T) : Result (HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (List T) self.hash_map_slots + let capacity := Vec.len (List T) self.hash_map_slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) let (i, i0) := self.hash_map_max_load_factor let i1 ← n1 / i @@ -242,9 +242,9 @@ def HashMap.contains_key_fwd (T : Type) (self : HashMap T) (key : Usize) : Result Bool := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index (List T) self.hash_map_slots hash_mod HashMap.contains_key_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_in_list] -/ @@ -266,9 +266,9 @@ def HashMap.get_in_list_fwd def HashMap.get_fwd (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index (List T) self.hash_map_slots hash_mod HashMap.get_in_list_fwd T key l /- [hashmap::HashMap::{0}::get_mut_in_list] -/ @@ -309,9 +309,9 @@ def HashMap.get_mut_fwd (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod HashMap.get_mut_in_list_fwd T l key /- [hashmap::HashMap::{0}::get_mut] -/ @@ -321,11 +321,11 @@ def HashMap.get_mut_back := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod let l0 ← HashMap.get_mut_in_list_back T l key ret0 - let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 + let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } /- [hashmap::HashMap::{0}::remove_from_list] -/ @@ -335,7 +335,7 @@ divergent def HashMap.remove_from_list_loop_fwd | List.Cons ckey t tl => if ckey = key then - let mv_ls := mem_replace_fwd (List T) (List.Cons ckey t tl) List.Nil + let mv_ls := mem.replace_fwd (List T) (List.Cons ckey t tl) List.Nil match mv_ls with | List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | List.Nil => Result.fail Error.panic @@ -354,7 +354,7 @@ divergent def HashMap.remove_from_list_loop_back | List.Cons ckey t tl => if ckey = key then - let mv_ls := mem_replace_fwd (List T) (List.Cons ckey t tl) List.Nil + let mv_ls := mem.replace_fwd (List T) (List.Cons ckey t tl) List.Nil match mv_ls with | List.Cons i cvalue tl0 => Result.ret tl0 | List.Nil => Result.fail Error.panic @@ -374,9 +374,9 @@ def HashMap.remove_fwd (T : Type) (self : HashMap T) (key : Usize) : Result (Option T) := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none @@ -390,21 +390,21 @@ def HashMap.remove_back (T : Type) (self : HashMap T) (key : Usize) : Result (HashMap T) := do let hash ← hash_key_fwd key - let i := vec_len (List T) self.hash_map_slots + let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i - let l ← vec_index_mut_fwd (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod let x ← HashMap.remove_from_list_fwd T key l match x with | Option.none => do let l0 ← HashMap.remove_from_list_back T key l - let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 + let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } | Option.some x0 => do let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.remove_from_list_back T key l - let v ← vec_index_mut_back (List T) self.hash_map_slots hash_mod l0 + let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index fd556878..1a741a2d 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -18,7 +18,7 @@ divergent def hashmap.HashMap.allocate_slots_loop_fwd if n > (Usize.ofInt 0 (by intlit)) then do - let slots0 ← vec_push_back (hashmap.List T) slots hashmap.List.Nil + let slots0 ← Vec.push (hashmap.List T) slots hashmap.List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) hashmap.HashMap.allocate_slots_loop_fwd T slots0 n0 else Result.ret slots @@ -37,7 +37,7 @@ def hashmap.HashMap.new_with_capacity_fwd Result (hashmap.HashMap T) := do - let v := vec_new (hashmap.List T) + let v := Vec.new (hashmap.List T) let slots ← hashmap.HashMap.allocate_slots_fwd T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor @@ -60,13 +60,13 @@ divergent def hashmap.HashMap.clear_loop_fwd_back (T : Type) (slots : Vec (hashmap.List T)) (i : Usize) : Result (Vec (hashmap.List T)) := - let i0 := vec_len (hashmap.List T) slots + let i0 := Vec.len (hashmap.List T) slots if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← - vec_index_mut_back (hashmap.List T) slots i hashmap.List.Nil + Vec.index_mut_back (hashmap.List T) slots i hashmap.List.Nil hashmap.HashMap.clear_loop_fwd_back T slots0 i1 else Result.ret slots @@ -136,10 +136,10 @@ def hashmap.HashMap.insert_no_resize_fwd_back := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod let inserted ← hashmap.HashMap.insert_in_list_fwd T key value l if inserted then @@ -148,7 +148,7 @@ def hashmap.HashMap.insert_no_resize_fwd_back (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← - vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots + Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { @@ -160,7 +160,7 @@ def hashmap.HashMap.insert_no_resize_fwd_back do let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← - vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots + Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } @@ -194,17 +194,17 @@ divergent def hashmap.HashMap.move_elements_loop_fwd_back (i : Usize) : Result ((hashmap.HashMap T) × (Vec (hashmap.List T))) := - let i0 := vec_len (hashmap.List T) slots + let i0 := Vec.len (hashmap.List T) slots if i < i0 then do - let l ← vec_index_mut_fwd (hashmap.List T) slots i - let ls := mem_replace_fwd (hashmap.List T) l hashmap.List.Nil + let l ← Vec.index_mut (hashmap.List T) slots i + let ls := mem.replace_fwd (hashmap.List T) l hashmap.List.Nil let ntable0 ← hashmap.HashMap.move_elements_from_list_fwd_back T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) - let l0 := mem_replace_back (hashmap.List T) l hashmap.List.Nil - let slots0 ← vec_index_mut_back (hashmap.List T) slots i l0 + let l0 := mem.replace_back (hashmap.List T) l hashmap.List.Nil + let slots0 ← Vec.index_mut_back (hashmap.List T) slots i l0 hashmap.HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 else Result.ret (ntable, slots) @@ -221,7 +221,7 @@ def hashmap.HashMap.try_resize_fwd_back (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let capacity := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) let (i, i0) := self.hashmap_hash_map_max_load_factor let i1 ← n1 / i @@ -274,10 +274,9 @@ def hashmap.HashMap.contains_key_fwd (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result Bool := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i - let l ← - vec_index_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.contains_key_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ @@ -300,10 +299,9 @@ def hashmap.HashMap.get_fwd (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i - let l ← - vec_index_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.get_in_list_fwd T key l /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ @@ -348,10 +346,10 @@ def hashmap.HashMap.get_mut_fwd (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod hashmap.HashMap.get_mut_in_list_fwd T l key /- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ @@ -361,13 +359,13 @@ def hashmap.HashMap.get_mut_back := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod let l0 ← hashmap.HashMap.get_mut_in_list_back T l key ret0 let v ← - vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } @@ -379,7 +377,7 @@ divergent def hashmap.HashMap.remove_from_list_loop_fwd if ckey = key then let mv_ls := - mem_replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + mem.replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) hashmap.List.Nil match mv_ls with | hashmap.List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) @@ -400,7 +398,7 @@ divergent def hashmap.HashMap.remove_from_list_loop_back if ckey = key then let mv_ls := - mem_replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + mem.replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) hashmap.List.Nil match mv_ls with | hashmap.List.Cons i cvalue tl0 => Result.ret tl0 @@ -421,10 +419,10 @@ def hashmap.HashMap.remove_fwd (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result (Option T) := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => Result.ret Option.none @@ -441,17 +439,17 @@ def hashmap.HashMap.remove_back := do let hash ← hashmap.hash_key_fwd key - let i := vec_len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← - vec_index_mut_fwd (hashmap.List T) self.hashmap_hash_map_slots hash_mod + Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod let x ← hashmap.HashMap.remove_from_list_fwd T key l match x with | Option.none => do let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← - vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots + Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { self with hashmap_hash_map_slots := v } | Option.some x0 => @@ -460,7 +458,7 @@ def hashmap.HashMap.remove_back (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← - vec_index_mut_back (hashmap.List T) self.hashmap_hash_map_slots + Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod l0 Result.ret { diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 383bc819..6e6eef3b 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -54,12 +54,12 @@ def sum_with_shared_borrows_fwd (max : U32) : Result U32 := /- [loops::clear] -/ divergent def clear_loop_fwd_back (v : Vec U32) (i : Usize) : Result (Vec U32) := - let i0 := vec_len U32 v + let i0 := Vec.len U32 v if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) - let v0 ← vec_index_mut_back U32 v i (U32.ofInt 0 (by intlit)) + let v0 ← Vec.index_mut_back U32 v i (U32.ofInt 0 (by intlit)) clear_loop_fwd_back v0 i1 else Result.ret v @@ -145,7 +145,7 @@ divergent def get_elem_mut_loop_fwd /- [loops::get_elem_mut] -/ def get_elem_mut_fwd (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← vec_index_mut_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0 (by intlit)) get_elem_mut_loop_fwd x l /- [loops::get_elem_mut] -/ @@ -167,9 +167,9 @@ def get_elem_mut_back Result (Vec (List Usize)) := do - let l ← vec_index_mut_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0 (by intlit)) let l0 ← get_elem_mut_loop_back x l ret0 - vec_index_mut_back (List Usize) slots (Usize.ofInt 0 (by intlit)) l0 + Vec.index_mut_back (List Usize) slots (Usize.ofInt 0 (by intlit)) l0 /- [loops::get_elem_shared] -/ divergent def get_elem_shared_loop_fwd @@ -185,7 +185,7 @@ divergent def get_elem_shared_loop_fwd def get_elem_shared_fwd (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← vec_index_fwd (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index (List Usize) slots (Usize.ofInt 0 (by intlit)) get_elem_shared_loop_fwd x l /- [loops::id_mut] -/ diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index cdbbcd67..e4fa7612 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -321,7 +321,7 @@ divergent def list_rev_aux_fwd /- [no_nested_borrows::list_rev] -/ def list_rev_fwd_back (T : Type) (l : List T) : Result (List T) := - let li := mem_replace_fwd (List T) l List.Nil + let li := mem.replace_fwd (List T) l List.Nil list_rev_aux_fwd T li List.Nil /- [no_nested_borrows::test_list_functions] -/ @@ -514,7 +514,7 @@ def test_weird_borrows1_fwd : Result Unit := /- [no_nested_borrows::test_mem_replace] -/ def test_mem_replace_fwd_back (px : U32) : Result U32 := - let y := mem_replace_fwd U32 px (U32.ofInt 1 (by intlit)) + let y := mem.replace_fwd U32 px (U32.ofInt 1 (by intlit)) if not (y = (U32.ofInt 0 (by intlit))) then Result.fail Error.panic else Result.ret (U32.ofInt 2 (by intlit)) diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json index 637bda23..75f7010a 100644 --- a/tests/lean/lake-manifest.json +++ b/tests/lean/lake-manifest.json @@ -11,7 +11,7 @@ {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "cc5d11f24e1b92db65ec3389bb5142f4b2d7670e", + "rev": "bb4fb766e41dd3a64197263ec132c7f9c4b50065", "name": "mathlib", "inputRev?": null}}, {"git": -- cgit v1.2.3 From 7c95800cefc87fad894f8bf855cfc047e713b3a7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 6 Jul 2023 12:20:28 +0200 Subject: Improve the generated comments --- backends/lean/Base/Primitives.lean | 2 +- compiler/Extract.ml | 84 +++- compiler/ExtractBase.ml | 38 +- compiler/Translate.ml | 4 + tests/coq/betree/BetreeMain_Funs.v | 118 +++--- tests/coq/betree/BetreeMain_Opaque.v | 10 +- tests/coq/betree/_CoqProject | 2 +- tests/coq/hashmap/Hashmap_Funs.v | 85 ++-- tests/coq/hashmap/_CoqProject | 2 +- tests/coq/hashmap_on_disk/HashmapMain_Funs.v | 89 ++-- tests/coq/hashmap_on_disk/HashmapMain_Opaque.v | 4 +- tests/coq/misc/Constants.v | 16 +- tests/coq/misc/External_Funs.v | 18 +- tests/coq/misc/External_Opaque.v | 10 +- tests/coq/misc/Loops.v | 124 +++--- tests/coq/misc/NoNestedBorrows.v | 112 ++--- tests/coq/misc/Paper.v | 21 +- tests/coq/misc/PoloniusList.v | 4 +- tests/coq/misc/_CoqProject | 6 +- tests/fstar/betree/BetreeMain.Funs.fst | 118 +++--- tests/fstar/betree/BetreeMain.Opaque.fsti | 10 +- .../fstar/betree_back_stateful/BetreeMain.Funs.fst | 128 +++--- .../betree_back_stateful/BetreeMain.Opaque.fsti | 10 +- tests/fstar/hashmap/Hashmap.Funs.fst | 85 ++-- tests/fstar/hashmap_on_disk/HashmapMain.Funs.fst | 89 ++-- .../fstar/hashmap_on_disk/HashmapMain.Opaque.fsti | 4 +- tests/fstar/misc/Constants.fst | 16 +- tests/fstar/misc/External.Funs.fst | 18 +- tests/fstar/misc/External.Opaque.fsti | 10 +- tests/fstar/misc/Loops.Funs.fst | 124 +++--- tests/fstar/misc/NoNestedBorrows.fst | 112 ++--- tests/fstar/misc/Paper.fst | 21 +- tests/fstar/misc/PoloniusList.fst | 4 +- tests/hol4/betree/betreeMain_FunsScript.sml | 118 +++--- tests/hol4/betree/betreeMain_OpaqueScript.sml | 10 +- tests/hol4/hashmap/hashmap_FunsScript.sml | 85 ++-- .../hashmap_on_disk/hashmapMain_FunsScript.sml | 89 ++-- .../hashmap_on_disk/hashmapMain_OpaqueScript.sml | 4 +- tests/hol4/misc-constants/constantsScript.sml | 16 +- tests/hol4/misc-external/external_FunsScript.sml | 18 +- tests/hol4/misc-external/external_OpaqueScript.sml | 10 +- tests/hol4/misc-loops/loops_FunsScript.sml | 124 +++--- .../noNestedBorrowsScript.sml | 112 ++--- tests/hol4/misc-paper/paperScript.sml | 21 +- .../hol4/misc-polonius_list/poloniusListScript.sml | 4 +- tests/lean/BetreeMain/Funs.lean | 472 ++++++++++----------- tests/lean/BetreeMain/FunsExternal.lean | 10 +- tests/lean/BetreeMain/FunsExternal_Template.lean | 20 +- tests/lean/Constants.lean | 54 +-- tests/lean/External/Funs.lean | 49 ++- tests/lean/External/FunsExternal.lean | 6 +- tests/lean/External/FunsExternal_Template.lean | 17 +- tests/lean/Hashmap/Funs.lean | 262 ++++++------ tests/lean/HashmapMain/Funs.lean | 276 ++++++------ tests/lean/HashmapMain/FunsExternal.lean | 4 +- tests/lean/HashmapMain/FunsExternal_Template.lean | 8 +- tests/lean/Loops/Funs.lean | 300 +++++++------ tests/lean/NoNestedBorrows.lean | 292 +++++++------ tests/lean/Paper.lean | 57 +-- tests/lean/PoloniusList.lean | 9 +- 60 files changed, 2056 insertions(+), 1889 deletions(-) diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 808c1461..14f5971e 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -656,7 +656,7 @@ def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec -- MISC -- ---------- -@[simp] def mem.replace_fwd (a : Type) (x : a) (_ : a) : a := x +@[simp] def mem.replace (a : Type) (x : a) (_ : a) : a := x @[simp] def mem.replace_back (a : Type) (_ : a) (y : a) : a := y /-- Aeneas-translated function -- useful to reduce non-recursive definitions. diff --git a/compiler/Extract.ml b/compiler/Extract.ml index 180ca7ca..cacb9b96 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -321,7 +321,7 @@ let assumed_llbc_functions () : ] | Lean -> [ - (Replace, None, "mem.replace_fwd"); + (Replace, None, "mem.replace"); (Replace, rg0, "mem.replace_back"); (VecNew, None, "Vec.new"); (VecPush, None, "Vec.push_fwd") (* Shouldn't be used *); @@ -1426,16 +1426,26 @@ let extract_type_decl_struct_body (ctx : extraction_ctx) (fmt : F.formatter) () (** Extract a nestable, muti-line comment *) -let extract_comment (fmt : F.formatter) (s : string) : unit = - match !backend with - | Coq | FStar | HOL4 -> - F.pp_print_string fmt "(** "; - F.pp_print_string fmt s; - F.pp_print_string fmt " *)" - | Lean -> - F.pp_print_string fmt "/- "; +let extract_comment (fmt : F.formatter) (sl : string list) : unit = + (* Delimiters, space after we break a line *) + let ld, space, rd = + match !backend with + | Coq | FStar | HOL4 -> ("(** ", 4, " *)") + | Lean -> ("/- ", 3, " -/") + in + F.pp_open_vbox fmt space; + F.pp_print_string fmt ld; + (match sl with + | [] -> () + | s :: sl -> F.pp_print_string fmt s; - F.pp_print_string fmt " -/" + List.iter + (fun s -> + F.pp_print_space fmt (); + F.pp_print_string fmt s) + sl); + F.pp_print_string fmt rd; + F.pp_close_box fmt () (** Extract a type declaration. @@ -1475,7 +1485,7 @@ let extract_type_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) if !backend <> HOL4 || not (decl_is_first_from_group kind) then F.pp_print_break fmt 0 0; (* Print a comment to link the extracted type to its original rust definition *) - extract_comment fmt ("[" ^ Print.name_to_string def.name ^ "]"); + extract_comment fmt [ "[" ^ Print.name_to_string def.name ^ "]" ]; F.pp_print_break fmt 0 0; (* Open a box for the definition, so that whenever possible it gets printed on * one line. Note however that in the case of Lean line breaks are important @@ -1872,7 +1882,7 @@ let extract_state_type (fmt : F.formatter) (ctx : extraction_ctx) (* Add a break before *) F.pp_print_break fmt 0 0; (* Print a comment *) - extract_comment fmt "The state type used in the state-error monad"; + extract_comment fmt [ "The state type used in the state-error monad" ]; F.pp_print_break fmt 0 0; (* Open a box for the definition, so that whenever possible it gets printed on * one line *) @@ -2817,7 +2827,7 @@ let extract_template_fstar_decreases_clause (ctx : extraction_ctx) F.pp_print_break fmt 0 0; (* Print a comment to link the extracted type to its original rust definition *) extract_comment fmt - ("[" ^ Print.fun_name_to_string def.basename ^ "]: decreases clause"); + [ "[" ^ Print.fun_name_to_string def.basename ^ "]: decreases clause" ]; F.pp_print_space fmt (); (* Open a box for the definition, so that whenever possible it gets printed on * one line *) @@ -2879,7 +2889,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) F.pp_print_break fmt 0 0; (* Print a comment to link the extracted type to its original rust definition *) extract_comment fmt - ("[" ^ Print.fun_name_to_string def.basename ^ "]: termination measure"); + [ "[" ^ Print.fun_name_to_string def.basename ^ "]: termination measure" ]; F.pp_print_space fmt (); (* Open a box for the definition, so that whenever possible it gets printed on * one line *) @@ -2933,7 +2943,7 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) (* syntax term ... term : tactic *) F.pp_print_break fmt 0 0; extract_comment fmt - ("[" ^ Print.fun_name_to_string def.basename ^ "]: decreases_by tactic"); + [ "[" ^ Print.fun_name_to_string def.basename ^ "]: decreases_by tactic" ]; F.pp_print_space fmt (); F.pp_open_hvbox fmt 0; F.pp_print_string fmt "syntax \""; @@ -2962,6 +2972,40 @@ let extract_template_lean_termination_and_decreasing (ctx : extraction_ctx) F.pp_close_box fmt (); F.pp_print_break fmt 0 0 +let extract_fun_comment (ctx : extraction_ctx) (fmt : F.formatter) + (def : fun_decl) : unit = + let { keep_fwd; num_backs } = + PureUtils.RegularFunIdMap.find + (A.Regular def.def_id, def.loop_id, def.back_id) + ctx.fun_name_info + in + let comment_pre = "[" ^ Print.fun_name_to_string def.basename ^ "]: " in + let comment = + let loop_comment = + match def.loop_id with + | None -> "" + | Some id -> "loop " ^ LoopId.to_string id ^ ": " + in + let fwd_back_comment = + match def.back_id with + | None -> [ "forward function" ] + | Some id -> + (* Check if there is only one backward function, and no forward function *) + if (not keep_fwd) && num_backs = 1 then + [ + "merged forward/backward function"; + "(there is a single backward function, and the forward function \ + returns ())"; + ] + else [ "backward function " ^ T.RegionGroupId.to_string id ] + in + match fwd_back_comment with + | [] -> raise (Failure "Unreachable") + | [ s ] -> [ comment_pre ^ loop_comment ^ s ] + | s :: sl -> (comment_pre ^ loop_comment ^ s) :: sl + in + extract_comment fmt comment + (** Extract a function declaration. This function is for all function declarations and all backends **at the exception** @@ -2981,8 +3025,8 @@ let extract_fun_decl_gen (ctx : extraction_ctx) (fmt : F.formatter) (* Add a break before *) if !backend <> HOL4 || not (decl_is_first_from_group kind) then F.pp_print_break fmt 0 0; - (* Print a comment to link the extracted type to its original rust definition *) - extract_comment fmt ("[" ^ Print.fun_name_to_string def.basename ^ "]"); + (* Print a comment to link the extracted definition to its original rust definition *) + extract_fun_comment ctx fmt def; F.pp_print_space fmt (); (* Open two boxes for the definition, so that whenever possible it gets printed on * one line and indents are correct *) @@ -3236,6 +3280,8 @@ let extract_fun_decl_hol4_opaque (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_break fmt 0 0; (* Open a box for the whole definition *) F.pp_open_hvbox fmt ctx.indent_incr; + (* Print a comment to link the extracted definition to its original rust definition *) + extract_fun_comment ctx fmt def; (* Generate: `val _ = new_constant ("...",` *) F.pp_print_string fmt ("val _ = new_constant (\"" ^ def_name ^ "\","); F.pp_print_space fmt (); @@ -3411,7 +3457,7 @@ let extract_global_decl (ctx : extraction_ctx) (fmt : F.formatter) (* Add a break then the name of the corresponding LLBC declaration *) F.pp_print_break fmt 0 0; - extract_comment fmt ("[" ^ Print.global_name_to_string global.name ^ "]"); + extract_comment fmt [ "[" ^ Print.global_name_to_string global.name ^ "]" ]; F.pp_print_space fmt (); let with_opaque_pre = false in @@ -3485,7 +3531,7 @@ let extract_unit_test_if_unit_fun (ctx : extraction_ctx) (fmt : F.formatter) F.pp_print_break fmt 0 0; (* Print a comment *) extract_comment fmt - ("Unit test for [" ^ Print.fun_name_to_string def.basename ^ "]"); + [ "Unit test for [" ^ Print.fun_name_to_string def.basename ^ "]" ]; F.pp_print_space fmt (); (* Open a box for the test *) F.pp_open_hovbox fmt ctx.indent_incr; diff --git a/compiler/ExtractBase.ml b/compiler/ExtractBase.ml index feab7706..ede7af29 100644 --- a/compiler/ExtractBase.ml +++ b/compiler/ExtractBase.ml @@ -520,6 +520,8 @@ let basename_to_unique (names_set : StringSet.t) in if StringSet.mem basename names_set then gen 0 else basename +type fun_name_info = { keep_fwd : bool; num_backs : int } + (** Extraction context. Note that the extraction context contains information coming from the @@ -551,6 +553,15 @@ type extraction_ctx = { -- makes the if then else dependent ]} *) + fun_name_info : fun_name_info PureUtils.RegularFunIdMap.t; + (** Information used to filter and name functions - we use it + to print comments in the generated code, to help link + the generated code to the original code (information such + as: "this function is the backward function of ...", or + "this function is the merged forward/backward function of ..." + in case a Rust function only has one backward translation + and we filter the forward function because it returns unit. + *) } (** Debugging function, used when communicating name collisions to the user, @@ -930,9 +941,15 @@ let ctx_add_fun_decl (trans_group : bool * pure_fun_translation) ctx.fmt.fun_name def.basename def.num_loops def.loop_id num_rgs rg_info (keep_fwd, num_backs) in - ctx_add is_opaque - (FunId (FromLlbc (A.Regular def_id, def.loop_id, def.back_id))) - def_name ctx + let fun_id = (A.Regular def_id, def.loop_id, def.back_id) in + let ctx = ctx_add is_opaque (FunId (FromLlbc fun_id)) def_name ctx in + (* Add the name info *) + { + ctx with + fun_name_info = + PureUtils.RegularFunIdMap.add fun_id { keep_fwd; num_backs } + ctx.fun_name_info; + } type names_map_init = { keywords : string list; @@ -1053,13 +1070,24 @@ let default_fun_suffix (num_loops : int) (loop_id : LoopId.id option) definitions (in particular between type and function definitions). *) let rg_suff = + (* TODO: make all the backends match what is done for Lean *) match rg with - | None -> "_fwd" + | None -> ( + match !Config.backend with + | FStar | Coq | HOL4 -> "_fwd" + | Lean -> + (* In order to avoid name conflicts: + * - if the forward is eliminated, we add the suffix "_fwd" (it won't be used) + * - otherwise, no suffix (because the backward functions will have a suffix) + *) + if num_backs = 1 && not keep_fwd then "_fwd" else "") | Some rg -> assert (num_region_groups > 0 && num_backs > 0); if num_backs = 1 then (* Exactly one backward function *) - if not keep_fwd then "_fwd_back" else "_back" + match !Config.backend with + | FStar | Coq | HOL4 -> if not keep_fwd then "_fwd_back" else "_back" + | Lean -> if not keep_fwd then "" else "_back" else if (* Several region groups/backward functions: - if all the regions in the group have names, we use those names diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 795674b4..444642c0 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -910,11 +910,14 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : prefixed with the type name to prevent collisions *) match !Config.backend with Coq | FStar | HOL4 -> true | Lean -> false in + (* Initialize the names map (we insert the names of the "primitives" + declarations, and insert the names of the local declarations later) *) let mk_formatter_and_names_map = Extract.mk_formatter_and_names_map in let fmt, names_map = mk_formatter_and_names_map trans_ctx crate.name variant_concatenate_type_name in + (* Put everything in the context *) let ctx = { ExtractBase.trans_ctx; @@ -923,6 +926,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : indent_incr = 2; use_opaque_pre = !Config.split_files; use_dep_ite = !Config.backend = Lean && !Config.extract_decreases_clauses; + fun_name_info = PureUtils.RegularFunIdMap.empty; } in diff --git a/tests/coq/betree/BetreeMain_Funs.v b/tests/coq/betree/BetreeMain_Funs.v index 940b8650..86a9d5f2 100644 --- a/tests/coq/betree/BetreeMain_Funs.v +++ b/tests/coq/betree/BetreeMain_Funs.v @@ -10,7 +10,7 @@ Require Export BetreeMain_Opaque. Import BetreeMain_Opaque. Module BetreeMain_Funs. -(** [betree_main::betree::load_internal_node] *) +(** [betree_main::betree::load_internal_node]: forward function *) Definition betree_load_internal_node_fwd (id : u64) (st : state) : result (state * (Betree_list_t (u64 * Betree_message_t))) @@ -18,7 +18,7 @@ Definition betree_load_internal_node_fwd betree_utils_load_internal_node_fwd id st . -(** [betree_main::betree::store_internal_node] *) +(** [betree_main::betree::store_internal_node]: forward function *) Definition betree_store_internal_node_fwd (id : u64) (content : Betree_list_t (u64 * Betree_message_t)) (st : state) : result (state * unit) @@ -28,13 +28,13 @@ Definition betree_store_internal_node_fwd Return (st0, tt) . -(** [betree_main::betree::load_leaf_node] *) +(** [betree_main::betree::load_leaf_node]: forward function *) Definition betree_load_leaf_node_fwd (id : u64) (st : state) : result (state * (Betree_list_t (u64 * u64))) := betree_utils_load_leaf_node_fwd id st . -(** [betree_main::betree::store_leaf_node] *) +(** [betree_main::betree::store_leaf_node]: forward function *) Definition betree_store_leaf_node_fwd (id : u64) (content : Betree_list_t (u64 * u64)) (st : state) : result (state * unit) @@ -44,29 +44,29 @@ Definition betree_store_leaf_node_fwd Return (st0, tt) . -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: forward function *) Definition betree_fresh_node_id_fwd (counter : u64) : result u64 := _ <- u64_add counter 1%u64; Return counter . -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: backward function 0 *) Definition betree_fresh_node_id_back (counter : u64) : result u64 := u64_add counter 1%u64 . -(** [betree_main::betree::NodeIdCounter::{0}::new] *) +(** [betree_main::betree::NodeIdCounter::{0}::new]: forward function *) Definition betree_node_id_counter_new_fwd : result Betree_node_id_counter_t := Return {| Betree_node_id_counter_next_node_id := 0%u64 |} . -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function *) Definition betree_node_id_counter_fresh_id_fwd (self : Betree_node_id_counter_t) : result u64 := _ <- u64_add self.(Betree_node_id_counter_next_node_id) 1%u64; Return self.(Betree_node_id_counter_next_node_id) . -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 *) Definition betree_node_id_counter_fresh_id_back (self : Betree_node_id_counter_t) : result Betree_node_id_counter_t := i <- u64_add self.(Betree_node_id_counter_next_node_id) 1%u64; @@ -79,7 +79,7 @@ Definition core_num_u64_max_body : result u64 := . Definition core_num_u64_max_c : u64 := core_num_u64_max_body%global. -(** [betree_main::betree::upsert_update] *) +(** [betree_main::betree::upsert_update]: forward function *) Definition betree_upsert_update_fwd (prev : option u64) (st : Betree_upsert_fun_state_t) : result u64 := match prev with @@ -99,7 +99,7 @@ Definition betree_upsert_update_fwd end . -(** [betree_main::betree::List::{1}::len] *) +(** [betree_main::betree::List::{1}::len]: forward function *) Fixpoint betree_list_len_fwd (T : Type) (n : nat) (self : Betree_list_t T) : result u64 := match n with @@ -112,7 +112,7 @@ Fixpoint betree_list_len_fwd end . -(** [betree_main::betree::List::{1}::split_at] *) +(** [betree_main::betree::List::{1}::split_at]: forward function *) Fixpoint betree_list_split_at_fwd (T : Type) (n : nat) (self : Betree_list_t T) (n0 : u64) : result ((Betree_list_t T) * (Betree_list_t T)) @@ -135,7 +135,8 @@ Fixpoint betree_list_split_at_fwd end . -(** [betree_main::betree::List::{1}::push_front] *) +(** [betree_main::betree::List::{1}::push_front]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition betree_list_push_front_fwd_back (T : Type) (self : Betree_list_t T) (x : T) : result (Betree_list_t T) := let tl := mem_replace_fwd (Betree_list_t T) self BetreeListNil in @@ -143,7 +144,7 @@ Definition betree_list_push_front_fwd_back Return (BetreeListCons x l) . -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: forward function *) Definition betree_list_pop_front_fwd (T : Type) (self : Betree_list_t T) : result T := let ls := mem_replace_fwd (Betree_list_t T) self BetreeListNil in @@ -153,7 +154,7 @@ Definition betree_list_pop_front_fwd end . -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: backward function 0 *) Definition betree_list_pop_front_back (T : Type) (self : Betree_list_t T) : result (Betree_list_t T) := let ls := mem_replace_fwd (Betree_list_t T) self BetreeListNil in @@ -163,7 +164,7 @@ Definition betree_list_pop_front_back end . -(** [betree_main::betree::List::{1}::hd] *) +(** [betree_main::betree::List::{1}::hd]: forward function *) Definition betree_list_hd_fwd (T : Type) (self : Betree_list_t T) : result T := match self with | BetreeListCons hd l => Return hd @@ -171,7 +172,7 @@ Definition betree_list_hd_fwd (T : Type) (self : Betree_list_t T) : result T := end . -(** [betree_main::betree::List::{2}::head_has_key] *) +(** [betree_main::betree::List::{2}::head_has_key]: forward function *) Definition betree_list_head_has_key_fwd (T : Type) (self : Betree_list_t (u64 * T)) (key : u64) : result bool := match self with @@ -180,7 +181,7 @@ Definition betree_list_head_has_key_fwd end . -(** [betree_main::betree::List::{2}::partition_at_pivot] *) +(** [betree_main::betree::List::{2}::partition_at_pivot]: forward function *) Fixpoint betree_list_partition_at_pivot_fwd (T : Type) (n : nat) (self : Betree_list_t (u64 * T)) (pivot : u64) : result ((Betree_list_t (u64 * T)) * (Betree_list_t (u64 * T))) @@ -203,7 +204,7 @@ Fixpoint betree_list_partition_at_pivot_fwd end . -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: forward function *) Definition betree_leaf_split_fwd (n : nat) (self : Betree_leaf_t) (content : Betree_list_t (u64 * u64)) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -236,7 +237,7 @@ Definition betree_leaf_split_fwd Return (st1, mkBetree_internal_t self.(Betree_leaf_id) pivot n0 n1) . -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: backward function 2 *) Definition betree_leaf_split_back (n : nat) (self : Betree_leaf_t) (content : Betree_list_t (u64 * u64)) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -257,7 +258,7 @@ Definition betree_leaf_split_back betree_node_id_counter_fresh_id_back node_id_cnt0 . -(** [betree_main::betree::Node::{5}::lookup_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_in_bindings]: forward function *) Fixpoint betree_node_lookup_in_bindings_fwd (n : nat) (key : u64) (bindings : Betree_list_t (u64 * u64)) : result (option u64) @@ -279,7 +280,7 @@ Fixpoint betree_node_lookup_in_bindings_fwd end . -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: forward function *) Fixpoint betree_node_lookup_first_message_for_key_fwd (n : nat) (key : u64) (msgs : Betree_list_t (u64 * Betree_message_t)) : result (Betree_list_t (u64 * Betree_message_t)) @@ -298,7 +299,7 @@ Fixpoint betree_node_lookup_first_message_for_key_fwd end . -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: backward function 0 *) Fixpoint betree_node_lookup_first_message_for_key_back (n : nat) (key : u64) (msgs : Betree_list_t (u64 * Betree_message_t)) (ret : Betree_list_t (u64 * Betree_message_t)) : @@ -321,7 +322,7 @@ Fixpoint betree_node_lookup_first_message_for_key_back end . -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: forward function *) Fixpoint betree_node_apply_upserts_fwd (n : nat) (msgs : Betree_list_t (u64 * Betree_message_t)) (prev : option u64) (key : u64) (st : state) : @@ -353,7 +354,7 @@ Fixpoint betree_node_apply_upserts_fwd end . -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: backward function 0 *) Fixpoint betree_node_apply_upserts_back (n : nat) (msgs : Betree_list_t (u64 * Betree_message_t)) (prev : option u64) (key : u64) (st : state) : @@ -383,7 +384,7 @@ Fixpoint betree_node_apply_upserts_back end . -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: forward function *) Fixpoint betree_node_lookup_fwd (n : nat) (self : Betree_node_t) (key : u64) (st : state) : result (state * (option u64)) @@ -455,7 +456,7 @@ Fixpoint betree_node_lookup_fwd end end -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: backward function 0 *) with betree_node_lookup_back (n : nat) (self : Betree_node_t) (key : u64) (st : state) : result Betree_node_t @@ -524,7 +525,7 @@ with betree_node_lookup_back end end -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: forward function *) with betree_internal_lookup_in_children_fwd (n : nat) (self : Betree_internal_t) (key : u64) (st : state) : result (state * (option u64)) @@ -537,7 +538,7 @@ with betree_internal_lookup_in_children_fwd else betree_node_lookup_fwd n0 self.(Betree_internal_right) key st end -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: backward function 0 *) with betree_internal_lookup_in_children_back (n : nat) (self : Betree_internal_t) (key : u64) (st : state) : result Betree_internal_t @@ -557,7 +558,7 @@ with betree_internal_lookup_in_children_back end . -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: forward function *) Fixpoint betree_node_lookup_mut_in_bindings_fwd (n : nat) (key : u64) (bindings : Betree_list_t (u64 * u64)) : result (Betree_list_t (u64 * u64)) @@ -576,7 +577,7 @@ Fixpoint betree_node_lookup_mut_in_bindings_fwd end . -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: backward function 0 *) Fixpoint betree_node_lookup_mut_in_bindings_back (n : nat) (key : u64) (bindings : Betree_list_t (u64 * u64)) (ret : Betree_list_t (u64 * u64)) : @@ -598,7 +599,8 @@ Fixpoint betree_node_lookup_mut_in_bindings_back end . -(** [betree_main::betree::Node::{5}::apply_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition betree_node_apply_to_leaf_fwd_back (n : nat) (bindings : Betree_list_t (u64 * u64)) (key : u64) (new_msg : Betree_message_t) : @@ -642,7 +644,8 @@ Definition betree_node_apply_to_leaf_fwd_back end . -(** [betree_main::betree::Node::{5}::apply_messages_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint betree_node_apply_messages_to_leaf_fwd_back (n : nat) (bindings : Betree_list_t (u64 * u64)) (new_msgs : Betree_list_t (u64 * Betree_message_t)) : @@ -661,7 +664,8 @@ Fixpoint betree_node_apply_messages_to_leaf_fwd_back end . -(** [betree_main::betree::Node::{5}::filter_messages_for_key] *) +(** [betree_main::betree::Node::{5}::filter_messages_for_key]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint betree_node_filter_messages_for_key_fwd_back (n : nat) (key : u64) (msgs : Betree_list_t (u64 * Betree_message_t)) : result (Betree_list_t (u64 * Betree_message_t)) @@ -684,7 +688,7 @@ Fixpoint betree_node_filter_messages_for_key_fwd_back end . -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: forward function *) Fixpoint betree_node_lookup_first_message_after_key_fwd (n : nat) (key : u64) (msgs : Betree_list_t (u64 * Betree_message_t)) : result (Betree_list_t (u64 * Betree_message_t)) @@ -703,7 +707,7 @@ Fixpoint betree_node_lookup_first_message_after_key_fwd end . -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: backward function 0 *) Fixpoint betree_node_lookup_first_message_after_key_back (n : nat) (key : u64) (msgs : Betree_list_t (u64 * Betree_message_t)) (ret : Betree_list_t (u64 * Betree_message_t)) : @@ -726,7 +730,8 @@ Fixpoint betree_node_lookup_first_message_after_key_back end . -(** [betree_main::betree::Node::{5}::apply_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition betree_node_apply_to_internal_fwd_back (n : nat) (msgs : Betree_list_t (u64 * Betree_message_t)) (key : u64) (new_msg : Betree_message_t) : @@ -784,7 +789,8 @@ Definition betree_node_apply_to_internal_fwd_back betree_node_lookup_first_message_for_key_back n key msgs msgs1) . -(** [betree_main::betree::Node::{5}::apply_messages_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint betree_node_apply_messages_to_internal_fwd_back (n : nat) (msgs : Betree_list_t (u64 * Betree_message_t)) (new_msgs : Betree_list_t (u64 * Betree_message_t)) : @@ -803,7 +809,7 @@ Fixpoint betree_node_apply_messages_to_internal_fwd_back end . -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: forward function *) Fixpoint betree_node_apply_messages_fwd (n : nat) (self : Betree_node_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -859,7 +865,7 @@ Fixpoint betree_node_apply_messages_fwd end end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: backward function 0 *) with betree_node_apply_messages_back (n : nat) (self : Betree_node_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -915,7 +921,7 @@ with betree_node_apply_messages_back end end -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: forward function *) with betree_internal_flush_fwd (n : nat) (self : Betree_internal_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -963,7 +969,7 @@ with betree_internal_flush_fwd Return (st0, msgs_left)) end -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: backward function 0 *) with betree_internal_flush_back (n : nat) (self : Betree_internal_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) @@ -1012,7 +1018,7 @@ with betree_internal_flush_back end . -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: forward function *) Definition betree_node_apply_fwd (n : nat) (self : Betree_node_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) (key : u64) @@ -1030,7 +1036,7 @@ Definition betree_node_apply_fwd Return (st0, tt) . -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: backward function 0 *) Definition betree_node_apply_back (n : nat) (self : Betree_node_t) (params : Betree_params_t) (node_id_cnt : Betree_node_id_counter_t) (key : u64) @@ -1042,7 +1048,7 @@ Definition betree_node_apply_back (key, new_msg) l) st . -(** [betree_main::betree::BeTree::{6}::new] *) +(** [betree_main::betree::BeTree::{6}::new]: forward function *) Definition betree_be_tree_new_fwd (min_flush_size : u64) (split_size : u64) (st : state) : result (state * Betree_be_tree_t) @@ -1065,7 +1071,7 @@ Definition betree_be_tree_new_fwd |}) . -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: forward function *) Definition betree_be_tree_apply_fwd (n : nat) (self : Betree_be_tree_t) (key : u64) (msg : Betree_message_t) (st : state) : @@ -1081,7 +1087,7 @@ Definition betree_be_tree_apply_fwd Return (st0, tt) . -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: backward function 0 *) Definition betree_be_tree_apply_back (n : nat) (self : Betree_be_tree_t) (key : u64) (msg : Betree_message_t) (st : state) : @@ -1099,7 +1105,7 @@ Definition betree_be_tree_apply_back |} . -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: forward function *) Definition betree_be_tree_insert_fwd (n : nat) (self : Betree_be_tree_t) (key : u64) (value : u64) (st : state) : result (state * unit) @@ -1110,7 +1116,7 @@ Definition betree_be_tree_insert_fwd Return (st0, tt) . -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: backward function 0 *) Definition betree_be_tree_insert_back (n : nat) (self : Betree_be_tree_t) (key : u64) (value : u64) (st : state) : result Betree_be_tree_t @@ -1118,7 +1124,7 @@ Definition betree_be_tree_insert_back betree_be_tree_apply_back n self key (BetreeMessageInsert value) st . -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: forward function *) Definition betree_be_tree_delete_fwd (n : nat) (self : Betree_be_tree_t) (key : u64) (st : state) : result (state * unit) @@ -1129,7 +1135,7 @@ Definition betree_be_tree_delete_fwd Return (st0, tt) . -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: backward function 0 *) Definition betree_be_tree_delete_back (n : nat) (self : Betree_be_tree_t) (key : u64) (st : state) : result Betree_be_tree_t @@ -1137,7 +1143,7 @@ Definition betree_be_tree_delete_back betree_be_tree_apply_back n self key BetreeMessageDelete st . -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: forward function *) Definition betree_be_tree_upsert_fwd (n : nat) (self : Betree_be_tree_t) (key : u64) (upd : Betree_upsert_fun_state_t) (st : state) : @@ -1149,7 +1155,7 @@ Definition betree_be_tree_upsert_fwd Return (st0, tt) . -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: backward function 0 *) Definition betree_be_tree_upsert_back (n : nat) (self : Betree_be_tree_t) (key : u64) (upd : Betree_upsert_fun_state_t) (st : state) : @@ -1158,7 +1164,7 @@ Definition betree_be_tree_upsert_back betree_be_tree_apply_back n self key (BetreeMessageUpsert upd) st . -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: forward function *) Definition betree_be_tree_lookup_fwd (n : nat) (self : Betree_be_tree_t) (key : u64) (st : state) : result (state * (option u64)) @@ -1166,7 +1172,7 @@ Definition betree_be_tree_lookup_fwd betree_node_lookup_fwd n self.(Betree_be_tree_root) key st . -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: backward function 0 *) Definition betree_be_tree_lookup_back (n : nat) (self : Betree_be_tree_t) (key : u64) (st : state) : result Betree_be_tree_t @@ -1180,7 +1186,7 @@ Definition betree_be_tree_lookup_back |} . -(** [betree_main::main] *) +(** [betree_main::main]: forward function *) Definition main_fwd : result unit := Return tt. diff --git a/tests/coq/betree/BetreeMain_Opaque.v b/tests/coq/betree/BetreeMain_Opaque.v index 51321f56..bd49500b 100644 --- a/tests/coq/betree/BetreeMain_Opaque.v +++ b/tests/coq/betree/BetreeMain_Opaque.v @@ -8,29 +8,29 @@ Require Export BetreeMain_Types. Import BetreeMain_Types. Module BetreeMain_Opaque. -(** [betree_main::betree_utils::load_internal_node] *) +(** [betree_main::betree_utils::load_internal_node]: forward function *) Axiom betree_utils_load_internal_node_fwd : u64 -> state -> result (state * (Betree_list_t (u64 * Betree_message_t))) . -(** [betree_main::betree_utils::store_internal_node] *) +(** [betree_main::betree_utils::store_internal_node]: forward function *) Axiom betree_utils_store_internal_node_fwd : u64 -> Betree_list_t (u64 * Betree_message_t) -> state -> result (state * unit) . -(** [betree_main::betree_utils::load_leaf_node] *) +(** [betree_main::betree_utils::load_leaf_node]: forward function *) Axiom betree_utils_load_leaf_node_fwd : u64 -> state -> result (state * (Betree_list_t (u64 * u64))) . -(** [betree_main::betree_utils::store_leaf_node] *) +(** [betree_main::betree_utils::store_leaf_node]: forward function *) Axiom betree_utils_store_leaf_node_fwd : u64 -> Betree_list_t (u64 * u64) -> state -> result (state * unit) . -(** [core::option::Option::{0}::unwrap] *) +(** [core::option::Option::{0}::unwrap]: forward function *) Axiom core_option_option_unwrap_fwd : forall(T : Type), option T -> state -> result (state * T) . diff --git a/tests/coq/betree/_CoqProject b/tests/coq/betree/_CoqProject index e5a3f799..42c62421 100644 --- a/tests/coq/betree/_CoqProject +++ b/tests/coq/betree/_CoqProject @@ -3,7 +3,7 @@ -arg -w -arg all -Primitives.v BetreeMain_Types.v +Primitives.v BetreeMain_Funs.v BetreeMain_Opaque.v diff --git a/tests/coq/hashmap/Hashmap_Funs.v b/tests/coq/hashmap/Hashmap_Funs.v index 6bc82677..c8630eb6 100644 --- a/tests/coq/hashmap/Hashmap_Funs.v +++ b/tests/coq/hashmap/Hashmap_Funs.v @@ -8,11 +8,11 @@ Require Export Hashmap_Types. Import Hashmap_Types. Module Hashmap_Funs. -(** [hashmap::hash_key] *) +(** [hashmap::hash_key]: forward function *) Definition hash_key_fwd (k : usize) : result usize := Return k. -(** [hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) Fixpoint hash_map_allocate_slots_loop_fwd (T : Type) (n : nat) (slots : vec (List_t T)) (n0 : usize) : result (vec (List_t T)) @@ -29,7 +29,7 @@ Fixpoint hash_map_allocate_slots_loop_fwd end . -(** [hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap::HashMap::{0}::allocate_slots]: forward function *) Definition hash_map_allocate_slots_fwd (T : Type) (n : nat) (slots : vec (List_t T)) (n0 : usize) : result (vec (List_t T)) @@ -37,7 +37,7 @@ Definition hash_map_allocate_slots_fwd hash_map_allocate_slots_loop_fwd T n slots n0 . -(** [hashmap::HashMap::{0}::new_with_capacity] *) +(** [hashmap::HashMap::{0}::new_with_capacity]: forward function *) Definition hash_map_new_with_capacity_fwd (T : Type) (n : nat) (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : @@ -56,12 +56,13 @@ Definition hash_map_new_with_capacity_fwd |} . -(** [hashmap::HashMap::{0}::new] *) +(** [hashmap::HashMap::{0}::new]: forward function *) Definition hash_map_new_fwd (T : Type) (n : nat) : result (Hash_map_t T) := hash_map_new_with_capacity_fwd T n 32%usize 4%usize 5%usize . -(** [hashmap::HashMap::{0}::clear] *) +(** [hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hash_map_clear_loop_fwd_back (T : Type) (n : nat) (slots : vec (List_t T)) (i : usize) : result (vec (List_t T)) @@ -79,7 +80,8 @@ Fixpoint hash_map_clear_loop_fwd_back end . -(** [hashmap::HashMap::{0}::clear] *) +(** [hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_clear_fwd_back (T : Type) (n : nat) (self : Hash_map_t T) : result (Hash_map_t T) := v <- hash_map_clear_loop_fwd_back T n self.(Hash_map_slots) 0%usize; @@ -92,12 +94,12 @@ Definition hash_map_clear_fwd_back |} . -(** [hashmap::HashMap::{0}::len] *) +(** [hashmap::HashMap::{0}::len]: forward function *) Definition hash_map_len_fwd (T : Type) (self : Hash_map_t T) : result usize := Return self.(Hash_map_num_entries) . -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) Fixpoint hash_map_insert_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (value : T) (ls : List_t T) : result bool @@ -115,7 +117,7 @@ Fixpoint hash_map_insert_in_list_loop_fwd end . -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: forward function *) Definition hash_map_insert_in_list_fwd (T : Type) (n : nat) (key : usize) (value : T) (ls : List_t T) : result bool @@ -123,7 +125,7 @@ Definition hash_map_insert_in_list_fwd hash_map_insert_in_list_loop_fwd T n key value ls . -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) Fixpoint hash_map_insert_in_list_loop_back (T : Type) (n : nat) (key : usize) (value : T) (ls : List_t T) : result (List_t T) @@ -143,7 +145,7 @@ Fixpoint hash_map_insert_in_list_loop_back end . -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) Definition hash_map_insert_in_list_back (T : Type) (n : nat) (key : usize) (value : T) (ls : List_t T) : result (List_t T) @@ -151,7 +153,8 @@ Definition hash_map_insert_in_list_back hash_map_insert_in_list_loop_back T n key value ls . -(** [hashmap::HashMap::{0}::insert_no_resize] *) +(** [hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_insert_no_resize_fwd_back (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) (value : T) : result (Hash_map_t T) @@ -189,7 +192,8 @@ Definition hash_map_insert_no_resize_fwd_back Definition core_num_u32_max_body : result u32 := Return 4294967295%u32. Definition core_num_u32_max_c : u32 := core_num_u32_max_body%global. -(** [hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hash_map_move_elements_from_list_loop_fwd_back (T : Type) (n : nat) (ntable : Hash_map_t T) (ls : List_t T) : result (Hash_map_t T) @@ -206,7 +210,8 @@ Fixpoint hash_map_move_elements_from_list_loop_fwd_back end . -(** [hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_move_elements_from_list_fwd_back (T : Type) (n : nat) (ntable : Hash_map_t T) (ls : List_t T) : result (Hash_map_t T) @@ -214,7 +219,8 @@ Definition hash_map_move_elements_from_list_fwd_back hash_map_move_elements_from_list_loop_fwd_back T n ntable ls . -(** [hashmap::HashMap::{0}::move_elements] *) +(** [hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hash_map_move_elements_loop_fwd_back (T : Type) (n : nat) (ntable : Hash_map_t T) (slots : vec (List_t T)) (i : usize) : @@ -237,7 +243,8 @@ Fixpoint hash_map_move_elements_loop_fwd_back end . -(** [hashmap::HashMap::{0}::move_elements] *) +(** [hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_move_elements_fwd_back (T : Type) (n : nat) (ntable : Hash_map_t T) (slots : vec (List_t T)) (i : usize) : @@ -246,7 +253,8 @@ Definition hash_map_move_elements_fwd_back hash_map_move_elements_loop_fwd_back T n ntable slots i . -(** [hashmap::HashMap::{0}::try_resize] *) +(** [hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_try_resize_fwd_back (T : Type) (n : nat) (self : Hash_map_t T) : result (Hash_map_t T) := max_usize <- scalar_cast U32 Usize core_num_u32_max_c; @@ -278,7 +286,8 @@ Definition hash_map_try_resize_fwd_back |} . -(** [hashmap::HashMap::{0}::insert] *) +(** [hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hash_map_insert_fwd_back (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) (value : T) : result (Hash_map_t T) @@ -290,7 +299,7 @@ Definition hash_map_insert_fwd_back else Return self0 . -(** [hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) Fixpoint hash_map_contains_key_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result bool := match n with @@ -306,13 +315,13 @@ Fixpoint hash_map_contains_key_in_list_loop_fwd end . -(** [hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap::HashMap::{0}::contains_key_in_list]: forward function *) Definition hash_map_contains_key_in_list_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result bool := hash_map_contains_key_in_list_loop_fwd T n key ls . -(** [hashmap::HashMap::{0}::contains_key] *) +(** [hashmap::HashMap::{0}::contains_key]: forward function *) Definition hash_map_contains_key_fwd (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) : result bool := hash <- hash_key_fwd key; @@ -322,7 +331,7 @@ Definition hash_map_contains_key_fwd hash_map_contains_key_in_list_fwd T n key l . -(** [hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) Fixpoint hash_map_get_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result T := match n with @@ -338,13 +347,13 @@ Fixpoint hash_map_get_in_list_loop_fwd end . -(** [hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap::HashMap::{0}::get_in_list]: forward function *) Definition hash_map_get_in_list_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result T := hash_map_get_in_list_loop_fwd T n key ls . -(** [hashmap::HashMap::{0}::get] *) +(** [hashmap::HashMap::{0}::get]: forward function *) Definition hash_map_get_fwd (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) : result T := hash <- hash_key_fwd key; @@ -354,7 +363,7 @@ Definition hash_map_get_fwd hash_map_get_in_list_fwd T n key l . -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) Fixpoint hash_map_get_mut_in_list_loop_fwd (T : Type) (n : nat) (ls : List_t T) (key : usize) : result T := match n with @@ -370,13 +379,13 @@ Fixpoint hash_map_get_mut_in_list_loop_fwd end . -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: forward function *) Definition hash_map_get_mut_in_list_fwd (T : Type) (n : nat) (ls : List_t T) (key : usize) : result T := hash_map_get_mut_in_list_loop_fwd T n ls key . -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) Fixpoint hash_map_get_mut_in_list_loop_back (T : Type) (n : nat) (ls : List_t T) (key : usize) (ret : T) : result (List_t T) @@ -396,7 +405,7 @@ Fixpoint hash_map_get_mut_in_list_loop_back end . -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) Definition hash_map_get_mut_in_list_back (T : Type) (n : nat) (ls : List_t T) (key : usize) (ret : T) : result (List_t T) @@ -404,7 +413,7 @@ Definition hash_map_get_mut_in_list_back hash_map_get_mut_in_list_loop_back T n ls key ret . -(** [hashmap::HashMap::{0}::get_mut] *) +(** [hashmap::HashMap::{0}::get_mut]: forward function *) Definition hash_map_get_mut_fwd (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) : result T := hash <- hash_key_fwd key; @@ -414,7 +423,7 @@ Definition hash_map_get_mut_fwd hash_map_get_mut_in_list_fwd T n l key . -(** [hashmap::HashMap::{0}::get_mut] *) +(** [hashmap::HashMap::{0}::get_mut]: backward function 0 *) Definition hash_map_get_mut_back (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) (ret : T) : result (Hash_map_t T) @@ -434,7 +443,7 @@ Definition hash_map_get_mut_back |} . -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) Fixpoint hash_map_remove_from_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result (option T) := match n with @@ -455,13 +464,13 @@ Fixpoint hash_map_remove_from_list_loop_fwd end . -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: forward function *) Definition hash_map_remove_from_list_fwd (T : Type) (n : nat) (key : usize) (ls : List_t T) : result (option T) := hash_map_remove_from_list_loop_fwd T n key ls . -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) Fixpoint hash_map_remove_from_list_loop_back (T : Type) (n : nat) (key : usize) (ls : List_t T) : result (List_t T) := match n with @@ -484,13 +493,13 @@ Fixpoint hash_map_remove_from_list_loop_back end . -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) Definition hash_map_remove_from_list_back (T : Type) (n : nat) (key : usize) (ls : List_t T) : result (List_t T) := hash_map_remove_from_list_loop_back T n key ls . -(** [hashmap::HashMap::{0}::remove] *) +(** [hashmap::HashMap::{0}::remove]: forward function *) Definition hash_map_remove_fwd (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) : result (option T) @@ -507,7 +516,7 @@ Definition hash_map_remove_fwd end . -(** [hashmap::HashMap::{0}::remove] *) +(** [hashmap::HashMap::{0}::remove]: backward function 0 *) Definition hash_map_remove_back (T : Type) (n : nat) (self : Hash_map_t T) (key : usize) : result (Hash_map_t T) @@ -542,7 +551,7 @@ Definition hash_map_remove_back end . -(** [hashmap::test1] *) +(** [hashmap::test1]: forward function *) Definition test1_fwd (n : nat) : result unit := hm <- hash_map_new_fwd u64 n; hm0 <- hash_map_insert_fwd_back u64 n hm 0%usize 42%u64; diff --git a/tests/coq/hashmap/_CoqProject b/tests/coq/hashmap/_CoqProject index daa9b2ba..7f80afbf 100644 --- a/tests/coq/hashmap/_CoqProject +++ b/tests/coq/hashmap/_CoqProject @@ -3,6 +3,6 @@ -arg -w -arg all -Primitives.v Hashmap_Types.v +Primitives.v Hashmap_Funs.v diff --git a/tests/coq/hashmap_on_disk/HashmapMain_Funs.v b/tests/coq/hashmap_on_disk/HashmapMain_Funs.v index 2d1bcda6..1b7304cc 100644 --- a/tests/coq/hashmap_on_disk/HashmapMain_Funs.v +++ b/tests/coq/hashmap_on_disk/HashmapMain_Funs.v @@ -10,11 +10,11 @@ Require Export HashmapMain_Opaque. Import HashmapMain_Opaque. Module HashmapMain_Funs. -(** [hashmap_main::hashmap::hash_key] *) +(** [hashmap_main::hashmap::hash_key]: forward function *) Definition hashmap_hash_key_fwd (k : usize) : result usize := Return k. -(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) Fixpoint hashmap_hash_map_allocate_slots_loop_fwd (T : Type) (n : nat) (slots : vec (Hashmap_list_t T)) (n0 : usize) : result (vec (Hashmap_list_t T)) @@ -31,7 +31,7 @@ Fixpoint hashmap_hash_map_allocate_slots_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: forward function *) Definition hashmap_hash_map_allocate_slots_fwd (T : Type) (n : nat) (slots : vec (Hashmap_list_t T)) (n0 : usize) : result (vec (Hashmap_list_t T)) @@ -39,7 +39,7 @@ Definition hashmap_hash_map_allocate_slots_fwd hashmap_hash_map_allocate_slots_loop_fwd T n slots n0 . -(** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] *) +(** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity]: forward function *) Definition hashmap_hash_map_new_with_capacity_fwd (T : Type) (n : nat) (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : @@ -58,13 +58,14 @@ Definition hashmap_hash_map_new_with_capacity_fwd |} . -(** [hashmap_main::hashmap::HashMap::{0}::new] *) +(** [hashmap_main::hashmap::HashMap::{0}::new]: forward function *) Definition hashmap_hash_map_new_fwd (T : Type) (n : nat) : result (Hashmap_hash_map_t T) := hashmap_hash_map_new_with_capacity_fwd T n 32%usize 4%usize 5%usize . -(** [hashmap_main::hashmap::HashMap::{0}::clear] *) +(** [hashmap_main::hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hashmap_hash_map_clear_loop_fwd_back (T : Type) (n : nat) (slots : vec (Hashmap_list_t T)) (i : usize) : result (vec (Hashmap_list_t T)) @@ -82,7 +83,8 @@ Fixpoint hashmap_hash_map_clear_loop_fwd_back end . -(** [hashmap_main::hashmap::HashMap::{0}::clear] *) +(** [hashmap_main::hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_clear_fwd_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) : result (Hashmap_hash_map_t T) @@ -100,13 +102,13 @@ Definition hashmap_hash_map_clear_fwd_back |} . -(** [hashmap_main::hashmap::HashMap::{0}::len] *) +(** [hashmap_main::hashmap::HashMap::{0}::len]: forward function *) Definition hashmap_hash_map_len_fwd (T : Type) (self : Hashmap_hash_map_t T) : result usize := Return self.(Hashmap_hash_map_num_entries) . -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) Fixpoint hashmap_hash_map_insert_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (value : T) (ls : Hashmap_list_t T) : result bool @@ -124,7 +126,7 @@ Fixpoint hashmap_hash_map_insert_in_list_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: forward function *) Definition hashmap_hash_map_insert_in_list_fwd (T : Type) (n : nat) (key : usize) (value : T) (ls : Hashmap_list_t T) : result bool @@ -132,7 +134,7 @@ Definition hashmap_hash_map_insert_in_list_fwd hashmap_hash_map_insert_in_list_loop_fwd T n key value ls . -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) Fixpoint hashmap_hash_map_insert_in_list_loop_back (T : Type) (n : nat) (key : usize) (value : T) (ls : Hashmap_list_t T) : result (Hashmap_list_t T) @@ -153,7 +155,7 @@ Fixpoint hashmap_hash_map_insert_in_list_loop_back end . -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) Definition hashmap_hash_map_insert_in_list_back (T : Type) (n : nat) (key : usize) (value : T) (ls : Hashmap_list_t T) : result (Hashmap_list_t T) @@ -161,7 +163,8 @@ Definition hashmap_hash_map_insert_in_list_back hashmap_hash_map_insert_in_list_loop_back T n key value ls . -(** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_insert_no_resize_fwd_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) (value : T) : @@ -207,7 +210,8 @@ Definition hashmap_hash_map_insert_no_resize_fwd_back Definition core_num_u32_max_body : result u32 := Return 4294967295%u32. Definition core_num_u32_max_c : u32 := core_num_u32_max_body%global. -(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hashmap_hash_map_move_elements_from_list_loop_fwd_back (T : Type) (n : nat) (ntable : Hashmap_hash_map_t T) (ls : Hashmap_list_t T) : @@ -225,7 +229,8 @@ Fixpoint hashmap_hash_map_move_elements_from_list_loop_fwd_back end . -(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_move_elements_from_list_fwd_back (T : Type) (n : nat) (ntable : Hashmap_hash_map_t T) (ls : Hashmap_list_t T) : @@ -234,7 +239,8 @@ Definition hashmap_hash_map_move_elements_from_list_fwd_back hashmap_hash_map_move_elements_from_list_loop_fwd_back T n ntable ls . -(** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint hashmap_hash_map_move_elements_loop_fwd_back (T : Type) (n : nat) (ntable : Hashmap_hash_map_t T) (slots : vec (Hashmap_list_t T)) (i : usize) : @@ -258,7 +264,8 @@ Fixpoint hashmap_hash_map_move_elements_loop_fwd_back end . -(** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_move_elements_fwd_back (T : Type) (n : nat) (ntable : Hashmap_hash_map_t T) (slots : vec (Hashmap_list_t T)) (i : usize) : @@ -267,7 +274,8 @@ Definition hashmap_hash_map_move_elements_fwd_back hashmap_hash_map_move_elements_loop_fwd_back T n ntable slots i . -(** [hashmap_main::hashmap::HashMap::{0}::try_resize] *) +(** [hashmap_main::hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_try_resize_fwd_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) : result (Hashmap_hash_map_t T) @@ -302,7 +310,8 @@ Definition hashmap_hash_map_try_resize_fwd_back |} . -(** [hashmap_main::hashmap::HashMap::{0}::insert] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition hashmap_hash_map_insert_fwd_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) (value : T) : @@ -315,7 +324,7 @@ Definition hashmap_hash_map_insert_fwd_back else Return self0 . -(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) Fixpoint hashmap_hash_map_contains_key_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result bool := match n with @@ -331,13 +340,13 @@ Fixpoint hashmap_hash_map_contains_key_in_list_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: forward function *) Definition hashmap_hash_map_contains_key_in_list_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result bool := hashmap_hash_map_contains_key_in_list_loop_fwd T n key ls . -(** [hashmap_main::hashmap::HashMap::{0}::contains_key] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key]: forward function *) Definition hashmap_hash_map_contains_key_fwd (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) : result bool @@ -349,7 +358,7 @@ Definition hashmap_hash_map_contains_key_fwd hashmap_hash_map_contains_key_in_list_fwd T n key l . -(** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) Fixpoint hashmap_hash_map_get_in_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result T := match n with @@ -365,13 +374,13 @@ Fixpoint hashmap_hash_map_get_in_list_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: forward function *) Definition hashmap_hash_map_get_in_list_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result T := hashmap_hash_map_get_in_list_loop_fwd T n key ls . -(** [hashmap_main::hashmap::HashMap::{0}::get] *) +(** [hashmap_main::hashmap::HashMap::{0}::get]: forward function *) Definition hashmap_hash_map_get_fwd (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) : result T @@ -383,7 +392,7 @@ Definition hashmap_hash_map_get_fwd hashmap_hash_map_get_in_list_fwd T n key l . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) Fixpoint hashmap_hash_map_get_mut_in_list_loop_fwd (T : Type) (n : nat) (ls : Hashmap_list_t T) (key : usize) : result T := match n with @@ -399,13 +408,13 @@ Fixpoint hashmap_hash_map_get_mut_in_list_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: forward function *) Definition hashmap_hash_map_get_mut_in_list_fwd (T : Type) (n : nat) (ls : Hashmap_list_t T) (key : usize) : result T := hashmap_hash_map_get_mut_in_list_loop_fwd T n ls key . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) Fixpoint hashmap_hash_map_get_mut_in_list_loop_back (T : Type) (n : nat) (ls : Hashmap_list_t T) (key : usize) (ret : T) : result (Hashmap_list_t T) @@ -425,7 +434,7 @@ Fixpoint hashmap_hash_map_get_mut_in_list_loop_back end . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) Definition hashmap_hash_map_get_mut_in_list_back (T : Type) (n : nat) (ls : Hashmap_list_t T) (key : usize) (ret : T) : result (Hashmap_list_t T) @@ -433,7 +442,7 @@ Definition hashmap_hash_map_get_mut_in_list_back hashmap_hash_map_get_mut_in_list_loop_back T n ls key ret . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut]: forward function *) Definition hashmap_hash_map_get_mut_fwd (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) : result T @@ -446,7 +455,7 @@ Definition hashmap_hash_map_get_mut_fwd hashmap_hash_map_get_mut_in_list_fwd T n l key . -(** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut]: backward function 0 *) Definition hashmap_hash_map_get_mut_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) (ret : T) : result (Hashmap_hash_map_t T) @@ -470,7 +479,7 @@ Definition hashmap_hash_map_get_mut_back |} . -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) Fixpoint hashmap_hash_map_remove_from_list_loop_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result (option T) @@ -495,7 +504,7 @@ Fixpoint hashmap_hash_map_remove_from_list_loop_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: forward function *) Definition hashmap_hash_map_remove_from_list_fwd (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result (option T) @@ -503,7 +512,7 @@ Definition hashmap_hash_map_remove_from_list_fwd hashmap_hash_map_remove_from_list_loop_fwd T n key ls . -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) Fixpoint hashmap_hash_map_remove_from_list_loop_back (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result (Hashmap_list_t T) @@ -530,7 +539,7 @@ Fixpoint hashmap_hash_map_remove_from_list_loop_back end . -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) Definition hashmap_hash_map_remove_from_list_back (T : Type) (n : nat) (key : usize) (ls : Hashmap_list_t T) : result (Hashmap_list_t T) @@ -538,7 +547,7 @@ Definition hashmap_hash_map_remove_from_list_back hashmap_hash_map_remove_from_list_loop_back T n key ls . -(** [hashmap_main::hashmap::HashMap::{0}::remove] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove]: forward function *) Definition hashmap_hash_map_remove_fwd (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) : result (option T) @@ -557,7 +566,7 @@ Definition hashmap_hash_map_remove_fwd end . -(** [hashmap_main::hashmap::HashMap::{0}::remove] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 *) Definition hashmap_hash_map_remove_back (T : Type) (n : nat) (self : Hashmap_hash_map_t T) (key : usize) : result (Hashmap_hash_map_t T) @@ -599,7 +608,7 @@ Definition hashmap_hash_map_remove_back end . -(** [hashmap_main::hashmap::test1] *) +(** [hashmap_main::hashmap::test1]: forward function *) Definition hashmap_test1_fwd (n : nat) : result unit := hm <- hashmap_hash_map_new_fwd u64 n; hm0 <- hashmap_hash_map_insert_fwd_back u64 n hm 0%usize 42%u64; @@ -636,7 +645,7 @@ Definition hashmap_test1_fwd (n : nat) : result unit := end)) . -(** [hashmap_main::insert_on_disk] *) +(** [hashmap_main::insert_on_disk]: forward function *) Definition insert_on_disk_fwd (n : nat) (key : usize) (value : u64) (st : state) : result (state * unit) := p <- hashmap_utils_deserialize_fwd st; @@ -647,7 +656,7 @@ Definition insert_on_disk_fwd Return (st1, tt) . -(** [hashmap_main::main] *) +(** [hashmap_main::main]: forward function *) Definition main_fwd : result unit := Return tt. diff --git a/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v b/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v index e1e7fe2b..1ad9c697 100644 --- a/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v +++ b/tests/coq/hashmap_on_disk/HashmapMain_Opaque.v @@ -8,12 +8,12 @@ Require Export HashmapMain_Types. Import HashmapMain_Types. Module HashmapMain_Opaque. -(** [hashmap_main::hashmap_utils::deserialize] *) +(** [hashmap_main::hashmap_utils::deserialize]: forward function *) Axiom hashmap_utils_deserialize_fwd : state -> result (state * (Hashmap_hash_map_t u64)) . -(** [hashmap_main::hashmap_utils::serialize] *) +(** [hashmap_main::hashmap_utils::serialize]: forward function *) Axiom hashmap_utils_serialize_fwd : Hashmap_hash_map_t u64 -> state -> result (state * unit) . diff --git a/tests/coq/misc/Constants.v b/tests/coq/misc/Constants.v index 6a5f2696..14c05c61 100644 --- a/tests/coq/misc/Constants.v +++ b/tests/coq/misc/Constants.v @@ -22,7 +22,7 @@ Definition x1_c : u32 := x1_body%global. Definition x2_body : result u32 := Return 3%u32. Definition x2_c : u32 := x2_body%global. -(** [constants::incr] *) +(** [constants::incr]: forward function *) Definition incr_fwd (n : u32) : result u32 := u32_add n 1%u32. @@ -30,7 +30,7 @@ Definition incr_fwd (n : u32) : result u32 := Definition x3_body : result u32 := incr_fwd 32%u32. Definition x3_c : u32 := x3_body%global. -(** [constants::mk_pair0] *) +(** [constants::mk_pair0]: forward function *) Definition mk_pair0_fwd (x : u32) (y : u32) : result (u32 * u32) := Return (x, y) . @@ -42,7 +42,7 @@ Arguments mkPair_t {T1} {T2} _ _. Arguments Pair_x {T1} {T2}. Arguments Pair_y {T1} {T2}. -(** [constants::mk_pair1] *) +(** [constants::mk_pair1]: forward function *) Definition mk_pair1_fwd (x : u32) (y : u32) : result (Pair_t u32 u32) := Return {| Pair_x := x; Pair_y := y |} . @@ -71,7 +71,7 @@ Record Wrap_t (T : Type) := mkWrap_t { Wrap_val : T; }. Arguments mkWrap_t {T} _. Arguments Wrap_val {T}. -(** [constants::Wrap::{0}::new] *) +(** [constants::Wrap::{0}::new]: forward function *) Definition wrap_new_fwd (T : Type) (val : T) : result (Wrap_t T) := Return {| Wrap_val := val |} . @@ -80,7 +80,7 @@ Definition wrap_new_fwd (T : Type) (val : T) : result (Wrap_t T) := Definition y_body : result (Wrap_t i32) := wrap_new_fwd i32 2%i32. Definition y_c : Wrap_t i32 := y_body%global. -(** [constants::unwrap_y] *) +(** [constants::unwrap_y]: forward function *) Definition unwrap_y_fwd : result i32 := Return y_c.(Wrap_val). @@ -92,11 +92,11 @@ Definition yval_c : i32 := yval_body%global. Definition get_z1_z1_body : result i32 := Return 3%i32. Definition get_z1_z1_c : i32 := get_z1_z1_body%global. -(** [constants::get_z1] *) +(** [constants::get_z1]: forward function *) Definition get_z1_fwd : result i32 := Return get_z1_z1_c. -(** [constants::add] *) +(** [constants::add]: forward function *) Definition add_fwd (a : i32) (b : i32) : result i32 := i32_add a b. @@ -112,7 +112,7 @@ Definition q2_c : i32 := q2_body%global. Definition q3_body : result i32 := add_fwd q2_c 3%i32. Definition q3_c : i32 := q3_body%global. -(** [constants::get_z2] *) +(** [constants::get_z2]: forward function *) Definition get_z2_fwd : result i32 := i <- get_z1_fwd; i0 <- add_fwd i q3_c; add_fwd q1_c i0 . diff --git a/tests/coq/misc/External_Funs.v b/tests/coq/misc/External_Funs.v index 05dd8f2e..f18bbd1f 100644 --- a/tests/coq/misc/External_Funs.v +++ b/tests/coq/misc/External_Funs.v @@ -10,7 +10,7 @@ Require Export External_Opaque. Import External_Opaque. Module External_Funs. -(** [external::swap] *) +(** [external::swap]: forward function *) Definition swap_fwd (T : Type) (x : T) (y : T) (st : state) : result (state * unit) := p <- core_mem_swap_fwd T x y st; @@ -22,7 +22,7 @@ Definition swap_fwd Return (st2, tt) . -(** [external::swap] *) +(** [external::swap]: backward function 0 *) Definition swap_back (T : Type) (x : T) (y : T) (st : state) (st0 : state) : result (state * (T * T)) @@ -36,7 +36,7 @@ Definition swap_back Return (st0, (x0, y0)) . -(** [external::test_new_non_zero_u32] *) +(** [external::test_new_non_zero_u32]: forward function *) Definition test_new_non_zero_u32_fwd (x : u32) (st : state) : result (state * Core_num_nonzero_non_zero_u32_t) := p <- core_num_nonzero_non_zero_u32_new_fwd x st; @@ -44,7 +44,7 @@ Definition test_new_non_zero_u32_fwd core_option_option_unwrap_fwd Core_num_nonzero_non_zero_u32_t opt st0 . -(** [external::test_vec] *) +(** [external::test_vec]: forward function *) Definition test_vec_fwd : result unit := let v := vec_new u32 in _ <- vec_push_back u32 v 0%u32; Return tt . @@ -52,7 +52,7 @@ Definition test_vec_fwd : result unit := (** Unit test for [external::test_vec] *) Check (test_vec_fwd )%return. -(** [external::custom_swap] *) +(** [external::custom_swap]: forward function *) Definition custom_swap_fwd (T : Type) (x : T) (y : T) (st : state) : result (state * T) := p <- core_mem_swap_fwd T x y st; @@ -64,7 +64,7 @@ Definition custom_swap_fwd Return (st2, x0) . -(** [external::custom_swap] *) +(** [external::custom_swap]: backward function 0 *) Definition custom_swap_back (T : Type) (x : T) (y : T) (st : state) (ret : T) (st0 : state) : result (state * (T * T)) @@ -78,13 +78,13 @@ Definition custom_swap_back Return (st0, (ret, y0)) . -(** [external::test_custom_swap] *) +(** [external::test_custom_swap]: forward function *) Definition test_custom_swap_fwd (x : u32) (y : u32) (st : state) : result (state * unit) := p <- custom_swap_fwd u32 x y st; let (st0, _) := p in Return (st0, tt) . -(** [external::test_custom_swap] *) +(** [external::test_custom_swap]: backward function 0 *) Definition test_custom_swap_back (x : u32) (y : u32) (st : state) (st0 : state) : result (state * (u32 * u32)) @@ -92,7 +92,7 @@ Definition test_custom_swap_back custom_swap_back u32 x y st 1%u32 st0 . -(** [external::test_swap_non_zero] *) +(** [external::test_swap_non_zero]: forward function *) Definition test_swap_non_zero_fwd (x : u32) (st : state) : result (state * u32) := p <- swap_fwd u32 x 0%u32 st; diff --git a/tests/coq/misc/External_Opaque.v b/tests/coq/misc/External_Opaque.v index 5ee65277..1224f426 100644 --- a/tests/coq/misc/External_Opaque.v +++ b/tests/coq/misc/External_Opaque.v @@ -8,27 +8,27 @@ Require Export External_Types. Import External_Types. Module External_Opaque. -(** [core::mem::swap] *) +(** [core::mem::swap]: forward function *) Axiom core_mem_swap_fwd : forall(T : Type), T -> T -> state -> result (state * unit) . -(** [core::mem::swap] *) +(** [core::mem::swap]: backward function 0 *) Axiom core_mem_swap_back0 : forall(T : Type), T -> T -> state -> state -> result (state * T) . -(** [core::mem::swap] *) +(** [core::mem::swap]: backward function 1 *) Axiom core_mem_swap_back1 : forall(T : Type), T -> T -> state -> state -> result (state * T) . -(** [core::num::nonzero::NonZeroU32::{14}::new] *) +(** [core::num::nonzero::NonZeroU32::{14}::new]: forward function *) Axiom core_num_nonzero_non_zero_u32_new_fwd : u32 -> state -> result (state * (option Core_num_nonzero_non_zero_u32_t)) . -(** [core::option::Option::{0}::unwrap] *) +(** [core::option::Option::{0}::unwrap]: forward function *) Axiom core_option_option_unwrap_fwd : forall(T : Type), option T -> state -> result (state * T) . diff --git a/tests/coq/misc/Loops.v b/tests/coq/misc/Loops.v index a5cb3688..f17eb986 100644 --- a/tests/coq/misc/Loops.v +++ b/tests/coq/misc/Loops.v @@ -6,7 +6,7 @@ Require Import Coq.ZArith.ZArith. Local Open Scope Primitives_scope. Module Loops. -(** [loops::sum] *) +(** [loops::sum]: loop 0: forward function *) Fixpoint sum_loop_fwd (n : nat) (max : u32) (i : u32) (s : u32) : result u32 := match n with | O => Fail_ OutOfFuel @@ -17,12 +17,12 @@ Fixpoint sum_loop_fwd (n : nat) (max : u32) (i : u32) (s : u32) : result u32 := end . -(** [loops::sum] *) +(** [loops::sum]: forward function *) Definition sum_fwd (n : nat) (max : u32) : result u32 := sum_loop_fwd n max 0%u32 0%u32 . -(** [loops::sum_with_mut_borrows] *) +(** [loops::sum_with_mut_borrows]: loop 0: forward function *) Fixpoint sum_with_mut_borrows_loop_fwd (n : nat) (max : u32) (mi : u32) (ms : u32) : result u32 := match n with @@ -37,12 +37,12 @@ Fixpoint sum_with_mut_borrows_loop_fwd end . -(** [loops::sum_with_mut_borrows] *) +(** [loops::sum_with_mut_borrows]: forward function *) Definition sum_with_mut_borrows_fwd (n : nat) (max : u32) : result u32 := sum_with_mut_borrows_loop_fwd n max 0%u32 0%u32 . -(** [loops::sum_with_shared_borrows] *) +(** [loops::sum_with_shared_borrows]: loop 0: forward function *) Fixpoint sum_with_shared_borrows_loop_fwd (n : nat) (max : u32) (i : u32) (s : u32) : result u32 := match n with @@ -57,12 +57,13 @@ Fixpoint sum_with_shared_borrows_loop_fwd end . -(** [loops::sum_with_shared_borrows] *) +(** [loops::sum_with_shared_borrows]: forward function *) Definition sum_with_shared_borrows_fwd (n : nat) (max : u32) : result u32 := sum_with_shared_borrows_loop_fwd n max 0%u32 0%u32 . -(** [loops::clear] *) +(** [loops::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Fixpoint clear_loop_fwd_back (n : nat) (v : vec u32) (i : usize) : result (vec u32) := match n with @@ -78,7 +79,8 @@ Fixpoint clear_loop_fwd_back end . -(** [loops::clear] *) +(** [loops::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition clear_fwd_back (n : nat) (v : vec u32) : result (vec u32) := clear_loop_fwd_back n v 0%usize . @@ -92,7 +94,7 @@ Inductive List_t (T : Type) := Arguments ListCons {T} _ _. Arguments ListNil {T}. -(** [loops::list_mem] *) +(** [loops::list_mem]: loop 0: forward function *) Fixpoint list_mem_loop_fwd (n : nat) (x : u32) (ls : List_t u32) : result bool := match n with @@ -106,12 +108,12 @@ Fixpoint list_mem_loop_fwd end . -(** [loops::list_mem] *) +(** [loops::list_mem]: forward function *) Definition list_mem_fwd (n : nat) (x : u32) (ls : List_t u32) : result bool := list_mem_loop_fwd n x ls . -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: loop 0: forward function *) Fixpoint list_nth_mut_loop_loop_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := match n with @@ -127,13 +129,13 @@ Fixpoint list_nth_mut_loop_loop_fwd end . -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: forward function *) Definition list_nth_mut_loop_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := list_nth_mut_loop_loop_fwd T n ls i . -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: loop 0: backward function 0 *) Fixpoint list_nth_mut_loop_loop_back (T : Type) (n : nat) (ls : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -154,7 +156,7 @@ Fixpoint list_nth_mut_loop_loop_back end . -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: backward function 0 *) Definition list_nth_mut_loop_back (T : Type) (n : nat) (ls : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -162,7 +164,7 @@ Definition list_nth_mut_loop_back list_nth_mut_loop_loop_back T n ls i ret . -(** [loops::list_nth_shared_loop] *) +(** [loops::list_nth_shared_loop]: loop 0: forward function *) Fixpoint list_nth_shared_loop_loop_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := match n with @@ -178,13 +180,13 @@ Fixpoint list_nth_shared_loop_loop_fwd end . -(** [loops::list_nth_shared_loop] *) +(** [loops::list_nth_shared_loop]: forward function *) Definition list_nth_shared_loop_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := list_nth_shared_loop_loop_fwd T n ls i . -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: loop 0: forward function *) Fixpoint get_elem_mut_loop_fwd (n : nat) (x : usize) (ls : List_t usize) : result usize := match n with @@ -198,14 +200,14 @@ Fixpoint get_elem_mut_loop_fwd end . -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: forward function *) Definition get_elem_mut_fwd (n : nat) (slots : vec (List_t usize)) (x : usize) : result usize := l <- vec_index_mut_fwd (List_t usize) slots 0%usize; get_elem_mut_loop_fwd n x l . -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: loop 0: backward function 0 *) Fixpoint get_elem_mut_loop_back (n : nat) (x : usize) (ls : List_t usize) (ret : usize) : result (List_t usize) @@ -223,7 +225,7 @@ Fixpoint get_elem_mut_loop_back end . -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: backward function 0 *) Definition get_elem_mut_back (n : nat) (slots : vec (List_t usize)) (x : usize) (ret : usize) : result (vec (List_t usize)) @@ -233,7 +235,7 @@ Definition get_elem_mut_back vec_index_mut_back (List_t usize) slots 0%usize l0 . -(** [loops::get_elem_shared] *) +(** [loops::get_elem_shared]: loop 0: forward function *) Fixpoint get_elem_shared_loop_fwd (n : nat) (x : usize) (ls : List_t usize) : result usize := match n with @@ -247,30 +249,30 @@ Fixpoint get_elem_shared_loop_fwd end . -(** [loops::get_elem_shared] *) +(** [loops::get_elem_shared]: forward function *) Definition get_elem_shared_fwd (n : nat) (slots : vec (List_t usize)) (x : usize) : result usize := l <- vec_index_fwd (List_t usize) slots 0%usize; get_elem_shared_loop_fwd n x l . -(** [loops::id_mut] *) +(** [loops::id_mut]: forward function *) Definition id_mut_fwd (T : Type) (ls : List_t T) : result (List_t T) := Return ls . -(** [loops::id_mut] *) +(** [loops::id_mut]: backward function 0 *) Definition id_mut_back (T : Type) (ls : List_t T) (ret : List_t T) : result (List_t T) := Return ret . -(** [loops::id_shared] *) +(** [loops::id_shared]: forward function *) Definition id_shared_fwd (T : Type) (ls : List_t T) : result (List_t T) := Return ls . -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: loop 0: forward function *) Fixpoint list_nth_mut_loop_with_id_loop_fwd (T : Type) (n : nat) (i : u32) (ls : List_t T) : result T := match n with @@ -287,13 +289,13 @@ Fixpoint list_nth_mut_loop_with_id_loop_fwd end . -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: forward function *) Definition list_nth_mut_loop_with_id_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := ls0 <- id_mut_fwd T ls; list_nth_mut_loop_with_id_loop_fwd T n i ls0 . -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: loop 0: backward function 0 *) Fixpoint list_nth_mut_loop_with_id_loop_back (T : Type) (n : nat) (i : u32) (ls : List_t T) (ret : T) : result (List_t T) @@ -314,7 +316,7 @@ Fixpoint list_nth_mut_loop_with_id_loop_back end . -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: backward function 0 *) Definition list_nth_mut_loop_with_id_back (T : Type) (n : nat) (ls : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -324,7 +326,7 @@ Definition list_nth_mut_loop_with_id_back id_mut_back T ls l . -(** [loops::list_nth_shared_loop_with_id] *) +(** [loops::list_nth_shared_loop_with_id]: loop 0: forward function *) Fixpoint list_nth_shared_loop_with_id_loop_fwd (T : Type) (n : nat) (i : u32) (ls : List_t T) : result T := match n with @@ -341,13 +343,13 @@ Fixpoint list_nth_shared_loop_with_id_loop_fwd end . -(** [loops::list_nth_shared_loop_with_id] *) +(** [loops::list_nth_shared_loop_with_id]: forward function *) Definition list_nth_shared_loop_with_id_fwd (T : Type) (n : nat) (ls : List_t T) (i : u32) : result T := ls0 <- id_shared_fwd T ls; list_nth_shared_loop_with_id_loop_fwd T n i ls0 . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: forward function *) Fixpoint list_nth_mut_loop_pair_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -371,7 +373,7 @@ Fixpoint list_nth_mut_loop_pair_loop_fwd end . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: forward function *) Definition list_nth_mut_loop_pair_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -379,7 +381,7 @@ Definition list_nth_mut_loop_pair_fwd list_nth_mut_loop_pair_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: backward function 0 *) Fixpoint list_nth_mut_loop_pair_loop_back'a (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -404,7 +406,7 @@ Fixpoint list_nth_mut_loop_pair_loop_back'a end . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: backward function 0 *) Definition list_nth_mut_loop_pair_back'a (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -412,7 +414,7 @@ Definition list_nth_mut_loop_pair_back'a list_nth_mut_loop_pair_loop_back'a T n ls0 ls1 i ret . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: backward function 1 *) Fixpoint list_nth_mut_loop_pair_loop_back'b (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -437,7 +439,7 @@ Fixpoint list_nth_mut_loop_pair_loop_back'b end . -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: backward function 1 *) Definition list_nth_mut_loop_pair_back'b (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -445,7 +447,7 @@ Definition list_nth_mut_loop_pair_back'b list_nth_mut_loop_pair_loop_back'b T n ls0 ls1 i ret . -(** [loops::list_nth_shared_loop_pair] *) +(** [loops::list_nth_shared_loop_pair]: loop 0: forward function *) Fixpoint list_nth_shared_loop_pair_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -469,7 +471,7 @@ Fixpoint list_nth_shared_loop_pair_loop_fwd end . -(** [loops::list_nth_shared_loop_pair] *) +(** [loops::list_nth_shared_loop_pair]: forward function *) Definition list_nth_shared_loop_pair_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -477,7 +479,7 @@ Definition list_nth_shared_loop_pair_fwd list_nth_shared_loop_pair_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: loop 0: forward function *) Fixpoint list_nth_mut_loop_pair_merge_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -501,7 +503,7 @@ Fixpoint list_nth_mut_loop_pair_merge_loop_fwd end . -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: forward function *) Definition list_nth_mut_loop_pair_merge_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -509,7 +511,7 @@ Definition list_nth_mut_loop_pair_merge_fwd list_nth_mut_loop_pair_merge_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: loop 0: backward function 0 *) Fixpoint list_nth_mut_loop_pair_merge_loop_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : (T * T)) : @@ -536,7 +538,7 @@ Fixpoint list_nth_mut_loop_pair_merge_loop_back end . -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: backward function 0 *) Definition list_nth_mut_loop_pair_merge_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : (T * T)) : @@ -545,7 +547,7 @@ Definition list_nth_mut_loop_pair_merge_back list_nth_mut_loop_pair_merge_loop_back T n ls0 ls1 i ret . -(** [loops::list_nth_shared_loop_pair_merge] *) +(** [loops::list_nth_shared_loop_pair_merge]: loop 0: forward function *) Fixpoint list_nth_shared_loop_pair_merge_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -569,7 +571,7 @@ Fixpoint list_nth_shared_loop_pair_merge_loop_fwd end . -(** [loops::list_nth_shared_loop_pair_merge] *) +(** [loops::list_nth_shared_loop_pair_merge]: forward function *) Definition list_nth_shared_loop_pair_merge_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -577,7 +579,7 @@ Definition list_nth_shared_loop_pair_merge_fwd list_nth_shared_loop_pair_merge_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: loop 0: forward function *) Fixpoint list_nth_mut_shared_loop_pair_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -601,7 +603,7 @@ Fixpoint list_nth_mut_shared_loop_pair_loop_fwd end . -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: forward function *) Definition list_nth_mut_shared_loop_pair_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -609,7 +611,7 @@ Definition list_nth_mut_shared_loop_pair_fwd list_nth_mut_shared_loop_pair_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: loop 0: backward function 0 *) Fixpoint list_nth_mut_shared_loop_pair_loop_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -634,7 +636,7 @@ Fixpoint list_nth_mut_shared_loop_pair_loop_back end . -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: backward function 0 *) Definition list_nth_mut_shared_loop_pair_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -642,7 +644,7 @@ Definition list_nth_mut_shared_loop_pair_back list_nth_mut_shared_loop_pair_loop_back T n ls0 ls1 i ret . -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: forward function *) Fixpoint list_nth_mut_shared_loop_pair_merge_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -666,7 +668,7 @@ Fixpoint list_nth_mut_shared_loop_pair_merge_loop_fwd end . -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: forward function *) Definition list_nth_mut_shared_loop_pair_merge_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -674,7 +676,7 @@ Definition list_nth_mut_shared_loop_pair_merge_fwd list_nth_mut_shared_loop_pair_merge_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: backward function 0 *) Fixpoint list_nth_mut_shared_loop_pair_merge_loop_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -700,7 +702,7 @@ Fixpoint list_nth_mut_shared_loop_pair_merge_loop_back end . -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: backward function 0 *) Definition list_nth_mut_shared_loop_pair_merge_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -708,7 +710,7 @@ Definition list_nth_mut_shared_loop_pair_merge_back list_nth_mut_shared_loop_pair_merge_loop_back T n ls0 ls1 i ret . -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: loop 0: forward function *) Fixpoint list_nth_shared_mut_loop_pair_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -732,7 +734,7 @@ Fixpoint list_nth_shared_mut_loop_pair_loop_fwd end . -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: forward function *) Definition list_nth_shared_mut_loop_pair_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -740,7 +742,7 @@ Definition list_nth_shared_mut_loop_pair_fwd list_nth_shared_mut_loop_pair_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: loop 0: backward function 1 *) Fixpoint list_nth_shared_mut_loop_pair_loop_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -765,7 +767,7 @@ Fixpoint list_nth_shared_mut_loop_pair_loop_back end . -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: backward function 1 *) Definition list_nth_shared_mut_loop_pair_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -773,7 +775,7 @@ Definition list_nth_shared_mut_loop_pair_back list_nth_shared_mut_loop_pair_loop_back T n ls0 ls1 i ret . -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: forward function *) Fixpoint list_nth_shared_mut_loop_pair_merge_loop_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -797,7 +799,7 @@ Fixpoint list_nth_shared_mut_loop_pair_merge_loop_fwd end . -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: forward function *) Definition list_nth_shared_mut_loop_pair_merge_fwd (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) : result (T * T) @@ -805,7 +807,7 @@ Definition list_nth_shared_mut_loop_pair_merge_fwd list_nth_shared_mut_loop_pair_merge_loop_fwd T n ls0 ls1 i . -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: backward function 0 *) Fixpoint list_nth_shared_mut_loop_pair_merge_loop_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) @@ -831,7 +833,7 @@ Fixpoint list_nth_shared_mut_loop_pair_merge_loop_back end . -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: backward function 0 *) Definition list_nth_shared_mut_loop_pair_merge_back (T : Type) (n : nat) (ls0 : List_t T) (ls1 : List_t T) (i : u32) (ret : T) : result (List_t T) diff --git a/tests/coq/misc/NoNestedBorrows.v b/tests/coq/misc/NoNestedBorrows.v index 96d62711..470a2cde 100644 --- a/tests/coq/misc/NoNestedBorrows.v +++ b/tests/coq/misc/NoNestedBorrows.v @@ -45,47 +45,47 @@ Inductive Sum_t (T1 T2 : Type) := Arguments SumLeft {T1} {T2} _. Arguments SumRight {T1} {T2} _. -(** [no_nested_borrows::neg_test] *) +(** [no_nested_borrows::neg_test]: forward function *) Definition neg_test_fwd (x : i32) : result i32 := i32_neg x. -(** [no_nested_borrows::add_test] *) +(** [no_nested_borrows::add_test]: forward function *) Definition add_test_fwd (x : u32) (y : u32) : result u32 := u32_add x y. -(** [no_nested_borrows::subs_test] *) +(** [no_nested_borrows::subs_test]: forward function *) Definition subs_test_fwd (x : u32) (y : u32) : result u32 := u32_sub x y. -(** [no_nested_borrows::div_test] *) +(** [no_nested_borrows::div_test]: forward function *) Definition div_test_fwd (x : u32) (y : u32) : result u32 := u32_div x y. -(** [no_nested_borrows::div_test1] *) +(** [no_nested_borrows::div_test1]: forward function *) Definition div_test1_fwd (x : u32) : result u32 := u32_div x 2%u32. -(** [no_nested_borrows::rem_test] *) +(** [no_nested_borrows::rem_test]: forward function *) Definition rem_test_fwd (x : u32) (y : u32) : result u32 := u32_rem x y. -(** [no_nested_borrows::cast_test] *) +(** [no_nested_borrows::cast_test]: forward function *) Definition cast_test_fwd (x : u32) : result i32 := scalar_cast U32 I32 x. -(** [no_nested_borrows::test2] *) +(** [no_nested_borrows::test2]: forward function *) Definition test2_fwd : result unit := _ <- u32_add 23%u32 44%u32; Return tt. (** Unit test for [no_nested_borrows::test2] *) Check (test2_fwd )%return. -(** [no_nested_borrows::get_max] *) +(** [no_nested_borrows::get_max]: forward function *) Definition get_max_fwd (x : u32) (y : u32) : result u32 := if x s>= y then Return x else Return y . -(** [no_nested_borrows::test3] *) +(** [no_nested_borrows::test3]: forward function *) Definition test3_fwd : result unit := x <- get_max_fwd 4%u32 3%u32; y <- get_max_fwd 10%u32 11%u32; @@ -96,7 +96,7 @@ Definition test3_fwd : result unit := (** Unit test for [no_nested_borrows::test3] *) Check (test3_fwd )%return. -(** [no_nested_borrows::test_neg1] *) +(** [no_nested_borrows::test_neg1]: forward function *) Definition test_neg1_fwd : result unit := y <- i32_neg 3%i32; if negb (y s= (-3)%i32) then Fail_ Failure else Return tt . @@ -104,7 +104,7 @@ Definition test_neg1_fwd : result unit := (** Unit test for [no_nested_borrows::test_neg1] *) Check (test_neg1_fwd )%return. -(** [no_nested_borrows::refs_test1] *) +(** [no_nested_borrows::refs_test1]: forward function *) Definition refs_test1_fwd : result unit := if negb (1%i32 s= 1%i32) then Fail_ Failure else Return tt . @@ -112,7 +112,7 @@ Definition refs_test1_fwd : result unit := (** Unit test for [no_nested_borrows::refs_test1] *) Check (refs_test1_fwd )%return. -(** [no_nested_borrows::refs_test2] *) +(** [no_nested_borrows::refs_test2]: forward function *) Definition refs_test2_fwd : result unit := if negb (2%i32 s= 2%i32) then Fail_ Failure @@ -128,14 +128,14 @@ Definition refs_test2_fwd : result unit := (** Unit test for [no_nested_borrows::refs_test2] *) Check (refs_test2_fwd )%return. -(** [no_nested_borrows::test_list1] *) +(** [no_nested_borrows::test_list1]: forward function *) Definition test_list1_fwd : result unit := Return tt. (** Unit test for [no_nested_borrows::test_list1] *) Check (test_list1_fwd )%return. -(** [no_nested_borrows::test_box1] *) +(** [no_nested_borrows::test_box1]: forward function *) Definition test_box1_fwd : result unit := let b := 1%i32 in let x := b in @@ -145,21 +145,21 @@ Definition test_box1_fwd : result unit := (** Unit test for [no_nested_borrows::test_box1] *) Check (test_box1_fwd )%return. -(** [no_nested_borrows::copy_int] *) +(** [no_nested_borrows::copy_int]: forward function *) Definition copy_int_fwd (x : i32) : result i32 := Return x. -(** [no_nested_borrows::test_unreachable] *) +(** [no_nested_borrows::test_unreachable]: forward function *) Definition test_unreachable_fwd (b : bool) : result unit := if b then Fail_ Failure else Return tt . -(** [no_nested_borrows::test_panic] *) +(** [no_nested_borrows::test_panic]: forward function *) Definition test_panic_fwd (b : bool) : result unit := if b then Fail_ Failure else Return tt . -(** [no_nested_borrows::test_copy_int] *) +(** [no_nested_borrows::test_copy_int]: forward function *) Definition test_copy_int_fwd : result unit := y <- copy_int_fwd 0%i32; if negb (0%i32 s= y) then Fail_ Failure else Return tt @@ -168,12 +168,12 @@ Definition test_copy_int_fwd : result unit := (** Unit test for [no_nested_borrows::test_copy_int] *) Check (test_copy_int_fwd )%return. -(** [no_nested_borrows::is_cons] *) +(** [no_nested_borrows::is_cons]: forward function *) Definition is_cons_fwd (T : Type) (l : List_t T) : result bool := match l with | ListCons t l0 => Return true | ListNil => Return false end . -(** [no_nested_borrows::test_is_cons] *) +(** [no_nested_borrows::test_is_cons]: forward function *) Definition test_is_cons_fwd : result unit := let l := ListNil in b <- is_cons_fwd i32 (ListCons 0%i32 l); @@ -183,7 +183,7 @@ Definition test_is_cons_fwd : result unit := (** Unit test for [no_nested_borrows::test_is_cons] *) Check (test_is_cons_fwd )%return. -(** [no_nested_borrows::split_list] *) +(** [no_nested_borrows::split_list]: forward function *) Definition split_list_fwd (T : Type) (l : List_t T) : result (T * (List_t T)) := match l with @@ -192,7 +192,7 @@ Definition split_list_fwd end . -(** [no_nested_borrows::test_split_list] *) +(** [no_nested_borrows::test_split_list]: forward function *) Definition test_split_list_fwd : result unit := let l := ListNil in p <- split_list_fwd i32 (ListCons 0%i32 l); @@ -203,18 +203,18 @@ Definition test_split_list_fwd : result unit := (** Unit test for [no_nested_borrows::test_split_list] *) Check (test_split_list_fwd )%return. -(** [no_nested_borrows::choose] *) +(** [no_nested_borrows::choose]: forward function *) Definition choose_fwd (T : Type) (b : bool) (x : T) (y : T) : result T := if b then Return x else Return y . -(** [no_nested_borrows::choose] *) +(** [no_nested_borrows::choose]: backward function 0 *) Definition choose_back (T : Type) (b : bool) (x : T) (y : T) (ret : T) : result (T * T) := if b then Return (ret, y) else Return (x, ret) . -(** [no_nested_borrows::choose_test] *) +(** [no_nested_borrows::choose_test]: forward function *) Definition choose_test_fwd : result unit := z <- choose_fwd i32 true 0%i32 0%i32; z0 <- i32_add z 1%i32; @@ -231,7 +231,7 @@ Definition choose_test_fwd : result unit := (** Unit test for [no_nested_borrows::choose_test] *) Check (choose_test_fwd )%return. -(** [no_nested_borrows::test_char] *) +(** [no_nested_borrows::test_char]: forward function *) Definition test_char_fwd : result char := Return (char_of_byte Coq.Init.Byte.x61) . @@ -253,7 +253,7 @@ Arguments NodeElemNil {T}. Arguments TreeLeaf {T} _. Arguments TreeNode {T} _ _ _. -(** [no_nested_borrows::list_length] *) +(** [no_nested_borrows::list_length]: forward function *) Fixpoint list_length_fwd (T : Type) (l : List_t T) : result u32 := match l with | ListCons t l1 => i <- list_length_fwd T l1; u32_add 1%u32 i @@ -261,7 +261,7 @@ Fixpoint list_length_fwd (T : Type) (l : List_t T) : result u32 := end . -(** [no_nested_borrows::list_nth_shared] *) +(** [no_nested_borrows::list_nth_shared]: forward function *) Fixpoint list_nth_shared_fwd (T : Type) (l : List_t T) (i : u32) : result T := match l with | ListCons x tl => @@ -272,7 +272,7 @@ Fixpoint list_nth_shared_fwd (T : Type) (l : List_t T) (i : u32) : result T := end . -(** [no_nested_borrows::list_nth_mut] *) +(** [no_nested_borrows::list_nth_mut]: forward function *) Fixpoint list_nth_mut_fwd (T : Type) (l : List_t T) (i : u32) : result T := match l with | ListCons x tl => @@ -283,7 +283,7 @@ Fixpoint list_nth_mut_fwd (T : Type) (l : List_t T) (i : u32) : result T := end . -(** [no_nested_borrows::list_nth_mut] *) +(** [no_nested_borrows::list_nth_mut]: backward function 0 *) Fixpoint list_nth_mut_back (T : Type) (l : List_t T) (i : u32) (ret : T) : result (List_t T) := match l with @@ -298,7 +298,7 @@ Fixpoint list_nth_mut_back end . -(** [no_nested_borrows::list_rev_aux] *) +(** [no_nested_borrows::list_rev_aux]: forward function *) Fixpoint list_rev_aux_fwd (T : Type) (li : List_t T) (lo : List_t T) : result (List_t T) := match li with @@ -307,13 +307,14 @@ Fixpoint list_rev_aux_fwd end . -(** [no_nested_borrows::list_rev] *) +(** [no_nested_borrows::list_rev]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition list_rev_fwd_back (T : Type) (l : List_t T) : result (List_t T) := let li := mem_replace_fwd (List_t T) l ListNil in list_rev_aux_fwd T li ListNil . -(** [no_nested_borrows::test_list_functions] *) +(** [no_nested_borrows::test_list_functions]: forward function *) Definition test_list_functions_fwd : result unit := let l := ListNil in let l0 := ListCons 2%i32 l in @@ -350,61 +351,61 @@ Definition test_list_functions_fwd : result unit := (** Unit test for [no_nested_borrows::test_list_functions] *) Check (test_list_functions_fwd )%return. -(** [no_nested_borrows::id_mut_pair1] *) +(** [no_nested_borrows::id_mut_pair1]: forward function *) Definition id_mut_pair1_fwd (T1 T2 : Type) (x : T1) (y : T2) : result (T1 * T2) := Return (x, y) . -(** [no_nested_borrows::id_mut_pair1] *) +(** [no_nested_borrows::id_mut_pair1]: backward function 0 *) Definition id_mut_pair1_back (T1 T2 : Type) (x : T1) (y : T2) (ret : (T1 * T2)) : result (T1 * T2) := let (t, t0) := ret in Return (t, t0) . -(** [no_nested_borrows::id_mut_pair2] *) +(** [no_nested_borrows::id_mut_pair2]: forward function *) Definition id_mut_pair2_fwd (T1 T2 : Type) (p : (T1 * T2)) : result (T1 * T2) := let (t, t0) := p in Return (t, t0) . -(** [no_nested_borrows::id_mut_pair2] *) +(** [no_nested_borrows::id_mut_pair2]: backward function 0 *) Definition id_mut_pair2_back (T1 T2 : Type) (p : (T1 * T2)) (ret : (T1 * T2)) : result (T1 * T2) := let (t, t0) := ret in Return (t, t0) . -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: forward function *) Definition id_mut_pair3_fwd (T1 T2 : Type) (x : T1) (y : T2) : result (T1 * T2) := Return (x, y) . -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: backward function 0 *) Definition id_mut_pair3_back'a (T1 T2 : Type) (x : T1) (y : T2) (ret : T1) : result T1 := Return ret . -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: backward function 1 *) Definition id_mut_pair3_back'b (T1 T2 : Type) (x : T1) (y : T2) (ret : T2) : result T2 := Return ret . -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: forward function *) Definition id_mut_pair4_fwd (T1 T2 : Type) (p : (T1 * T2)) : result (T1 * T2) := let (t, t0) := p in Return (t, t0) . -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: backward function 0 *) Definition id_mut_pair4_back'a (T1 T2 : Type) (p : (T1 * T2)) (ret : T1) : result T1 := Return ret . -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: backward function 1 *) Definition id_mut_pair4_back'b (T1 T2 : Type) (p : (T1 * T2)) (ret : T2) : result T2 := Return ret @@ -420,17 +421,17 @@ mkStruct_with_tuple_t { Arguments mkStruct_with_tuple_t {T1} {T2} _. Arguments Struct_with_tuple_p {T1} {T2}. -(** [no_nested_borrows::new_tuple1] *) +(** [no_nested_borrows::new_tuple1]: forward function *) Definition new_tuple1_fwd : result (Struct_with_tuple_t u32 u32) := Return {| Struct_with_tuple_p := (1%u32, 2%u32) |} . -(** [no_nested_borrows::new_tuple2] *) +(** [no_nested_borrows::new_tuple2]: forward function *) Definition new_tuple2_fwd : result (Struct_with_tuple_t i16 i16) := Return {| Struct_with_tuple_p := (1%i16, 2%i16) |} . -(** [no_nested_borrows::new_tuple3] *) +(** [no_nested_borrows::new_tuple3]: forward function *) Definition new_tuple3_fwd : result (Struct_with_tuple_t u64 i64) := Return {| Struct_with_tuple_p := (1%u64, 2%i64) |} . @@ -445,12 +446,12 @@ mkStruct_with_pair_t { Arguments mkStruct_with_pair_t {T1} {T2} _. Arguments Struct_with_pair_p {T1} {T2}. -(** [no_nested_borrows::new_pair1] *) +(** [no_nested_borrows::new_pair1]: forward function *) Definition new_pair1_fwd : result (Struct_with_pair_t u32 u32) := Return {| Struct_with_pair_p := {| Pair_x := 1%u32; Pair_y := 2%u32 |} |} . -(** [no_nested_borrows::test_constants] *) +(** [no_nested_borrows::test_constants]: forward function *) Definition test_constants_fwd : result unit := swt <- new_tuple1_fwd; let (i, _) := swt.(Struct_with_tuple_p) in @@ -476,34 +477,35 @@ Definition test_constants_fwd : result unit := (** Unit test for [no_nested_borrows::test_constants] *) Check (test_constants_fwd )%return. -(** [no_nested_borrows::test_weird_borrows1] *) +(** [no_nested_borrows::test_weird_borrows1]: forward function *) Definition test_weird_borrows1_fwd : result unit := Return tt. (** Unit test for [no_nested_borrows::test_weird_borrows1] *) Check (test_weird_borrows1_fwd )%return. -(** [no_nested_borrows::test_mem_replace] *) +(** [no_nested_borrows::test_mem_replace]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition test_mem_replace_fwd_back (px : u32) : result u32 := let y := mem_replace_fwd u32 px 1%u32 in if negb (y s= 0%u32) then Fail_ Failure else Return 2%u32 . -(** [no_nested_borrows::test_shared_borrow_bool1] *) +(** [no_nested_borrows::test_shared_borrow_bool1]: forward function *) Definition test_shared_borrow_bool1_fwd (b : bool) : result u32 := if b then Return 0%u32 else Return 1%u32 . -(** [no_nested_borrows::test_shared_borrow_bool2] *) +(** [no_nested_borrows::test_shared_borrow_bool2]: forward function *) Definition test_shared_borrow_bool2_fwd : result u32 := Return 0%u32. -(** [no_nested_borrows::test_shared_borrow_enum1] *) +(** [no_nested_borrows::test_shared_borrow_enum1]: forward function *) Definition test_shared_borrow_enum1_fwd (l : List_t u32) : result u32 := match l with | ListCons i l0 => Return 1%u32 | ListNil => Return 0%u32 end . -(** [no_nested_borrows::test_shared_borrow_enum2] *) +(** [no_nested_borrows::test_shared_borrow_enum2]: forward function *) Definition test_shared_borrow_enum2_fwd : result u32 := Return 0%u32. diff --git a/tests/coq/misc/Paper.v b/tests/coq/misc/Paper.v index 513bc749..0f854f31 100644 --- a/tests/coq/misc/Paper.v +++ b/tests/coq/misc/Paper.v @@ -6,11 +6,12 @@ Require Import Coq.ZArith.ZArith. Local Open Scope Primitives_scope. Module Paper. -(** [paper::ref_incr] *) +(** [paper::ref_incr]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) Definition ref_incr_fwd_back (x : i32) : result i32 := i32_add x 1%i32. -(** [paper::test_incr] *) +(** [paper::test_incr]: forward function *) Definition test_incr_fwd : result unit := x <- ref_incr_fwd_back 0%i32; if negb (x s= 1%i32) then Fail_ Failure else Return tt @@ -19,18 +20,18 @@ Definition test_incr_fwd : result unit := (** Unit test for [paper::test_incr] *) Check (test_incr_fwd )%return. -(** [paper::choose] *) +(** [paper::choose]: forward function *) Definition choose_fwd (T : Type) (b : bool) (x : T) (y : T) : result T := if b then Return x else Return y . -(** [paper::choose] *) +(** [paper::choose]: backward function 0 *) Definition choose_back (T : Type) (b : bool) (x : T) (y : T) (ret : T) : result (T * T) := if b then Return (ret, y) else Return (x, ret) . -(** [paper::test_choose] *) +(** [paper::test_choose]: forward function *) Definition test_choose_fwd : result unit := z <- choose_fwd i32 true 0%i32 0%i32; z0 <- i32_add z 1%i32; @@ -56,7 +57,7 @@ Inductive List_t (T : Type) := Arguments ListCons {T} _ _. Arguments ListNil {T}. -(** [paper::list_nth_mut] *) +(** [paper::list_nth_mut]: forward function *) Fixpoint list_nth_mut_fwd (T : Type) (l : List_t T) (i : u32) : result T := match l with | ListCons x tl => @@ -67,7 +68,7 @@ Fixpoint list_nth_mut_fwd (T : Type) (l : List_t T) (i : u32) : result T := end . -(** [paper::list_nth_mut] *) +(** [paper::list_nth_mut]: backward function 0 *) Fixpoint list_nth_mut_back (T : Type) (l : List_t T) (i : u32) (ret : T) : result (List_t T) := match l with @@ -82,7 +83,7 @@ Fixpoint list_nth_mut_back end . -(** [paper::sum] *) +(** [paper::sum]: forward function *) Fixpoint sum_fwd (l : List_t i32) : result i32 := match l with | ListCons x tl => i <- sum_fwd tl; i32_add x i @@ -90,7 +91,7 @@ Fixpoint sum_fwd (l : List_t i32) : result i32 := end . -(** [paper::test_nth] *) +(** [paper::test_nth]: forward function *) Definition test_nth_fwd : result unit := let l := ListNil in let l0 := ListCons 3%i32 l in @@ -105,7 +106,7 @@ Definition test_nth_fwd : result unit := (** Unit test for [paper::test_nth] *) Check (test_nth_fwd )%return. -(** [paper::call_choose] *) +(** [paper::call_choose]: forward function *) Definition call_choose_fwd (p : (u32 * u32)) : result u32 := let (px, py) := p in pz <- choose_fwd u32 true px py; diff --git a/tests/coq/misc/PoloniusList.v b/tests/coq/misc/PoloniusList.v index bd6df02e..e94b6dcb 100644 --- a/tests/coq/misc/PoloniusList.v +++ b/tests/coq/misc/PoloniusList.v @@ -15,7 +15,7 @@ Inductive List_t (T : Type) := Arguments ListCons {T} _ _. Arguments ListNil {T}. -(** [polonius_list::get_list_at_x] *) +(** [polonius_list::get_list_at_x]: forward function *) Fixpoint get_list_at_x_fwd (ls : List_t u32) (x : u32) : result (List_t u32) := match ls with | ListCons hd tl => @@ -24,7 +24,7 @@ Fixpoint get_list_at_x_fwd (ls : List_t u32) (x : u32) : result (List_t u32) := end . -(** [polonius_list::get_list_at_x] *) +(** [polonius_list::get_list_at_x]: backward function 0 *) Fixpoint get_list_at_x_back (ls : List_t u32) (x : u32) (ret : List_t u32) : result (List_t u32) := match ls with diff --git a/tests/coq/misc/_CoqProject b/tests/coq/misc/_CoqProject index 87dea3e6..db6c2742 100644 --- a/tests/coq/misc/_CoqProject +++ b/tests/coq/misc/_CoqProject @@ -3,12 +3,12 @@ -arg -w -arg all -Constants.v -External_Types.v -Primitives.v Loops.v +Primitives.v External_Funs.v +Constants.v PoloniusList.v +External_Types.v NoNestedBorrows.v External_Opaque.v Paper.v diff --git a/tests/fstar/betree/BetreeMain.Funs.fst b/tests/fstar/betree/BetreeMain.Funs.fst index 0c868f47..f1bc1191 100644 --- a/tests/fstar/betree/BetreeMain.Funs.fst +++ b/tests/fstar/betree/BetreeMain.Funs.fst @@ -8,14 +8,14 @@ include BetreeMain.Clauses #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [betree_main::betree::load_internal_node] *) +(** [betree_main::betree::load_internal_node]: forward function *) let betree_load_internal_node_fwd (id : u64) (st : state) : result (state & (betree_list_t (u64 & betree_message_t))) = betree_utils_load_internal_node_fwd id st -(** [betree_main::betree::store_internal_node] *) +(** [betree_main::betree::store_internal_node]: forward function *) let betree_store_internal_node_fwd (id : u64) (content : betree_list_t (u64 & betree_message_t)) (st : state) : result (state & unit) @@ -23,12 +23,12 @@ let betree_store_internal_node_fwd let* (st0, _) = betree_utils_store_internal_node_fwd id content st in Return (st0, ()) -(** [betree_main::betree::load_leaf_node] *) +(** [betree_main::betree::load_leaf_node]: forward function *) let betree_load_leaf_node_fwd (id : u64) (st : state) : result (state & (betree_list_t (u64 & u64))) = betree_utils_load_leaf_node_fwd id st -(** [betree_main::betree::store_leaf_node] *) +(** [betree_main::betree::store_leaf_node]: forward function *) let betree_store_leaf_node_fwd (id : u64) (content : betree_list_t (u64 & u64)) (st : state) : result (state & unit) @@ -36,25 +36,25 @@ let betree_store_leaf_node_fwd let* (st0, _) = betree_utils_store_leaf_node_fwd id content st in Return (st0, ()) -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: forward function *) let betree_fresh_node_id_fwd (counter : u64) : result u64 = let* _ = u64_add counter 1 in Return counter -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: backward function 0 *) let betree_fresh_node_id_back (counter : u64) : result u64 = u64_add counter 1 -(** [betree_main::betree::NodeIdCounter::{0}::new] *) +(** [betree_main::betree::NodeIdCounter::{0}::new]: forward function *) let betree_node_id_counter_new_fwd : result betree_node_id_counter_t = Return { betree_node_id_counter_next_node_id = 0 } -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function *) let betree_node_id_counter_fresh_id_fwd (self : betree_node_id_counter_t) : result u64 = let* _ = u64_add self.betree_node_id_counter_next_node_id 1 in Return self.betree_node_id_counter_next_node_id -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 *) let betree_node_id_counter_fresh_id_back (self : betree_node_id_counter_t) : result betree_node_id_counter_t = let* i = u64_add self.betree_node_id_counter_next_node_id 1 in @@ -64,7 +64,7 @@ let betree_node_id_counter_fresh_id_back let core_num_u64_max_body : result u64 = Return 18446744073709551615 let core_num_u64_max_c : u64 = eval_global core_num_u64_max_body -(** [betree_main::betree::upsert_update] *) +(** [betree_main::betree::upsert_update]: forward function *) let betree_upsert_update_fwd (prev : option u64) (st : betree_upsert_fun_state_t) : result u64 = begin match prev with @@ -83,7 +83,7 @@ let betree_upsert_update_fwd end end -(** [betree_main::betree::List::{1}::len] *) +(** [betree_main::betree::List::{1}::len]: forward function *) let rec betree_list_len_fwd (t : Type0) (self : betree_list_t t) : Tot (result u64) (decreases (betree_list_len_decreases t self)) @@ -93,7 +93,7 @@ let rec betree_list_len_fwd | BetreeListNil -> Return 0 end -(** [betree_main::betree::List::{1}::split_at] *) +(** [betree_main::betree::List::{1}::split_at]: forward function *) let rec betree_list_split_at_fwd (t : Type0) (self : betree_list_t t) (n : u64) : Tot (result ((betree_list_t t) & (betree_list_t t))) @@ -112,14 +112,15 @@ let rec betree_list_split_at_fwd | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::push_front] *) +(** [betree_main::betree::List::{1}::push_front]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_list_push_front_fwd_back (t : Type0) (self : betree_list_t t) (x : t) : result (betree_list_t t) = let tl = mem_replace_fwd (betree_list_t t) self BetreeListNil in let l = tl in Return (BetreeListCons x l) -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: forward function *) let betree_list_pop_front_fwd (t : Type0) (self : betree_list_t t) : result t = let ls = mem_replace_fwd (betree_list_t t) self BetreeListNil in begin match ls with @@ -127,7 +128,7 @@ let betree_list_pop_front_fwd (t : Type0) (self : betree_list_t t) : result t = | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: backward function 0 *) let betree_list_pop_front_back (t : Type0) (self : betree_list_t t) : result (betree_list_t t) = let ls = mem_replace_fwd (betree_list_t t) self BetreeListNil in @@ -136,14 +137,14 @@ let betree_list_pop_front_back | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::hd] *) +(** [betree_main::betree::List::{1}::hd]: forward function *) let betree_list_hd_fwd (t : Type0) (self : betree_list_t t) : result t = begin match self with | BetreeListCons hd l -> Return hd | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{2}::head_has_key] *) +(** [betree_main::betree::List::{2}::head_has_key]: forward function *) let betree_list_head_has_key_fwd (t : Type0) (self : betree_list_t (u64 & t)) (key : u64) : result bool = begin match self with @@ -151,7 +152,7 @@ let betree_list_head_has_key_fwd | BetreeListNil -> Return false end -(** [betree_main::betree::List::{2}::partition_at_pivot] *) +(** [betree_main::betree::List::{2}::partition_at_pivot]: forward function *) let rec betree_list_partition_at_pivot_fwd (t : Type0) (self : betree_list_t (u64 & t)) (pivot : u64) : Tot (result ((betree_list_t (u64 & t)) & (betree_list_t (u64 & t)))) @@ -170,7 +171,7 @@ let rec betree_list_partition_at_pivot_fwd | BetreeListNil -> Return (BetreeListNil, BetreeListNil) end -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: forward function *) let betree_leaf_split_fwd (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -202,7 +203,7 @@ let betree_leaf_split_fwd betree_internal_right = n0 }) -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: backward function 2 *) let betree_leaf_split_back (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -221,7 +222,7 @@ let betree_leaf_split_back let* _ = betree_store_leaf_node_fwd id1 content1 st0 in betree_node_id_counter_fresh_id_back node_id_cnt0 -(** [betree_main::betree::Node::{5}::lookup_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_in_bindings]: forward function *) let rec betree_node_lookup_in_bindings_fwd (key : u64) (bindings : betree_list_t (u64 & u64)) : Tot (result (option u64)) @@ -239,7 +240,7 @@ let rec betree_node_lookup_in_bindings_fwd | BetreeListNil -> Return None end -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: forward function *) let rec betree_node_lookup_first_message_for_key_fwd (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -254,7 +255,7 @@ let rec betree_node_lookup_first_message_for_key_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: backward function 0 *) let rec betree_node_lookup_first_message_for_key_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) (ret : betree_list_t (u64 & betree_message_t)) : @@ -273,7 +274,7 @@ let rec betree_node_lookup_first_message_for_key_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: forward function *) let rec betree_node_apply_upserts_fwd (msgs : betree_list_t (u64 & betree_message_t)) (prev : option u64) (key : u64) (st : state) : @@ -300,7 +301,7 @@ let rec betree_node_apply_upserts_fwd BetreeMessageInsert v) in Return (st0, v) -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: backward function 0 *) let rec betree_node_apply_upserts_back (msgs : betree_list_t (u64 & betree_message_t)) (prev : option u64) (key : u64) (st : state) : @@ -325,7 +326,7 @@ let rec betree_node_apply_upserts_back betree_list_push_front_fwd_back (u64 & betree_message_t) msgs (key, BetreeMessageInsert v) -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: forward function *) let rec betree_node_lookup_fwd (self : betree_node_t) (key : u64) (st : state) : Tot (result (state & (option u64))) @@ -388,7 +389,7 @@ let rec betree_node_lookup_fwd Return (st0, opt) end -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: backward function 0 *) and betree_node_lookup_back (self : betree_node_t) (key : u64) (st : state) : Tot (result betree_node_t) @@ -450,7 +451,7 @@ and betree_node_lookup_back Return (BetreeNodeLeaf node) end -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: forward function *) and betree_internal_lookup_in_children_fwd (self : betree_internal_t) (key : u64) (st : state) : Tot (result (state & (option u64))) @@ -460,7 +461,7 @@ and betree_internal_lookup_in_children_fwd then betree_node_lookup_fwd self.betree_internal_left key st else betree_node_lookup_fwd self.betree_internal_right key st -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: backward function 0 *) and betree_internal_lookup_in_children_back (self : betree_internal_t) (key : u64) (st : state) : Tot (result betree_internal_t) @@ -474,7 +475,7 @@ and betree_internal_lookup_in_children_back let* n = betree_node_lookup_back self.betree_internal_right key st in Return { self with betree_internal_right = n } -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: forward function *) let rec betree_node_lookup_mut_in_bindings_fwd (key : u64) (bindings : betree_list_t (u64 & u64)) : Tot (result (betree_list_t (u64 & u64))) @@ -489,7 +490,7 @@ let rec betree_node_lookup_mut_in_bindings_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: backward function 0 *) let rec betree_node_lookup_mut_in_bindings_back (key : u64) (bindings : betree_list_t (u64 & u64)) (ret : betree_list_t (u64 & u64)) : @@ -507,7 +508,8 @@ let rec betree_node_lookup_mut_in_bindings_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_node_apply_to_leaf_fwd_back (bindings : betree_list_t (u64 & u64)) (key : u64) (new_msg : betree_message_t) : @@ -550,7 +552,8 @@ let betree_node_apply_to_leaf_fwd_back betree_node_lookup_mut_in_bindings_back key bindings bindings1 end -(** [betree_main::betree::Node::{5}::apply_messages_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_apply_messages_to_leaf_fwd_back (bindings : betree_list_t (u64 & u64)) (new_msgs : betree_list_t (u64 & betree_message_t)) : @@ -565,7 +568,8 @@ let rec betree_node_apply_messages_to_leaf_fwd_back | BetreeListNil -> Return bindings end -(** [betree_main::betree::Node::{5}::filter_messages_for_key] *) +(** [betree_main::betree::Node::{5}::filter_messages_for_key]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_filter_messages_for_key_fwd_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -584,7 +588,7 @@ let rec betree_node_filter_messages_for_key_fwd_back | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: forward function *) let rec betree_node_lookup_first_message_after_key_fwd (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -599,7 +603,7 @@ let rec betree_node_lookup_first_message_after_key_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: backward function 0 *) let rec betree_node_lookup_first_message_after_key_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) (ret : betree_list_t (u64 & betree_message_t)) : @@ -618,7 +622,8 @@ let rec betree_node_lookup_first_message_after_key_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_node_apply_to_internal_fwd_back (msgs : betree_list_t (u64 & betree_message_t)) (key : u64) (new_msg : betree_message_t) : @@ -678,7 +683,8 @@ let betree_node_apply_to_internal_fwd_back new_msg) in betree_node_lookup_first_message_for_key_back key msgs msgs1 -(** [betree_main::betree::Node::{5}::apply_messages_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_apply_messages_to_internal_fwd_back (msgs : betree_list_t (u64 & betree_message_t)) (new_msgs : betree_list_t (u64 & betree_message_t)) : @@ -693,7 +699,7 @@ let rec betree_node_apply_messages_to_internal_fwd_back | BetreeListNil -> Return msgs end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: forward function *) let rec betree_node_apply_messages_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -740,7 +746,7 @@ let rec betree_node_apply_messages_fwd Return (st1, ()) end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: backward function 0 *) and betree_node_apply_messages_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -788,7 +794,7 @@ and betree_node_apply_messages_back Return (BetreeNodeLeaf { node with betree_leaf_size = len }, node_id_cnt) end -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: forward function *) and betree_internal_flush_fwd (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -830,7 +836,7 @@ and betree_internal_flush_fwd node_id_cnt msgs_right st in Return (st0, msgs_left) -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: backward function 0 *) and betree_internal_flush_back (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -868,7 +874,7 @@ and betree_internal_flush_back node_id_cnt msgs_right st in Return ({ self with betree_internal_right = n }, node_id_cnt0) -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: forward function *) let betree_node_apply_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -884,7 +890,7 @@ let betree_node_apply_fwd (key, new_msg) l) st in Return (st0, ()) -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: backward function 0 *) let betree_node_apply_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -895,7 +901,7 @@ let betree_node_apply_back betree_node_apply_messages_back self params node_id_cnt (BetreeListCons (key, new_msg) l) st -(** [betree_main::betree::BeTree::{6}::new] *) +(** [betree_main::betree::BeTree::{6}::new]: forward function *) let betree_be_tree_new_fwd (min_flush_size : u64) (split_size : u64) (st : state) : result (state & betree_be_tree_t) @@ -916,7 +922,7 @@ let betree_be_tree_new_fwd (BetreeNodeLeaf { betree_leaf_id = id; betree_leaf_size = 0 }) }) -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: forward function *) let betree_be_tree_apply_fwd (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) : result (state & unit) @@ -929,7 +935,7 @@ let betree_be_tree_apply_fwd self.betree_be_tree_node_id_cnt key msg st in Return (st0, ()) -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: backward function 0 *) let betree_be_tree_apply_back (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) : result betree_be_tree_t @@ -940,7 +946,7 @@ let betree_be_tree_apply_back Return { self with betree_be_tree_node_id_cnt = nic; betree_be_tree_root = n } -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: forward function *) let betree_be_tree_insert_fwd (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) : result (state & unit) @@ -950,28 +956,28 @@ let betree_be_tree_insert_fwd let* _ = betree_be_tree_apply_back self key (BetreeMessageInsert value) st in Return (st0, ()) -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: backward function 0 *) let betree_be_tree_insert_back (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) : result betree_be_tree_t = betree_be_tree_apply_back self key (BetreeMessageInsert value) st -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: forward function *) let betree_be_tree_delete_fwd (self : betree_be_tree_t) (key : u64) (st : state) : result (state & unit) = let* (st0, _) = betree_be_tree_apply_fwd self key BetreeMessageDelete st in let* _ = betree_be_tree_apply_back self key BetreeMessageDelete st in Return (st0, ()) -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: backward function 0 *) let betree_be_tree_delete_back (self : betree_be_tree_t) (key : u64) (st : state) : result betree_be_tree_t = betree_be_tree_apply_back self key BetreeMessageDelete st -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: forward function *) let betree_be_tree_upsert_fwd (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) : @@ -982,7 +988,7 @@ let betree_be_tree_upsert_fwd let* _ = betree_be_tree_apply_back self key (BetreeMessageUpsert upd) st in Return (st0, ()) -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: backward function 0 *) let betree_be_tree_upsert_back (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) : @@ -990,14 +996,14 @@ let betree_be_tree_upsert_back = betree_be_tree_apply_back self key (BetreeMessageUpsert upd) st -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: forward function *) let betree_be_tree_lookup_fwd (self : betree_be_tree_t) (key : u64) (st : state) : result (state & (option u64)) = betree_node_lookup_fwd self.betree_be_tree_root key st -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: backward function 0 *) let betree_be_tree_lookup_back (self : betree_be_tree_t) (key : u64) (st : state) : result betree_be_tree_t @@ -1005,7 +1011,7 @@ let betree_be_tree_lookup_back let* n = betree_node_lookup_back self.betree_be_tree_root key st in Return { self with betree_be_tree_root = n } -(** [betree_main::main] *) +(** [betree_main::main]: forward function *) let main_fwd : result unit = Return () diff --git a/tests/fstar/betree/BetreeMain.Opaque.fsti b/tests/fstar/betree/BetreeMain.Opaque.fsti index dfbd73d6..c33cf225 100644 --- a/tests/fstar/betree/BetreeMain.Opaque.fsti +++ b/tests/fstar/betree/BetreeMain.Opaque.fsti @@ -6,25 +6,25 @@ include BetreeMain.Types #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [betree_main::betree_utils::load_internal_node] *) +(** [betree_main::betree_utils::load_internal_node]: forward function *) val betree_utils_load_internal_node_fwd : u64 -> state -> result (state & (betree_list_t (u64 & betree_message_t))) -(** [betree_main::betree_utils::store_internal_node] *) +(** [betree_main::betree_utils::store_internal_node]: forward function *) val betree_utils_store_internal_node_fwd : u64 -> betree_list_t (u64 & betree_message_t) -> state -> result (state & unit) -(** [betree_main::betree_utils::load_leaf_node] *) +(** [betree_main::betree_utils::load_leaf_node]: forward function *) val betree_utils_load_leaf_node_fwd : u64 -> state -> result (state & (betree_list_t (u64 & u64))) -(** [betree_main::betree_utils::store_leaf_node] *) +(** [betree_main::betree_utils::store_leaf_node]: forward function *) val betree_utils_store_leaf_node_fwd : u64 -> betree_list_t (u64 & u64) -> state -> result (state & unit) -(** [core::option::Option::{0}::unwrap] *) +(** [core::option::Option::{0}::unwrap]: forward function *) val core_option_option_unwrap_fwd (t : Type0) : option t -> state -> result (state & t) diff --git a/tests/fstar/betree_back_stateful/BetreeMain.Funs.fst b/tests/fstar/betree_back_stateful/BetreeMain.Funs.fst index c70bef08..12402fb4 100644 --- a/tests/fstar/betree_back_stateful/BetreeMain.Funs.fst +++ b/tests/fstar/betree_back_stateful/BetreeMain.Funs.fst @@ -8,14 +8,14 @@ include BetreeMain.Clauses #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [betree_main::betree::load_internal_node] *) +(** [betree_main::betree::load_internal_node]: forward function *) let betree_load_internal_node_fwd (id : u64) (st : state) : result (state & (betree_list_t (u64 & betree_message_t))) = betree_utils_load_internal_node_fwd id st -(** [betree_main::betree::store_internal_node] *) +(** [betree_main::betree::store_internal_node]: forward function *) let betree_store_internal_node_fwd (id : u64) (content : betree_list_t (u64 & betree_message_t)) (st : state) : result (state & unit) @@ -23,12 +23,12 @@ let betree_store_internal_node_fwd let* (st0, _) = betree_utils_store_internal_node_fwd id content st in Return (st0, ()) -(** [betree_main::betree::load_leaf_node] *) +(** [betree_main::betree::load_leaf_node]: forward function *) let betree_load_leaf_node_fwd (id : u64) (st : state) : result (state & (betree_list_t (u64 & u64))) = betree_utils_load_leaf_node_fwd id st -(** [betree_main::betree::store_leaf_node] *) +(** [betree_main::betree::store_leaf_node]: forward function *) let betree_store_leaf_node_fwd (id : u64) (content : betree_list_t (u64 & u64)) (st : state) : result (state & unit) @@ -36,25 +36,25 @@ let betree_store_leaf_node_fwd let* (st0, _) = betree_utils_store_leaf_node_fwd id content st in Return (st0, ()) -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: forward function *) let betree_fresh_node_id_fwd (counter : u64) : result u64 = let* _ = u64_add counter 1 in Return counter -(** [betree_main::betree::fresh_node_id] *) +(** [betree_main::betree::fresh_node_id]: backward function 0 *) let betree_fresh_node_id_back (counter : u64) : result u64 = u64_add counter 1 -(** [betree_main::betree::NodeIdCounter::{0}::new] *) +(** [betree_main::betree::NodeIdCounter::{0}::new]: forward function *) let betree_node_id_counter_new_fwd : result betree_node_id_counter_t = Return { betree_node_id_counter_next_node_id = 0 } -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function *) let betree_node_id_counter_fresh_id_fwd (self : betree_node_id_counter_t) : result u64 = let* _ = u64_add self.betree_node_id_counter_next_node_id 1 in Return self.betree_node_id_counter_next_node_id -(** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) +(** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 *) let betree_node_id_counter_fresh_id_back (self : betree_node_id_counter_t) : result betree_node_id_counter_t = let* i = u64_add self.betree_node_id_counter_next_node_id 1 in @@ -64,7 +64,7 @@ let betree_node_id_counter_fresh_id_back let core_num_u64_max_body : result u64 = Return 18446744073709551615 let core_num_u64_max_c : u64 = eval_global core_num_u64_max_body -(** [betree_main::betree::upsert_update] *) +(** [betree_main::betree::upsert_update]: forward function *) let betree_upsert_update_fwd (prev : option u64) (st : betree_upsert_fun_state_t) : result u64 = begin match prev with @@ -83,7 +83,7 @@ let betree_upsert_update_fwd end end -(** [betree_main::betree::List::{1}::len] *) +(** [betree_main::betree::List::{1}::len]: forward function *) let rec betree_list_len_fwd (t : Type0) (self : betree_list_t t) : Tot (result u64) (decreases (betree_list_len_decreases t self)) @@ -93,7 +93,7 @@ let rec betree_list_len_fwd | BetreeListNil -> Return 0 end -(** [betree_main::betree::List::{1}::split_at] *) +(** [betree_main::betree::List::{1}::split_at]: forward function *) let rec betree_list_split_at_fwd (t : Type0) (self : betree_list_t t) (n : u64) : Tot (result ((betree_list_t t) & (betree_list_t t))) @@ -112,14 +112,15 @@ let rec betree_list_split_at_fwd | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::push_front] *) +(** [betree_main::betree::List::{1}::push_front]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_list_push_front_fwd_back (t : Type0) (self : betree_list_t t) (x : t) : result (betree_list_t t) = let tl = mem_replace_fwd (betree_list_t t) self BetreeListNil in let l = tl in Return (BetreeListCons x l) -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: forward function *) let betree_list_pop_front_fwd (t : Type0) (self : betree_list_t t) : result t = let ls = mem_replace_fwd (betree_list_t t) self BetreeListNil in begin match ls with @@ -127,7 +128,7 @@ let betree_list_pop_front_fwd (t : Type0) (self : betree_list_t t) : result t = | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::pop_front] *) +(** [betree_main::betree::List::{1}::pop_front]: backward function 0 *) let betree_list_pop_front_back (t : Type0) (self : betree_list_t t) : result (betree_list_t t) = let ls = mem_replace_fwd (betree_list_t t) self BetreeListNil in @@ -136,14 +137,14 @@ let betree_list_pop_front_back | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{1}::hd] *) +(** [betree_main::betree::List::{1}::hd]: forward function *) let betree_list_hd_fwd (t : Type0) (self : betree_list_t t) : result t = begin match self with | BetreeListCons hd l -> Return hd | BetreeListNil -> Fail Failure end -(** [betree_main::betree::List::{2}::head_has_key] *) +(** [betree_main::betree::List::{2}::head_has_key]: forward function *) let betree_list_head_has_key_fwd (t : Type0) (self : betree_list_t (u64 & t)) (key : u64) : result bool = begin match self with @@ -151,7 +152,7 @@ let betree_list_head_has_key_fwd | BetreeListNil -> Return false end -(** [betree_main::betree::List::{2}::partition_at_pivot] *) +(** [betree_main::betree::List::{2}::partition_at_pivot]: forward function *) let rec betree_list_partition_at_pivot_fwd (t : Type0) (self : betree_list_t (u64 & t)) (pivot : u64) : Tot (result ((betree_list_t (u64 & t)) & (betree_list_t (u64 & t)))) @@ -170,7 +171,7 @@ let rec betree_list_partition_at_pivot_fwd | BetreeListNil -> Return (BetreeListNil, BetreeListNil) end -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: forward function *) let betree_leaf_split_fwd (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -202,7 +203,7 @@ let betree_leaf_split_fwd betree_internal_right = n0 }) -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: backward function 0 *) let betree_leaf_split_back0 (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -221,7 +222,7 @@ let betree_leaf_split_back0 let* _ = betree_store_leaf_node_fwd id1 content1 st1 in Return (st0, ()) -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: backward function 1 *) let betree_leaf_split_back1 (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -240,7 +241,7 @@ let betree_leaf_split_back1 let* _ = betree_store_leaf_node_fwd id1 content1 st1 in Return (st0, ()) -(** [betree_main::betree::Leaf::{3}::split] *) +(** [betree_main::betree::Leaf::{3}::split]: backward function 2 *) let betree_leaf_split_back2 (self : betree_leaf_t) (content : betree_list_t (u64 & u64)) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -260,7 +261,7 @@ let betree_leaf_split_back2 let* node_id_cnt1 = betree_node_id_counter_fresh_id_back node_id_cnt0 in Return (st0, node_id_cnt1) -(** [betree_main::betree::Node::{5}::lookup_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_in_bindings]: forward function *) let rec betree_node_lookup_in_bindings_fwd (key : u64) (bindings : betree_list_t (u64 & u64)) : Tot (result (option u64)) @@ -278,7 +279,7 @@ let rec betree_node_lookup_in_bindings_fwd | BetreeListNil -> Return None end -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: forward function *) let rec betree_node_lookup_first_message_for_key_fwd (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -293,7 +294,7 @@ let rec betree_node_lookup_first_message_for_key_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: backward function 0 *) let rec betree_node_lookup_first_message_for_key_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) (ret : betree_list_t (u64 & betree_message_t)) : @@ -312,7 +313,7 @@ let rec betree_node_lookup_first_message_for_key_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: forward function *) let rec betree_node_apply_upserts_fwd (msgs : betree_list_t (u64 & betree_message_t)) (prev : option u64) (key : u64) (st : state) : @@ -339,7 +340,7 @@ let rec betree_node_apply_upserts_fwd BetreeMessageInsert v) in Return (st0, v) -(** [betree_main::betree::Node::{5}::apply_upserts] *) +(** [betree_main::betree::Node::{5}::apply_upserts]: backward function 0 *) let rec betree_node_apply_upserts_back (msgs : betree_list_t (u64 & betree_message_t)) (prev : option u64) (key : u64) (st : state) (st0 : state) : @@ -366,7 +367,7 @@ let rec betree_node_apply_upserts_back BetreeMessageInsert v) in Return (st0, msgs0) -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: forward function *) let rec betree_node_lookup_fwd (self : betree_node_t) (key : u64) (st : state) : Tot (result (state & (option u64))) @@ -430,7 +431,7 @@ let rec betree_node_lookup_fwd Return (st0, opt) end -(** [betree_main::betree::Node::{5}::lookup] *) +(** [betree_main::betree::Node::{5}::lookup]: backward function 0 *) and betree_node_lookup_back (self : betree_node_t) (key : u64) (st : state) (st0 : state) : Tot (result (state & betree_node_t)) @@ -495,7 +496,7 @@ and betree_node_lookup_back Return (st0, BetreeNodeLeaf node) end -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: forward function *) and betree_internal_lookup_in_children_fwd (self : betree_internal_t) (key : u64) (st : state) : Tot (result (state & (option u64))) @@ -505,7 +506,7 @@ and betree_internal_lookup_in_children_fwd then betree_node_lookup_fwd self.betree_internal_left key st else betree_node_lookup_fwd self.betree_internal_right key st -(** [betree_main::betree::Internal::{4}::lookup_in_children] *) +(** [betree_main::betree::Internal::{4}::lookup_in_children]: backward function 0 *) and betree_internal_lookup_in_children_back (self : betree_internal_t) (key : u64) (st : state) (st0 : state) : Tot (result (state & betree_internal_t)) @@ -521,7 +522,7 @@ and betree_internal_lookup_in_children_back betree_node_lookup_back self.betree_internal_right key st st0 in Return (st1, { self with betree_internal_right = n }) -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: forward function *) let rec betree_node_lookup_mut_in_bindings_fwd (key : u64) (bindings : betree_list_t (u64 & u64)) : Tot (result (betree_list_t (u64 & u64))) @@ -536,7 +537,7 @@ let rec betree_node_lookup_mut_in_bindings_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) +(** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: backward function 0 *) let rec betree_node_lookup_mut_in_bindings_back (key : u64) (bindings : betree_list_t (u64 & u64)) (ret : betree_list_t (u64 & u64)) : @@ -554,7 +555,8 @@ let rec betree_node_lookup_mut_in_bindings_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_node_apply_to_leaf_fwd_back (bindings : betree_list_t (u64 & u64)) (key : u64) (new_msg : betree_message_t) : @@ -597,7 +599,8 @@ let betree_node_apply_to_leaf_fwd_back betree_node_lookup_mut_in_bindings_back key bindings bindings1 end -(** [betree_main::betree::Node::{5}::apply_messages_to_leaf] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_apply_messages_to_leaf_fwd_back (bindings : betree_list_t (u64 & u64)) (new_msgs : betree_list_t (u64 & betree_message_t)) : @@ -612,7 +615,8 @@ let rec betree_node_apply_messages_to_leaf_fwd_back | BetreeListNil -> Return bindings end -(** [betree_main::betree::Node::{5}::filter_messages_for_key] *) +(** [betree_main::betree::Node::{5}::filter_messages_for_key]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_filter_messages_for_key_fwd_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -631,7 +635,7 @@ let rec betree_node_filter_messages_for_key_fwd_back | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: forward function *) let rec betree_node_lookup_first_message_after_key_fwd (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) : Tot (result (betree_list_t (u64 & betree_message_t))) @@ -646,7 +650,7 @@ let rec betree_node_lookup_first_message_after_key_fwd | BetreeListNil -> Return BetreeListNil end -(** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) +(** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: backward function 0 *) let rec betree_node_lookup_first_message_after_key_back (key : u64) (msgs : betree_list_t (u64 & betree_message_t)) (ret : betree_list_t (u64 & betree_message_t)) : @@ -665,7 +669,8 @@ let rec betree_node_lookup_first_message_after_key_back | BetreeListNil -> Return ret end -(** [betree_main::betree::Node::{5}::apply_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let betree_node_apply_to_internal_fwd_back (msgs : betree_list_t (u64 & betree_message_t)) (key : u64) (new_msg : betree_message_t) : @@ -725,7 +730,8 @@ let betree_node_apply_to_internal_fwd_back new_msg) in betree_node_lookup_first_message_for_key_back key msgs msgs1 -(** [betree_main::betree::Node::{5}::apply_messages_to_internal] *) +(** [betree_main::betree::Node::{5}::apply_messages_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec betree_node_apply_messages_to_internal_fwd_back (msgs : betree_list_t (u64 & betree_message_t)) (new_msgs : betree_list_t (u64 & betree_message_t)) : @@ -740,7 +746,7 @@ let rec betree_node_apply_messages_to_internal_fwd_back | BetreeListNil -> Return msgs end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: forward function *) let rec betree_node_apply_messages_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -788,7 +794,7 @@ let rec betree_node_apply_messages_fwd Return (st1, ()) end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: backward function 0 *) and betree_node_apply_messages_back'a (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -840,7 +846,7 @@ and betree_node_apply_messages_back'a node_id_cnt)) end -(** [betree_main::betree::Node::{5}::apply_messages] *) +(** [betree_main::betree::Node::{5}::apply_messages]: backward function 1 *) and betree_node_apply_messages_back1 (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -889,7 +895,7 @@ and betree_node_apply_messages_back1 Return (st0, ()) end -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: forward function *) and betree_internal_flush_fwd (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -940,7 +946,7 @@ and betree_internal_flush_fwd node_id_cnt msgs_right st st1 in Return (st2, msgs_left) -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: backward function 0 *) and betree_internal_flush_back'a (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -994,7 +1000,7 @@ and betree_internal_flush_back'a node_id_cnt msgs_right st st2 in Return (st0, ({ self with betree_internal_right = n }, node_id_cnt0)) -(** [betree_main::betree::Internal::{4}::flush] *) +(** [betree_main::betree::Internal::{4}::flush]: backward function 1 *) and betree_internal_flush_back1 (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -1046,7 +1052,7 @@ and betree_internal_flush_back1 node_id_cnt msgs_right st st2 in Return (st0, ()) -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: forward function *) let betree_node_apply_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -1063,7 +1069,7 @@ let betree_node_apply_fwd betree_node_apply_messages_back1 self params node_id_cnt (BetreeListCons (key, new_msg) l) st st1 -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: backward function 0 *) let betree_node_apply_back'a (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -1082,7 +1088,7 @@ let betree_node_apply_back'a (key, new_msg) l) st st2 in Return (st0, (self0, node_id_cnt0)) -(** [betree_main::betree::Node::{5}::apply] *) +(** [betree_main::betree::Node::{5}::apply]: backward function 1 *) let betree_node_apply_back1 (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -1101,7 +1107,7 @@ let betree_node_apply_back1 (key, new_msg) l) st st2 in Return (st0, ()) -(** [betree_main::betree::BeTree::{6}::new] *) +(** [betree_main::betree::BeTree::{6}::new]: forward function *) let betree_be_tree_new_fwd (min_flush_size : u64) (split_size : u64) (st : state) : result (state & betree_be_tree_t) @@ -1122,7 +1128,7 @@ let betree_be_tree_new_fwd (BetreeNodeLeaf { betree_leaf_id = id; betree_leaf_size = 0 }) }) -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: forward function *) let betree_be_tree_apply_fwd (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) : result (state & unit) @@ -1137,7 +1143,7 @@ let betree_be_tree_apply_fwd betree_node_apply_back1 self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st st1 -(** [betree_main::betree::BeTree::{6}::apply] *) +(** [betree_main::betree::BeTree::{6}::apply]: backward function 0 *) let betree_be_tree_apply_back (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) (st0 : state) : @@ -1156,7 +1162,7 @@ let betree_be_tree_apply_back Return (st0, { self with betree_be_tree_node_id_cnt = nic; betree_be_tree_root = n }) -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: forward function *) let betree_be_tree_insert_fwd (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) : result (state & unit) @@ -1167,7 +1173,7 @@ let betree_be_tree_insert_fwd betree_be_tree_apply_back self key (BetreeMessageInsert value) st st0 in Return (st1, ()) -(** [betree_main::betree::BeTree::{6}::insert] *) +(** [betree_main::betree::BeTree::{6}::insert]: backward function 0 *) let betree_be_tree_insert_back (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) (st0 : state) : @@ -1179,7 +1185,7 @@ let betree_be_tree_insert_back betree_be_tree_apply_back self key (BetreeMessageInsert value) st st1 in Return (st0, self0) -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: forward function *) let betree_be_tree_delete_fwd (self : betree_be_tree_t) (key : u64) (st : state) : result (state & unit) = let* (st0, _) = betree_be_tree_apply_fwd self key BetreeMessageDelete st in @@ -1187,7 +1193,7 @@ let betree_be_tree_delete_fwd in Return (st1, ()) -(** [betree_main::betree::BeTree::{6}::delete] *) +(** [betree_main::betree::BeTree::{6}::delete]: backward function 0 *) let betree_be_tree_delete_back (self : betree_be_tree_t) (key : u64) (st : state) (st0 : state) : result (state & betree_be_tree_t) @@ -1197,7 +1203,7 @@ let betree_be_tree_delete_back betree_be_tree_apply_back self key BetreeMessageDelete st st1 in Return (st0, self0) -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: forward function *) let betree_be_tree_upsert_fwd (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) : @@ -1209,7 +1215,7 @@ let betree_be_tree_upsert_fwd betree_be_tree_apply_back self key (BetreeMessageUpsert upd) st st0 in Return (st1, ()) -(** [betree_main::betree::BeTree::{6}::upsert] *) +(** [betree_main::betree::BeTree::{6}::upsert]: backward function 0 *) let betree_be_tree_upsert_back (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) (st0 : state) : @@ -1221,14 +1227,14 @@ let betree_be_tree_upsert_back betree_be_tree_apply_back self key (BetreeMessageUpsert upd) st st1 in Return (st0, self0) -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: forward function *) let betree_be_tree_lookup_fwd (self : betree_be_tree_t) (key : u64) (st : state) : result (state & (option u64)) = betree_node_lookup_fwd self.betree_be_tree_root key st -(** [betree_main::betree::BeTree::{6}::lookup] *) +(** [betree_main::betree::BeTree::{6}::lookup]: backward function 0 *) let betree_be_tree_lookup_back (self : betree_be_tree_t) (key : u64) (st : state) (st0 : state) : result (state & betree_be_tree_t) @@ -1237,7 +1243,7 @@ let betree_be_tree_lookup_back in Return (st1, { self with betree_be_tree_root = n }) -(** [betree_main::main] *) +(** [betree_main::main]: forward function *) let main_fwd : result unit = Return () diff --git a/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti b/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti index dfbd73d6..c33cf225 100644 --- a/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti +++ b/tests/fstar/betree_back_stateful/BetreeMain.Opaque.fsti @@ -6,25 +6,25 @@ include BetreeMain.Types #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [betree_main::betree_utils::load_internal_node] *) +(** [betree_main::betree_utils::load_internal_node]: forward function *) val betree_utils_load_internal_node_fwd : u64 -> state -> result (state & (betree_list_t (u64 & betree_message_t))) -(** [betree_main::betree_utils::store_internal_node] *) +(** [betree_main::betree_utils::store_internal_node]: forward function *) val betree_utils_store_internal_node_fwd : u64 -> betree_list_t (u64 & betree_message_t) -> state -> result (state & unit) -(** [betree_main::betree_utils::load_leaf_node] *) +(** [betree_main::betree_utils::load_leaf_node]: forward function *) val betree_utils_load_leaf_node_fwd : u64 -> state -> result (state & (betree_list_t (u64 & u64))) -(** [betree_main::betree_utils::store_leaf_node] *) +(** [betree_main::betree_utils::store_leaf_node]: forward function *) val betree_utils_store_leaf_node_fwd : u64 -> betree_list_t (u64 & u64) -> state -> result (state & unit) -(** [core::option::Option::{0}::unwrap] *) +(** [core::option::Option::{0}::unwrap]: forward function *) val core_option_option_unwrap_fwd (t : Type0) : option t -> state -> result (state & t) diff --git a/tests/fstar/hashmap/Hashmap.Funs.fst b/tests/fstar/hashmap/Hashmap.Funs.fst index 44ad7463..950f1490 100644 --- a/tests/fstar/hashmap/Hashmap.Funs.fst +++ b/tests/fstar/hashmap/Hashmap.Funs.fst @@ -7,11 +7,11 @@ include Hashmap.Clauses #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [hashmap::hash_key] *) +(** [hashmap::hash_key]: forward function *) let hash_key_fwd (k : usize) : result usize = Return k -(** [hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) let rec hash_map_allocate_slots_loop_fwd (t : Type0) (slots : vec (list_t t)) (n : usize) : Tot (result (vec (list_t t))) @@ -24,12 +24,12 @@ let rec hash_map_allocate_slots_loop_fwd hash_map_allocate_slots_loop_fwd t slots0 n0 else Return slots -(** [hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap::HashMap::{0}::allocate_slots]: forward function *) let hash_map_allocate_slots_fwd (t : Type0) (slots : vec (list_t t)) (n : usize) : result (vec (list_t t)) = hash_map_allocate_slots_loop_fwd t slots n -(** [hashmap::HashMap::{0}::new_with_capacity] *) +(** [hashmap::HashMap::{0}::new_with_capacity]: forward function *) let hash_map_new_with_capacity_fwd (t : Type0) (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : @@ -47,11 +47,12 @@ let hash_map_new_with_capacity_fwd hash_map_slots = slots } -(** [hashmap::HashMap::{0}::new] *) +(** [hashmap::HashMap::{0}::new]: forward function *) let hash_map_new_fwd (t : Type0) : result (hash_map_t t) = hash_map_new_with_capacity_fwd t 32 4 5 -(** [hashmap::HashMap::{0}::clear] *) +(** [hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hash_map_clear_loop_fwd_back (t : Type0) (slots : vec (list_t t)) (i : usize) : Tot (result (vec (list_t t))) @@ -65,17 +66,18 @@ let rec hash_map_clear_loop_fwd_back hash_map_clear_loop_fwd_back t slots0 i1 else Return slots -(** [hashmap::HashMap::{0}::clear] *) +(** [hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_clear_fwd_back (t : Type0) (self : hash_map_t t) : result (hash_map_t t) = let* v = hash_map_clear_loop_fwd_back t self.hash_map_slots 0 in Return { self with hash_map_num_entries = 0; hash_map_slots = v } -(** [hashmap::HashMap::{0}::len] *) +(** [hashmap::HashMap::{0}::len]: forward function *) let hash_map_len_fwd (t : Type0) (self : hash_map_t t) : result usize = Return self.hash_map_num_entries -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) let rec hash_map_insert_in_list_loop_fwd (t : Type0) (key : usize) (value : t) (ls : list_t t) : Tot (result bool) @@ -89,12 +91,12 @@ let rec hash_map_insert_in_list_loop_fwd | ListNil -> Return true end -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: forward function *) let hash_map_insert_in_list_fwd (t : Type0) (key : usize) (value : t) (ls : list_t t) : result bool = hash_map_insert_in_list_loop_fwd t key value ls -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) let rec hash_map_insert_in_list_loop_back (t : Type0) (key : usize) (value : t) (ls : list_t t) : Tot (result (list_t t)) @@ -110,12 +112,13 @@ let rec hash_map_insert_in_list_loop_back | ListNil -> let l = ListNil in Return (ListCons key value l) end -(** [hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) let hash_map_insert_in_list_back (t : Type0) (key : usize) (value : t) (ls : list_t t) : result (list_t t) = hash_map_insert_in_list_loop_back t key value ls -(** [hashmap::HashMap::{0}::insert_no_resize] *) +(** [hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_insert_no_resize_fwd_back (t : Type0) (self : hash_map_t t) (key : usize) (value : t) : result (hash_map_t t) @@ -140,7 +143,8 @@ let hash_map_insert_no_resize_fwd_back let core_num_u32_max_body : result u32 = Return 4294967295 let core_num_u32_max_c : u32 = eval_global core_num_u32_max_body -(** [hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hash_map_move_elements_from_list_loop_fwd_back (t : Type0) (ntable : hash_map_t t) (ls : list_t t) : Tot (result (hash_map_t t)) @@ -153,12 +157,14 @@ let rec hash_map_move_elements_from_list_loop_fwd_back | ListNil -> Return ntable end -(** [hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_move_elements_from_list_fwd_back (t : Type0) (ntable : hash_map_t t) (ls : list_t t) : result (hash_map_t t) = hash_map_move_elements_from_list_loop_fwd_back t ntable ls -(** [hashmap::HashMap::{0}::move_elements] *) +(** [hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hash_map_move_elements_loop_fwd_back (t : Type0) (ntable : hash_map_t t) (slots : vec (list_t t)) (i : usize) : Tot (result ((hash_map_t t) & (vec (list_t t)))) @@ -176,14 +182,16 @@ let rec hash_map_move_elements_loop_fwd_back hash_map_move_elements_loop_fwd_back t ntable0 slots0 i1 else Return (ntable, slots) -(** [hashmap::HashMap::{0}::move_elements] *) +(** [hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_move_elements_fwd_back (t : Type0) (ntable : hash_map_t t) (slots : vec (list_t t)) (i : usize) : result ((hash_map_t t) & (vec (list_t t))) = hash_map_move_elements_loop_fwd_back t ntable slots i -(** [hashmap::HashMap::{0}::try_resize] *) +(** [hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_try_resize_fwd_back (t : Type0) (self : hash_map_t t) : result (hash_map_t t) = let* max_usize = scalar_cast U32 Usize core_num_u32_max_c in @@ -206,7 +214,8 @@ let hash_map_try_resize_fwd_back } else Return { self with hash_map_max_load_factor = (i, i0) } -(** [hashmap::HashMap::{0}::insert] *) +(** [hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hash_map_insert_fwd_back (t : Type0) (self : hash_map_t t) (key : usize) (value : t) : result (hash_map_t t) @@ -217,7 +226,7 @@ let hash_map_insert_fwd_back then hash_map_try_resize_fwd_back t self0 else Return self0 -(** [hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) let rec hash_map_contains_key_in_list_loop_fwd (t : Type0) (key : usize) (ls : list_t t) : Tot (result bool) @@ -231,12 +240,12 @@ let rec hash_map_contains_key_in_list_loop_fwd | ListNil -> Return false end -(** [hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap::HashMap::{0}::contains_key_in_list]: forward function *) let hash_map_contains_key_in_list_fwd (t : Type0) (key : usize) (ls : list_t t) : result bool = hash_map_contains_key_in_list_loop_fwd t key ls -(** [hashmap::HashMap::{0}::contains_key] *) +(** [hashmap::HashMap::{0}::contains_key]: forward function *) let hash_map_contains_key_fwd (t : Type0) (self : hash_map_t t) (key : usize) : result bool = let* hash = hash_key_fwd key in @@ -245,7 +254,7 @@ let hash_map_contains_key_fwd let* l = vec_index_fwd (list_t t) self.hash_map_slots hash_mod in hash_map_contains_key_in_list_fwd t key l -(** [hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) let rec hash_map_get_in_list_loop_fwd (t : Type0) (key : usize) (ls : list_t t) : Tot (result t) (decreases (hash_map_get_in_list_loop_decreases t key ls)) @@ -258,12 +267,12 @@ let rec hash_map_get_in_list_loop_fwd | ListNil -> Fail Failure end -(** [hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap::HashMap::{0}::get_in_list]: forward function *) let hash_map_get_in_list_fwd (t : Type0) (key : usize) (ls : list_t t) : result t = hash_map_get_in_list_loop_fwd t key ls -(** [hashmap::HashMap::{0}::get] *) +(** [hashmap::HashMap::{0}::get]: forward function *) let hash_map_get_fwd (t : Type0) (self : hash_map_t t) (key : usize) : result t = let* hash = hash_key_fwd key in @@ -272,7 +281,7 @@ let hash_map_get_fwd let* l = vec_index_fwd (list_t t) self.hash_map_slots hash_mod in hash_map_get_in_list_fwd t key l -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) let rec hash_map_get_mut_in_list_loop_fwd (t : Type0) (ls : list_t t) (key : usize) : Tot (result t) (decreases (hash_map_get_mut_in_list_loop_decreases t ls key)) @@ -285,12 +294,12 @@ let rec hash_map_get_mut_in_list_loop_fwd | ListNil -> Fail Failure end -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: forward function *) let hash_map_get_mut_in_list_fwd (t : Type0) (ls : list_t t) (key : usize) : result t = hash_map_get_mut_in_list_loop_fwd t ls key -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) let rec hash_map_get_mut_in_list_loop_back (t : Type0) (ls : list_t t) (key : usize) (ret : t) : Tot (result (list_t t)) @@ -306,12 +315,12 @@ let rec hash_map_get_mut_in_list_loop_back | ListNil -> Fail Failure end -(** [hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) let hash_map_get_mut_in_list_back (t : Type0) (ls : list_t t) (key : usize) (ret : t) : result (list_t t) = hash_map_get_mut_in_list_loop_back t ls key ret -(** [hashmap::HashMap::{0}::get_mut] *) +(** [hashmap::HashMap::{0}::get_mut]: forward function *) let hash_map_get_mut_fwd (t : Type0) (self : hash_map_t t) (key : usize) : result t = let* hash = hash_key_fwd key in @@ -320,7 +329,7 @@ let hash_map_get_mut_fwd let* l = vec_index_mut_fwd (list_t t) self.hash_map_slots hash_mod in hash_map_get_mut_in_list_fwd t l key -(** [hashmap::HashMap::{0}::get_mut] *) +(** [hashmap::HashMap::{0}::get_mut]: backward function 0 *) let hash_map_get_mut_back (t : Type0) (self : hash_map_t t) (key : usize) (ret : t) : result (hash_map_t t) @@ -333,7 +342,7 @@ let hash_map_get_mut_back let* v = vec_index_mut_back (list_t t) self.hash_map_slots hash_mod l0 in Return { self with hash_map_slots = v } -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) let rec hash_map_remove_from_list_loop_fwd (t : Type0) (key : usize) (ls : list_t t) : Tot (result (option t)) @@ -352,12 +361,12 @@ let rec hash_map_remove_from_list_loop_fwd | ListNil -> Return None end -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: forward function *) let hash_map_remove_from_list_fwd (t : Type0) (key : usize) (ls : list_t t) : result (option t) = hash_map_remove_from_list_loop_fwd t key ls -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) let rec hash_map_remove_from_list_loop_back (t : Type0) (key : usize) (ls : list_t t) : Tot (result (list_t t)) @@ -378,12 +387,12 @@ let rec hash_map_remove_from_list_loop_back | ListNil -> Return ListNil end -(** [hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) let hash_map_remove_from_list_back (t : Type0) (key : usize) (ls : list_t t) : result (list_t t) = hash_map_remove_from_list_loop_back t key ls -(** [hashmap::HashMap::{0}::remove] *) +(** [hashmap::HashMap::{0}::remove]: forward function *) let hash_map_remove_fwd (t : Type0) (self : hash_map_t t) (key : usize) : result (option t) = let* hash = hash_key_fwd key in @@ -397,7 +406,7 @@ let hash_map_remove_fwd let* _ = usize_sub self.hash_map_num_entries 1 in Return (Some x0) end -(** [hashmap::HashMap::{0}::remove] *) +(** [hashmap::HashMap::{0}::remove]: backward function 0 *) let hash_map_remove_back (t : Type0) (self : hash_map_t t) (key : usize) : result (hash_map_t t) = let* hash = hash_key_fwd key in @@ -417,7 +426,7 @@ let hash_map_remove_back Return { self with hash_map_num_entries = i0; hash_map_slots = v } end -(** [hashmap::test1] *) +(** [hashmap::test1]: forward function *) let test1_fwd : result unit = let* hm = hash_map_new_fwd u64 in let* hm0 = hash_map_insert_fwd_back u64 hm 0 42 in diff --git a/tests/fstar/hashmap_on_disk/HashmapMain.Funs.fst b/tests/fstar/hashmap_on_disk/HashmapMain.Funs.fst index e8cd54c1..f6d9c8cf 100644 --- a/tests/fstar/hashmap_on_disk/HashmapMain.Funs.fst +++ b/tests/fstar/hashmap_on_disk/HashmapMain.Funs.fst @@ -8,11 +8,11 @@ include HashmapMain.Clauses #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [hashmap_main::hashmap::hash_key] *) +(** [hashmap_main::hashmap::hash_key]: forward function *) let hashmap_hash_key_fwd (k : usize) : result usize = Return k -(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) let rec hashmap_hash_map_allocate_slots_loop_fwd (t : Type0) (slots : vec (hashmap_list_t t)) (n : usize) : Tot (result (vec (hashmap_list_t t))) @@ -25,14 +25,14 @@ let rec hashmap_hash_map_allocate_slots_loop_fwd hashmap_hash_map_allocate_slots_loop_fwd t slots0 n0 else Return slots -(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) +(** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: forward function *) let hashmap_hash_map_allocate_slots_fwd (t : Type0) (slots : vec (hashmap_list_t t)) (n : usize) : result (vec (hashmap_list_t t)) = hashmap_hash_map_allocate_slots_loop_fwd t slots n -(** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] *) +(** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity]: forward function *) let hashmap_hash_map_new_with_capacity_fwd (t : Type0) (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : @@ -50,11 +50,12 @@ let hashmap_hash_map_new_with_capacity_fwd hashmap_hash_map_slots = slots } -(** [hashmap_main::hashmap::HashMap::{0}::new] *) +(** [hashmap_main::hashmap::HashMap::{0}::new]: forward function *) let hashmap_hash_map_new_fwd (t : Type0) : result (hashmap_hash_map_t t) = hashmap_hash_map_new_with_capacity_fwd t 32 4 5 -(** [hashmap_main::hashmap::HashMap::{0}::clear] *) +(** [hashmap_main::hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hashmap_hash_map_clear_loop_fwd_back (t : Type0) (slots : vec (hashmap_list_t t)) (i : usize) : Tot (result (vec (hashmap_list_t t))) @@ -69,7 +70,8 @@ let rec hashmap_hash_map_clear_loop_fwd_back hashmap_hash_map_clear_loop_fwd_back t slots0 i1 else Return slots -(** [hashmap_main::hashmap::HashMap::{0}::clear] *) +(** [hashmap_main::hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_clear_fwd_back (t : Type0) (self : hashmap_hash_map_t t) : result (hashmap_hash_map_t t) = let* v = hashmap_hash_map_clear_loop_fwd_back t self.hashmap_hash_map_slots 0 @@ -77,12 +79,12 @@ let hashmap_hash_map_clear_fwd_back Return { self with hashmap_hash_map_num_entries = 0; hashmap_hash_map_slots = v } -(** [hashmap_main::hashmap::HashMap::{0}::len] *) +(** [hashmap_main::hashmap::HashMap::{0}::len]: forward function *) let hashmap_hash_map_len_fwd (t : Type0) (self : hashmap_hash_map_t t) : result usize = Return self.hashmap_hash_map_num_entries -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) let rec hashmap_hash_map_insert_in_list_loop_fwd (t : Type0) (key : usize) (value : t) (ls : hashmap_list_t t) : Tot (result bool) @@ -96,12 +98,12 @@ let rec hashmap_hash_map_insert_in_list_loop_fwd | HashmapListNil -> Return true end -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: forward function *) let hashmap_hash_map_insert_in_list_fwd (t : Type0) (key : usize) (value : t) (ls : hashmap_list_t t) : result bool = hashmap_hash_map_insert_in_list_loop_fwd t key value ls -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) let rec hashmap_hash_map_insert_in_list_loop_back (t : Type0) (key : usize) (value : t) (ls : hashmap_list_t t) : Tot (result (hashmap_list_t t)) @@ -118,14 +120,15 @@ let rec hashmap_hash_map_insert_in_list_loop_back let l = HashmapListNil in Return (HashmapListCons key value l) end -(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) let hashmap_hash_map_insert_in_list_back (t : Type0) (key : usize) (value : t) (ls : hashmap_list_t t) : result (hashmap_list_t t) = hashmap_hash_map_insert_in_list_loop_back t key value ls -(** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_insert_no_resize_fwd_back (t : Type0) (self : hashmap_hash_map_t t) (key : usize) (value : t) : result (hashmap_hash_map_t t) @@ -158,7 +161,8 @@ let hashmap_hash_map_insert_no_resize_fwd_back let core_num_u32_max_body : result u32 = Return 4294967295 let core_num_u32_max_c : u32 = eval_global core_num_u32_max_body -(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hashmap_hash_map_move_elements_from_list_loop_fwd_back (t : Type0) (ntable : hashmap_hash_map_t t) (ls : hashmap_list_t t) : Tot (result (hashmap_hash_map_t t)) @@ -172,14 +176,16 @@ let rec hashmap_hash_map_move_elements_from_list_loop_fwd_back | HashmapListNil -> Return ntable end -(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_move_elements_from_list_fwd_back (t : Type0) (ntable : hashmap_hash_map_t t) (ls : hashmap_list_t t) : result (hashmap_hash_map_t t) = hashmap_hash_map_move_elements_from_list_loop_fwd_back t ntable ls -(** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec hashmap_hash_map_move_elements_loop_fwd_back (t : Type0) (ntable : hashmap_hash_map_t t) (slots : vec (hashmap_list_t t)) (i : usize) : @@ -199,7 +205,8 @@ let rec hashmap_hash_map_move_elements_loop_fwd_back hashmap_hash_map_move_elements_loop_fwd_back t ntable0 slots0 i1 else Return (ntable, slots) -(** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) +(** [hashmap_main::hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_move_elements_fwd_back (t : Type0) (ntable : hashmap_hash_map_t t) (slots : vec (hashmap_list_t t)) (i : usize) : @@ -207,7 +214,8 @@ let hashmap_hash_map_move_elements_fwd_back = hashmap_hash_map_move_elements_loop_fwd_back t ntable slots i -(** [hashmap_main::hashmap::HashMap::{0}::try_resize] *) +(** [hashmap_main::hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_try_resize_fwd_back (t : Type0) (self : hashmap_hash_map_t t) : result (hashmap_hash_map_t t) = let* max_usize = scalar_cast U32 Usize core_num_u32_max_c in @@ -231,7 +239,8 @@ let hashmap_hash_map_try_resize_fwd_back } else Return { self with hashmap_hash_map_max_load_factor = (i, i0) } -(** [hashmap_main::hashmap::HashMap::{0}::insert] *) +(** [hashmap_main::hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let hashmap_hash_map_insert_fwd_back (t : Type0) (self : hashmap_hash_map_t t) (key : usize) (value : t) : result (hashmap_hash_map_t t) @@ -242,7 +251,7 @@ let hashmap_hash_map_insert_fwd_back then hashmap_hash_map_try_resize_fwd_back t self0 else Return self0 -(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) let rec hashmap_hash_map_contains_key_in_list_loop_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : Tot (result bool) @@ -256,12 +265,12 @@ let rec hashmap_hash_map_contains_key_in_list_loop_fwd | HashmapListNil -> Return false end -(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: forward function *) let hashmap_hash_map_contains_key_in_list_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : result bool = hashmap_hash_map_contains_key_in_list_loop_fwd t key ls -(** [hashmap_main::hashmap::HashMap::{0}::contains_key] *) +(** [hashmap_main::hashmap::HashMap::{0}::contains_key]: forward function *) let hashmap_hash_map_contains_key_fwd (t : Type0) (self : hashmap_hash_map_t t) (key : usize) : result bool = let* hash = hashmap_hash_key_fwd key in @@ -271,7 +280,7 @@ let hashmap_hash_map_contains_key_fwd vec_index_fwd (hashmap_list_t t) self.hashmap_hash_map_slots hash_mod in hashmap_hash_map_contains_key_in_list_fwd t key l -(** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) let rec hashmap_hash_map_get_in_list_loop_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : Tot (result t) @@ -285,12 +294,12 @@ let rec hashmap_hash_map_get_in_list_loop_fwd | HashmapListNil -> Fail Failure end -(** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: forward function *) let hashmap_hash_map_get_in_list_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : result t = hashmap_hash_map_get_in_list_loop_fwd t key ls -(** [hashmap_main::hashmap::HashMap::{0}::get] *) +(** [hashmap_main::hashmap::HashMap::{0}::get]: forward function *) let hashmap_hash_map_get_fwd (t : Type0) (self : hashmap_hash_map_t t) (key : usize) : result t = let* hash = hashmap_hash_key_fwd key in @@ -300,7 +309,7 @@ let hashmap_hash_map_get_fwd vec_index_fwd (hashmap_list_t t) self.hashmap_hash_map_slots hash_mod in hashmap_hash_map_get_in_list_fwd t key l -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) let rec hashmap_hash_map_get_mut_in_list_loop_fwd (t : Type0) (ls : hashmap_list_t t) (key : usize) : Tot (result t) @@ -314,12 +323,12 @@ let rec hashmap_hash_map_get_mut_in_list_loop_fwd | HashmapListNil -> Fail Failure end -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: forward function *) let hashmap_hash_map_get_mut_in_list_fwd (t : Type0) (ls : hashmap_list_t t) (key : usize) : result t = hashmap_hash_map_get_mut_in_list_loop_fwd t ls key -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) let rec hashmap_hash_map_get_mut_in_list_loop_back (t : Type0) (ls : hashmap_list_t t) (key : usize) (ret : t) : Tot (result (hashmap_list_t t)) @@ -335,14 +344,14 @@ let rec hashmap_hash_map_get_mut_in_list_loop_back | HashmapListNil -> Fail Failure end -(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) let hashmap_hash_map_get_mut_in_list_back (t : Type0) (ls : hashmap_list_t t) (key : usize) (ret : t) : result (hashmap_list_t t) = hashmap_hash_map_get_mut_in_list_loop_back t ls key ret -(** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut]: forward function *) let hashmap_hash_map_get_mut_fwd (t : Type0) (self : hashmap_hash_map_t t) (key : usize) : result t = let* hash = hashmap_hash_key_fwd key in @@ -353,7 +362,7 @@ let hashmap_hash_map_get_mut_fwd in hashmap_hash_map_get_mut_in_list_fwd t l key -(** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) +(** [hashmap_main::hashmap::HashMap::{0}::get_mut]: backward function 0 *) let hashmap_hash_map_get_mut_back (t : Type0) (self : hashmap_hash_map_t t) (key : usize) (ret : t) : result (hashmap_hash_map_t t) @@ -370,7 +379,7 @@ let hashmap_hash_map_get_mut_back l0 in Return { self with hashmap_hash_map_slots = v } -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) let rec hashmap_hash_map_remove_from_list_loop_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : Tot (result (option t)) @@ -391,12 +400,12 @@ let rec hashmap_hash_map_remove_from_list_loop_fwd | HashmapListNil -> Return None end -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: forward function *) let hashmap_hash_map_remove_from_list_fwd (t : Type0) (key : usize) (ls : hashmap_list_t t) : result (option t) = hashmap_hash_map_remove_from_list_loop_fwd t key ls -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) let rec hashmap_hash_map_remove_from_list_loop_back (t : Type0) (key : usize) (ls : hashmap_list_t t) : Tot (result (hashmap_list_t t)) @@ -419,14 +428,14 @@ let rec hashmap_hash_map_remove_from_list_loop_back | HashmapListNil -> Return HashmapListNil end -(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) let hashmap_hash_map_remove_from_list_back (t : Type0) (key : usize) (ls : hashmap_list_t t) : result (hashmap_list_t t) = hashmap_hash_map_remove_from_list_loop_back t key ls -(** [hashmap_main::hashmap::HashMap::{0}::remove] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove]: forward function *) let hashmap_hash_map_remove_fwd (t : Type0) (self : hashmap_hash_map_t t) (key : usize) : result (option t) = let* hash = hashmap_hash_key_fwd key in @@ -442,7 +451,7 @@ let hashmap_hash_map_remove_fwd let* _ = usize_sub self.hashmap_hash_map_num_entries 1 in Return (Some x0) end -(** [hashmap_main::hashmap::HashMap::{0}::remove] *) +(** [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 *) let hashmap_hash_map_remove_back (t : Type0) (self : hashmap_hash_map_t t) (key : usize) : result (hashmap_hash_map_t t) @@ -472,7 +481,7 @@ let hashmap_hash_map_remove_back } end -(** [hashmap_main::hashmap::test1] *) +(** [hashmap_main::hashmap::test1]: forward function *) let hashmap_test1_fwd : result unit = let* hm = hashmap_hash_map_new_fwd u64 in let* hm0 = hashmap_hash_map_insert_fwd_back u64 hm 0 42 in @@ -511,7 +520,7 @@ let hashmap_test1_fwd : result unit = (** Unit test for [hashmap_main::hashmap::test1] *) let _ = assert_norm (hashmap_test1_fwd = Return ()) -(** [hashmap_main::insert_on_disk] *) +(** [hashmap_main::insert_on_disk]: forward function *) let insert_on_disk_fwd (key : usize) (value : u64) (st : state) : result (state & unit) = let* (st0, hm) = hashmap_utils_deserialize_fwd st in @@ -519,7 +528,7 @@ let insert_on_disk_fwd let* (st1, _) = hashmap_utils_serialize_fwd hm0 st0 in Return (st1, ()) -(** [hashmap_main::main] *) +(** [hashmap_main::main]: forward function *) let main_fwd : result unit = Return () diff --git a/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti b/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti index 6e6a0e2b..78a6c3ba 100644 --- a/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti +++ b/tests/fstar/hashmap_on_disk/HashmapMain.Opaque.fsti @@ -6,11 +6,11 @@ include HashmapMain.Types #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [hashmap_main::hashmap_utils::deserialize] *) +(** [hashmap_main::hashmap_utils::deserialize]: forward function *) val hashmap_utils_deserialize_fwd : state -> result (state & (hashmap_hash_map_t u64)) -(** [hashmap_main::hashmap_utils::serialize] *) +(** [hashmap_main::hashmap_utils::serialize]: forward function *) val hashmap_utils_serialize_fwd : hashmap_hash_map_t u64 -> state -> result (state & unit) diff --git a/tests/fstar/misc/Constants.fst b/tests/fstar/misc/Constants.fst index bf2f0b1b..aae997fa 100644 --- a/tests/fstar/misc/Constants.fst +++ b/tests/fstar/misc/Constants.fst @@ -21,7 +21,7 @@ let x1_c : u32 = eval_global x1_body let x2_body : result u32 = Return 3 let x2_c : u32 = eval_global x2_body -(** [constants::incr] *) +(** [constants::incr]: forward function *) let incr_fwd (n : u32) : result u32 = u32_add n 1 @@ -29,14 +29,14 @@ let incr_fwd (n : u32) : result u32 = let x3_body : result u32 = incr_fwd 32 let x3_c : u32 = eval_global x3_body -(** [constants::mk_pair0] *) +(** [constants::mk_pair0]: forward function *) let mk_pair0_fwd (x : u32) (y : u32) : result (u32 & u32) = Return (x, y) (** [constants::Pair] *) type pair_t (t1 t2 : Type0) = { pair_x : t1; pair_y : t2; } -(** [constants::mk_pair1] *) +(** [constants::mk_pair1]: forward function *) let mk_pair1_fwd (x : u32) (y : u32) : result (pair_t u32 u32) = Return { pair_x = x; pair_y = y } @@ -59,7 +59,7 @@ let p3_c : pair_t u32 u32 = eval_global p3_body (** [constants::Wrap] *) type wrap_t (t : Type0) = { wrap_val : t; } -(** [constants::Wrap::{0}::new] *) +(** [constants::Wrap::{0}::new]: forward function *) let wrap_new_fwd (t : Type0) (val0 : t) : result (wrap_t t) = Return { wrap_val = val0 } @@ -67,7 +67,7 @@ let wrap_new_fwd (t : Type0) (val0 : t) : result (wrap_t t) = let y_body : result (wrap_t i32) = wrap_new_fwd i32 2 let y_c : wrap_t i32 = eval_global y_body -(** [constants::unwrap_y] *) +(** [constants::unwrap_y]: forward function *) let unwrap_y_fwd : result i32 = Return y_c.wrap_val @@ -79,11 +79,11 @@ let yval_c : i32 = eval_global yval_body let get_z1_z1_body : result i32 = Return 3 let get_z1_z1_c : i32 = eval_global get_z1_z1_body -(** [constants::get_z1] *) +(** [constants::get_z1]: forward function *) let get_z1_fwd : result i32 = Return get_z1_z1_c -(** [constants::add] *) +(** [constants::add]: forward function *) let add_fwd (a : i32) (b : i32) : result i32 = i32_add a b @@ -99,7 +99,7 @@ let q2_c : i32 = eval_global q2_body let q3_body : result i32 = add_fwd q2_c 3 let q3_c : i32 = eval_global q3_body -(** [constants::get_z2] *) +(** [constants::get_z2]: forward function *) let get_z2_fwd : result i32 = let* i = get_z1_fwd in let* i0 = add_fwd i q3_c in add_fwd q1_c i0 diff --git a/tests/fstar/misc/External.Funs.fst b/tests/fstar/misc/External.Funs.fst index f70a9fc6..f118a2cf 100644 --- a/tests/fstar/misc/External.Funs.fst +++ b/tests/fstar/misc/External.Funs.fst @@ -7,14 +7,14 @@ include External.Opaque #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [external::swap] *) +(** [external::swap]: forward function *) let swap_fwd (t : Type0) (x : t) (y : t) (st : state) : result (state & unit) = let* (st0, _) = core_mem_swap_fwd t x y st in let* (st1, _) = core_mem_swap_back0 t x y st st0 in let* (st2, _) = core_mem_swap_back1 t x y st st1 in Return (st2, ()) -(** [external::swap] *) +(** [external::swap]: backward function 0 *) let swap_back (t : Type0) (x : t) (y : t) (st : state) (st0 : state) : result (state & (t & t)) @@ -24,20 +24,20 @@ let swap_back let* (_, y0) = core_mem_swap_back1 t x y st st2 in Return (st0, (x0, y0)) -(** [external::test_new_non_zero_u32] *) +(** [external::test_new_non_zero_u32]: forward function *) let test_new_non_zero_u32_fwd (x : u32) (st : state) : result (state & core_num_nonzero_non_zero_u32_t) = let* (st0, opt) = core_num_nonzero_non_zero_u32_new_fwd x st in core_option_option_unwrap_fwd core_num_nonzero_non_zero_u32_t opt st0 -(** [external::test_vec] *) +(** [external::test_vec]: forward function *) let test_vec_fwd : result unit = let v = vec_new u32 in let* _ = vec_push_back u32 v 0 in Return () (** Unit test for [external::test_vec] *) let _ = assert_norm (test_vec_fwd = Return ()) -(** [external::custom_swap] *) +(** [external::custom_swap]: forward function *) let custom_swap_fwd (t : Type0) (x : t) (y : t) (st : state) : result (state & t) = let* (st0, _) = core_mem_swap_fwd t x y st in @@ -45,7 +45,7 @@ let custom_swap_fwd let* (st2, _) = core_mem_swap_back1 t x y st st1 in Return (st2, x0) -(** [external::custom_swap] *) +(** [external::custom_swap]: backward function 0 *) let custom_swap_back (t : Type0) (x : t) (y : t) (st : state) (ret : t) (st0 : state) : result (state & (t & t)) @@ -55,19 +55,19 @@ let custom_swap_back let* (_, y0) = core_mem_swap_back1 t x y st st2 in Return (st0, (ret, y0)) -(** [external::test_custom_swap] *) +(** [external::test_custom_swap]: forward function *) let test_custom_swap_fwd (x : u32) (y : u32) (st : state) : result (state & unit) = let* (st0, _) = custom_swap_fwd u32 x y st in Return (st0, ()) -(** [external::test_custom_swap] *) +(** [external::test_custom_swap]: backward function 0 *) let test_custom_swap_back (x : u32) (y : u32) (st : state) (st0 : state) : result (state & (u32 & u32)) = custom_swap_back u32 x y st 1 st0 -(** [external::test_swap_non_zero] *) +(** [external::test_swap_non_zero]: forward function *) let test_swap_non_zero_fwd (x : u32) (st : state) : result (state & u32) = let* (st0, _) = swap_fwd u32 x 0 st in let* (st1, (x0, _)) = swap_back u32 x 0 st st0 in diff --git a/tests/fstar/misc/External.Opaque.fsti b/tests/fstar/misc/External.Opaque.fsti index 356d5fc4..2e19f767 100644 --- a/tests/fstar/misc/External.Opaque.fsti +++ b/tests/fstar/misc/External.Opaque.fsti @@ -6,22 +6,22 @@ include External.Types #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [core::mem::swap] *) +(** [core::mem::swap]: forward function *) val core_mem_swap_fwd (t : Type0) : t -> t -> state -> result (state & unit) -(** [core::mem::swap] *) +(** [core::mem::swap]: backward function 0 *) val core_mem_swap_back0 (t : Type0) : t -> t -> state -> state -> result (state & t) -(** [core::mem::swap] *) +(** [core::mem::swap]: backward function 1 *) val core_mem_swap_back1 (t : Type0) : t -> t -> state -> state -> result (state & t) -(** [core::num::nonzero::NonZeroU32::{14}::new] *) +(** [core::num::nonzero::NonZeroU32::{14}::new]: forward function *) val core_num_nonzero_non_zero_u32_new_fwd : u32 -> state -> result (state & (option core_num_nonzero_non_zero_u32_t)) -(** [core::option::Option::{0}::unwrap] *) +(** [core::option::Option::{0}::unwrap]: forward function *) val core_option_option_unwrap_fwd (t : Type0) : option t -> state -> result (state & t) diff --git a/tests/fstar/misc/Loops.Funs.fst b/tests/fstar/misc/Loops.Funs.fst index 7fe175e5..9a80f415 100644 --- a/tests/fstar/misc/Loops.Funs.fst +++ b/tests/fstar/misc/Loops.Funs.fst @@ -7,7 +7,7 @@ include Loops.Clauses #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [loops::sum] *) +(** [loops::sum]: loop 0: forward function *) let rec sum_loop_fwd (max : u32) (i : u32) (s : u32) : Tot (result u32) (decreases (sum_loop_decreases max i s)) @@ -16,11 +16,11 @@ let rec sum_loop_fwd then let* s0 = u32_add s i in let* i0 = u32_add i 1 in sum_loop_fwd max i0 s0 else u32_mul s 2 -(** [loops::sum] *) +(** [loops::sum]: forward function *) let sum_fwd (max : u32) : result u32 = sum_loop_fwd max 0 0 -(** [loops::sum_with_mut_borrows] *) +(** [loops::sum_with_mut_borrows]: loop 0: forward function *) let rec sum_with_mut_borrows_loop_fwd (max : u32) (mi : u32) (ms : u32) : Tot (result u32) (decreases (sum_with_mut_borrows_loop_decreases max mi ms)) @@ -32,11 +32,11 @@ let rec sum_with_mut_borrows_loop_fwd sum_with_mut_borrows_loop_fwd max mi0 ms0 else u32_mul ms 2 -(** [loops::sum_with_mut_borrows] *) +(** [loops::sum_with_mut_borrows]: forward function *) let sum_with_mut_borrows_fwd (max : u32) : result u32 = sum_with_mut_borrows_loop_fwd max 0 0 -(** [loops::sum_with_shared_borrows] *) +(** [loops::sum_with_shared_borrows]: loop 0: forward function *) let rec sum_with_shared_borrows_loop_fwd (max : u32) (i : u32) (s : u32) : Tot (result u32) (decreases (sum_with_shared_borrows_loop_decreases max i s)) @@ -48,11 +48,12 @@ let rec sum_with_shared_borrows_loop_fwd sum_with_shared_borrows_loop_fwd max i0 s0 else u32_mul s 2 -(** [loops::sum_with_shared_borrows] *) +(** [loops::sum_with_shared_borrows]: forward function *) let sum_with_shared_borrows_fwd (max : u32) : result u32 = sum_with_shared_borrows_loop_fwd max 0 0 -(** [loops::clear] *) +(** [loops::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let rec clear_loop_fwd_back (v : vec u32) (i : usize) : Tot (result (vec u32)) (decreases (clear_loop_decreases v i)) @@ -65,11 +66,12 @@ let rec clear_loop_fwd_back clear_loop_fwd_back v0 i1 else Return v -(** [loops::clear] *) +(** [loops::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let clear_fwd_back (v : vec u32) : result (vec u32) = clear_loop_fwd_back v 0 -(** [loops::list_mem] *) +(** [loops::list_mem]: loop 0: forward function *) let rec list_mem_loop_fwd (x : u32) (ls : list_t u32) : Tot (result bool) (decreases (list_mem_loop_decreases x ls)) @@ -79,11 +81,11 @@ let rec list_mem_loop_fwd | ListNil -> Return false end -(** [loops::list_mem] *) +(** [loops::list_mem]: forward function *) let list_mem_fwd (x : u32) (ls : list_t u32) : result bool = list_mem_loop_fwd x ls -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: loop 0: forward function *) let rec list_nth_mut_loop_loop_fwd (t : Type0) (ls : list_t t) (i : u32) : Tot (result t) (decreases (list_nth_mut_loop_loop_decreases t ls i)) @@ -96,11 +98,11 @@ let rec list_nth_mut_loop_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: forward function *) let list_nth_mut_loop_fwd (t : Type0) (ls : list_t t) (i : u32) : result t = list_nth_mut_loop_loop_fwd t ls i -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: loop 0: backward function 0 *) let rec list_nth_mut_loop_loop_back (t : Type0) (ls : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) (decreases (list_nth_mut_loop_loop_decreases t ls i)) @@ -116,12 +118,12 @@ let rec list_nth_mut_loop_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop] *) +(** [loops::list_nth_mut_loop]: backward function 0 *) let list_nth_mut_loop_back (t : Type0) (ls : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_mut_loop_loop_back t ls i ret -(** [loops::list_nth_shared_loop] *) +(** [loops::list_nth_shared_loop]: loop 0: forward function *) let rec list_nth_shared_loop_loop_fwd (t : Type0) (ls : list_t t) (i : u32) : Tot (result t) (decreases (list_nth_shared_loop_loop_decreases t ls i)) @@ -134,11 +136,11 @@ let rec list_nth_shared_loop_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_loop] *) +(** [loops::list_nth_shared_loop]: forward function *) let list_nth_shared_loop_fwd (t : Type0) (ls : list_t t) (i : u32) : result t = list_nth_shared_loop_loop_fwd t ls i -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: loop 0: forward function *) let rec get_elem_mut_loop_fwd (x : usize) (ls : list_t usize) : Tot (result usize) (decreases (get_elem_mut_loop_decreases x ls)) @@ -148,12 +150,12 @@ let rec get_elem_mut_loop_fwd | ListNil -> Fail Failure end -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: forward function *) let get_elem_mut_fwd (slots : vec (list_t usize)) (x : usize) : result usize = let* l = vec_index_mut_fwd (list_t usize) slots 0 in get_elem_mut_loop_fwd x l -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: loop 0: backward function 0 *) let rec get_elem_mut_loop_back (x : usize) (ls : list_t usize) (ret : usize) : Tot (result (list_t usize)) (decreases (get_elem_mut_loop_decreases x ls)) @@ -166,7 +168,7 @@ let rec get_elem_mut_loop_back | ListNil -> Fail Failure end -(** [loops::get_elem_mut] *) +(** [loops::get_elem_mut]: backward function 0 *) let get_elem_mut_back (slots : vec (list_t usize)) (x : usize) (ret : usize) : result (vec (list_t usize)) @@ -175,7 +177,7 @@ let get_elem_mut_back let* l0 = get_elem_mut_loop_back x l ret in vec_index_mut_back (list_t usize) slots 0 l0 -(** [loops::get_elem_shared] *) +(** [loops::get_elem_shared]: loop 0: forward function *) let rec get_elem_shared_loop_fwd (x : usize) (ls : list_t usize) : Tot (result usize) (decreases (get_elem_shared_loop_decreases x ls)) @@ -185,25 +187,25 @@ let rec get_elem_shared_loop_fwd | ListNil -> Fail Failure end -(** [loops::get_elem_shared] *) +(** [loops::get_elem_shared]: forward function *) let get_elem_shared_fwd (slots : vec (list_t usize)) (x : usize) : result usize = let* l = vec_index_fwd (list_t usize) slots 0 in get_elem_shared_loop_fwd x l -(** [loops::id_mut] *) +(** [loops::id_mut]: forward function *) let id_mut_fwd (t : Type0) (ls : list_t t) : result (list_t t) = Return ls -(** [loops::id_mut] *) +(** [loops::id_mut]: backward function 0 *) let id_mut_back (t : Type0) (ls : list_t t) (ret : list_t t) : result (list_t t) = Return ret -(** [loops::id_shared] *) +(** [loops::id_shared]: forward function *) let id_shared_fwd (t : Type0) (ls : list_t t) : result (list_t t) = Return ls -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: loop 0: forward function *) let rec list_nth_mut_loop_with_id_loop_fwd (t : Type0) (i : u32) (ls : list_t t) : Tot (result t) (decreases (list_nth_mut_loop_with_id_loop_decreases t i ls)) @@ -216,12 +218,12 @@ let rec list_nth_mut_loop_with_id_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: forward function *) let list_nth_mut_loop_with_id_fwd (t : Type0) (ls : list_t t) (i : u32) : result t = let* ls0 = id_mut_fwd t ls in list_nth_mut_loop_with_id_loop_fwd t i ls0 -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: loop 0: backward function 0 *) let rec list_nth_mut_loop_with_id_loop_back (t : Type0) (i : u32) (ls : list_t t) (ret : t) : Tot (result (list_t t)) @@ -238,14 +240,14 @@ let rec list_nth_mut_loop_with_id_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_with_id] *) +(** [loops::list_nth_mut_loop_with_id]: backward function 0 *) let list_nth_mut_loop_with_id_back (t : Type0) (ls : list_t t) (i : u32) (ret : t) : result (list_t t) = let* ls0 = id_mut_fwd t ls in let* l = list_nth_mut_loop_with_id_loop_back t i ls0 ret in id_mut_back t ls l -(** [loops::list_nth_shared_loop_with_id] *) +(** [loops::list_nth_shared_loop_with_id]: loop 0: forward function *) let rec list_nth_shared_loop_with_id_loop_fwd (t : Type0) (i : u32) (ls : list_t t) : Tot (result t) @@ -259,13 +261,13 @@ let rec list_nth_shared_loop_with_id_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_loop_with_id] *) +(** [loops::list_nth_shared_loop_with_id]: forward function *) let list_nth_shared_loop_with_id_fwd (t : Type0) (ls : list_t t) (i : u32) : result t = let* ls0 = id_shared_fwd t ls in list_nth_shared_loop_with_id_loop_fwd t i ls0 -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: forward function *) let rec list_nth_mut_loop_pair_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -284,12 +286,12 @@ let rec list_nth_mut_loop_pair_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: forward function *) let list_nth_mut_loop_pair_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_mut_loop_pair_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: backward function 0 *) let rec list_nth_mut_loop_pair_loop_back'a (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -310,14 +312,14 @@ let rec list_nth_mut_loop_pair_loop_back'a | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: backward function 0 *) let list_nth_mut_loop_pair_back'a (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_mut_loop_pair_loop_back'a t ls0 ls1 i ret -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: loop 0: backward function 1 *) let rec list_nth_mut_loop_pair_loop_back'b (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -338,14 +340,14 @@ let rec list_nth_mut_loop_pair_loop_back'b | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_pair] *) +(** [loops::list_nth_mut_loop_pair]: backward function 1 *) let list_nth_mut_loop_pair_back'b (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_mut_loop_pair_loop_back'b t ls0 ls1 i ret -(** [loops::list_nth_shared_loop_pair] *) +(** [loops::list_nth_shared_loop_pair]: loop 0: forward function *) let rec list_nth_shared_loop_pair_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -365,12 +367,12 @@ let rec list_nth_shared_loop_pair_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_loop_pair] *) +(** [loops::list_nth_shared_loop_pair]: forward function *) let list_nth_shared_loop_pair_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_shared_loop_pair_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: loop 0: forward function *) let rec list_nth_mut_loop_pair_merge_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -390,12 +392,12 @@ let rec list_nth_mut_loop_pair_merge_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: forward function *) let list_nth_mut_loop_pair_merge_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_mut_loop_pair_merge_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: loop 0: backward function 0 *) let rec list_nth_mut_loop_pair_merge_loop_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : (t & t)) : Tot (result ((list_t t) & (list_t t))) @@ -417,14 +419,14 @@ let rec list_nth_mut_loop_pair_merge_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_mut_loop_pair_merge] *) +(** [loops::list_nth_mut_loop_pair_merge]: backward function 0 *) let list_nth_mut_loop_pair_merge_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : (t & t)) : result ((list_t t) & (list_t t)) = list_nth_mut_loop_pair_merge_loop_back t ls0 ls1 i ret -(** [loops::list_nth_shared_loop_pair_merge] *) +(** [loops::list_nth_shared_loop_pair_merge]: loop 0: forward function *) let rec list_nth_shared_loop_pair_merge_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -444,12 +446,12 @@ let rec list_nth_shared_loop_pair_merge_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_loop_pair_merge] *) +(** [loops::list_nth_shared_loop_pair_merge]: forward function *) let list_nth_shared_loop_pair_merge_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_shared_loop_pair_merge_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: loop 0: forward function *) let rec list_nth_mut_shared_loop_pair_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -469,12 +471,12 @@ let rec list_nth_mut_shared_loop_pair_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: forward function *) let list_nth_mut_shared_loop_pair_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_mut_shared_loop_pair_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: loop 0: backward function 0 *) let rec list_nth_mut_shared_loop_pair_loop_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -495,14 +497,14 @@ let rec list_nth_mut_shared_loop_pair_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_mut_shared_loop_pair] *) +(** [loops::list_nth_mut_shared_loop_pair]: backward function 0 *) let list_nth_mut_shared_loop_pair_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_mut_shared_loop_pair_loop_back t ls0 ls1 i ret -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: forward function *) let rec list_nth_mut_shared_loop_pair_merge_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -522,12 +524,12 @@ let rec list_nth_mut_shared_loop_pair_merge_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: forward function *) let list_nth_mut_shared_loop_pair_merge_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_mut_shared_loop_pair_merge_loop_fwd t ls0 ls1 i -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: backward function 0 *) let rec list_nth_mut_shared_loop_pair_merge_loop_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -549,14 +551,14 @@ let rec list_nth_mut_shared_loop_pair_merge_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_mut_shared_loop_pair_merge] *) +(** [loops::list_nth_mut_shared_loop_pair_merge]: backward function 0 *) let list_nth_mut_shared_loop_pair_merge_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_mut_shared_loop_pair_merge_loop_back t ls0 ls1 i ret -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: loop 0: forward function *) let rec list_nth_shared_mut_loop_pair_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -576,12 +578,12 @@ let rec list_nth_shared_mut_loop_pair_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: forward function *) let list_nth_shared_mut_loop_pair_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_shared_mut_loop_pair_loop_fwd t ls0 ls1 i -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: loop 0: backward function 1 *) let rec list_nth_shared_mut_loop_pair_loop_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -602,14 +604,14 @@ let rec list_nth_shared_mut_loop_pair_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_shared_mut_loop_pair] *) +(** [loops::list_nth_shared_mut_loop_pair]: backward function 1 *) let list_nth_shared_mut_loop_pair_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) = list_nth_shared_mut_loop_pair_loop_back t ls0 ls1 i ret -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: forward function *) let rec list_nth_shared_mut_loop_pair_merge_loop_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : Tot (result (t & t)) @@ -629,12 +631,12 @@ let rec list_nth_shared_mut_loop_pair_merge_loop_fwd | ListNil -> Fail Failure end -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: forward function *) let list_nth_shared_mut_loop_pair_merge_fwd (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) : result (t & t) = list_nth_shared_mut_loop_pair_merge_loop_fwd t ls0 ls1 i -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: backward function 0 *) let rec list_nth_shared_mut_loop_pair_merge_loop_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : Tot (result (list_t t)) @@ -656,7 +658,7 @@ let rec list_nth_shared_mut_loop_pair_merge_loop_back | ListNil -> Fail Failure end -(** [loops::list_nth_shared_mut_loop_pair_merge] *) +(** [loops::list_nth_shared_mut_loop_pair_merge]: backward function 0 *) let list_nth_shared_mut_loop_pair_merge_back (t : Type0) (ls0 : list_t t) (ls1 : list_t t) (i : u32) (ret : t) : result (list_t t) diff --git a/tests/fstar/misc/NoNestedBorrows.fst b/tests/fstar/misc/NoNestedBorrows.fst index 3770ab5d..d790bfa9 100644 --- a/tests/fstar/misc/NoNestedBorrows.fst +++ b/tests/fstar/misc/NoNestedBorrows.fst @@ -30,46 +30,46 @@ type sum_t (t1 t2 : Type0) = | SumLeft : t1 -> sum_t t1 t2 | SumRight : t2 -> sum_t t1 t2 -(** [no_nested_borrows::neg_test] *) +(** [no_nested_borrows::neg_test]: forward function *) let neg_test_fwd (x : i32) : result i32 = i32_neg x -(** [no_nested_borrows::add_test] *) +(** [no_nested_borrows::add_test]: forward function *) let add_test_fwd (x : u32) (y : u32) : result u32 = u32_add x y -(** [no_nested_borrows::subs_test] *) +(** [no_nested_borrows::subs_test]: forward function *) let subs_test_fwd (x : u32) (y : u32) : result u32 = u32_sub x y -(** [no_nested_borrows::div_test] *) +(** [no_nested_borrows::div_test]: forward function *) let div_test_fwd (x : u32) (y : u32) : result u32 = u32_div x y -(** [no_nested_borrows::div_test1] *) +(** [no_nested_borrows::div_test1]: forward function *) let div_test1_fwd (x : u32) : result u32 = u32_div x 2 -(** [no_nested_borrows::rem_test] *) +(** [no_nested_borrows::rem_test]: forward function *) let rem_test_fwd (x : u32) (y : u32) : result u32 = u32_rem x y -(** [no_nested_borrows::cast_test] *) +(** [no_nested_borrows::cast_test]: forward function *) let cast_test_fwd (x : u32) : result i32 = scalar_cast U32 I32 x -(** [no_nested_borrows::test2] *) +(** [no_nested_borrows::test2]: forward function *) let test2_fwd : result unit = let* _ = u32_add 23 44 in Return () (** Unit test for [no_nested_borrows::test2] *) let _ = assert_norm (test2_fwd = Return ()) -(** [no_nested_borrows::get_max] *) +(** [no_nested_borrows::get_max]: forward function *) let get_max_fwd (x : u32) (y : u32) : result u32 = if x >= y then Return x else Return y -(** [no_nested_borrows::test3] *) +(** [no_nested_borrows::test3]: forward function *) let test3_fwd : result unit = let* x = get_max_fwd 4 3 in let* y = get_max_fwd 10 11 in @@ -79,21 +79,21 @@ let test3_fwd : result unit = (** Unit test for [no_nested_borrows::test3] *) let _ = assert_norm (test3_fwd = Return ()) -(** [no_nested_borrows::test_neg1] *) +(** [no_nested_borrows::test_neg1]: forward function *) let test_neg1_fwd : result unit = let* y = i32_neg 3 in if not (y = -3) then Fail Failure else Return () (** Unit test for [no_nested_borrows::test_neg1] *) let _ = assert_norm (test_neg1_fwd = Return ()) -(** [no_nested_borrows::refs_test1] *) +(** [no_nested_borrows::refs_test1]: forward function *) let refs_test1_fwd : result unit = if not (1 = 1) then Fail Failure else Return () (** Unit test for [no_nested_borrows::refs_test1] *) let _ = assert_norm (refs_test1_fwd = Return ()) -(** [no_nested_borrows::refs_test2] *) +(** [no_nested_borrows::refs_test2]: forward function *) let refs_test2_fwd : result unit = if not (2 = 2) then Fail Failure @@ -108,47 +108,47 @@ let refs_test2_fwd : result unit = (** Unit test for [no_nested_borrows::refs_test2] *) let _ = assert_norm (refs_test2_fwd = Return ()) -(** [no_nested_borrows::test_list1] *) +(** [no_nested_borrows::test_list1]: forward function *) let test_list1_fwd : result unit = Return () (** Unit test for [no_nested_borrows::test_list1] *) let _ = assert_norm (test_list1_fwd = Return ()) -(** [no_nested_borrows::test_box1] *) +(** [no_nested_borrows::test_box1]: forward function *) let test_box1_fwd : result unit = let b = 1 in let x = b in if not (x = 1) then Fail Failure else Return () (** Unit test for [no_nested_borrows::test_box1] *) let _ = assert_norm (test_box1_fwd = Return ()) -(** [no_nested_borrows::copy_int] *) +(** [no_nested_borrows::copy_int]: forward function *) let copy_int_fwd (x : i32) : result i32 = Return x -(** [no_nested_borrows::test_unreachable] *) +(** [no_nested_borrows::test_unreachable]: forward function *) let test_unreachable_fwd (b : bool) : result unit = if b then Fail Failure else Return () -(** [no_nested_borrows::test_panic] *) +(** [no_nested_borrows::test_panic]: forward function *) let test_panic_fwd (b : bool) : result unit = if b then Fail Failure else Return () -(** [no_nested_borrows::test_copy_int] *) +(** [no_nested_borrows::test_copy_int]: forward function *) let test_copy_int_fwd : result unit = let* y = copy_int_fwd 0 in if not (0 = y) then Fail Failure else Return () (** Unit test for [no_nested_borrows::test_copy_int] *) let _ = assert_norm (test_copy_int_fwd = Return ()) -(** [no_nested_borrows::is_cons] *) +(** [no_nested_borrows::is_cons]: forward function *) let is_cons_fwd (t : Type0) (l : list_t t) : result bool = begin match l with | ListCons x l0 -> Return true | ListNil -> Return false end -(** [no_nested_borrows::test_is_cons] *) +(** [no_nested_borrows::test_is_cons]: forward function *) let test_is_cons_fwd : result unit = let l = ListNil in let* b = is_cons_fwd i32 (ListCons 0 l) in @@ -157,14 +157,14 @@ let test_is_cons_fwd : result unit = (** Unit test for [no_nested_borrows::test_is_cons] *) let _ = assert_norm (test_is_cons_fwd = Return ()) -(** [no_nested_borrows::split_list] *) +(** [no_nested_borrows::split_list]: forward function *) let split_list_fwd (t : Type0) (l : list_t t) : result (t & (list_t t)) = begin match l with | ListCons hd tl -> Return (hd, tl) | ListNil -> Fail Failure end -(** [no_nested_borrows::test_split_list] *) +(** [no_nested_borrows::test_split_list]: forward function *) let test_split_list_fwd : result unit = let l = ListNil in let* p = split_list_fwd i32 (ListCons 0 l) in @@ -174,16 +174,16 @@ let test_split_list_fwd : result unit = (** Unit test for [no_nested_borrows::test_split_list] *) let _ = assert_norm (test_split_list_fwd = Return ()) -(** [no_nested_borrows::choose] *) +(** [no_nested_borrows::choose]: forward function *) let choose_fwd (t : Type0) (b : bool) (x : t) (y : t) : result t = if b then Return x else Return y -(** [no_nested_borrows::choose] *) +(** [no_nested_borrows::choose]: backward function 0 *) let choose_back (t : Type0) (b : bool) (x : t) (y : t) (ret : t) : result (t & t) = if b then Return (ret, y) else Return (x, ret) -(** [no_nested_borrows::choose_test] *) +(** [no_nested_borrows::choose_test]: forward function *) let choose_test_fwd : result unit = let* z = choose_fwd i32 true 0 0 in let* z0 = i32_add z 1 in @@ -198,7 +198,7 @@ let choose_test_fwd : result unit = (** Unit test for [no_nested_borrows::choose_test] *) let _ = assert_norm (choose_test_fwd = Return ()) -(** [no_nested_borrows::test_char] *) +(** [no_nested_borrows::test_char]: forward function *) let test_char_fwd : result char = Return 'a' @@ -212,14 +212,14 @@ and tree_t (t : Type0) = | TreeLeaf : t -> tree_t t | TreeNode : t -> node_elem_t t -> tree_t t -> tree_t t -(** [no_nested_borrows::list_length] *) +(** [no_nested_borrows::list_length]: forward function *) let rec list_length_fwd (t : Type0) (l : list_t t) : result u32 = begin match l with | ListCons x l1 -> let* i = list_length_fwd t l1 in u32_add 1 i | ListNil -> Return 0 end -(** [no_nested_borrows::list_nth_shared] *) +(** [no_nested_borrows::list_nth_shared]: forward function *) let rec list_nth_shared_fwd (t : Type0) (l : list_t t) (i : u32) : result t = begin match l with | ListCons x tl -> @@ -229,7 +229,7 @@ let rec list_nth_shared_fwd (t : Type0) (l : list_t t) (i : u32) : result t = | ListNil -> Fail Failure end -(** [no_nested_borrows::list_nth_mut] *) +(** [no_nested_borrows::list_nth_mut]: forward function *) let rec list_nth_mut_fwd (t : Type0) (l : list_t t) (i : u32) : result t = begin match l with | ListCons x tl -> @@ -239,7 +239,7 @@ let rec list_nth_mut_fwd (t : Type0) (l : list_t t) (i : u32) : result t = | ListNil -> Fail Failure end -(** [no_nested_borrows::list_nth_mut] *) +(** [no_nested_borrows::list_nth_mut]: backward function 0 *) let rec list_nth_mut_back (t : Type0) (l : list_t t) (i : u32) (ret : t) : result (list_t t) = begin match l with @@ -253,7 +253,7 @@ let rec list_nth_mut_back | ListNil -> Fail Failure end -(** [no_nested_borrows::list_rev_aux] *) +(** [no_nested_borrows::list_rev_aux]: forward function *) let rec list_rev_aux_fwd (t : Type0) (li : list_t t) (lo : list_t t) : result (list_t t) = begin match li with @@ -261,12 +261,13 @@ let rec list_rev_aux_fwd | ListNil -> Return lo end -(** [no_nested_borrows::list_rev] *) +(** [no_nested_borrows::list_rev]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let list_rev_fwd_back (t : Type0) (l : list_t t) : result (list_t t) = let li = mem_replace_fwd (list_t t) l ListNil in list_rev_aux_fwd t li ListNil -(** [no_nested_borrows::test_list_functions] *) +(** [no_nested_borrows::test_list_functions]: forward function *) let test_list_functions_fwd : result unit = let l = ListNil in let l0 = ListCons 2 l in @@ -302,48 +303,48 @@ let test_list_functions_fwd : result unit = (** Unit test for [no_nested_borrows::test_list_functions] *) let _ = assert_norm (test_list_functions_fwd = Return ()) -(** [no_nested_borrows::id_mut_pair1] *) +(** [no_nested_borrows::id_mut_pair1]: forward function *) let id_mut_pair1_fwd (t1 t2 : Type0) (x : t1) (y : t2) : result (t1 & t2) = Return (x, y) -(** [no_nested_borrows::id_mut_pair1] *) +(** [no_nested_borrows::id_mut_pair1]: backward function 0 *) let id_mut_pair1_back (t1 t2 : Type0) (x : t1) (y : t2) (ret : (t1 & t2)) : result (t1 & t2) = let (x0, x1) = ret in Return (x0, x1) -(** [no_nested_borrows::id_mut_pair2] *) +(** [no_nested_borrows::id_mut_pair2]: forward function *) let id_mut_pair2_fwd (t1 t2 : Type0) (p : (t1 & t2)) : result (t1 & t2) = let (x, x0) = p in Return (x, x0) -(** [no_nested_borrows::id_mut_pair2] *) +(** [no_nested_borrows::id_mut_pair2]: backward function 0 *) let id_mut_pair2_back (t1 t2 : Type0) (p : (t1 & t2)) (ret : (t1 & t2)) : result (t1 & t2) = let (x, x0) = ret in Return (x, x0) -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: forward function *) let id_mut_pair3_fwd (t1 t2 : Type0) (x : t1) (y : t2) : result (t1 & t2) = Return (x, y) -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: backward function 0 *) let id_mut_pair3_back'a (t1 t2 : Type0) (x : t1) (y : t2) (ret : t1) : result t1 = Return ret -(** [no_nested_borrows::id_mut_pair3] *) +(** [no_nested_borrows::id_mut_pair3]: backward function 1 *) let id_mut_pair3_back'b (t1 t2 : Type0) (x : t1) (y : t2) (ret : t2) : result t2 = Return ret -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: forward function *) let id_mut_pair4_fwd (t1 t2 : Type0) (p : (t1 & t2)) : result (t1 & t2) = let (x, x0) = p in Return (x, x0) -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: backward function 0 *) let id_mut_pair4_back'a (t1 t2 : Type0) (p : (t1 & t2)) (ret : t1) : result t1 = Return ret -(** [no_nested_borrows::id_mut_pair4] *) +(** [no_nested_borrows::id_mut_pair4]: backward function 1 *) let id_mut_pair4_back'b (t1 t2 : Type0) (p : (t1 & t2)) (ret : t2) : result t2 = Return ret @@ -351,15 +352,15 @@ let id_mut_pair4_back'b (** [no_nested_borrows::StructWithTuple] *) type struct_with_tuple_t (t1 t2 : Type0) = { struct_with_tuple_p : (t1 & t2); } -(** [no_nested_borrows::new_tuple1] *) +(** [no_nested_borrows::new_tuple1]: forward function *) let new_tuple1_fwd : result (struct_with_tuple_t u32 u32) = Return { struct_with_tuple_p = (1, 2) } -(** [no_nested_borrows::new_tuple2] *) +(** [no_nested_borrows::new_tuple2]: forward function *) let new_tuple2_fwd : result (struct_with_tuple_t i16 i16) = Return { struct_with_tuple_p = (1, 2) } -(** [no_nested_borrows::new_tuple3] *) +(** [no_nested_borrows::new_tuple3]: forward function *) let new_tuple3_fwd : result (struct_with_tuple_t u64 i64) = Return { struct_with_tuple_p = (1, 2) } @@ -369,11 +370,11 @@ type struct_with_pair_t (t1 t2 : Type0) = struct_with_pair_p : pair_t t1 t2; } -(** [no_nested_borrows::new_pair1] *) +(** [no_nested_borrows::new_pair1]: forward function *) let new_pair1_fwd : result (struct_with_pair_t u32 u32) = Return { struct_with_pair_p = { pair_x = 1; pair_y = 2 } } -(** [no_nested_borrows::test_constants] *) +(** [no_nested_borrows::test_constants]: forward function *) let test_constants_fwd : result unit = let* swt = new_tuple1_fwd in let (i, _) = swt.struct_with_tuple_p in @@ -398,31 +399,32 @@ let test_constants_fwd : result unit = (** Unit test for [no_nested_borrows::test_constants] *) let _ = assert_norm (test_constants_fwd = Return ()) -(** [no_nested_borrows::test_weird_borrows1] *) +(** [no_nested_borrows::test_weird_borrows1]: forward function *) let test_weird_borrows1_fwd : result unit = Return () (** Unit test for [no_nested_borrows::test_weird_borrows1] *) let _ = assert_norm (test_weird_borrows1_fwd = Return ()) -(** [no_nested_borrows::test_mem_replace] *) +(** [no_nested_borrows::test_mem_replace]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let test_mem_replace_fwd_back (px : u32) : result u32 = let y = mem_replace_fwd u32 px 1 in if not (y = 0) then Fail Failure else Return 2 -(** [no_nested_borrows::test_shared_borrow_bool1] *) +(** [no_nested_borrows::test_shared_borrow_bool1]: forward function *) let test_shared_borrow_bool1_fwd (b : bool) : result u32 = if b then Return 0 else Return 1 -(** [no_nested_borrows::test_shared_borrow_bool2] *) +(** [no_nested_borrows::test_shared_borrow_bool2]: forward function *) let test_shared_borrow_bool2_fwd : result u32 = Return 0 -(** [no_nested_borrows::test_shared_borrow_enum1] *) +(** [no_nested_borrows::test_shared_borrow_enum1]: forward function *) let test_shared_borrow_enum1_fwd (l : list_t u32) : result u32 = begin match l with | ListCons i l0 -> Return 1 | ListNil -> Return 0 end -(** [no_nested_borrows::test_shared_borrow_enum2] *) +(** [no_nested_borrows::test_shared_borrow_enum2]: forward function *) let test_shared_borrow_enum2_fwd : result u32 = Return 0 diff --git a/tests/fstar/misc/Paper.fst b/tests/fstar/misc/Paper.fst index 4ab31de3..e2d692c2 100644 --- a/tests/fstar/misc/Paper.fst +++ b/tests/fstar/misc/Paper.fst @@ -5,11 +5,12 @@ open Primitives #set-options "--z3rlimit 50 --fuel 1 --ifuel 1" -(** [paper::ref_incr] *) +(** [paper::ref_incr]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) let ref_incr_fwd_back (x : i32) : result i32 = i32_add x 1 -(** [paper::test_incr] *) +(** [paper::test_incr]: forward function *) let test_incr_fwd : result unit = let* x = ref_incr_fwd_back 0 in if not (x = 1) then Fail Failure else Return () @@ -17,16 +18,16 @@ let test_incr_fwd : result unit = (** Unit test for [paper::test_incr] *) let _ = assert_norm (test_incr_fwd = Return ()) -(** [paper::choose] *) +(** [paper::choose]: forward function *) let choose_fwd (t : Type0) (b : bool) (x : t) (y : t) : result t = if b then Return x else Return y -(** [paper::choose] *) +(** [paper::choose]: backward function 0 *) let choose_back (t : Type0) (b : bool) (x : t) (y : t) (ret : t) : result (t & t) = if b then Return (ret, y) else Return (x, ret) -(** [paper::test_choose] *) +(** [paper::test_choose]: forward function *) let test_choose_fwd : result unit = let* z = choose_fwd i32 true 0 0 in let* z0 = i32_add z 1 in @@ -46,7 +47,7 @@ type list_t (t : Type0) = | ListCons : t -> list_t t -> list_t t | ListNil : list_t t -(** [paper::list_nth_mut] *) +(** [paper::list_nth_mut]: forward function *) let rec list_nth_mut_fwd (t : Type0) (l : list_t t) (i : u32) : result t = begin match l with | ListCons x tl -> @@ -56,7 +57,7 @@ let rec list_nth_mut_fwd (t : Type0) (l : list_t t) (i : u32) : result t = | ListNil -> Fail Failure end -(** [paper::list_nth_mut] *) +(** [paper::list_nth_mut]: backward function 0 *) let rec list_nth_mut_back (t : Type0) (l : list_t t) (i : u32) (ret : t) : result (list_t t) = begin match l with @@ -70,14 +71,14 @@ let rec list_nth_mut_back | ListNil -> Fail Failure end -(** [paper::sum] *) +(** [paper::sum]: forward function *) let rec sum_fwd (l : list_t i32) : result i32 = begin match l with | ListCons x tl -> let* i = sum_fwd tl in i32_add x i | ListNil -> Return 0 end -(** [paper::test_nth] *) +(** [paper::test_nth]: forward function *) let test_nth_fwd : result unit = let l = ListNil in let l0 = ListCons 3 l in @@ -91,7 +92,7 @@ let test_nth_fwd : result unit = (** Unit test for [paper::test_nth] *) let _ = assert_norm (test_nth_fwd = Return ()) -(** [paper::call_choose] *) +(** [paper::call_choose]: forward function *) let call_choose_fwd (p : (u32 & u32)) : result u32 = let (px, py) = p in let* pz = choose_fwd u32 true px py in diff --git a/tests/fstar/misc/PoloniusList.fst b/tests/fstar/misc/PoloniusList.fst index e2144487..79c86606 100644 --- a/tests/fstar/misc/PoloniusList.fst +++ b/tests/fstar/misc/PoloniusList.fst @@ -10,7 +10,7 @@ type list_t (t : Type0) = | ListCons : t -> list_t t -> list_t t | ListNil : list_t t -(** [polonius_list::get_list_at_x] *) +(** [polonius_list::get_list_at_x]: forward function *) let rec get_list_at_x_fwd (ls : list_t u32) (x : u32) : result (list_t u32) = begin match ls with | ListCons hd tl -> @@ -18,7 +18,7 @@ let rec get_list_at_x_fwd (ls : list_t u32) (x : u32) : result (list_t u32) = | ListNil -> Return ListNil end -(** [polonius_list::get_list_at_x] *) +(** [polonius_list::get_list_at_x]: backward function 0 *) let rec get_list_at_x_back (ls : list_t u32) (x : u32) (ret : list_t u32) : result (list_t u32) = begin match ls with diff --git a/tests/hol4/betree/betreeMain_FunsScript.sml b/tests/hol4/betree/betreeMain_FunsScript.sml index df0c6a24..03ff2671 100644 --- a/tests/hol4/betree/betreeMain_FunsScript.sml +++ b/tests/hol4/betree/betreeMain_FunsScript.sml @@ -7,7 +7,7 @@ val _ = new_theory "betreeMain_Funs" val betree_load_internal_node_fwd_def = Define ‘ - (** [betree_main::betree::load_internal_node] *) + (** [betree_main::betree::load_internal_node]: forward function *) betree_load_internal_node_fwd (id : u64) (st : state) : (state # (u64 # betree_message_t) betree_list_t) result @@ -16,7 +16,7 @@ val betree_load_internal_node_fwd_def = Define ‘ ’ val betree_store_internal_node_fwd_def = Define ‘ - (** [betree_main::betree::store_internal_node] *) + (** [betree_main::betree::store_internal_node]: forward function *) betree_store_internal_node_fwd (id : u64) (content : (u64 # betree_message_t) betree_list_t) (st : state) : @@ -29,14 +29,14 @@ val betree_store_internal_node_fwd_def = Define ‘ ’ val betree_load_leaf_node_fwd_def = Define ‘ - (** [betree_main::betree::load_leaf_node] *) + (** [betree_main::betree::load_leaf_node]: forward function *) betree_load_leaf_node_fwd (id : u64) (st : state) : (state # (u64 # u64) betree_list_t) result = betree_utils_load_leaf_node_fwd id st ’ val betree_store_leaf_node_fwd_def = Define ‘ - (** [betree_main::betree::store_leaf_node] *) + (** [betree_main::betree::store_leaf_node]: forward function *) betree_store_leaf_node_fwd (id : u64) (content : (u64 # u64) betree_list_t) (st : state) : (state # unit) result @@ -48,7 +48,7 @@ val betree_store_leaf_node_fwd_def = Define ‘ ’ val betree_fresh_node_id_fwd_def = Define ‘ - (** [betree_main::betree::fresh_node_id] *) + (** [betree_main::betree::fresh_node_id]: forward function *) betree_fresh_node_id_fwd (counter : u64) : u64 result = do _ <- u64_add counter (int_to_u64 1); @@ -57,19 +57,19 @@ val betree_fresh_node_id_fwd_def = Define ‘ ’ val betree_fresh_node_id_back_def = Define ‘ - (** [betree_main::betree::fresh_node_id] *) + (** [betree_main::betree::fresh_node_id]: backward function 0 *) betree_fresh_node_id_back (counter : u64) : u64 result = u64_add counter (int_to_u64 1) ’ val betree_node_id_counter_new_fwd_def = Define ‘ - (** [betree_main::betree::NodeIdCounter::{0}::new] *) + (** [betree_main::betree::NodeIdCounter::{0}::new]: forward function *) betree_node_id_counter_new_fwd : betree_node_id_counter_t result = Return (<| betree_node_id_counter_next_node_id := (int_to_u64 0) |>) ’ val betree_node_id_counter_fresh_id_fwd_def = Define ‘ - (** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) + (** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function *) betree_node_id_counter_fresh_id_fwd (self : betree_node_id_counter_t) : u64 result = do @@ -79,7 +79,7 @@ val betree_node_id_counter_fresh_id_fwd_def = Define ‘ ’ val betree_node_id_counter_fresh_id_back_def = Define ‘ - (** [betree_main::betree::NodeIdCounter::{0}::fresh_id] *) + (** [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 *) betree_node_id_counter_fresh_id_back (self : betree_node_id_counter_t) : betree_node_id_counter_t result = do @@ -97,7 +97,7 @@ Definition core_num_u64_max_c_def: End val betree_upsert_update_fwd_def = Define ‘ - (** [betree_main::betree::upsert_update] *) + (** [betree_main::betree::upsert_update]: forward function *) betree_upsert_update_fwd (prev : u64 option) (st : betree_upsert_fun_state_t) : u64 result = (case prev of @@ -117,7 +117,7 @@ val betree_upsert_update_fwd_def = Define ‘ ’ val [betree_list_len_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::List::{1}::len] *) + (** [betree_main::betree::List::{1}::len]: forward function *) betree_list_len_fwd (self : 't betree_list_t) : u64 result = (case self of | BetreeListCons t tl => @@ -129,7 +129,7 @@ val [betree_list_len_fwd_def] = DefineDiv ‘ ’ val [betree_list_split_at_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::List::{1}::split_at] *) + (** [betree_main::betree::List::{1}::split_at]: forward function *) betree_list_split_at_fwd (self : 't betree_list_t) (n : u64) : ('t betree_list_t # 't betree_list_t) result @@ -148,7 +148,8 @@ val [betree_list_split_at_fwd_def] = DefineDiv ‘ ’ val betree_list_push_front_fwd_back_def = Define ‘ - (** [betree_main::betree::List::{1}::push_front] *) + (** [betree_main::betree::List::{1}::push_front]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_list_push_front_fwd_back (self : 't betree_list_t) (x : 't) : 't betree_list_t result = let tl = mem_replace_fwd self BetreeListNil in @@ -157,7 +158,7 @@ val betree_list_push_front_fwd_back_def = Define ‘ ’ val betree_list_pop_front_fwd_def = Define ‘ - (** [betree_main::betree::List::{1}::pop_front] *) + (** [betree_main::betree::List::{1}::pop_front]: forward function *) betree_list_pop_front_fwd (self : 't betree_list_t) : 't result = let ls = mem_replace_fwd self BetreeListNil in (case ls of @@ -166,7 +167,7 @@ val betree_list_pop_front_fwd_def = Define ‘ ’ val betree_list_pop_front_back_def = Define ‘ - (** [betree_main::betree::List::{1}::pop_front] *) + (** [betree_main::betree::List::{1}::pop_front]: backward function 0 *) betree_list_pop_front_back (self : 't betree_list_t) : 't betree_list_t result = let ls = mem_replace_fwd self BetreeListNil in @@ -176,7 +177,7 @@ val betree_list_pop_front_back_def = Define ‘ ’ val betree_list_hd_fwd_def = Define ‘ - (** [betree_main::betree::List::{1}::hd] *) + (** [betree_main::betree::List::{1}::hd]: forward function *) betree_list_hd_fwd (self : 't betree_list_t) : 't result = (case self of | BetreeListCons hd l => Return hd @@ -184,7 +185,7 @@ val betree_list_hd_fwd_def = Define ‘ ’ val betree_list_head_has_key_fwd_def = Define ‘ - (** [betree_main::betree::List::{2}::head_has_key] *) + (** [betree_main::betree::List::{2}::head_has_key]: forward function *) betree_list_head_has_key_fwd (self : (u64 # 't) betree_list_t) (key : u64) : bool result = (case self of @@ -193,7 +194,7 @@ val betree_list_head_has_key_fwd_def = Define ‘ ’ val [betree_list_partition_at_pivot_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::List::{2}::partition_at_pivot] *) + (** [betree_main::betree::List::{2}::partition_at_pivot]: forward function *) betree_list_partition_at_pivot_fwd (self : (u64 # 't) betree_list_t) (pivot : u64) : ((u64 # 't) betree_list_t # (u64 # 't) betree_list_t) result @@ -214,7 +215,7 @@ val [betree_list_partition_at_pivot_fwd_def] = DefineDiv ‘ ’ val betree_leaf_split_fwd_def = Define ‘ - (** [betree_main::betree::Leaf::{3}::split] *) + (** [betree_main::betree::Leaf::{3}::split]: forward function *) betree_leaf_split_fwd (self : betree_leaf_t) (content : (u64 # u64) betree_list_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -256,7 +257,7 @@ val betree_leaf_split_fwd_def = Define ‘ ’ val betree_leaf_split_back_def = Define ‘ - (** [betree_main::betree::Leaf::{3}::split] *) + (** [betree_main::betree::Leaf::{3}::split]: backward function 2 *) betree_leaf_split_back (self : betree_leaf_t) (content : (u64 # u64) betree_list_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -279,7 +280,7 @@ val betree_leaf_split_back_def = Define ‘ ’ val [betree_node_lookup_in_bindings_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_in_bindings] *) + (** [betree_main::betree::Node::{5}::lookup_in_bindings]: forward function *) betree_node_lookup_in_bindings_fwd (key : u64) (bindings : (u64 # u64) betree_list_t) : u64 option result = (case bindings of @@ -295,7 +296,7 @@ val [betree_node_lookup_in_bindings_fwd_def] = DefineDiv ‘ ’ val [betree_node_lookup_first_message_for_key_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) + (** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: forward function *) betree_node_lookup_first_message_for_key_fwd (key : u64) (msgs : (u64 # betree_message_t) betree_list_t) : (u64 # betree_message_t) betree_list_t result @@ -310,7 +311,7 @@ val [betree_node_lookup_first_message_for_key_fwd_def] = DefineDiv ‘ ’ val [betree_node_lookup_first_message_for_key_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_first_message_for_key] *) + (** [betree_main::betree::Node::{5}::lookup_first_message_for_key]: backward function 0 *) betree_node_lookup_first_message_for_key_back (key : u64) (msgs : (u64 # betree_message_t) betree_list_t) (ret : (u64 # betree_message_t) betree_list_t) : @@ -331,7 +332,7 @@ val [betree_node_lookup_first_message_for_key_back_def] = DefineDiv ‘ ’ val [betree_node_apply_upserts_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::apply_upserts] *) + (** [betree_main::betree::Node::{5}::apply_upserts]: forward function *) betree_node_apply_upserts_fwd (msgs : (u64 # betree_message_t) betree_list_t) (prev : u64 option) (key : u64) (st : state) : @@ -364,7 +365,7 @@ val [betree_node_apply_upserts_fwd_def] = DefineDiv ‘ ’ val [betree_node_apply_upserts_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::apply_upserts] *) + (** [betree_main::betree::Node::{5}::apply_upserts]: backward function 0 *) betree_node_apply_upserts_back (msgs : (u64 # betree_message_t) betree_list_t) (prev : u64 option) (key : u64) (st : state) : @@ -396,7 +397,7 @@ val [betree_node_apply_upserts_back_def] = DefineDiv ‘ ’ val [betree_node_lookup_fwd_def, betree_node_lookup_back_def, betree_internal_lookup_in_children_fwd_def, betree_internal_lookup_in_children_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup] *) + (** [betree_main::betree::Node::{5}::lookup]: forward function *) (betree_node_lookup_fwd (self : betree_node_t) (key : u64) (st : state) : (state # u64 option) result @@ -466,7 +467,7 @@ val [betree_node_lookup_fwd_def, betree_node_lookup_back_def, betree_internal_lo od)) /\ - (** [betree_main::betree::Node::{5}::lookup] *) + (** [betree_main::betree::Node::{5}::lookup]: backward function 0 *) (betree_node_lookup_back (self : betree_node_t) (key : u64) (st : state) : betree_node_t result = (case self of @@ -534,7 +535,7 @@ val [betree_node_lookup_fwd_def, betree_node_lookup_back_def, betree_internal_lo od)) /\ - (** [betree_main::betree::Internal::{4}::lookup_in_children] *) + (** [betree_main::betree::Internal::{4}::lookup_in_children]: forward function *) (betree_internal_lookup_in_children_fwd (self : betree_internal_t) (key : u64) (st : state) : (state # u64 option) result @@ -544,7 +545,7 @@ val [betree_node_lookup_fwd_def, betree_node_lookup_back_def, betree_internal_lo else betree_node_lookup_fwd self.betree_internal_right key st) /\ - (** [betree_main::betree::Internal::{4}::lookup_in_children] *) + (** [betree_main::betree::Internal::{4}::lookup_in_children]: backward function 0 *) betree_internal_lookup_in_children_back (self : betree_internal_t) (key : u64) (st : state) : betree_internal_t result @@ -563,7 +564,7 @@ val [betree_node_lookup_fwd_def, betree_node_lookup_back_def, betree_internal_lo ’ val [betree_node_lookup_mut_in_bindings_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) + (** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: forward function *) betree_node_lookup_mut_in_bindings_fwd (key : u64) (bindings : (u64 # u64) betree_list_t) : (u64 # u64) betree_list_t result @@ -578,7 +579,7 @@ val [betree_node_lookup_mut_in_bindings_fwd_def] = DefineDiv ‘ ’ val [betree_node_lookup_mut_in_bindings_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_mut_in_bindings] *) + (** [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: backward function 0 *) betree_node_lookup_mut_in_bindings_back (key : u64) (bindings : (u64 # u64) betree_list_t) (ret : (u64 # u64) betree_list_t) : @@ -598,7 +599,8 @@ val [betree_node_lookup_mut_in_bindings_back_def] = DefineDiv ‘ ’ val betree_node_apply_to_leaf_fwd_back_def = Define ‘ - (** [betree_main::betree::Node::{5}::apply_to_leaf] *) + (** [betree_main::betree::Node::{5}::apply_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_node_apply_to_leaf_fwd_back (bindings : (u64 # u64) betree_list_t) (key : u64) (new_msg : betree_message_t) : @@ -651,7 +653,8 @@ val betree_node_apply_to_leaf_fwd_back_def = Define ‘ ’ val [betree_node_apply_messages_to_leaf_fwd_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::apply_messages_to_leaf] *) + (** [betree_main::betree::Node::{5}::apply_messages_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_node_apply_messages_to_leaf_fwd_back (bindings : (u64 # u64) betree_list_t) (new_msgs : (u64 # betree_message_t) betree_list_t) : @@ -668,7 +671,8 @@ val [betree_node_apply_messages_to_leaf_fwd_back_def] = DefineDiv ‘ ’ val [betree_node_filter_messages_for_key_fwd_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::filter_messages_for_key] *) + (** [betree_main::betree::Node::{5}::filter_messages_for_key]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_node_filter_messages_for_key_fwd_back (key : u64) (msgs : (u64 # betree_message_t) betree_list_t) : (u64 # betree_message_t) betree_list_t result @@ -687,7 +691,7 @@ val [betree_node_filter_messages_for_key_fwd_back_def] = DefineDiv ‘ ’ val [betree_node_lookup_first_message_after_key_fwd_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) + (** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: forward function *) betree_node_lookup_first_message_after_key_fwd (key : u64) (msgs : (u64 # betree_message_t) betree_list_t) : (u64 # betree_message_t) betree_list_t result @@ -702,7 +706,7 @@ val [betree_node_lookup_first_message_after_key_fwd_def] = DefineDiv ‘ ’ val [betree_node_lookup_first_message_after_key_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::lookup_first_message_after_key] *) + (** [betree_main::betree::Node::{5}::lookup_first_message_after_key]: backward function 0 *) betree_node_lookup_first_message_after_key_back (key : u64) (msgs : (u64 # betree_message_t) betree_list_t) (ret : (u64 # betree_message_t) betree_list_t) : @@ -723,7 +727,8 @@ val [betree_node_lookup_first_message_after_key_back_def] = DefineDiv ‘ ’ val betree_node_apply_to_internal_fwd_back_def = Define ‘ - (** [betree_main::betree::Node::{5}::apply_to_internal] *) + (** [betree_main::betree::Node::{5}::apply_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_node_apply_to_internal_fwd_back (msgs : (u64 # betree_message_t) betree_list_t) (key : u64) (new_msg : betree_message_t) : @@ -789,7 +794,8 @@ val betree_node_apply_to_internal_fwd_back_def = Define ‘ ’ val [betree_node_apply_messages_to_internal_fwd_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::apply_messages_to_internal] *) + (** [betree_main::betree::Node::{5}::apply_messages_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) betree_node_apply_messages_to_internal_fwd_back (msgs : (u64 # betree_message_t) betree_list_t) (new_msgs : (u64 # betree_message_t) betree_list_t) : @@ -806,7 +812,7 @@ val [betree_node_apply_messages_to_internal_fwd_back_def] = DefineDiv ‘ ’ val [betree_node_apply_messages_fwd_def, betree_node_apply_messages_back_def, betree_internal_flush_fwd_def, betree_internal_flush_back_def] = DefineDiv ‘ - (** [betree_main::betree::Node::{5}::apply_messages] *) + (** [betree_main::betree::Node::{5}::apply_messages]: forward function *) (betree_node_apply_messages_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -861,7 +867,7 @@ val [betree_node_apply_messages_fwd_def, betree_node_apply_messages_back_def, be od)) /\ - (** [betree_main::betree::Node::{5}::apply_messages] *) + (** [betree_main::betree::Node::{5}::apply_messages]: backward function 0 *) (betree_node_apply_messages_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -918,7 +924,7 @@ val [betree_node_apply_messages_fwd_def, betree_node_apply_messages_back_def, be od)) /\ - (** [betree_main::betree::Internal::{4}::flush] *) + (** [betree_main::betree::Internal::{4}::flush]: forward function *) (betree_internal_flush_fwd (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -967,7 +973,7 @@ val [betree_node_apply_messages_fwd_def, betree_node_apply_messages_back_def, be od) /\ - (** [betree_main::betree::Internal::{4}::flush] *) + (** [betree_main::betree::Internal::{4}::flush]: backward function 0 *) betree_internal_flush_back (self : betree_internal_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) @@ -1016,7 +1022,7 @@ val [betree_node_apply_messages_fwd_def, betree_node_apply_messages_back_def, be ’ val betree_node_apply_fwd_def = Define ‘ - (** [betree_main::betree::Node::{5}::apply] *) + (** [betree_main::betree::Node::{5}::apply]: forward function *) betree_node_apply_fwd (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -1036,7 +1042,7 @@ val betree_node_apply_fwd_def = Define ‘ ’ val betree_node_apply_back_def = Define ‘ - (** [betree_main::betree::Node::{5}::apply] *) + (** [betree_main::betree::Node::{5}::apply]: backward function 0 *) betree_node_apply_back (self : betree_node_t) (params : betree_params_t) (node_id_cnt : betree_node_id_counter_t) (key : u64) @@ -1049,7 +1055,7 @@ val betree_node_apply_back_def = Define ‘ ’ val betree_be_tree_new_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::new] *) + (** [betree_main::betree::BeTree::{6}::new]: forward function *) betree_be_tree_new_fwd (min_flush_size : u64) (split_size : u64) (st : state) : (state # betree_be_tree_t) result @@ -1075,7 +1081,7 @@ val betree_be_tree_new_fwd_def = Define ‘ ’ val betree_be_tree_apply_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::apply] *) + (** [betree_main::betree::BeTree::{6}::apply]: forward function *) betree_be_tree_apply_fwd (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) : @@ -1093,7 +1099,7 @@ val betree_be_tree_apply_fwd_def = Define ‘ ’ val betree_be_tree_apply_back_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::apply] *) + (** [betree_main::betree::BeTree::{6}::apply]: backward function 0 *) betree_be_tree_apply_back (self : betree_be_tree_t) (key : u64) (msg : betree_message_t) (st : state) : @@ -1113,7 +1119,7 @@ val betree_be_tree_apply_back_def = Define ‘ ’ val betree_be_tree_insert_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::insert] *) + (** [betree_main::betree::BeTree::{6}::insert]: forward function *) betree_be_tree_insert_fwd (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) : (state # unit) result @@ -1127,7 +1133,7 @@ val betree_be_tree_insert_fwd_def = Define ‘ ’ val betree_be_tree_insert_back_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::insert] *) + (** [betree_main::betree::BeTree::{6}::insert]: backward function 0 *) betree_be_tree_insert_back (self : betree_be_tree_t) (key : u64) (value : u64) (st : state) : betree_be_tree_t result @@ -1136,7 +1142,7 @@ val betree_be_tree_insert_back_def = Define ‘ ’ val betree_be_tree_delete_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::delete] *) + (** [betree_main::betree::BeTree::{6}::delete]: forward function *) betree_be_tree_delete_fwd (self : betree_be_tree_t) (key : u64) (st : state) : (state # unit) result @@ -1149,7 +1155,7 @@ val betree_be_tree_delete_fwd_def = Define ‘ ’ val betree_be_tree_delete_back_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::delete] *) + (** [betree_main::betree::BeTree::{6}::delete]: backward function 0 *) betree_be_tree_delete_back (self : betree_be_tree_t) (key : u64) (st : state) : betree_be_tree_t result @@ -1158,7 +1164,7 @@ val betree_be_tree_delete_back_def = Define ‘ ’ val betree_be_tree_upsert_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::upsert] *) + (** [betree_main::betree::BeTree::{6}::upsert]: forward function *) betree_be_tree_upsert_fwd (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) : @@ -1172,7 +1178,7 @@ val betree_be_tree_upsert_fwd_def = Define ‘ ’ val betree_be_tree_upsert_back_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::upsert] *) + (** [betree_main::betree::BeTree::{6}::upsert]: backward function 0 *) betree_be_tree_upsert_back (self : betree_be_tree_t) (key : u64) (upd : betree_upsert_fun_state_t) (st : state) : @@ -1182,7 +1188,7 @@ val betree_be_tree_upsert_back_def = Define ‘ ’ val betree_be_tree_lookup_fwd_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::lookup] *) + (** [betree_main::betree::BeTree::{6}::lookup]: forward function *) betree_be_tree_lookup_fwd (self : betree_be_tree_t) (key : u64) (st : state) : (state # u64 option) result @@ -1191,7 +1197,7 @@ val betree_be_tree_lookup_fwd_def = Define ‘ ’ val betree_be_tree_lookup_back_def = Define ‘ - (** [betree_main::betree::BeTree::{6}::lookup] *) + (** [betree_main::betree::BeTree::{6}::lookup]: backward function 0 *) betree_be_tree_lookup_back (self : betree_be_tree_t) (key : u64) (st : state) : betree_be_tree_t result @@ -1203,7 +1209,7 @@ val betree_be_tree_lookup_back_def = Define ‘ ’ val main_fwd_def = Define ‘ - (** [betree_main::main] *) + (** [betree_main::main]: forward function *) main_fwd : unit result = Return () ’ diff --git a/tests/hol4/betree/betreeMain_OpaqueScript.sml b/tests/hol4/betree/betreeMain_OpaqueScript.sml index 10d67cca..1d16db4c 100644 --- a/tests/hol4/betree/betreeMain_OpaqueScript.sml +++ b/tests/hol4/betree/betreeMain_OpaqueScript.sml @@ -6,21 +6,21 @@ open betreeMain_TypesTheory val _ = new_theory "betreeMain_Opaque" -val _ = new_constant ("betree_utils_load_internal_node_fwd", +(** [betree_main::betree_utils::load_internal_node]: forward function *)val _ = new_constant ("betree_utils_load_internal_node_fwd", “:u64 -> state -> (state # (u64 # betree_message_t) betree_list_t) result”) -val _ = new_constant ("betree_utils_store_internal_node_fwd", +(** [betree_main::betree_utils::store_internal_node]: forward function *)val _ = new_constant ("betree_utils_store_internal_node_fwd", “:u64 -> (u64 # betree_message_t) betree_list_t -> state -> (state # unit) result”) -val _ = new_constant ("betree_utils_load_leaf_node_fwd", +(** [betree_main::betree_utils::load_leaf_node]: forward function *)val _ = new_constant ("betree_utils_load_leaf_node_fwd", “:u64 -> state -> (state # (u64 # u64) betree_list_t) result”) -val _ = new_constant ("betree_utils_store_leaf_node_fwd", +(** [betree_main::betree_utils::store_leaf_node]: forward function *)val _ = new_constant ("betree_utils_store_leaf_node_fwd", “:u64 -> (u64 # u64) betree_list_t -> state -> (state # unit) result”) -val _ = new_constant ("core_option_option_unwrap_fwd", +(** [core::option::Option::{0}::unwrap]: forward function *)val _ = new_constant ("core_option_option_unwrap_fwd", “:'t option -> state -> (state # 't) result”) val _ = export_theory () diff --git a/tests/hol4/hashmap/hashmap_FunsScript.sml b/tests/hol4/hashmap/hashmap_FunsScript.sml index 9ad497f5..1ed57080 100644 --- a/tests/hol4/hashmap/hashmap_FunsScript.sml +++ b/tests/hol4/hashmap/hashmap_FunsScript.sml @@ -7,13 +7,13 @@ val _ = new_theory "hashmap_Funs" val hash_key_fwd_def = Define ‘ - (** [hashmap::hash_key] *) + (** [hashmap::hash_key]: forward function *) hash_key_fwd (k : usize) : usize result = Return k ’ val [hash_map_allocate_slots_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::allocate_slots] *) + (** [hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) hash_map_allocate_slots_loop_fwd (slots : 't list_t vec) (n : usize) : 't list_t vec result = if usize_gt n (int_to_usize 0) @@ -27,14 +27,14 @@ val [hash_map_allocate_slots_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_allocate_slots_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::allocate_slots] *) + (** [hashmap::HashMap::{0}::allocate_slots]: forward function *) hash_map_allocate_slots_fwd (slots : 't list_t vec) (n : usize) : 't list_t vec result = hash_map_allocate_slots_loop_fwd slots n ’ val hash_map_new_with_capacity_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::new_with_capacity] *) + (** [hashmap::HashMap::{0}::new_with_capacity]: forward function *) hash_map_new_with_capacity_fwd (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : 't hash_map_t result @@ -55,14 +55,15 @@ val hash_map_new_with_capacity_fwd_def = Define ‘ ’ val hash_map_new_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::new] *) + (** [hashmap::HashMap::{0}::new]: forward function *) hash_map_new_fwd : 't hash_map_t result = hash_map_new_with_capacity_fwd (int_to_usize 32) (int_to_usize 4) (int_to_usize 5) ’ val [hash_map_clear_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::clear] *) + (** [hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_clear_loop_fwd_back (slots : 't list_t vec) (i : usize) : 't list_t vec result = let i0 = vec_len slots in @@ -77,7 +78,8 @@ val [hash_map_clear_loop_fwd_back_def] = DefineDiv ‘ ’ val hash_map_clear_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::clear] *) + (** [hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_clear_fwd_back (self : 't hash_map_t) : 't hash_map_t result = do v <- hash_map_clear_loop_fwd_back self.hash_map_slots (int_to_usize 0); @@ -91,13 +93,13 @@ val hash_map_clear_fwd_back_def = Define ‘ ’ val hash_map_len_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::len] *) + (** [hashmap::HashMap::{0}::len]: forward function *) hash_map_len_fwd (self : 't hash_map_t) : usize result = Return self.hash_map_num_entries ’ val [hash_map_insert_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) hash_map_insert_in_list_loop_fwd (key : usize) (value : 't) (ls : 't list_t) : bool result = (case ls of @@ -109,14 +111,14 @@ val [hash_map_insert_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_insert_in_list_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap::HashMap::{0}::insert_in_list]: forward function *) hash_map_insert_in_list_fwd (key : usize) (value : 't) (ls : 't list_t) : bool result = hash_map_insert_in_list_loop_fwd key value ls ’ val [hash_map_insert_in_list_loop_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) hash_map_insert_in_list_loop_back (key : usize) (value : 't) (ls : 't list_t) : 't list_t result = (case ls of @@ -132,14 +134,15 @@ val [hash_map_insert_in_list_loop_back_def] = DefineDiv ‘ ’ val hash_map_insert_in_list_back_def = Define ‘ - (** [hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) hash_map_insert_in_list_back (key : usize) (value : 't) (ls : 't list_t) : 't list_t result = hash_map_insert_in_list_loop_back key value ls ’ val hash_map_insert_no_resize_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::insert_no_resize] *) + (** [hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_insert_no_resize_fwd_back (self : 't hash_map_t) (key : usize) (value : 't) : 't hash_map_t result = do @@ -176,7 +179,8 @@ Definition core_num_u32_max_c_def: End val [hash_map_move_elements_from_list_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::move_elements_from_list] *) + (** [hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_move_elements_from_list_loop_fwd_back (ntable : 't hash_map_t) (ls : 't list_t) : 't hash_map_t result = (case ls of @@ -189,14 +193,16 @@ val [hash_map_move_elements_from_list_loop_fwd_back_def] = DefineDiv ‘ ’ val hash_map_move_elements_from_list_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::move_elements_from_list] *) + (** [hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_move_elements_from_list_fwd_back (ntable : 't hash_map_t) (ls : 't list_t) : 't hash_map_t result = hash_map_move_elements_from_list_loop_fwd_back ntable ls ’ val [hash_map_move_elements_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::move_elements] *) + (** [hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_move_elements_loop_fwd_back (ntable : 't hash_map_t) (slots : 't list_t vec) (i : usize) : ('t hash_map_t # 't list_t vec) result @@ -221,7 +227,8 @@ val [hash_map_move_elements_loop_fwd_back_def] = DefineDiv ‘ ’ val hash_map_move_elements_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::move_elements] *) + (** [hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_move_elements_fwd_back (ntable : 't hash_map_t) (slots : 't list_t vec) (i : usize) : ('t hash_map_t # 't list_t vec) result @@ -230,7 +237,8 @@ val hash_map_move_elements_fwd_back_def = Define ‘ ’ val hash_map_try_resize_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::try_resize] *) + (** [hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_try_resize_fwd_back (self : 't hash_map_t) : 't hash_map_t result = do max_usize <- mk_usize (u32_to_int core_num_u32_max_c); @@ -263,7 +271,8 @@ val hash_map_try_resize_fwd_back_def = Define ‘ ’ val hash_map_insert_fwd_back_def = Define ‘ - (** [hashmap::HashMap::{0}::insert] *) + (** [hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hash_map_insert_fwd_back (self : 't hash_map_t) (key : usize) (value : 't) : 't hash_map_t result = do @@ -276,7 +285,7 @@ val hash_map_insert_fwd_back_def = Define ‘ ’ val [hash_map_contains_key_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::contains_key_in_list] *) + (** [hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) hash_map_contains_key_in_list_loop_fwd (key : usize) (ls : 't list_t) : bool result = (case ls of @@ -288,14 +297,14 @@ val [hash_map_contains_key_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_contains_key_in_list_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::contains_key_in_list] *) + (** [hashmap::HashMap::{0}::contains_key_in_list]: forward function *) hash_map_contains_key_in_list_fwd (key : usize) (ls : 't list_t) : bool result = hash_map_contains_key_in_list_loop_fwd key ls ’ val hash_map_contains_key_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::contains_key] *) + (** [hashmap::HashMap::{0}::contains_key]: forward function *) hash_map_contains_key_fwd (self : 't hash_map_t) (key : usize) : bool result = do @@ -310,7 +319,7 @@ val hash_map_contains_key_fwd_def = Define ‘ ’ val [hash_map_get_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::get_in_list] *) + (** [hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) hash_map_get_in_list_loop_fwd (key : usize) (ls : 't list_t) : 't result = (case ls of | ListCons ckey cvalue tl => @@ -321,13 +330,13 @@ val [hash_map_get_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_get_in_list_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::get_in_list] *) + (** [hashmap::HashMap::{0}::get_in_list]: forward function *) hash_map_get_in_list_fwd (key : usize) (ls : 't list_t) : 't result = hash_map_get_in_list_loop_fwd key ls ’ val hash_map_get_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::get] *) + (** [hashmap::HashMap::{0}::get]: forward function *) hash_map_get_fwd (self : 't hash_map_t) (key : usize) : 't result = do hash <- hash_key_fwd key; @@ -341,7 +350,7 @@ val hash_map_get_fwd_def = Define ‘ ’ val [hash_map_get_mut_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) hash_map_get_mut_in_list_loop_fwd (ls : 't list_t) (key : usize) : 't result = (case ls of @@ -353,13 +362,13 @@ val [hash_map_get_mut_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_get_mut_in_list_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap::HashMap::{0}::get_mut_in_list]: forward function *) hash_map_get_mut_in_list_fwd (ls : 't list_t) (key : usize) : 't result = hash_map_get_mut_in_list_loop_fwd ls key ’ val [hash_map_get_mut_in_list_loop_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) hash_map_get_mut_in_list_loop_back (ls : 't list_t) (key : usize) (ret : 't) : 't list_t result = (case ls of @@ -375,14 +384,14 @@ val [hash_map_get_mut_in_list_loop_back_def] = DefineDiv ‘ ’ val hash_map_get_mut_in_list_back_def = Define ‘ - (** [hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) hash_map_get_mut_in_list_back (ls : 't list_t) (key : usize) (ret : 't) : 't list_t result = hash_map_get_mut_in_list_loop_back ls key ret ’ val hash_map_get_mut_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::get_mut] *) + (** [hashmap::HashMap::{0}::get_mut]: forward function *) hash_map_get_mut_fwd (self : 't hash_map_t) (key : usize) : 't result = do hash <- hash_key_fwd key; @@ -396,7 +405,7 @@ val hash_map_get_mut_fwd_def = Define ‘ ’ val hash_map_get_mut_back_def = Define ‘ - (** [hashmap::HashMap::{0}::get_mut] *) + (** [hashmap::HashMap::{0}::get_mut]: backward function 0 *) hash_map_get_mut_back (self : 't hash_map_t) (key : usize) (ret : 't) : 't hash_map_t result = do @@ -413,7 +422,7 @@ val hash_map_get_mut_back_def = Define ‘ ’ val [hash_map_remove_from_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) hash_map_remove_from_list_loop_fwd (key : usize) (ls : 't list_t) : 't option result = (case ls of @@ -429,14 +438,14 @@ val [hash_map_remove_from_list_loop_fwd_def] = DefineDiv ‘ ’ val hash_map_remove_from_list_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap::HashMap::{0}::remove_from_list]: forward function *) hash_map_remove_from_list_fwd (key : usize) (ls : 't list_t) : 't option result = hash_map_remove_from_list_loop_fwd key ls ’ val [hash_map_remove_from_list_loop_back_def] = DefineDiv ‘ - (** [hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) hash_map_remove_from_list_loop_back (key : usize) (ls : 't list_t) : 't list_t result = (case ls of @@ -456,14 +465,14 @@ val [hash_map_remove_from_list_loop_back_def] = DefineDiv ‘ ’ val hash_map_remove_from_list_back_def = Define ‘ - (** [hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) hash_map_remove_from_list_back (key : usize) (ls : 't list_t) : 't list_t result = hash_map_remove_from_list_loop_back key ls ’ val hash_map_remove_fwd_def = Define ‘ - (** [hashmap::HashMap::{0}::remove] *) + (** [hashmap::HashMap::{0}::remove]: forward function *) hash_map_remove_fwd (self : 't hash_map_t) (key : usize) : 't option result = do hash <- hash_key_fwd key; @@ -484,7 +493,7 @@ val hash_map_remove_fwd_def = Define ‘ ’ val hash_map_remove_back_def = Define ‘ - (** [hashmap::HashMap::{0}::remove] *) + (** [hashmap::HashMap::{0}::remove]: backward function 0 *) hash_map_remove_back (self : 't hash_map_t) (key : usize) : 't hash_map_t result = do @@ -513,7 +522,7 @@ val hash_map_remove_back_def = Define ‘ ’ val test1_fwd_def = Define ‘ - (** [hashmap::test1] *) + (** [hashmap::test1]: forward function *) test1_fwd : unit result = do hm <- hash_map_new_fwd; diff --git a/tests/hol4/hashmap_on_disk/hashmapMain_FunsScript.sml b/tests/hol4/hashmap_on_disk/hashmapMain_FunsScript.sml index 5a8f7ff8..6ec6223d 100644 --- a/tests/hol4/hashmap_on_disk/hashmapMain_FunsScript.sml +++ b/tests/hol4/hashmap_on_disk/hashmapMain_FunsScript.sml @@ -7,13 +7,13 @@ val _ = new_theory "hashmapMain_Funs" val hashmap_hash_key_fwd_def = Define ‘ - (** [hashmap_main::hashmap::hash_key] *) + (** [hashmap_main::hashmap::hash_key]: forward function *) hashmap_hash_key_fwd (k : usize) : usize result = Return k ’ val [hashmap_hash_map_allocate_slots_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) + (** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function *) hashmap_hash_map_allocate_slots_loop_fwd (slots : 't hashmap_list_t vec) (n : usize) : 't hashmap_list_t vec result @@ -29,7 +29,7 @@ val [hashmap_hash_map_allocate_slots_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_allocate_slots_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::allocate_slots] *) + (** [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: forward function *) hashmap_hash_map_allocate_slots_fwd (slots : 't hashmap_list_t vec) (n : usize) : 't hashmap_list_t vec result @@ -38,7 +38,7 @@ val hashmap_hash_map_allocate_slots_fwd_def = Define ‘ ’ val hashmap_hash_map_new_with_capacity_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] *) + (** [hashmap_main::hashmap::HashMap::{0}::new_with_capacity]: forward function *) hashmap_hash_map_new_with_capacity_fwd (capacity : usize) (max_load_dividend : usize) (max_load_divisor : usize) : 't hashmap_hash_map_t result @@ -60,14 +60,15 @@ val hashmap_hash_map_new_with_capacity_fwd_def = Define ‘ ’ val hashmap_hash_map_new_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::new] *) + (** [hashmap_main::hashmap::HashMap::{0}::new]: forward function *) hashmap_hash_map_new_fwd : 't hashmap_hash_map_t result = hashmap_hash_map_new_with_capacity_fwd (int_to_usize 32) (int_to_usize 4) (int_to_usize 5) ’ val [hashmap_hash_map_clear_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::clear] *) + (** [hashmap_main::hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_clear_loop_fwd_back (slots : 't hashmap_list_t vec) (i : usize) : 't hashmap_list_t vec result @@ -84,7 +85,8 @@ val [hashmap_hash_map_clear_loop_fwd_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_clear_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::clear] *) + (** [hashmap_main::hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_clear_fwd_back (self : 't hashmap_hash_map_t) : 't hashmap_hash_map_t result = do @@ -102,13 +104,13 @@ val hashmap_hash_map_clear_fwd_back_def = Define ‘ ’ val hashmap_hash_map_len_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::len] *) + (** [hashmap_main::hashmap::HashMap::{0}::len]: forward function *) hashmap_hash_map_len_fwd (self : 't hashmap_hash_map_t) : usize result = Return self.hashmap_hash_map_num_entries ’ val [hashmap_hash_map_insert_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function *) hashmap_hash_map_insert_in_list_loop_fwd (key : usize) (value : 't) (ls : 't hashmap_list_t) : bool result = (case ls of @@ -120,14 +122,14 @@ val [hashmap_hash_map_insert_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_insert_in_list_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: forward function *) hashmap_hash_map_insert_in_list_fwd (key : usize) (value : 't) (ls : 't hashmap_list_t) : bool result = hashmap_hash_map_insert_in_list_loop_fwd key value ls ’ val [hashmap_hash_map_insert_in_list_loop_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 *) hashmap_hash_map_insert_in_list_loop_back (key : usize) (value : 't) (ls : 't hashmap_list_t) : 't hashmap_list_t result @@ -146,7 +148,7 @@ val [hashmap_hash_map_insert_in_list_loop_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_insert_in_list_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: backward function 0 *) hashmap_hash_map_insert_in_list_back (key : usize) (value : 't) (ls : 't hashmap_list_t) : 't hashmap_list_t result @@ -155,7 +157,8 @@ val hashmap_hash_map_insert_in_list_back_def = Define ‘ ’ val hashmap_hash_map_insert_no_resize_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_insert_no_resize_fwd_back (self : 't hashmap_hash_map_t) (key : usize) (value : 't) : 't hashmap_hash_map_t result @@ -199,7 +202,8 @@ Definition core_num_u32_max_c_def: End val [hashmap_hash_map_move_elements_from_list_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_move_elements_from_list_loop_fwd_back (ntable : 't hashmap_hash_map_t) (ls : 't hashmap_list_t) : 't hashmap_hash_map_t result @@ -214,7 +218,8 @@ val [hashmap_hash_map_move_elements_from_list_loop_fwd_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_move_elements_from_list_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_move_elements_from_list_fwd_back (ntable : 't hashmap_hash_map_t) (ls : 't hashmap_list_t) : 't hashmap_hash_map_t result @@ -223,7 +228,8 @@ val hashmap_hash_map_move_elements_from_list_fwd_back_def = Define ‘ ’ val [hashmap_hash_map_move_elements_loop_fwd_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) + (** [hashmap_main::hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_move_elements_loop_fwd_back (ntable : 't hashmap_hash_map_t) (slots : 't hashmap_list_t vec) (i : usize) : @@ -249,7 +255,8 @@ val [hashmap_hash_map_move_elements_loop_fwd_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_move_elements_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::move_elements] *) + (** [hashmap_main::hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_move_elements_fwd_back (ntable : 't hashmap_hash_map_t) (slots : 't hashmap_list_t vec) (i : usize) : @@ -259,7 +266,8 @@ val hashmap_hash_map_move_elements_fwd_back_def = Define ‘ ’ val hashmap_hash_map_try_resize_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::try_resize] *) + (** [hashmap_main::hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_try_resize_fwd_back (self : 't hashmap_hash_map_t) : 't hashmap_hash_map_t result = do @@ -293,7 +301,8 @@ val hashmap_hash_map_try_resize_fwd_back_def = Define ‘ ’ val hashmap_hash_map_insert_fwd_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::insert] *) + (** [hashmap_main::hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) hashmap_hash_map_insert_fwd_back (self : 't hashmap_hash_map_t) (key : usize) (value : 't) : 't hashmap_hash_map_t result @@ -308,7 +317,7 @@ val hashmap_hash_map_insert_fwd_back_def = Define ‘ ’ val [hashmap_hash_map_contains_key_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function *) hashmap_hash_map_contains_key_in_list_loop_fwd (key : usize) (ls : 't hashmap_list_t) : bool result = (case ls of @@ -320,14 +329,14 @@ val [hashmap_hash_map_contains_key_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_contains_key_in_list_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: forward function *) hashmap_hash_map_contains_key_in_list_fwd (key : usize) (ls : 't hashmap_list_t) : bool result = hashmap_hash_map_contains_key_in_list_loop_fwd key ls ’ val hashmap_hash_map_contains_key_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::contains_key] *) + (** [hashmap_main::hashmap::HashMap::{0}::contains_key]: forward function *) hashmap_hash_map_contains_key_fwd (self : 't hashmap_hash_map_t) (key : usize) : bool result = do @@ -342,7 +351,7 @@ val hashmap_hash_map_contains_key_fwd_def = Define ‘ ’ val [hashmap_hash_map_get_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: loop 0: forward function *) hashmap_hash_map_get_in_list_loop_fwd (key : usize) (ls : 't hashmap_list_t) : 't result = (case ls of @@ -354,14 +363,14 @@ val [hashmap_hash_map_get_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_get_in_list_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_in_list]: forward function *) hashmap_hash_map_get_in_list_fwd (key : usize) (ls : 't hashmap_list_t) : 't result = hashmap_hash_map_get_in_list_loop_fwd key ls ’ val hashmap_hash_map_get_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get] *) + (** [hashmap_main::hashmap::HashMap::{0}::get]: forward function *) hashmap_hash_map_get_fwd (self : 't hashmap_hash_map_t) (key : usize) : 't result = do @@ -376,7 +385,7 @@ val hashmap_hash_map_get_fwd_def = Define ‘ ’ val [hashmap_hash_map_get_mut_in_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function *) hashmap_hash_map_get_mut_in_list_loop_fwd (ls : 't hashmap_list_t) (key : usize) : 't result = (case ls of @@ -388,14 +397,14 @@ val [hashmap_hash_map_get_mut_in_list_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_get_mut_in_list_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: forward function *) hashmap_hash_map_get_mut_in_list_fwd (ls : 't hashmap_list_t) (key : usize) : 't result = hashmap_hash_map_get_mut_in_list_loop_fwd ls key ’ val [hashmap_hash_map_get_mut_in_list_loop_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 *) hashmap_hash_map_get_mut_in_list_loop_back (ls : 't hashmap_list_t) (key : usize) (ret : 't) : 't hashmap_list_t result @@ -413,7 +422,7 @@ val [hashmap_hash_map_get_mut_in_list_loop_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_get_mut_in_list_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 *) hashmap_hash_map_get_mut_in_list_back (ls : 't hashmap_list_t) (key : usize) (ret : 't) : 't hashmap_list_t result @@ -422,7 +431,7 @@ val hashmap_hash_map_get_mut_in_list_back_def = Define ‘ ’ val hashmap_hash_map_get_mut_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut]: forward function *) hashmap_hash_map_get_mut_fwd (self : 't hashmap_hash_map_t) (key : usize) : 't result = do @@ -437,7 +446,7 @@ val hashmap_hash_map_get_mut_fwd_def = Define ‘ ’ val hashmap_hash_map_get_mut_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::get_mut] *) + (** [hashmap_main::hashmap::HashMap::{0}::get_mut]: backward function 0 *) hashmap_hash_map_get_mut_back (self : 't hashmap_hash_map_t) (key : usize) (ret : 't) : 't hashmap_hash_map_t result @@ -456,7 +465,7 @@ val hashmap_hash_map_get_mut_back_def = Define ‘ ’ val [hashmap_hash_map_remove_from_list_loop_fwd_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function *) hashmap_hash_map_remove_from_list_loop_fwd (key : usize) (ls : 't hashmap_list_t) : 't option result = (case ls of @@ -473,14 +482,14 @@ val [hashmap_hash_map_remove_from_list_loop_fwd_def] = DefineDiv ‘ ’ val hashmap_hash_map_remove_from_list_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: forward function *) hashmap_hash_map_remove_from_list_fwd (key : usize) (ls : 't hashmap_list_t) : 't option result = hashmap_hash_map_remove_from_list_loop_fwd key ls ’ val [hashmap_hash_map_remove_from_list_loop_back_def] = DefineDiv ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 *) hashmap_hash_map_remove_from_list_loop_back (key : usize) (ls : 't hashmap_list_t) : 't hashmap_list_t result = (case ls of @@ -501,14 +510,14 @@ val [hashmap_hash_map_remove_from_list_loop_back_def] = DefineDiv ‘ ’ val hashmap_hash_map_remove_from_list_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: backward function 1 *) hashmap_hash_map_remove_from_list_back (key : usize) (ls : 't hashmap_list_t) : 't hashmap_list_t result = hashmap_hash_map_remove_from_list_loop_back key ls ’ val hashmap_hash_map_remove_fwd_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove]: forward function *) hashmap_hash_map_remove_fwd (self : 't hashmap_hash_map_t) (key : usize) : 't option result = do @@ -530,7 +539,7 @@ val hashmap_hash_map_remove_fwd_def = Define ‘ ’ val hashmap_hash_map_remove_back_def = Define ‘ - (** [hashmap_main::hashmap::HashMap::{0}::remove] *) + (** [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 *) hashmap_hash_map_remove_back (self : 't hashmap_hash_map_t) (key : usize) : 't hashmap_hash_map_t result @@ -566,7 +575,7 @@ val hashmap_hash_map_remove_back_def = Define ‘ ’ val hashmap_test1_fwd_def = Define ‘ - (** [hashmap_main::hashmap::test1] *) + (** [hashmap_main::hashmap::test1]: forward function *) hashmap_test1_fwd : unit result = do hm <- hashmap_hash_map_new_fwd; @@ -623,7 +632,7 @@ val hashmap_test1_fwd_def = Define ‘ val _ = assert_return (“hashmap_test1_fwd”) val insert_on_disk_fwd_def = Define ‘ - (** [hashmap_main::insert_on_disk] *) + (** [hashmap_main::insert_on_disk]: forward function *) insert_on_disk_fwd (key : usize) (value : u64) (st : state) : (state # unit) result = do @@ -635,7 +644,7 @@ val insert_on_disk_fwd_def = Define ‘ ’ val main_fwd_def = Define ‘ - (** [hashmap_main::main] *) + (** [hashmap_main::main]: forward function *) main_fwd : unit result = Return () ’ diff --git a/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml b/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml index c38eca01..f7221d92 100644 --- a/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml +++ b/tests/hol4/hashmap_on_disk/hashmapMain_OpaqueScript.sml @@ -6,10 +6,10 @@ open hashmapMain_TypesTheory val _ = new_theory "hashmapMain_Opaque" -val _ = new_constant ("hashmap_utils_deserialize_fwd", +(** [hashmap_main::hashmap_utils::deserialize]: forward function *)val _ = new_constant ("hashmap_utils_deserialize_fwd", “:state -> (state # u64 hashmap_hash_map_t) result”) -val _ = new_constant ("hashmap_utils_serialize_fwd", +(** [hashmap_main::hashmap_utils::serialize]: forward function *)val _ = new_constant ("hashmap_utils_serialize_fwd", “:u64 hashmap_hash_map_t -> state -> (state # unit) result”) val _ = export_theory () diff --git a/tests/hol4/misc-constants/constantsScript.sml b/tests/hol4/misc-constants/constantsScript.sml index 324d553d..145c3e0f 100644 --- a/tests/hol4/misc-constants/constantsScript.sml +++ b/tests/hol4/misc-constants/constantsScript.sml @@ -38,7 +38,7 @@ Definition x2_c_def: End val incr_fwd_def = Define ‘ - (** [constants::incr] *) + (** [constants::incr]: forward function *) incr_fwd (n : u32) : u32 result = u32_add n (int_to_u32 1) ’ @@ -52,7 +52,7 @@ Definition x3_c_def: End val mk_pair0_fwd_def = Define ‘ - (** [constants::mk_pair0] *) + (** [constants::mk_pair0]: forward function *) mk_pair0_fwd (x : u32) (y : u32) : (u32 # u32) result = Return (x, y) ’ @@ -63,7 +63,7 @@ Datatype: End val mk_pair1_fwd_def = Define ‘ - (** [constants::mk_pair1] *) + (** [constants::mk_pair1]: forward function *) mk_pair1_fwd (x : u32) (y : u32) : (u32, u32) pair_t result = Return (<| pair_x := x; pair_y := y |>) ’ @@ -108,7 +108,7 @@ Datatype: End val wrap_new_fwd_def = Define ‘ - (** [constants::Wrap::{0}::new] *) + (** [constants::Wrap::{0}::new]: forward function *) wrap_new_fwd (val : 't) : 't wrap_t result = Return (<| wrap_val := val |>) ’ @@ -122,7 +122,7 @@ Definition y_c_def: End val unwrap_y_fwd_def = Define ‘ - (** [constants::unwrap_y] *) + (** [constants::unwrap_y]: forward function *) unwrap_y_fwd : i32 result = Return y_c.wrap_val ’ @@ -144,13 +144,13 @@ Definition get_z1_z1_c_def: End val get_z1_fwd_def = Define ‘ - (** [constants::get_z1] *) + (** [constants::get_z1]: forward function *) get_z1_fwd : i32 result = Return get_z1_z1_c ’ val add_fwd_def = Define ‘ - (** [constants::add] *) + (** [constants::add]: forward function *) add_fwd (a : i32) (b : i32) : i32 result = i32_add a b ’ @@ -180,7 +180,7 @@ Definition q3_c_def: End val get_z2_fwd_def = Define ‘ - (** [constants::get_z2] *) + (** [constants::get_z2]: forward function *) get_z2_fwd : i32 result = do i <- get_z1_fwd; diff --git a/tests/hol4/misc-external/external_FunsScript.sml b/tests/hol4/misc-external/external_FunsScript.sml index 8172bc1c..f3692ee2 100644 --- a/tests/hol4/misc-external/external_FunsScript.sml +++ b/tests/hol4/misc-external/external_FunsScript.sml @@ -7,7 +7,7 @@ val _ = new_theory "external_Funs" val swap_fwd_def = Define ‘ - (** [external::swap] *) + (** [external::swap]: forward function *) swap_fwd (x : 't) (y : 't) (st : state) : (state # unit) result = do (st0, _) <- core_mem_swap_fwd x y st; @@ -18,7 +18,7 @@ val swap_fwd_def = Define ‘ ’ val swap_back_def = Define ‘ - (** [external::swap] *) + (** [external::swap]: backward function 0 *) swap_back (x : 't) (y : 't) (st : state) (st0 : state) : (state # ('t # 't)) result = do @@ -30,7 +30,7 @@ val swap_back_def = Define ‘ ’ val test_new_non_zero_u32_fwd_def = Define ‘ - (** [external::test_new_non_zero_u32] *) + (** [external::test_new_non_zero_u32]: forward function *) test_new_non_zero_u32_fwd (x : u32) (st : state) : (state # core_num_nonzero_non_zero_u32_t) result = do @@ -40,7 +40,7 @@ val test_new_non_zero_u32_fwd_def = Define ‘ ’ val test_vec_fwd_def = Define ‘ - (** [external::test_vec] *) + (** [external::test_vec]: forward function *) test_vec_fwd : unit result = let v = vec_new in do _ <- vec_push_back v (int_to_u32 0); @@ -52,7 +52,7 @@ val test_vec_fwd_def = Define ‘ val _ = assert_return (“test_vec_fwd”) val custom_swap_fwd_def = Define ‘ - (** [external::custom_swap] *) + (** [external::custom_swap]: forward function *) custom_swap_fwd (x : 't) (y : 't) (st : state) : (state # 't) result = do (st0, _) <- core_mem_swap_fwd x y st; @@ -63,7 +63,7 @@ val custom_swap_fwd_def = Define ‘ ’ val custom_swap_back_def = Define ‘ - (** [external::custom_swap] *) + (** [external::custom_swap]: backward function 0 *) custom_swap_back (x : 't) (y : 't) (st : state) (ret : 't) (st0 : state) : (state # ('t # 't)) result @@ -77,7 +77,7 @@ val custom_swap_back_def = Define ‘ ’ val test_custom_swap_fwd_def = Define ‘ - (** [external::test_custom_swap] *) + (** [external::test_custom_swap]: forward function *) test_custom_swap_fwd (x : u32) (y : u32) (st : state) : (state # unit) result = do @@ -87,7 +87,7 @@ val test_custom_swap_fwd_def = Define ‘ ’ val test_custom_swap_back_def = Define ‘ - (** [external::test_custom_swap] *) + (** [external::test_custom_swap]: backward function 0 *) test_custom_swap_back (x : u32) (y : u32) (st : state) (st0 : state) : (state # (u32 # u32)) result @@ -96,7 +96,7 @@ val test_custom_swap_back_def = Define ‘ ’ val test_swap_non_zero_fwd_def = Define ‘ - (** [external::test_swap_non_zero] *) + (** [external::test_swap_non_zero]: forward function *) test_swap_non_zero_fwd (x : u32) (st : state) : (state # u32) result = do (st0, _) <- swap_fwd x (int_to_u32 0) st; diff --git a/tests/hol4/misc-external/external_OpaqueScript.sml b/tests/hol4/misc-external/external_OpaqueScript.sml index 02efc2be..b5a6d91d 100644 --- a/tests/hol4/misc-external/external_OpaqueScript.sml +++ b/tests/hol4/misc-external/external_OpaqueScript.sml @@ -6,20 +6,20 @@ open external_TypesTheory val _ = new_theory "external_Opaque" -val _ = new_constant ("core_mem_swap_fwd", +(** [core::mem::swap]: forward function *)val _ = new_constant ("core_mem_swap_fwd", “:'t -> 't -> state -> (state # unit) result”) -val _ = new_constant ("core_mem_swap_back0", +(** [core::mem::swap]: backward function 0 *)val _ = new_constant ("core_mem_swap_back0", “:'t -> 't -> state -> state -> (state # 't) result”) -val _ = new_constant ("core_mem_swap_back1", +(** [core::mem::swap]: backward function 1 *)val _ = new_constant ("core_mem_swap_back1", “:'t -> 't -> state -> state -> (state # 't) result”) -val _ = new_constant ("core_num_nonzero_non_zero_u32_new_fwd", +(** [core::num::nonzero::NonZeroU32::{14}::new]: forward function *)val _ = new_constant ("core_num_nonzero_non_zero_u32_new_fwd", “:u32 -> state -> (state # core_num_nonzero_non_zero_u32_t option) result”) -val _ = new_constant ("core_option_option_unwrap_fwd", +(** [core::option::Option::{0}::unwrap]: forward function *)val _ = new_constant ("core_option_option_unwrap_fwd", “:'t option -> state -> (state # 't) result”) val _ = export_theory () diff --git a/tests/hol4/misc-loops/loops_FunsScript.sml b/tests/hol4/misc-loops/loops_FunsScript.sml index f0ef036b..65cf77d4 100644 --- a/tests/hol4/misc-loops/loops_FunsScript.sml +++ b/tests/hol4/misc-loops/loops_FunsScript.sml @@ -7,7 +7,7 @@ val _ = new_theory "loops_Funs" val [sum_loop_fwd_def] = DefineDiv ‘ - (** [loops::sum] *) + (** [loops::sum]: loop 0: forward function *) sum_loop_fwd (max : u32) (i : u32) (s : u32) : u32 result = if u32_lt i max then ( @@ -20,13 +20,13 @@ val [sum_loop_fwd_def] = DefineDiv ‘ ’ val sum_fwd_def = Define ‘ - (** [loops::sum] *) + (** [loops::sum]: forward function *) sum_fwd (max : u32) : u32 result = sum_loop_fwd max (int_to_u32 0) (int_to_u32 0) ’ val [sum_with_mut_borrows_loop_fwd_def] = DefineDiv ‘ - (** [loops::sum_with_mut_borrows] *) + (** [loops::sum_with_mut_borrows]: loop 0: forward function *) sum_with_mut_borrows_loop_fwd (max : u32) (mi : u32) (ms : u32) : u32 result = if u32_lt mi max @@ -40,13 +40,13 @@ val [sum_with_mut_borrows_loop_fwd_def] = DefineDiv ‘ ’ val sum_with_mut_borrows_fwd_def = Define ‘ - (** [loops::sum_with_mut_borrows] *) + (** [loops::sum_with_mut_borrows]: forward function *) sum_with_mut_borrows_fwd (max : u32) : u32 result = sum_with_mut_borrows_loop_fwd max (int_to_u32 0) (int_to_u32 0) ’ val [sum_with_shared_borrows_loop_fwd_def] = DefineDiv ‘ - (** [loops::sum_with_shared_borrows] *) + (** [loops::sum_with_shared_borrows]: loop 0: forward function *) sum_with_shared_borrows_loop_fwd (max : u32) (i : u32) (s : u32) : u32 result = if u32_lt i max @@ -60,13 +60,14 @@ val [sum_with_shared_borrows_loop_fwd_def] = DefineDiv ‘ ’ val sum_with_shared_borrows_fwd_def = Define ‘ - (** [loops::sum_with_shared_borrows] *) + (** [loops::sum_with_shared_borrows]: forward function *) sum_with_shared_borrows_fwd (max : u32) : u32 result = sum_with_shared_borrows_loop_fwd max (int_to_u32 0) (int_to_u32 0) ’ val [clear_loop_fwd_back_def] = DefineDiv ‘ - (** [loops::clear] *) + (** [loops::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) clear_loop_fwd_back (v : u32 vec) (i : usize) : u32 vec result = let i0 = vec_len v in if usize_lt i i0 @@ -80,13 +81,14 @@ val [clear_loop_fwd_back_def] = DefineDiv ‘ ’ val clear_fwd_back_def = Define ‘ - (** [loops::clear] *) + (** [loops::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) clear_fwd_back (v : u32 vec) : u32 vec result = clear_loop_fwd_back v (int_to_usize 0) ’ val [list_mem_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_mem] *) + (** [loops::list_mem]: loop 0: forward function *) list_mem_loop_fwd (x : u32) (ls : u32 list_t) : bool result = (case ls of | ListCons y tl => if y = x then Return T else list_mem_loop_fwd x tl @@ -94,13 +96,13 @@ val [list_mem_loop_fwd_def] = DefineDiv ‘ ’ val list_mem_fwd_def = Define ‘ - (** [loops::list_mem] *) + (** [loops::list_mem]: forward function *) list_mem_fwd (x : u32) (ls : u32 list_t) : bool result = list_mem_loop_fwd x ls ’ val [list_nth_mut_loop_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop] *) + (** [loops::list_nth_mut_loop]: loop 0: forward function *) list_nth_mut_loop_loop_fwd (ls : 't list_t) (i : u32) : 't result = (case ls of | ListCons x tl => @@ -115,13 +117,13 @@ val [list_nth_mut_loop_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_loop_fwd_def = Define ‘ - (** [loops::list_nth_mut_loop] *) + (** [loops::list_nth_mut_loop]: forward function *) list_nth_mut_loop_fwd (ls : 't list_t) (i : u32) : 't result = list_nth_mut_loop_loop_fwd ls i ’ val [list_nth_mut_loop_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop] *) + (** [loops::list_nth_mut_loop]: loop 0: backward function 0 *) list_nth_mut_loop_loop_back (ls : 't list_t) (i : u32) (ret : 't) : 't list_t result = (case ls of @@ -138,14 +140,14 @@ val [list_nth_mut_loop_loop_back_def] = DefineDiv ‘ ’ val list_nth_mut_loop_back_def = Define ‘ - (** [loops::list_nth_mut_loop] *) + (** [loops::list_nth_mut_loop]: backward function 0 *) list_nth_mut_loop_back (ls : 't list_t) (i : u32) (ret : 't) : 't list_t result = list_nth_mut_loop_loop_back ls i ret ’ val [list_nth_shared_loop_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_loop] *) + (** [loops::list_nth_shared_loop]: loop 0: forward function *) list_nth_shared_loop_loop_fwd (ls : 't list_t) (i : u32) : 't result = (case ls of | ListCons x tl => @@ -160,13 +162,13 @@ val [list_nth_shared_loop_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_loop_fwd_def = Define ‘ - (** [loops::list_nth_shared_loop] *) + (** [loops::list_nth_shared_loop]: forward function *) list_nth_shared_loop_fwd (ls : 't list_t) (i : u32) : 't result = list_nth_shared_loop_loop_fwd ls i ’ val [get_elem_mut_loop_fwd_def] = DefineDiv ‘ - (** [loops::get_elem_mut] *) + (** [loops::get_elem_mut]: loop 0: forward function *) get_elem_mut_loop_fwd (x : usize) (ls : usize list_t) : usize result = (case ls of | ListCons y tl => if y = x then Return y else get_elem_mut_loop_fwd x tl @@ -174,7 +176,7 @@ val [get_elem_mut_loop_fwd_def] = DefineDiv ‘ ’ val get_elem_mut_fwd_def = Define ‘ - (** [loops::get_elem_mut] *) + (** [loops::get_elem_mut]: forward function *) get_elem_mut_fwd (slots : usize list_t vec) (x : usize) : usize result = do l <- vec_index_mut_fwd slots (int_to_usize 0); @@ -183,7 +185,7 @@ val get_elem_mut_fwd_def = Define ‘ ’ val [get_elem_mut_loop_back_def] = DefineDiv ‘ - (** [loops::get_elem_mut] *) + (** [loops::get_elem_mut]: loop 0: backward function 0 *) get_elem_mut_loop_back (x : usize) (ls : usize list_t) (ret : usize) : usize list_t result = (case ls of @@ -199,7 +201,7 @@ val [get_elem_mut_loop_back_def] = DefineDiv ‘ ’ val get_elem_mut_back_def = Define ‘ - (** [loops::get_elem_mut] *) + (** [loops::get_elem_mut]: backward function 0 *) get_elem_mut_back (slots : usize list_t vec) (x : usize) (ret : usize) : usize list_t vec result @@ -212,7 +214,7 @@ val get_elem_mut_back_def = Define ‘ ’ val [get_elem_shared_loop_fwd_def] = DefineDiv ‘ - (** [loops::get_elem_shared] *) + (** [loops::get_elem_shared]: loop 0: forward function *) get_elem_shared_loop_fwd (x : usize) (ls : usize list_t) : usize result = (case ls of | ListCons y tl => @@ -221,7 +223,7 @@ val [get_elem_shared_loop_fwd_def] = DefineDiv ‘ ’ val get_elem_shared_fwd_def = Define ‘ - (** [loops::get_elem_shared] *) + (** [loops::get_elem_shared]: forward function *) get_elem_shared_fwd (slots : usize list_t vec) (x : usize) : usize result = do l <- vec_index_fwd slots (int_to_usize 0); @@ -230,25 +232,25 @@ val get_elem_shared_fwd_def = Define ‘ ’ val id_mut_fwd_def = Define ‘ - (** [loops::id_mut] *) + (** [loops::id_mut]: forward function *) id_mut_fwd (ls : 't list_t) : 't list_t result = Return ls ’ val id_mut_back_def = Define ‘ - (** [loops::id_mut] *) + (** [loops::id_mut]: backward function 0 *) id_mut_back (ls : 't list_t) (ret : 't list_t) : 't list_t result = Return ret ’ val id_shared_fwd_def = Define ‘ - (** [loops::id_shared] *) + (** [loops::id_shared]: forward function *) id_shared_fwd (ls : 't list_t) : 't list_t result = Return ls ’ val [list_nth_mut_loop_with_id_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_with_id] *) + (** [loops::list_nth_mut_loop_with_id]: loop 0: forward function *) list_nth_mut_loop_with_id_loop_fwd (i : u32) (ls : 't list_t) : 't result = (case ls of | ListCons x tl => @@ -263,7 +265,7 @@ val [list_nth_mut_loop_with_id_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_loop_with_id_fwd_def = Define ‘ - (** [loops::list_nth_mut_loop_with_id] *) + (** [loops::list_nth_mut_loop_with_id]: forward function *) list_nth_mut_loop_with_id_fwd (ls : 't list_t) (i : u32) : 't result = do ls0 <- id_mut_fwd ls; @@ -272,7 +274,7 @@ val list_nth_mut_loop_with_id_fwd_def = Define ‘ ’ val [list_nth_mut_loop_with_id_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_with_id] *) + (** [loops::list_nth_mut_loop_with_id]: loop 0: backward function 0 *) list_nth_mut_loop_with_id_loop_back (i : u32) (ls : 't list_t) (ret : 't) : 't list_t result = (case ls of @@ -289,7 +291,7 @@ val [list_nth_mut_loop_with_id_loop_back_def] = DefineDiv ‘ ’ val list_nth_mut_loop_with_id_back_def = Define ‘ - (** [loops::list_nth_mut_loop_with_id] *) + (** [loops::list_nth_mut_loop_with_id]: backward function 0 *) list_nth_mut_loop_with_id_back (ls : 't list_t) (i : u32) (ret : 't) : 't list_t result = do @@ -300,7 +302,7 @@ val list_nth_mut_loop_with_id_back_def = Define ‘ ’ val [list_nth_shared_loop_with_id_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_loop_with_id] *) + (** [loops::list_nth_shared_loop_with_id]: loop 0: forward function *) list_nth_shared_loop_with_id_loop_fwd (i : u32) (ls : 't list_t) : 't result = (case ls of @@ -316,7 +318,7 @@ val [list_nth_shared_loop_with_id_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_loop_with_id_fwd_def = Define ‘ - (** [loops::list_nth_shared_loop_with_id] *) + (** [loops::list_nth_shared_loop_with_id]: forward function *) list_nth_shared_loop_with_id_fwd (ls : 't list_t) (i : u32) : 't result = do ls0 <- id_shared_fwd ls; @@ -325,7 +327,7 @@ val list_nth_shared_loop_with_id_fwd_def = Define ‘ ’ val [list_nth_mut_loop_pair_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: loop 0: forward function *) list_nth_mut_loop_pair_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -344,14 +346,14 @@ val [list_nth_mut_loop_pair_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_loop_pair_fwd_def = Define ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: forward function *) list_nth_mut_loop_pair_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_mut_loop_pair_loop_fwd ls0 ls1 i ’ val [list_nth_mut_loop_pair_loop_back'a_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: loop 0: backward function 0 *) list_nth_mut_loop_pair_loop_back'a (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -373,7 +375,7 @@ val [list_nth_mut_loop_pair_loop_back'a_def] = DefineDiv ‘ ’ val list_nth_mut_loop_pair_back'a_def = Define ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: backward function 0 *) list_nth_mut_loop_pair_back'a (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -382,7 +384,7 @@ val list_nth_mut_loop_pair_back'a_def = Define ‘ ’ val [list_nth_mut_loop_pair_loop_back'b_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: loop 0: backward function 1 *) list_nth_mut_loop_pair_loop_back'b (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -404,7 +406,7 @@ val [list_nth_mut_loop_pair_loop_back'b_def] = DefineDiv ‘ ’ val list_nth_mut_loop_pair_back'b_def = Define ‘ - (** [loops::list_nth_mut_loop_pair] *) + (** [loops::list_nth_mut_loop_pair]: backward function 1 *) list_nth_mut_loop_pair_back'b (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -413,7 +415,7 @@ val list_nth_mut_loop_pair_back'b_def = Define ‘ ’ val [list_nth_shared_loop_pair_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_loop_pair] *) + (** [loops::list_nth_shared_loop_pair]: loop 0: forward function *) list_nth_shared_loop_pair_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -432,14 +434,14 @@ val [list_nth_shared_loop_pair_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_loop_pair_fwd_def = Define ‘ - (** [loops::list_nth_shared_loop_pair] *) + (** [loops::list_nth_shared_loop_pair]: forward function *) list_nth_shared_loop_pair_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_shared_loop_pair_loop_fwd ls0 ls1 i ’ val [list_nth_mut_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_pair_merge] *) + (** [loops::list_nth_mut_loop_pair_merge]: loop 0: forward function *) list_nth_mut_loop_pair_merge_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -458,14 +460,14 @@ val [list_nth_mut_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_loop_pair_merge_fwd_def = Define ‘ - (** [loops::list_nth_mut_loop_pair_merge] *) + (** [loops::list_nth_mut_loop_pair_merge]: forward function *) list_nth_mut_loop_pair_merge_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_mut_loop_pair_merge_loop_fwd ls0 ls1 i ’ val [list_nth_mut_loop_pair_merge_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_mut_loop_pair_merge] *) + (** [loops::list_nth_mut_loop_pair_merge]: loop 0: backward function 0 *) list_nth_mut_loop_pair_merge_loop_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : ('t # 't)) : ('t list_t # 't list_t) result @@ -488,7 +490,7 @@ val [list_nth_mut_loop_pair_merge_loop_back_def] = DefineDiv ‘ ’ val list_nth_mut_loop_pair_merge_back_def = Define ‘ - (** [loops::list_nth_mut_loop_pair_merge] *) + (** [loops::list_nth_mut_loop_pair_merge]: backward function 0 *) list_nth_mut_loop_pair_merge_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : ('t # 't)) : ('t list_t # 't list_t) result @@ -497,7 +499,7 @@ val list_nth_mut_loop_pair_merge_back_def = Define ‘ ’ val [list_nth_shared_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_loop_pair_merge] *) + (** [loops::list_nth_shared_loop_pair_merge]: loop 0: forward function *) list_nth_shared_loop_pair_merge_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -516,14 +518,14 @@ val [list_nth_shared_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_loop_pair_merge_fwd_def = Define ‘ - (** [loops::list_nth_shared_loop_pair_merge] *) + (** [loops::list_nth_shared_loop_pair_merge]: forward function *) list_nth_shared_loop_pair_merge_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_shared_loop_pair_merge_loop_fwd ls0 ls1 i ’ val [list_nth_mut_shared_loop_pair_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_shared_loop_pair] *) + (** [loops::list_nth_mut_shared_loop_pair]: loop 0: forward function *) list_nth_mut_shared_loop_pair_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -542,14 +544,14 @@ val [list_nth_mut_shared_loop_pair_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_shared_loop_pair_fwd_def = Define ‘ - (** [loops::list_nth_mut_shared_loop_pair] *) + (** [loops::list_nth_mut_shared_loop_pair]: forward function *) list_nth_mut_shared_loop_pair_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_mut_shared_loop_pair_loop_fwd ls0 ls1 i ’ val [list_nth_mut_shared_loop_pair_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_mut_shared_loop_pair] *) + (** [loops::list_nth_mut_shared_loop_pair]: loop 0: backward function 0 *) list_nth_mut_shared_loop_pair_loop_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -571,7 +573,7 @@ val [list_nth_mut_shared_loop_pair_loop_back_def] = DefineDiv ‘ ’ val list_nth_mut_shared_loop_pair_back_def = Define ‘ - (** [loops::list_nth_mut_shared_loop_pair] *) + (** [loops::list_nth_mut_shared_loop_pair]: backward function 0 *) list_nth_mut_shared_loop_pair_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -580,7 +582,7 @@ val list_nth_mut_shared_loop_pair_back_def = Define ‘ ’ val [list_nth_mut_shared_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_mut_shared_loop_pair_merge] *) + (** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: forward function *) list_nth_mut_shared_loop_pair_merge_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -599,14 +601,14 @@ val [list_nth_mut_shared_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_mut_shared_loop_pair_merge_fwd_def = Define ‘ - (** [loops::list_nth_mut_shared_loop_pair_merge] *) + (** [loops::list_nth_mut_shared_loop_pair_merge]: forward function *) list_nth_mut_shared_loop_pair_merge_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_mut_shared_loop_pair_merge_loop_fwd ls0 ls1 i ’ val [list_nth_mut_shared_loop_pair_merge_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_mut_shared_loop_pair_merge] *) + (** [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: backward function 0 *) list_nth_mut_shared_loop_pair_merge_loop_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -628,7 +630,7 @@ val [list_nth_mut_shared_loop_pair_merge_loop_back_def] = DefineDiv ‘ ’ val list_nth_mut_shared_loop_pair_merge_back_def = Define ‘ - (** [loops::list_nth_mut_shared_loop_pair_merge] *) + (** [loops::list_nth_mut_shared_loop_pair_merge]: backward function 0 *) list_nth_mut_shared_loop_pair_merge_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -637,7 +639,7 @@ val list_nth_mut_shared_loop_pair_merge_back_def = Define ‘ ’ val [list_nth_shared_mut_loop_pair_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_mut_loop_pair] *) + (** [loops::list_nth_shared_mut_loop_pair]: loop 0: forward function *) list_nth_shared_mut_loop_pair_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -656,14 +658,14 @@ val [list_nth_shared_mut_loop_pair_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_mut_loop_pair_fwd_def = Define ‘ - (** [loops::list_nth_shared_mut_loop_pair] *) + (** [loops::list_nth_shared_mut_loop_pair]: forward function *) list_nth_shared_mut_loop_pair_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_shared_mut_loop_pair_loop_fwd ls0 ls1 i ’ val [list_nth_shared_mut_loop_pair_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_shared_mut_loop_pair] *) + (** [loops::list_nth_shared_mut_loop_pair]: loop 0: backward function 1 *) list_nth_shared_mut_loop_pair_loop_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -685,7 +687,7 @@ val [list_nth_shared_mut_loop_pair_loop_back_def] = DefineDiv ‘ ’ val list_nth_shared_mut_loop_pair_back_def = Define ‘ - (** [loops::list_nth_shared_mut_loop_pair] *) + (** [loops::list_nth_shared_mut_loop_pair]: backward function 1 *) list_nth_shared_mut_loop_pair_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -694,7 +696,7 @@ val list_nth_shared_mut_loop_pair_back_def = Define ‘ ’ val [list_nth_shared_mut_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ - (** [loops::list_nth_shared_mut_loop_pair_merge] *) + (** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: forward function *) list_nth_shared_mut_loop_pair_merge_loop_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = (case ls0 of @@ -713,14 +715,14 @@ val [list_nth_shared_mut_loop_pair_merge_loop_fwd_def] = DefineDiv ‘ ’ val list_nth_shared_mut_loop_pair_merge_fwd_def = Define ‘ - (** [loops::list_nth_shared_mut_loop_pair_merge] *) + (** [loops::list_nth_shared_mut_loop_pair_merge]: forward function *) list_nth_shared_mut_loop_pair_merge_fwd (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) : ('t # 't) result = list_nth_shared_mut_loop_pair_merge_loop_fwd ls0 ls1 i ’ val [list_nth_shared_mut_loop_pair_merge_loop_back_def] = DefineDiv ‘ - (** [loops::list_nth_shared_mut_loop_pair_merge] *) + (** [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: backward function 0 *) list_nth_shared_mut_loop_pair_merge_loop_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result @@ -742,7 +744,7 @@ val [list_nth_shared_mut_loop_pair_merge_loop_back_def] = DefineDiv ‘ ’ val list_nth_shared_mut_loop_pair_merge_back_def = Define ‘ - (** [loops::list_nth_shared_mut_loop_pair_merge] *) + (** [loops::list_nth_shared_mut_loop_pair_merge]: backward function 0 *) list_nth_shared_mut_loop_pair_merge_back (ls0 : 't list_t) (ls1 : 't list_t) (i : u32) (ret : 't) : 't list_t result diff --git a/tests/hol4/misc-no_nested_borrows/noNestedBorrowsScript.sml b/tests/hol4/misc-no_nested_borrows/noNestedBorrowsScript.sml index c8b106cd..66614c3f 100644 --- a/tests/hol4/misc-no_nested_borrows/noNestedBorrowsScript.sml +++ b/tests/hol4/misc-no_nested_borrows/noNestedBorrowsScript.sml @@ -38,49 +38,49 @@ Datatype: End val neg_test_fwd_def = Define ‘ - (** [no_nested_borrows::neg_test] *) + (** [no_nested_borrows::neg_test]: forward function *) neg_test_fwd (x : i32) : i32 result = i32_neg x ’ val add_test_fwd_def = Define ‘ - (** [no_nested_borrows::add_test] *) + (** [no_nested_borrows::add_test]: forward function *) add_test_fwd (x : u32) (y : u32) : u32 result = u32_add x y ’ val subs_test_fwd_def = Define ‘ - (** [no_nested_borrows::subs_test] *) + (** [no_nested_borrows::subs_test]: forward function *) subs_test_fwd (x : u32) (y : u32) : u32 result = u32_sub x y ’ val div_test_fwd_def = Define ‘ - (** [no_nested_borrows::div_test] *) + (** [no_nested_borrows::div_test]: forward function *) div_test_fwd (x : u32) (y : u32) : u32 result = u32_div x y ’ val div_test1_fwd_def = Define ‘ - (** [no_nested_borrows::div_test1] *) + (** [no_nested_borrows::div_test1]: forward function *) div_test1_fwd (x : u32) : u32 result = u32_div x (int_to_u32 2) ’ val rem_test_fwd_def = Define ‘ - (** [no_nested_borrows::rem_test] *) + (** [no_nested_borrows::rem_test]: forward function *) rem_test_fwd (x : u32) (y : u32) : u32 result = u32_rem x y ’ val cast_test_fwd_def = Define ‘ - (** [no_nested_borrows::cast_test] *) + (** [no_nested_borrows::cast_test]: forward function *) cast_test_fwd (x : u32) : i32 result = mk_i32 (u32_to_int x) ’ val test2_fwd_def = Define ‘ - (** [no_nested_borrows::test2] *) + (** [no_nested_borrows::test2]: forward function *) test2_fwd : unit result = do _ <- u32_add (int_to_u32 23) (int_to_u32 44); @@ -92,13 +92,13 @@ val test2_fwd_def = Define ‘ val _ = assert_return (“test2_fwd”) val get_max_fwd_def = Define ‘ - (** [no_nested_borrows::get_max] *) + (** [no_nested_borrows::get_max]: forward function *) get_max_fwd (x : u32) (y : u32) : u32 result = if u32_ge x y then Return x else Return y ’ val test3_fwd_def = Define ‘ - (** [no_nested_borrows::test3] *) + (** [no_nested_borrows::test3]: forward function *) test3_fwd : unit result = do x <- get_max_fwd (int_to_u32 4) (int_to_u32 3); @@ -112,7 +112,7 @@ val test3_fwd_def = Define ‘ val _ = assert_return (“test3_fwd”) val test_neg1_fwd_def = Define ‘ - (** [no_nested_borrows::test_neg1] *) + (** [no_nested_borrows::test_neg1]: forward function *) test_neg1_fwd : unit result = do y <- i32_neg (int_to_i32 3); @@ -124,7 +124,7 @@ val test_neg1_fwd_def = Define ‘ val _ = assert_return (“test_neg1_fwd”) val refs_test1_fwd_def = Define ‘ - (** [no_nested_borrows::refs_test1] *) + (** [no_nested_borrows::refs_test1]: forward function *) refs_test1_fwd : unit result = if ~ (int_to_i32 1 = int_to_i32 1) then Fail Failure else Return () ’ @@ -133,7 +133,7 @@ val refs_test1_fwd_def = Define ‘ val _ = assert_return (“refs_test1_fwd”) val refs_test2_fwd_def = Define ‘ - (** [no_nested_borrows::refs_test2] *) + (** [no_nested_borrows::refs_test2]: forward function *) refs_test2_fwd : unit result = if ~ (int_to_i32 2 = int_to_i32 2) then Fail Failure @@ -151,7 +151,7 @@ val refs_test2_fwd_def = Define ‘ val _ = assert_return (“refs_test2_fwd”) val test_list1_fwd_def = Define ‘ - (** [no_nested_borrows::test_list1] *) + (** [no_nested_borrows::test_list1]: forward function *) test_list1_fwd : unit result = Return () ’ @@ -160,7 +160,7 @@ val test_list1_fwd_def = Define ‘ val _ = assert_return (“test_list1_fwd”) val test_box1_fwd_def = Define ‘ - (** [no_nested_borrows::test_box1] *) + (** [no_nested_borrows::test_box1]: forward function *) test_box1_fwd : unit result = let b = int_to_i32 1 in let x = b in @@ -171,25 +171,25 @@ val test_box1_fwd_def = Define ‘ val _ = assert_return (“test_box1_fwd”) val copy_int_fwd_def = Define ‘ - (** [no_nested_borrows::copy_int] *) + (** [no_nested_borrows::copy_int]: forward function *) copy_int_fwd (x : i32) : i32 result = Return x ’ val test_unreachable_fwd_def = Define ‘ - (** [no_nested_borrows::test_unreachable] *) + (** [no_nested_borrows::test_unreachable]: forward function *) test_unreachable_fwd (b : bool) : unit result = if b then Fail Failure else Return () ’ val test_panic_fwd_def = Define ‘ - (** [no_nested_borrows::test_panic] *) + (** [no_nested_borrows::test_panic]: forward function *) test_panic_fwd (b : bool) : unit result = if b then Fail Failure else Return () ’ val test_copy_int_fwd_def = Define ‘ - (** [no_nested_borrows::test_copy_int] *) + (** [no_nested_borrows::test_copy_int]: forward function *) test_copy_int_fwd : unit result = do y <- copy_int_fwd (int_to_i32 0); @@ -201,13 +201,13 @@ val test_copy_int_fwd_def = Define ‘ val _ = assert_return (“test_copy_int_fwd”) val is_cons_fwd_def = Define ‘ - (** [no_nested_borrows::is_cons] *) + (** [no_nested_borrows::is_cons]: forward function *) is_cons_fwd (l : 't list_t) : bool result = (case l of | ListCons t l0 => Return T | ListNil => Return F) ’ val test_is_cons_fwd_def = Define ‘ - (** [no_nested_borrows::test_is_cons] *) + (** [no_nested_borrows::test_is_cons]: forward function *) test_is_cons_fwd : unit result = let l = ListNil in do @@ -220,13 +220,13 @@ val test_is_cons_fwd_def = Define ‘ val _ = assert_return (“test_is_cons_fwd”) val split_list_fwd_def = Define ‘ - (** [no_nested_borrows::split_list] *) + (** [no_nested_borrows::split_list]: forward function *) split_list_fwd (l : 't list_t) : ('t # 't list_t) result = (case l of | ListCons hd tl => Return (hd, tl) | ListNil => Fail Failure) ’ val test_split_list_fwd_def = Define ‘ - (** [no_nested_borrows::test_split_list] *) + (** [no_nested_borrows::test_split_list]: forward function *) test_split_list_fwd : unit result = let l = ListNil in do @@ -240,19 +240,19 @@ val test_split_list_fwd_def = Define ‘ val _ = assert_return (“test_split_list_fwd”) val choose_fwd_def = Define ‘ - (** [no_nested_borrows::choose] *) + (** [no_nested_borrows::choose]: forward function *) choose_fwd (b : bool) (x : 't) (y : 't) : 't result = if b then Return x else Return y ’ val choose_back_def = Define ‘ - (** [no_nested_borrows::choose] *) + (** [no_nested_borrows::choose]: backward function 0 *) choose_back (b : bool) (x : 't) (y : 't) (ret : 't) : ('t # 't) result = if b then Return (ret, y) else Return (x, ret) ’ val choose_test_fwd_def = Define ‘ - (** [no_nested_borrows::choose_test] *) + (** [no_nested_borrows::choose_test]: forward function *) choose_test_fwd : unit result = do z <- choose_fwd T (int_to_i32 0) (int_to_i32 0); @@ -273,7 +273,7 @@ val choose_test_fwd_def = Define ‘ val _ = assert_return (“choose_test_fwd”) val test_char_fwd_def = Define ‘ - (** [no_nested_borrows::test_char] *) + (** [no_nested_borrows::test_char]: forward function *) test_char_fwd : char result = Return #"a" ’ @@ -287,7 +287,7 @@ Datatype: End val [list_length_fwd_def] = DefineDiv ‘ - (** [no_nested_borrows::list_length] *) + (** [no_nested_borrows::list_length]: forward function *) list_length_fwd (l : 't list_t) : u32 result = (case l of | ListCons t l1 => do @@ -298,7 +298,7 @@ val [list_length_fwd_def] = DefineDiv ‘ ’ val [list_nth_shared_fwd_def] = DefineDiv ‘ - (** [no_nested_borrows::list_nth_shared] *) + (** [no_nested_borrows::list_nth_shared]: forward function *) list_nth_shared_fwd (l : 't list_t) (i : u32) : 't result = (case l of | ListCons x tl => @@ -312,7 +312,7 @@ val [list_nth_shared_fwd_def] = DefineDiv ‘ ’ val [list_nth_mut_fwd_def] = DefineDiv ‘ - (** [no_nested_borrows::list_nth_mut] *) + (** [no_nested_borrows::list_nth_mut]: forward function *) list_nth_mut_fwd (l : 't list_t) (i : u32) : 't result = (case l of | ListCons x tl => @@ -326,7 +326,7 @@ val [list_nth_mut_fwd_def] = DefineDiv ‘ ’ val [list_nth_mut_back_def] = DefineDiv ‘ - (** [no_nested_borrows::list_nth_mut] *) + (** [no_nested_borrows::list_nth_mut]: backward function 0 *) list_nth_mut_back (l : 't list_t) (i : u32) (ret : 't) : 't list_t result = (case l of | ListCons x tl => @@ -342,7 +342,7 @@ val [list_nth_mut_back_def] = DefineDiv ‘ ’ val [list_rev_aux_fwd_def] = DefineDiv ‘ - (** [no_nested_borrows::list_rev_aux] *) + (** [no_nested_borrows::list_rev_aux]: forward function *) list_rev_aux_fwd (li : 't list_t) (lo : 't list_t) : 't list_t result = (case li of | ListCons hd tl => list_rev_aux_fwd tl (ListCons hd lo) @@ -350,13 +350,14 @@ val [list_rev_aux_fwd_def] = DefineDiv ‘ ’ val list_rev_fwd_back_def = Define ‘ - (** [no_nested_borrows::list_rev] *) + (** [no_nested_borrows::list_rev]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) list_rev_fwd_back (l : 't list_t) : 't list_t result = let li = mem_replace_fwd l ListNil in list_rev_aux_fwd li ListNil ’ val test_list_functions_fwd_def = Define ‘ - (** [no_nested_borrows::test_list_functions] *) + (** [no_nested_borrows::test_list_functions]: forward function *) test_list_functions_fwd : unit result = let l = ListNil in let l0 = ListCons (int_to_i32 2) l in @@ -411,63 +412,63 @@ val test_list_functions_fwd_def = Define ‘ val _ = assert_return (“test_list_functions_fwd”) val id_mut_pair1_fwd_def = Define ‘ - (** [no_nested_borrows::id_mut_pair1] *) + (** [no_nested_borrows::id_mut_pair1]: forward function *) id_mut_pair1_fwd (x : 't1) (y : 't2) : ('t1 # 't2) result = Return (x, y) ’ val id_mut_pair1_back_def = Define ‘ - (** [no_nested_borrows::id_mut_pair1] *) + (** [no_nested_borrows::id_mut_pair1]: backward function 0 *) id_mut_pair1_back (x : 't1) (y : 't2) (ret : ('t1 # 't2)) : ('t1 # 't2) result = let (t, t0) = ret in Return (t, t0) ’ val id_mut_pair2_fwd_def = Define ‘ - (** [no_nested_borrows::id_mut_pair2] *) + (** [no_nested_borrows::id_mut_pair2]: forward function *) id_mut_pair2_fwd (p : ('t1 # 't2)) : ('t1 # 't2) result = let (t, t0) = p in Return (t, t0) ’ val id_mut_pair2_back_def = Define ‘ - (** [no_nested_borrows::id_mut_pair2] *) + (** [no_nested_borrows::id_mut_pair2]: backward function 0 *) id_mut_pair2_back (p : ('t1 # 't2)) (ret : ('t1 # 't2)) : ('t1 # 't2) result = let (t, t0) = ret in Return (t, t0) ’ val id_mut_pair3_fwd_def = Define ‘ - (** [no_nested_borrows::id_mut_pair3] *) + (** [no_nested_borrows::id_mut_pair3]: forward function *) id_mut_pair3_fwd (x : 't1) (y : 't2) : ('t1 # 't2) result = Return (x, y) ’ val id_mut_pair3_back'a_def = Define ‘ - (** [no_nested_borrows::id_mut_pair3] *) + (** [no_nested_borrows::id_mut_pair3]: backward function 0 *) id_mut_pair3_back'a (x : 't1) (y : 't2) (ret : 't1) : 't1 result = Return ret ’ val id_mut_pair3_back'b_def = Define ‘ - (** [no_nested_borrows::id_mut_pair3] *) + (** [no_nested_borrows::id_mut_pair3]: backward function 1 *) id_mut_pair3_back'b (x : 't1) (y : 't2) (ret : 't2) : 't2 result = Return ret ’ val id_mut_pair4_fwd_def = Define ‘ - (** [no_nested_borrows::id_mut_pair4] *) + (** [no_nested_borrows::id_mut_pair4]: forward function *) id_mut_pair4_fwd (p : ('t1 # 't2)) : ('t1 # 't2) result = let (t, t0) = p in Return (t, t0) ’ val id_mut_pair4_back'a_def = Define ‘ - (** [no_nested_borrows::id_mut_pair4] *) + (** [no_nested_borrows::id_mut_pair4]: backward function 0 *) id_mut_pair4_back'a (p : ('t1 # 't2)) (ret : 't1) : 't1 result = Return ret ’ val id_mut_pair4_back'b_def = Define ‘ - (** [no_nested_borrows::id_mut_pair4] *) + (** [no_nested_borrows::id_mut_pair4]: backward function 1 *) id_mut_pair4_back'b (p : ('t1 # 't2)) (ret : 't2) : 't2 result = Return ret ’ @@ -478,19 +479,19 @@ Datatype: End val new_tuple1_fwd_def = Define ‘ - (** [no_nested_borrows::new_tuple1] *) + (** [no_nested_borrows::new_tuple1]: forward function *) new_tuple1_fwd : (u32, u32) struct_with_tuple_t result = Return (<| struct_with_tuple_p := (int_to_u32 1, int_to_u32 2) |>) ’ val new_tuple2_fwd_def = Define ‘ - (** [no_nested_borrows::new_tuple2] *) + (** [no_nested_borrows::new_tuple2]: forward function *) new_tuple2_fwd : (i16, i16) struct_with_tuple_t result = Return (<| struct_with_tuple_p := (int_to_i16 1, int_to_i16 2) |>) ’ val new_tuple3_fwd_def = Define ‘ - (** [no_nested_borrows::new_tuple3] *) + (** [no_nested_borrows::new_tuple3]: forward function *) new_tuple3_fwd : (u64, i64) struct_with_tuple_t result = Return (<| struct_with_tuple_p := (int_to_u64 1, int_to_i64 2) |>) ’ @@ -501,7 +502,7 @@ Datatype: End val new_pair1_fwd_def = Define ‘ - (** [no_nested_borrows::new_pair1] *) + (** [no_nested_borrows::new_pair1]: forward function *) new_pair1_fwd : (u32, u32) struct_with_pair_t result = Return (<| @@ -511,7 +512,7 @@ val new_pair1_fwd_def = Define ‘ ’ val test_constants_fwd_def = Define ‘ - (** [no_nested_borrows::test_constants] *) + (** [no_nested_borrows::test_constants]: forward function *) test_constants_fwd : unit result = do swt <- new_tuple1_fwd; @@ -546,7 +547,7 @@ val test_constants_fwd_def = Define ‘ val _ = assert_return (“test_constants_fwd”) val test_weird_borrows1_fwd_def = Define ‘ - (** [no_nested_borrows::test_weird_borrows1] *) + (** [no_nested_borrows::test_weird_borrows1]: forward function *) test_weird_borrows1_fwd : unit result = Return () ’ @@ -555,26 +556,27 @@ val test_weird_borrows1_fwd_def = Define ‘ val _ = assert_return (“test_weird_borrows1_fwd”) val test_mem_replace_fwd_back_def = Define ‘ - (** [no_nested_borrows::test_mem_replace] *) + (** [no_nested_borrows::test_mem_replace]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) test_mem_replace_fwd_back (px : u32) : u32 result = let y = mem_replace_fwd px (int_to_u32 1) in if ~ (y = int_to_u32 0) then Fail Failure else Return (int_to_u32 2) ’ val test_shared_borrow_bool1_fwd_def = Define ‘ - (** [no_nested_borrows::test_shared_borrow_bool1] *) + (** [no_nested_borrows::test_shared_borrow_bool1]: forward function *) test_shared_borrow_bool1_fwd (b : bool) : u32 result = if b then Return (int_to_u32 0) else Return (int_to_u32 1) ’ val test_shared_borrow_bool2_fwd_def = Define ‘ - (** [no_nested_borrows::test_shared_borrow_bool2] *) + (** [no_nested_borrows::test_shared_borrow_bool2]: forward function *) test_shared_borrow_bool2_fwd : u32 result = Return (int_to_u32 0) ’ val test_shared_borrow_enum1_fwd_def = Define ‘ - (** [no_nested_borrows::test_shared_borrow_enum1] *) + (** [no_nested_borrows::test_shared_borrow_enum1]: forward function *) test_shared_borrow_enum1_fwd (l : u32 list_t) : u32 result = (case l of | ListCons i l0 => Return (int_to_u32 1) @@ -582,7 +584,7 @@ val test_shared_borrow_enum1_fwd_def = Define ‘ ’ val test_shared_borrow_enum2_fwd_def = Define ‘ - (** [no_nested_borrows::test_shared_borrow_enum2] *) + (** [no_nested_borrows::test_shared_borrow_enum2]: forward function *) test_shared_borrow_enum2_fwd : u32 result = Return (int_to_u32 0) ’ diff --git a/tests/hol4/misc-paper/paperScript.sml b/tests/hol4/misc-paper/paperScript.sml index 4d6e99ba..3ac5b6ca 100644 --- a/tests/hol4/misc-paper/paperScript.sml +++ b/tests/hol4/misc-paper/paperScript.sml @@ -6,13 +6,14 @@ val _ = new_theory "paper" val ref_incr_fwd_back_def = Define ‘ - (** [paper::ref_incr] *) + (** [paper::ref_incr]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) *) ref_incr_fwd_back (x : i32) : i32 result = i32_add x (int_to_i32 1) ’ val test_incr_fwd_def = Define ‘ - (** [paper::test_incr] *) + (** [paper::test_incr]: forward function *) test_incr_fwd : unit result = do x <- ref_incr_fwd_back (int_to_i32 0); @@ -24,19 +25,19 @@ val test_incr_fwd_def = Define ‘ val _ = assert_return (“test_incr_fwd”) val choose_fwd_def = Define ‘ - (** [paper::choose] *) + (** [paper::choose]: forward function *) choose_fwd (b : bool) (x : 't) (y : 't) : 't result = if b then Return x else Return y ’ val choose_back_def = Define ‘ - (** [paper::choose] *) + (** [paper::choose]: backward function 0 *) choose_back (b : bool) (x : 't) (y : 't) (ret : 't) : ('t # 't) result = if b then Return (ret, y) else Return (x, ret) ’ val test_choose_fwd_def = Define ‘ - (** [paper::test_choose] *) + (** [paper::test_choose]: forward function *) test_choose_fwd : unit result = do z <- choose_fwd T (int_to_i32 0) (int_to_i32 0); @@ -62,7 +63,7 @@ Datatype: End val [list_nth_mut_fwd_def] = DefineDiv ‘ - (** [paper::list_nth_mut] *) + (** [paper::list_nth_mut]: forward function *) list_nth_mut_fwd (l : 't list_t) (i : u32) : 't result = (case l of | ListCons x tl => @@ -76,7 +77,7 @@ val [list_nth_mut_fwd_def] = DefineDiv ‘ ’ val [list_nth_mut_back_def] = DefineDiv ‘ - (** [paper::list_nth_mut] *) + (** [paper::list_nth_mut]: backward function 0 *) list_nth_mut_back (l : 't list_t) (i : u32) (ret : 't) : 't list_t result = (case l of | ListCons x tl => @@ -92,7 +93,7 @@ val [list_nth_mut_back_def] = DefineDiv ‘ ’ val [sum_fwd_def] = DefineDiv ‘ - (** [paper::sum] *) + (** [paper::sum]: forward function *) sum_fwd (l : i32 list_t) : i32 result = (case l of | ListCons x tl => do @@ -103,7 +104,7 @@ val [sum_fwd_def] = DefineDiv ‘ ’ val test_nth_fwd_def = Define ‘ - (** [paper::test_nth] *) + (** [paper::test_nth]: forward function *) test_nth_fwd : unit result = let l = ListNil in let l0 = ListCons (int_to_i32 3) l in @@ -121,7 +122,7 @@ val test_nth_fwd_def = Define ‘ val _ = assert_return (“test_nth_fwd”) val call_choose_fwd_def = Define ‘ - (** [paper::call_choose] *) + (** [paper::call_choose]: forward function *) call_choose_fwd (p : (u32 # u32)) : u32 result = let (px, py) = p in do diff --git a/tests/hol4/misc-polonius_list/poloniusListScript.sml b/tests/hol4/misc-polonius_list/poloniusListScript.sml index dd631169..06876ed4 100644 --- a/tests/hol4/misc-polonius_list/poloniusListScript.sml +++ b/tests/hol4/misc-polonius_list/poloniusListScript.sml @@ -11,7 +11,7 @@ Datatype: End val [get_list_at_x_fwd_def] = DefineDiv ‘ - (** [polonius_list::get_list_at_x] *) + (** [polonius_list::get_list_at_x]: forward function *) get_list_at_x_fwd (ls : u32 list_t) (x : u32) : u32 list_t result = (case ls of | ListCons hd tl => @@ -20,7 +20,7 @@ val [get_list_at_x_fwd_def] = DefineDiv ‘ ’ val [get_list_at_x_back_def] = DefineDiv ‘ - (** [polonius_list::get_list_at_x] *) + (** [polonius_list::get_list_at_x]: backward function 0 *) get_list_at_x_back (ls : u32 list_t) (x : u32) (ret : u32 list_t) : u32 list_t result = (case ls of diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index 074fff5e..41e4349e 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -6,60 +6,59 @@ import BetreeMain.FunsExternal open Primitives namespace betree_main -/- [betree_main::betree::load_internal_node] -/ -def betree.load_internal_node_fwd +/- [betree_main::betree::load_internal_node]: forward function -/ +def betree.load_internal_node (id : U64) (st : State) : Result (State × (betree.List (U64 × betree.Message))) := - betree_utils.load_internal_node_fwd id st + betree_utils.load_internal_node id st -/- [betree_main::betree::store_internal_node] -/ -def betree.store_internal_node_fwd +/- [betree_main::betree::store_internal_node]: forward function -/ +def betree.store_internal_node (id : U64) (content : betree.List (U64 × betree.Message)) (st : State) : Result (State × Unit) := do - let (st0, _) ← betree_utils.store_internal_node_fwd id content st + let (st0, _) ← betree_utils.store_internal_node id content st Result.ret (st0, ()) -/- [betree_main::betree::load_leaf_node] -/ -def betree.load_leaf_node_fwd +/- [betree_main::betree::load_leaf_node]: forward function -/ +def betree.load_leaf_node (id : U64) (st : State) : Result (State × (betree.List (U64 × U64))) := - betree_utils.load_leaf_node_fwd id st + betree_utils.load_leaf_node id st -/- [betree_main::betree::store_leaf_node] -/ -def betree.store_leaf_node_fwd +/- [betree_main::betree::store_leaf_node]: forward function -/ +def betree.store_leaf_node (id : U64) (content : betree.List (U64 × U64)) (st : State) : Result (State × Unit) := do - let (st0, _) ← betree_utils.store_leaf_node_fwd id content st + let (st0, _) ← betree_utils.store_leaf_node id content st Result.ret (st0, ()) -/- [betree_main::betree::fresh_node_id] -/ -def betree.fresh_node_id_fwd (counter : U64) : Result U64 := +/- [betree_main::betree::fresh_node_id]: forward function -/ +def betree.fresh_node_id (counter : U64) : Result U64 := do let _ ← counter + (U64.ofInt 1 (by intlit)) Result.ret counter -/- [betree_main::betree::fresh_node_id] -/ +/- [betree_main::betree::fresh_node_id]: backward function 0 -/ def betree.fresh_node_id_back (counter : U64) : Result U64 := counter + (U64.ofInt 1 (by intlit)) -/- [betree_main::betree::NodeIdCounter::{0}::new] -/ -def betree.NodeIdCounter.new_fwd : Result betree.NodeIdCounter := +/- [betree_main::betree::NodeIdCounter::{0}::new]: forward function -/ +def betree.NodeIdCounter.new : Result betree.NodeIdCounter := Result.ret { betree_node_id_counter_next_node_id := (U64.ofInt 0 (by intlit)) } -/- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ -def betree.NodeIdCounter.fresh_id_fwd - (self : betree.NodeIdCounter) : Result U64 := +/- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function -/ +def betree.NodeIdCounter.fresh_id (self : betree.NodeIdCounter) : Result U64 := do let _ ← self.betree_node_id_counter_next_node_id + (U64.ofInt 1 (by intlit)) Result.ret self.betree_node_id_counter_next_node_id -/- [betree_main::betree::NodeIdCounter::{0}::fresh_id] -/ +/- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 -/ def betree.NodeIdCounter.fresh_id_back (self : betree.NodeIdCounter) : Result betree.NodeIdCounter := do @@ -72,8 +71,8 @@ def core_num_u64_max_body : Result U64 := Result.ret (U64.ofInt 18446744073709551615 (by intlit)) def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) -/- [betree_main::betree::upsert_update] -/ -def betree.upsert_update_fwd +/- [betree_main::betree::upsert_update]: forward function -/ +def betree.upsert_update (prev : Option U64) (st : betree.UpsertFunState) : Result U64 := match prev with | Option.none => @@ -93,18 +92,17 @@ def betree.upsert_update_fwd then prev0 - v else Result.ret (U64.ofInt 0 (by intlit)) -/- [betree_main::betree::List::{1}::len] -/ -divergent def betree.List.len_fwd - (T : Type) (self : betree.List T) : Result U64 := +/- [betree_main::betree::List::{1}::len]: forward function -/ +divergent def betree.List.len (T : Type) (self : betree.List T) : Result U64 := match self with | betree.List.Cons t tl => do - let i ← betree.List.len_fwd T tl + let i ← betree.List.len T tl (U64.ofInt 1 (by intlit)) + i | betree.List.Nil => Result.ret (U64.ofInt 0 (by intlit)) -/- [betree_main::betree::List::{1}::split_at] -/ -divergent def betree.List.split_at_fwd +/- [betree_main::betree::List::{1}::split_at]: forward function -/ +divergent def betree.List.split_at (T : Type) (self : betree.List T) (n : U64) : Result ((betree.List T) × (betree.List T)) := @@ -115,50 +113,51 @@ divergent def betree.List.split_at_fwd | betree.List.Cons hd tl => do let i ← n - (U64.ofInt 1 (by intlit)) - let p ← betree.List.split_at_fwd T tl i + let p ← betree.List.split_at T tl i let (ls0, ls1) := p let l := ls0 Result.ret (betree.List.Cons hd l, ls1) | betree.List.Nil => Result.fail Error.panic -/- [betree_main::betree::List::{1}::push_front] -/ -def betree.List.push_front_fwd_back +/- [betree_main::betree::List::{1}::push_front]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def betree.List.push_front (T : Type) (self : betree.List T) (x : T) : Result (betree.List T) := - let tl := mem.replace_fwd (betree.List T) self betree.List.Nil + let tl := mem.replace (betree.List T) self betree.List.Nil let l := tl Result.ret (betree.List.Cons x l) -/- [betree_main::betree::List::{1}::pop_front] -/ -def betree.List.pop_front_fwd (T : Type) (self : betree.List T) : Result T := - let ls := mem.replace_fwd (betree.List T) self betree.List.Nil +/- [betree_main::betree::List::{1}::pop_front]: forward function -/ +def betree.List.pop_front (T : Type) (self : betree.List T) : Result T := + let ls := mem.replace (betree.List T) self betree.List.Nil match ls with | betree.List.Cons x tl => Result.ret x | betree.List.Nil => Result.fail Error.panic -/- [betree_main::betree::List::{1}::pop_front] -/ +/- [betree_main::betree::List::{1}::pop_front]: backward function 0 -/ def betree.List.pop_front_back (T : Type) (self : betree.List T) : Result (betree.List T) := - let ls := mem.replace_fwd (betree.List T) self betree.List.Nil + let ls := mem.replace (betree.List T) self betree.List.Nil match ls with | betree.List.Cons x tl => Result.ret tl | betree.List.Nil => Result.fail Error.panic -/- [betree_main::betree::List::{1}::hd] -/ -def betree.List.hd_fwd (T : Type) (self : betree.List T) : Result T := +/- [betree_main::betree::List::{1}::hd]: forward function -/ +def betree.List.hd (T : Type) (self : betree.List T) : Result T := match self with | betree.List.Cons hd l => Result.ret hd | betree.List.Nil => Result.fail Error.panic -/- [betree_main::betree::List::{2}::head_has_key] -/ -def betree.List.head_has_key_fwd +/- [betree_main::betree::List::{2}::head_has_key]: forward function -/ +def betree.List.head_has_key (T : Type) (self : betree.List (U64 × T)) (key : U64) : Result Bool := match self with | betree.List.Cons hd l => let (i, _) := hd Result.ret (i = key) | betree.List.Nil => Result.ret false -/- [betree_main::betree::List::{2}::partition_at_pivot] -/ -divergent def betree.List.partition_at_pivot_fwd +/- [betree_main::betree::List::{2}::partition_at_pivot]: forward function -/ +divergent def betree.List.partition_at_pivot (T : Type) (self : betree.List (U64 × T)) (pivot : U64) : Result ((betree.List (U64 × T)) × (betree.List (U64 × T))) := @@ -169,30 +168,29 @@ divergent def betree.List.partition_at_pivot_fwd then Result.ret (betree.List.Nil, betree.List.Cons (i, t) tl) else do - let p ← betree.List.partition_at_pivot_fwd T tl pivot + let p ← betree.List.partition_at_pivot T tl pivot let (ls0, ls1) := p let l := ls0 Result.ret (betree.List.Cons (i, t) l, ls1) | betree.List.Nil => Result.ret (betree.List.Nil, betree.List.Nil) -/- [betree_main::betree::Leaf::{3}::split] -/ -def betree.Leaf.split_fwd +/- [betree_main::betree::Leaf::{3}::split]: forward function -/ +def betree.Leaf.split (self : betree.Leaf) (content : betree.List (U64 × U64)) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (st : State) : Result (State × betree.Internal) := do let p ← - betree.List.split_at_fwd (U64 × U64) content - params.betree_params_split_size + betree.List.split_at (U64 × U64) content params.betree_params_split_size let (content0, content1) := p - let p0 ← betree.List.hd_fwd (U64 × U64) content1 + let p0 ← betree.List.hd (U64 × U64) content1 let (pivot, _) := p0 - let id0 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt + let id0 ← betree.NodeIdCounter.fresh_id node_id_cnt let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt - let id1 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt0 - let (st0, _) ← betree.store_leaf_node_fwd id0 content0 st - let (st1, _) ← betree.store_leaf_node_fwd id1 content1 st0 + let id1 ← betree.NodeIdCounter.fresh_id node_id_cnt0 + let (st0, _) ← betree.store_leaf_node id0 content0 st + let (st1, _) ← betree.store_leaf_node id1 content1 st0 let n := betree.Node.Leaf { betree_leaf_id := id0, @@ -205,7 +203,7 @@ def betree.Leaf.split_fwd } Result.ret (st1, betree.Internal.mk self.betree_leaf_id pivot n n0) -/- [betree_main::betree::Leaf::{3}::split] -/ +/- [betree_main::betree::Leaf::{3}::split]: backward function 2 -/ def betree.Leaf.split_back (self : betree.Leaf) (content : betree.List (U64 × U64)) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (st : State) : @@ -213,19 +211,18 @@ def betree.Leaf.split_back := do let p ← - betree.List.split_at_fwd (U64 × U64) content - params.betree_params_split_size + betree.List.split_at (U64 × U64) content params.betree_params_split_size let (content0, content1) := p - let _ ← betree.List.hd_fwd (U64 × U64) content1 - let id0 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt + let _ ← betree.List.hd (U64 × U64) content1 + let id0 ← betree.NodeIdCounter.fresh_id node_id_cnt let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt - let id1 ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt0 - let (st0, _) ← betree.store_leaf_node_fwd id0 content0 st - let _ ← betree.store_leaf_node_fwd id1 content1 st0 + let id1 ← betree.NodeIdCounter.fresh_id node_id_cnt0 + let (st0, _) ← betree.store_leaf_node id0 content0 st + let _ ← betree.store_leaf_node id1 content1 st0 betree.NodeIdCounter.fresh_id_back node_id_cnt0 -/- [betree_main::betree::Node::{5}::lookup_in_bindings] -/ -divergent def betree.Node.lookup_in_bindings_fwd +/- [betree_main::betree::Node::{5}::lookup_in_bindings]: forward function -/ +divergent def betree.Node.lookup_in_bindings (key : U64) (bindings : betree.List (U64 × U64)) : Result (Option U64) := match bindings with | betree.List.Cons hd tl => @@ -235,11 +232,11 @@ divergent def betree.Node.lookup_in_bindings_fwd else if i > key then Result.ret Option.none - else betree.Node.lookup_in_bindings_fwd key tl + else betree.Node.lookup_in_bindings key tl | betree.List.Nil => Result.ret Option.none -/- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ -divergent def betree.Node.lookup_first_message_for_key_fwd +/- [betree_main::betree::Node::{5}::lookup_first_message_for_key]: forward function -/ +divergent def betree.Node.lookup_first_message_for_key (key : U64) (msgs : betree.List (U64 × betree.Message)) : Result (betree.List (U64 × betree.Message)) := @@ -248,10 +245,10 @@ divergent def betree.Node.lookup_first_message_for_key_fwd let (i, m) := x if i >= key then Result.ret (betree.List.Cons (i, m) next_msgs) - else betree.Node.lookup_first_message_for_key_fwd key next_msgs + else betree.Node.lookup_first_message_for_key key next_msgs | betree.List.Nil => Result.ret betree.List.Nil -/- [betree_main::betree::Node::{5}::lookup_first_message_for_key] -/ +/- [betree_main::betree::Node::{5}::lookup_first_message_for_key]: backward function 0 -/ divergent def betree.Node.lookup_first_message_for_key_back (key : U64) (msgs : betree.List (U64 × betree.Message)) (ret0 : betree.List (U64 × betree.Message)) : @@ -269,66 +266,66 @@ divergent def betree.Node.lookup_first_message_for_key_back Result.ret (betree.List.Cons (i, m) next_msgs0) | betree.List.Nil => Result.ret ret0 -/- [betree_main::betree::Node::{5}::apply_upserts] -/ -divergent def betree.Node.apply_upserts_fwd +/- [betree_main::betree::Node::{5}::apply_upserts]: forward function -/ +divergent def betree.Node.apply_upserts (msgs : betree.List (U64 × betree.Message)) (prev : Option U64) (key : U64) (st : State) : Result (State × U64) := do - let b ← betree.List.head_has_key_fwd betree.Message msgs key + let b ← betree.List.head_has_key betree.Message msgs key if b then do - let msg ← betree.List.pop_front_fwd (U64 × betree.Message) msgs + let msg ← betree.List.pop_front (U64 × betree.Message) msgs let (_, m) := msg match m with | betree.Message.Insert i => Result.fail Error.panic | betree.Message.Delete => Result.fail Error.panic | betree.Message.Upsert s => do - let v ← betree.upsert_update_fwd prev s + let v ← betree.upsert_update prev s let msgs0 ← betree.List.pop_front_back (U64 × betree.Message) msgs - betree.Node.apply_upserts_fwd msgs0 (Option.some v) key st + betree.Node.apply_upserts msgs0 (Option.some v) key st else do - let (st0, v) ← core.option.Option.unwrap_fwd U64 prev st + let (st0, v) ← core.option.Option.unwrap U64 prev st let _ ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs (key, + betree.List.push_front (U64 × betree.Message) msgs (key, betree.Message.Insert v) Result.ret (st0, v) -/- [betree_main::betree::Node::{5}::apply_upserts] -/ +/- [betree_main::betree::Node::{5}::apply_upserts]: backward function 0 -/ divergent def betree.Node.apply_upserts_back (msgs : betree.List (U64 × betree.Message)) (prev : Option U64) (key : U64) (st : State) : Result (betree.List (U64 × betree.Message)) := do - let b ← betree.List.head_has_key_fwd betree.Message msgs key + let b ← betree.List.head_has_key betree.Message msgs key if b then do - let msg ← betree.List.pop_front_fwd (U64 × betree.Message) msgs + let msg ← betree.List.pop_front (U64 × betree.Message) msgs let (_, m) := msg match m with | betree.Message.Insert i => Result.fail Error.panic | betree.Message.Delete => Result.fail Error.panic | betree.Message.Upsert s => do - let v ← betree.upsert_update_fwd prev s + let v ← betree.upsert_update prev s let msgs0 ← betree.List.pop_front_back (U64 × betree.Message) msgs betree.Node.apply_upserts_back msgs0 (Option.some v) key st else do - let (_, v) ← core.option.Option.unwrap_fwd U64 prev st - betree.List.push_front_fwd_back (U64 × betree.Message) msgs (key, + let (_, v) ← core.option.Option.unwrap U64 prev st + betree.List.push_front (U64 × betree.Message) msgs (key, betree.Message.Insert v) -/- [betree_main::betree::Node::{5}::lookup] -/ -mutual divergent def betree.Node.lookup_fwd +/- [betree_main::betree::Node::{5}::lookup]: forward function -/ +mutual divergent def betree.Node.lookup (self : betree.Node) (key : U64) (st : State) : Result (State × (Option U64)) := @@ -336,8 +333,8 @@ mutual divergent def betree.Node.lookup_fwd | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, msgs) ← betree.load_internal_node_fwd i st - let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs + let (st0, msgs) ← betree.load_internal_node i st + let pending ← betree.Node.lookup_first_message_for_key key msgs match pending with | betree.List.Cons p l => let (k, msg) := p @@ -345,8 +342,8 @@ mutual divergent def betree.Node.lookup_fwd then do let (st1, opt) ← - betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 n - n0) key st0 + betree.Internal.lookup_in_children (betree.Internal.mk i i0 n n0) + key st0 let _ ← betree.Node.lookup_first_message_for_key_back key msgs (betree.List.Cons (k, msg) l) @@ -368,10 +365,10 @@ mutual divergent def betree.Node.lookup_fwd | betree.Message.Upsert ufs => do let (st1, v) ← - betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 - n n0) key st0 + betree.Internal.lookup_in_children (betree.Internal.mk i i0 n + n0) key st0 let (st2, v0) ← - betree.Node.apply_upserts_fwd (betree.List.Cons (k, + betree.Node.apply_upserts (betree.List.Cons (k, betree.Message.Upsert ufs) l) v key st1 let node0 ← betree.Internal.lookup_in_children_back (betree.Internal.mk i @@ -382,32 +379,32 @@ mutual divergent def betree.Node.lookup_fwd betree.Message.Upsert ufs) l) v key st1 let msgs0 ← betree.Node.lookup_first_message_for_key_back key msgs pending0 - let (st3, _) ← betree.store_internal_node_fwd i1 msgs0 st2 + let (st3, _) ← betree.store_internal_node i1 msgs0 st2 Result.ret (st3, Option.some v0) | betree.List.Nil => do let (st1, opt) ← - betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 n - n0) key st0 + betree.Internal.lookup_in_children (betree.Internal.mk i i0 n n0) + key st0 let _ ← betree.Node.lookup_first_message_for_key_back key msgs betree.List.Nil Result.ret (st1, opt) | betree.Node.Leaf node => do - let (st0, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st - let opt ← betree.Node.lookup_in_bindings_fwd key bindings + let (st0, bindings) ← betree.load_leaf_node node.betree_leaf_id st + let opt ← betree.Node.lookup_in_bindings key bindings Result.ret (st0, opt) -/- [betree_main::betree::Node::{5}::lookup] -/ +/- [betree_main::betree::Node::{5}::lookup]: backward function 0 -/ divergent def betree.Node.lookup_back (self : betree.Node) (key : U64) (st : State) : Result betree.Node := match self with | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, msgs) ← betree.load_internal_node_fwd i st - let pending ← betree.Node.lookup_first_message_for_key_fwd key msgs + let (st0, msgs) ← betree.load_internal_node i st + let pending ← betree.Node.lookup_first_message_for_key key msgs match pending with | betree.List.Cons p l => let (k, msg) := p @@ -438,10 +435,10 @@ divergent def betree.Node.lookup_back | betree.Message.Upsert ufs => do let (st1, v) ← - betree.Internal.lookup_in_children_fwd (betree.Internal.mk i i0 - n n0) key st0 + betree.Internal.lookup_in_children (betree.Internal.mk i i0 n + n0) key st0 let (st2, _) ← - betree.Node.apply_upserts_fwd (betree.List.Cons (k, + betree.Node.apply_upserts (betree.List.Cons (k, betree.Message.Upsert ufs) l) v key st1 let node0 ← betree.Internal.lookup_in_children_back (betree.Internal.mk i @@ -452,7 +449,7 @@ divergent def betree.Node.lookup_back betree.Message.Upsert ufs) l) v key st1 let msgs0 ← betree.Node.lookup_first_message_for_key_back key msgs pending0 - let _ ← betree.store_internal_node_fwd i1 msgs0 st2 + let _ ← betree.store_internal_node i1 msgs0 st2 Result.ret (betree.Node.Internal (betree.Internal.mk i1 i2 n1 n2)) | betree.List.Nil => @@ -466,21 +463,21 @@ divergent def betree.Node.lookup_back Result.ret (betree.Node.Internal node0) | betree.Node.Leaf node => do - let (_, bindings) ← betree.load_leaf_node_fwd node.betree_leaf_id st - let _ ← betree.Node.lookup_in_bindings_fwd key bindings + let (_, bindings) ← betree.load_leaf_node node.betree_leaf_id st + let _ ← betree.Node.lookup_in_bindings key bindings Result.ret (betree.Node.Leaf node) -/- [betree_main::betree::Internal::{4}::lookup_in_children] -/ -divergent def betree.Internal.lookup_in_children_fwd +/- [betree_main::betree::Internal::{4}::lookup_in_children]: forward function -/ +divergent def betree.Internal.lookup_in_children (self : betree.Internal) (key : U64) (st : State) : Result (State × (Option U64)) := let ⟨ _, i, n, n0 ⟩ := self if key < i - then betree.Node.lookup_fwd n key st - else betree.Node.lookup_fwd n0 key st + then betree.Node.lookup n key st + else betree.Node.lookup n0 key st -/- [betree_main::betree::Internal::{4}::lookup_in_children] -/ +/- [betree_main::betree::Internal::{4}::lookup_in_children]: backward function 0 -/ divergent def betree.Internal.lookup_in_children_back (self : betree.Internal) (key : U64) (st : State) : Result betree.Internal := let ⟨ i, i0, n, n0 ⟩ := self @@ -496,8 +493,8 @@ divergent def betree.Internal.lookup_in_children_back end -/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ -divergent def betree.Node.lookup_mut_in_bindings_fwd +/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: forward function -/ +divergent def betree.Node.lookup_mut_in_bindings (key : U64) (bindings : betree.List (U64 × U64)) : Result (betree.List (U64 × U64)) := @@ -506,10 +503,10 @@ divergent def betree.Node.lookup_mut_in_bindings_fwd let (i, i0) := hd if i >= key then Result.ret (betree.List.Cons (i, i0) tl) - else betree.Node.lookup_mut_in_bindings_fwd key tl + else betree.Node.lookup_mut_in_bindings key tl | betree.List.Nil => Result.ret betree.List.Nil -/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings] -/ +/- [betree_main::betree::Node::{5}::lookup_mut_in_bindings]: backward function 0 -/ divergent def betree.Node.lookup_mut_in_bindings_back (key : U64) (bindings : betree.List (U64 × U64)) (ret0 : betree.List (U64 × U64)) : @@ -526,25 +523,26 @@ divergent def betree.Node.lookup_mut_in_bindings_back Result.ret (betree.List.Cons (i, i0) tl0) | betree.List.Nil => Result.ret ret0 -/- [betree_main::betree::Node::{5}::apply_to_leaf] -/ -def betree.Node.apply_to_leaf_fwd_back +/- [betree_main::betree::Node::{5}::apply_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def betree.Node.apply_to_leaf (bindings : betree.List (U64 × U64)) (key : U64) (new_msg : betree.Message) : Result (betree.List (U64 × U64)) := do - let bindings0 ← betree.Node.lookup_mut_in_bindings_fwd key bindings - let b ← betree.List.head_has_key_fwd U64 bindings0 key + let bindings0 ← betree.Node.lookup_mut_in_bindings key bindings + let b ← betree.List.head_has_key U64 bindings0 key if b then do - let hd ← betree.List.pop_front_fwd (U64 × U64) bindings0 + let hd ← betree.List.pop_front (U64 × U64) bindings0 match new_msg with | betree.Message.Insert v => do let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 let bindings2 ← - betree.List.push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree.List.push_front (U64 × U64) bindings1 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings2 | betree.Message.Delete => do @@ -553,29 +551,30 @@ def betree.Node.apply_to_leaf_fwd_back | betree.Message.Upsert s => do let (_, i) := hd - let v ← betree.upsert_update_fwd (Option.some i) s + let v ← betree.upsert_update (Option.some i) s let bindings1 ← betree.List.pop_front_back (U64 × U64) bindings0 let bindings2 ← - betree.List.push_front_fwd_back (U64 × U64) bindings1 (key, v) + betree.List.push_front (U64 × U64) bindings1 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings2 else match new_msg with | betree.Message.Insert v => do let bindings1 ← - betree.List.push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree.List.push_front (U64 × U64) bindings0 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings1 | betree.Message.Delete => betree.Node.lookup_mut_in_bindings_back key bindings bindings0 | betree.Message.Upsert s => do - let v ← betree.upsert_update_fwd Option.none s + let v ← betree.upsert_update Option.none s let bindings1 ← - betree.List.push_front_fwd_back (U64 × U64) bindings0 (key, v) + betree.List.push_front (U64 × U64) bindings0 (key, v) betree.Node.lookup_mut_in_bindings_back key bindings bindings1 -/- [betree_main::betree::Node::{5}::apply_messages_to_leaf] -/ -divergent def betree.Node.apply_messages_to_leaf_fwd_back +/- [betree_main::betree::Node::{5}::apply_messages_to_leaf]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def betree.Node.apply_messages_to_leaf (bindings : betree.List (U64 × U64)) (new_msgs : betree.List (U64 × betree.Message)) : Result (betree.List (U64 × U64)) @@ -584,12 +583,13 @@ divergent def betree.Node.apply_messages_to_leaf_fwd_back | betree.List.Cons new_msg new_msgs_tl => do let (i, m) := new_msg - let bindings0 ← betree.Node.apply_to_leaf_fwd_back bindings i m - betree.Node.apply_messages_to_leaf_fwd_back bindings0 new_msgs_tl + let bindings0 ← betree.Node.apply_to_leaf bindings i m + betree.Node.apply_messages_to_leaf bindings0 new_msgs_tl | betree.List.Nil => Result.ret bindings -/- [betree_main::betree::Node::{5}::filter_messages_for_key] -/ -divergent def betree.Node.filter_messages_for_key_fwd_back +/- [betree_main::betree::Node::{5}::filter_messages_for_key]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def betree.Node.filter_messages_for_key (key : U64) (msgs : betree.List (U64 × betree.Message)) : Result (betree.List (U64 × betree.Message)) := @@ -602,12 +602,12 @@ divergent def betree.Node.filter_messages_for_key_fwd_back let msgs0 ← betree.List.pop_front_back (U64 × betree.Message) (betree.List.Cons (k, m) l) - betree.Node.filter_messages_for_key_fwd_back key msgs0 + betree.Node.filter_messages_for_key key msgs0 else Result.ret (betree.List.Cons (k, m) l) | betree.List.Nil => Result.ret betree.List.Nil -/- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ -divergent def betree.Node.lookup_first_message_after_key_fwd +/- [betree_main::betree::Node::{5}::lookup_first_message_after_key]: forward function -/ +divergent def betree.Node.lookup_first_message_after_key (key : U64) (msgs : betree.List (U64 × betree.Message)) : Result (betree.List (U64 × betree.Message)) := @@ -615,11 +615,11 @@ divergent def betree.Node.lookup_first_message_after_key_fwd | betree.List.Cons p next_msgs => let (k, m) := p if k = key - then betree.Node.lookup_first_message_after_key_fwd key next_msgs + then betree.Node.lookup_first_message_after_key key next_msgs else Result.ret (betree.List.Cons (k, m) next_msgs) | betree.List.Nil => Result.ret betree.List.Nil -/- [betree_main::betree::Node::{5}::lookup_first_message_after_key] -/ +/- [betree_main::betree::Node::{5}::lookup_first_message_after_key]: backward function 0 -/ divergent def betree.Node.lookup_first_message_after_key_back (key : U64) (msgs : betree.List (U64 × betree.Message)) (ret0 : betree.List (U64 × betree.Message)) : @@ -637,74 +637,75 @@ divergent def betree.Node.lookup_first_message_after_key_back else Result.ret ret0 | betree.List.Nil => Result.ret ret0 -/- [betree_main::betree::Node::{5}::apply_to_internal] -/ -def betree.Node.apply_to_internal_fwd_back +/- [betree_main::betree::Node::{5}::apply_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def betree.Node.apply_to_internal (msgs : betree.List (U64 × betree.Message)) (key : U64) (new_msg : betree.Message) : Result (betree.List (U64 × betree.Message)) := do - let msgs0 ← betree.Node.lookup_first_message_for_key_fwd key msgs - let b ← betree.List.head_has_key_fwd betree.Message msgs0 key + let msgs0 ← betree.Node.lookup_first_message_for_key key msgs + let b ← betree.List.head_has_key betree.Message msgs0 key if b then match new_msg with | betree.Message.Insert i => do - let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 + let msgs1 ← betree.Node.filter_messages_for_key key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 (key, + betree.List.push_front (U64 × betree.Message) msgs1 (key, betree.Message.Insert i) betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree.Message.Delete => do - let msgs1 ← betree.Node.filter_messages_for_key_fwd_back key msgs0 + let msgs1 ← betree.Node.filter_messages_for_key key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 (key, + betree.List.push_front (U64 × betree.Message) msgs1 (key, betree.Message.Delete) betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree.Message.Upsert s => do - let p ← betree.List.hd_fwd (U64 × betree.Message) msgs0 + let p ← betree.List.hd (U64 × betree.Message) msgs0 let (_, m) := p match m with | betree.Message.Insert prev => do - let v ← betree.upsert_update_fwd (Option.some prev) s + let v ← betree.upsert_update (Option.some prev) s let msgs1 ← betree.List.pop_front_back (U64 × betree.Message) msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 - (key, betree.Message.Insert v) + betree.List.push_front (U64 × betree.Message) msgs1 (key, + betree.Message.Insert v) betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree.Message.Delete => do - let v ← betree.upsert_update_fwd Option.none s + let v ← betree.upsert_update Option.none s let msgs1 ← betree.List.pop_front_back (U64 × betree.Message) msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 - (key, betree.Message.Insert v) + betree.List.push_front (U64 × betree.Message) msgs1 (key, + betree.Message.Insert v) betree.Node.lookup_first_message_for_key_back key msgs msgs2 | betree.Message.Upsert ufs => do let msgs1 ← - betree.Node.lookup_first_message_after_key_fwd key msgs0 + betree.Node.lookup_first_message_after_key key msgs0 let msgs2 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs1 - (key, betree.Message.Upsert s) + betree.List.push_front (U64 × betree.Message) msgs1 (key, + betree.Message.Upsert s) let msgs3 ← betree.Node.lookup_first_message_after_key_back key msgs0 msgs2 betree.Node.lookup_first_message_for_key_back key msgs msgs3 else do let msgs1 ← - betree.List.push_front_fwd_back (U64 × betree.Message) msgs0 (key, - new_msg) + betree.List.push_front (U64 × betree.Message) msgs0 (key, new_msg) betree.Node.lookup_first_message_for_key_back key msgs msgs1 -/- [betree_main::betree::Node::{5}::apply_messages_to_internal] -/ -divergent def betree.Node.apply_messages_to_internal_fwd_back +/- [betree_main::betree::Node::{5}::apply_messages_to_internal]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def betree.Node.apply_messages_to_internal (msgs : betree.List (U64 × betree.Message)) (new_msgs : betree.List (U64 × betree.Message)) : Result (betree.List (U64 × betree.Message)) @@ -713,12 +714,12 @@ divergent def betree.Node.apply_messages_to_internal_fwd_back | betree.List.Cons new_msg new_msgs_tl => do let (i, m) := new_msg - let msgs0 ← betree.Node.apply_to_internal_fwd_back msgs i m - betree.Node.apply_messages_to_internal_fwd_back msgs0 new_msgs_tl + let msgs0 ← betree.Node.apply_to_internal msgs i m + betree.Node.apply_messages_to_internal msgs0 new_msgs_tl | betree.List.Nil => Result.ret msgs -/- [betree_main::betree::Node::{5}::apply_messages] -/ -mutual divergent def betree.Node.apply_messages_fwd +/- [betree_main::betree::Node::{5}::apply_messages]: forward function -/ +mutual divergent def betree.Node.apply_messages (self : betree.Node) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (msgs : betree.List (U64 × betree.Message)) (st : State) : @@ -728,47 +729,46 @@ mutual divergent def betree.Node.apply_messages_fwd | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, content) ← betree.load_internal_node_fwd i st - let content0 ← - betree.Node.apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree.List.len_fwd (U64 × betree.Message) content0 + let (st0, content) ← betree.load_internal_node i st + let content0 ← betree.Node.apply_messages_to_internal content msgs + let num_msgs ← betree.List.len (U64 × betree.Message) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree.Internal.flush_fwd (betree.Internal.mk i i0 n n0) params + betree.Internal.flush (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, _) ← betree.Internal.flush_back (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, _, _, _ ⟩ := node0 - let (st2, _) ← betree.store_internal_node_fwd i1 content1 st1 + let (st2, _) ← betree.store_internal_node i1 content1 st1 Result.ret (st2, ()) else do - let (st1, _) ← betree.store_internal_node_fwd i content0 st0 + let (st1, _) ← betree.store_internal_node i content0 st0 Result.ret (st1, ()) | betree.Node.Leaf node => do - let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st - let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs - let len ← betree.List.len_fwd (U64 × U64) content0 + let (st0, content) ← betree.load_leaf_node node.betree_leaf_id st + let content0 ← betree.Node.apply_messages_to_leaf content msgs + let len ← betree.List.len (U64 × U64) content0 let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size if len >= i then do let (st1, _) ← - betree.Leaf.split_fwd node content0 params node_id_cnt st0 + betree.Leaf.split node content0 params node_id_cnt st0 let (st2, _) ← - betree.store_leaf_node_fwd node.betree_leaf_id betree.List.Nil st1 + betree.store_leaf_node node.betree_leaf_id betree.List.Nil st1 Result.ret (st2, ()) else do let (st1, _) ← - betree.store_leaf_node_fwd node.betree_leaf_id content0 st0 + betree.store_leaf_node node.betree_leaf_id content0 st0 Result.ret (st1, ()) -/- [betree_main::betree::Node::{5}::apply_messages] -/ +/- [betree_main::betree::Node::{5}::apply_messages]: backward function 0 -/ divergent def betree.Node.apply_messages_back (self : betree.Node) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) @@ -779,52 +779,51 @@ divergent def betree.Node.apply_messages_back | betree.Node.Internal node => do let ⟨ i, i0, n, n0 ⟩ := node - let (st0, content) ← betree.load_internal_node_fwd i st - let content0 ← - betree.Node.apply_messages_to_internal_fwd_back content msgs - let num_msgs ← betree.List.len_fwd (U64 × betree.Message) content0 + let (st0, content) ← betree.load_internal_node i st + let content0 ← betree.Node.apply_messages_to_internal content msgs + let num_msgs ← betree.List.len (U64 × betree.Message) content0 if num_msgs >= params.betree_params_min_flush_size then do let (st1, content1) ← - betree.Internal.flush_fwd (betree.Internal.mk i i0 n n0) params + betree.Internal.flush (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let (node0, node_id_cnt0) ← betree.Internal.flush_back (betree.Internal.mk i i0 n n0) params node_id_cnt content0 st0 let ⟨ i1, i2, n1, n2 ⟩ := node0 - let _ ← betree.store_internal_node_fwd i1 content1 st1 + let _ ← betree.store_internal_node i1 content1 st1 Result.ret (betree.Node.Internal (betree.Internal.mk i1 i2 n1 n2), node_id_cnt0) else do - let _ ← betree.store_internal_node_fwd i content0 st0 + let _ ← betree.store_internal_node i content0 st0 Result.ret (betree.Node.Internal (betree.Internal.mk i i0 n n0), node_id_cnt) | betree.Node.Leaf node => do - let (st0, content) ← betree.load_leaf_node_fwd node.betree_leaf_id st - let content0 ← betree.Node.apply_messages_to_leaf_fwd_back content msgs - let len ← betree.List.len_fwd (U64 × U64) content0 + let (st0, content) ← betree.load_leaf_node node.betree_leaf_id st + let content0 ← betree.Node.apply_messages_to_leaf content msgs + let len ← betree.List.len (U64 × U64) content0 let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size if len >= i then do let (st1, new_node) ← - betree.Leaf.split_fwd node content0 params node_id_cnt st0 + betree.Leaf.split node content0 params node_id_cnt st0 let _ ← - betree.store_leaf_node_fwd node.betree_leaf_id betree.List.Nil st1 + betree.store_leaf_node node.betree_leaf_id betree.List.Nil st1 let node_id_cnt0 ← betree.Leaf.split_back node content0 params node_id_cnt st0 Result.ret (betree.Node.Internal new_node, node_id_cnt0) else do - let _ ← betree.store_leaf_node_fwd node.betree_leaf_id content0 st0 + let _ ← betree.store_leaf_node node.betree_leaf_id content0 st0 Result.ret (betree.Node.Leaf { node with betree_leaf_size := len }, node_id_cnt) -/- [betree_main::betree::Internal::{4}::flush] -/ -divergent def betree.Internal.flush_fwd +/- [betree_main::betree::Internal::{4}::flush]: forward function -/ +divergent def betree.Internal.flush (self : betree.Internal) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (content : betree.List (U64 × betree.Message)) (st : State) : @@ -832,24 +831,22 @@ divergent def betree.Internal.flush_fwd := do let ⟨ _, i, n, n0 ⟩ := self - let p ← betree.List.partition_at_pivot_fwd betree.Message content i + let p ← betree.List.partition_at_pivot betree.Message content i let (msgs_left, msgs_right) := p - let len_left ← betree.List.len_fwd (U64 × betree.Message) msgs_left + let len_left ← betree.List.len (U64 × betree.Message) msgs_left if len_left >= params.betree_params_min_flush_size then do let (st0, _) ← - betree.Node.apply_messages_fwd n params node_id_cnt msgs_left st + betree.Node.apply_messages n params node_id_cnt msgs_left st let (_, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st - let len_right ← - betree.List.len_fwd (U64 × betree.Message) msgs_right + let len_right ← betree.List.len (U64 × betree.Message) msgs_right if len_right >= params.betree_params_min_flush_size then do let (st1, _) ← - betree.Node.apply_messages_fwd n0 params node_id_cnt0 msgs_right - st0 + betree.Node.apply_messages n0 params node_id_cnt0 msgs_right st0 let _ ← betree.Node.apply_messages_back n0 params node_id_cnt0 msgs_right st0 @@ -858,12 +855,12 @@ divergent def betree.Internal.flush_fwd else do let (st0, _) ← - betree.Node.apply_messages_fwd n0 params node_id_cnt msgs_right st + betree.Node.apply_messages n0 params node_id_cnt msgs_right st let _ ← betree.Node.apply_messages_back n0 params node_id_cnt msgs_right st Result.ret (st0, msgs_left) -/- [betree_main::betree::Internal::{4}::flush] -/ +/- [betree_main::betree::Internal::{4}::flush]: backward function 0 -/ divergent def betree.Internal.flush_back (self : betree.Internal) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) @@ -872,18 +869,17 @@ divergent def betree.Internal.flush_back := do let ⟨ i, i0, n, n0 ⟩ := self - let p ← betree.List.partition_at_pivot_fwd betree.Message content i0 + let p ← betree.List.partition_at_pivot betree.Message content i0 let (msgs_left, msgs_right) := p - let len_left ← betree.List.len_fwd (U64 × betree.Message) msgs_left + let len_left ← betree.List.len (U64 × betree.Message) msgs_left if len_left >= params.betree_params_min_flush_size then do let (st0, _) ← - betree.Node.apply_messages_fwd n params node_id_cnt msgs_left st + betree.Node.apply_messages n params node_id_cnt msgs_left st let (n1, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st - let len_right ← - betree.List.len_fwd (U64 × betree.Message) msgs_right + let len_right ← betree.List.len (U64 × betree.Message) msgs_right if len_right >= params.betree_params_min_flush_size then do @@ -900,8 +896,8 @@ divergent def betree.Internal.flush_back end -/- [betree_main::betree::Node::{5}::apply] -/ -def betree.Node.apply_fwd +/- [betree_main::betree::Node::{5}::apply]: forward function -/ +def betree.Node.apply (self : betree.Node) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (key : U64) (new_msg : betree.Message) (st : State) : @@ -910,14 +906,14 @@ def betree.Node.apply_fwd do let l := betree.List.Nil let (st0, _) ← - betree.Node.apply_messages_fwd self params node_id_cnt (betree.List.Cons + betree.Node.apply_messages self params node_id_cnt (betree.List.Cons (key, new_msg) l) st let _ ← betree.Node.apply_messages_back self params node_id_cnt (betree.List.Cons (key, new_msg) l) st Result.ret (st0, ()) -/- [betree_main::betree::Node::{5}::apply] -/ +/- [betree_main::betree::Node::{5}::apply]: backward function 0 -/ def betree.Node.apply_back (self : betree.Node) (params : betree.Params) (node_id_cnt : betree.NodeIdCounter) (key : U64) (new_msg : betree.Message) @@ -928,15 +924,15 @@ def betree.Node.apply_back betree.Node.apply_messages_back self params node_id_cnt (betree.List.Cons (key, new_msg) l) st -/- [betree_main::betree::BeTree::{6}::new] -/ -def betree.BeTree.new_fwd +/- [betree_main::betree::BeTree::{6}::new]: forward function -/ +def betree.BeTree.new (min_flush_size : U64) (split_size : U64) (st : State) : Result (State × betree.BeTree) := do - let node_id_cnt ← betree.NodeIdCounter.new_fwd - let id ← betree.NodeIdCounter.fresh_id_fwd node_id_cnt - let (st0, _) ← betree.store_leaf_node_fwd id betree.List.Nil st + let node_id_cnt ← betree.NodeIdCounter.new + let id ← betree.NodeIdCounter.fresh_id node_id_cnt + let (st0, _) ← betree.store_leaf_node id betree.List.Nil st let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt Result.ret (st0, { @@ -954,21 +950,21 @@ def betree.BeTree.new_fwd }) }) -/- [betree_main::betree::BeTree::{6}::apply] -/ -def betree.BeTree.apply_fwd +/- [betree_main::betree::BeTree::{6}::apply]: forward function -/ +def betree.BeTree.apply (self : betree.BeTree) (key : U64) (msg : betree.Message) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree.Node.apply_fwd self.betree_be_tree_root self.betree_be_tree_params + betree.Node.apply self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st let _ ← betree.Node.apply_back self.betree_be_tree_root self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st Result.ret (st0, ()) -/- [betree_main::betree::BeTree::{6}::apply] -/ +/- [betree_main::betree::BeTree::{6}::apply]: backward function 0 -/ def betree.BeTree.apply_back (self : betree.BeTree) (key : U64) (msg : betree.Message) (st : State) : Result betree.BeTree @@ -980,51 +976,51 @@ def betree.BeTree.apply_back Result.ret { self with betree_be_tree_node_id_cnt := nic, betree_be_tree_root := n } -/- [betree_main::betree::BeTree::{6}::insert] -/ -def betree.BeTree.insert_fwd +/- [betree_main::betree::BeTree::{6}::insert]: forward function -/ +def betree.BeTree.insert (self : betree.BeTree) (key : U64) (value : U64) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree.BeTree.apply_fwd self key (betree.Message.Insert value) st + betree.BeTree.apply self key (betree.Message.Insert value) st let _ ← betree.BeTree.apply_back self key (betree.Message.Insert value) st Result.ret (st0, ()) -/- [betree_main::betree::BeTree::{6}::insert] -/ +/- [betree_main::betree::BeTree::{6}::insert]: backward function 0 -/ def betree.BeTree.insert_back (self : betree.BeTree) (key : U64) (value : U64) (st : State) : Result betree.BeTree := betree.BeTree.apply_back self key (betree.Message.Insert value) st -/- [betree_main::betree::BeTree::{6}::delete] -/ -def betree.BeTree.delete_fwd +/- [betree_main::betree::BeTree::{6}::delete]: forward function -/ +def betree.BeTree.delete (self : betree.BeTree) (key : U64) (st : State) : Result (State × Unit) := do - let (st0, _) ← betree.BeTree.apply_fwd self key betree.Message.Delete st + let (st0, _) ← betree.BeTree.apply self key betree.Message.Delete st let _ ← betree.BeTree.apply_back self key betree.Message.Delete st Result.ret (st0, ()) -/- [betree_main::betree::BeTree::{6}::delete] -/ +/- [betree_main::betree::BeTree::{6}::delete]: backward function 0 -/ def betree.BeTree.delete_back (self : betree.BeTree) (key : U64) (st : State) : Result betree.BeTree := betree.BeTree.apply_back self key betree.Message.Delete st -/- [betree_main::betree::BeTree::{6}::upsert] -/ -def betree.BeTree.upsert_fwd +/- [betree_main::betree::BeTree::{6}::upsert]: forward function -/ +def betree.BeTree.upsert (self : betree.BeTree) (key : U64) (upd : betree.UpsertFunState) (st : State) : Result (State × Unit) := do let (st0, _) ← - betree.BeTree.apply_fwd self key (betree.Message.Upsert upd) st + betree.BeTree.apply self key (betree.Message.Upsert upd) st let _ ← betree.BeTree.apply_back self key (betree.Message.Upsert upd) st Result.ret (st0, ()) -/- [betree_main::betree::BeTree::{6}::upsert] -/ +/- [betree_main::betree::BeTree::{6}::upsert]: backward function 0 -/ def betree.BeTree.upsert_back (self : betree.BeTree) (key : U64) (upd : betree.UpsertFunState) (st : State) : @@ -1032,25 +1028,25 @@ def betree.BeTree.upsert_back := betree.BeTree.apply_back self key (betree.Message.Upsert upd) st -/- [betree_main::betree::BeTree::{6}::lookup] -/ -def betree.BeTree.lookup_fwd +/- [betree_main::betree::BeTree::{6}::lookup]: forward function -/ +def betree.BeTree.lookup (self : betree.BeTree) (key : U64) (st : State) : Result (State × (Option U64)) := - betree.Node.lookup_fwd self.betree_be_tree_root key st + betree.Node.lookup self.betree_be_tree_root key st -/- [betree_main::betree::BeTree::{6}::lookup] -/ +/- [betree_main::betree::BeTree::{6}::lookup]: backward function 0 -/ def betree.BeTree.lookup_back (self : betree.BeTree) (key : U64) (st : State) : Result betree.BeTree := do let n ← betree.Node.lookup_back self.betree_be_tree_root key st Result.ret { self with betree_be_tree_root := n } -/- [betree_main::main] -/ -def main_fwd : Result Unit := +/- [betree_main::main]: forward function -/ +def main : Result Unit := Result.ret () /- Unit test for [betree_main::main] -/ -#assert (main_fwd == .ret ()) +#assert (main == .ret ()) end betree_main diff --git a/tests/lean/BetreeMain/FunsExternal.lean b/tests/lean/BetreeMain/FunsExternal.lean index 7bcba380..71d26da4 100644 --- a/tests/lean/BetreeMain/FunsExternal.lean +++ b/tests/lean/BetreeMain/FunsExternal.lean @@ -7,29 +7,29 @@ open betree_main -- TODO: fill those bodies /- [betree_main::betree_utils::load_internal_node] -/ -def betree_utils.load_internal_node_fwd +def betree_utils.load_internal_node : U64 → State → Result (State × (betree.List (U64 × betree.Message))) := fun _ _ => .fail .panic /- [betree_main::betree_utils::store_internal_node] -/ -def betree_utils.store_internal_node_fwd +def betree_utils.store_internal_node : U64 → betree.List (U64 × betree.Message) → State → Result (State × Unit) := fun _ _ _ => .fail .panic /- [betree_main::betree_utils::load_leaf_node] -/ -def betree_utils.load_leaf_node_fwd +def betree_utils.load_leaf_node : U64 → State → Result (State × (betree.List (U64 × U64))) := fun _ _ => .fail .panic /- [betree_main::betree_utils::store_leaf_node] -/ -def betree_utils.store_leaf_node_fwd +def betree_utils.store_leaf_node : U64 → betree.List (U64 × U64) → State → Result (State × Unit) := fun _ _ _ => .fail .panic /- [core::option::Option::{0}::unwrap] -/ -def core.option.Option.unwrap_fwd +def core.option.Option.unwrap (T : Type) : Option T → State → Result (State × T) := fun _ _ => .fail .panic diff --git a/tests/lean/BetreeMain/FunsExternal_Template.lean b/tests/lean/BetreeMain/FunsExternal_Template.lean index d768bb20..430d2dda 100644 --- a/tests/lean/BetreeMain/FunsExternal_Template.lean +++ b/tests/lean/BetreeMain/FunsExternal_Template.lean @@ -6,25 +6,25 @@ import BetreeMain.Types open Primitives open betree_main -/- [betree_main::betree_utils::load_internal_node] -/ -axiom betree_utils.load_internal_node_fwd +/- [betree_main::betree_utils::load_internal_node]: forward function -/ +axiom betree_utils.load_internal_node : U64 → State → Result (State × (betree.List (U64 × betree.Message))) -/- [betree_main::betree_utils::store_internal_node] -/ -axiom betree_utils.store_internal_node_fwd +/- [betree_main::betree_utils::store_internal_node]: forward function -/ +axiom betree_utils.store_internal_node : U64 → betree.List (U64 × betree.Message) → State → Result (State × Unit) -/- [betree_main::betree_utils::load_leaf_node] -/ -axiom betree_utils.load_leaf_node_fwd +/- [betree_main::betree_utils::load_leaf_node]: forward function -/ +axiom betree_utils.load_leaf_node : U64 → State → Result (State × (betree.List (U64 × U64))) -/- [betree_main::betree_utils::store_leaf_node] -/ -axiom betree_utils.store_leaf_node_fwd +/- [betree_main::betree_utils::store_leaf_node]: forward function -/ +axiom betree_utils.store_leaf_node : U64 → betree.List (U64 × U64) → State → Result (State × Unit) -/- [core::option::Option::{0}::unwrap] -/ -axiom core.option.Option.unwrap_fwd +/- [core::option::Option::{0}::unwrap]: forward function -/ +axiom core.option.Option.unwrap (T : Type) : Option T → State → Result (State × T) diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index 7014b0d8..f37c9204 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -21,16 +21,16 @@ def x1_c : U32 := eval_global x1_body (by simp) def x2_body : Result U32 := Result.ret (U32.ofInt 3 (by intlit)) def x2_c : U32 := eval_global x2_body (by simp) -/- [constants::incr] -/ -def incr_fwd (n : U32) : Result U32 := +/- [constants::incr]: forward function -/ +def incr (n : U32) : Result U32 := n + (U32.ofInt 1 (by intlit)) /- [constants::X3] -/ -def x3_body : Result U32 := incr_fwd (U32.ofInt 32 (by intlit)) +def x3_body : Result U32 := incr (U32.ofInt 32 (by intlit)) def x3_c : U32 := eval_global x3_body (by simp) -/- [constants::mk_pair0] -/ -def mk_pair0_fwd (x : U32) (y : U32) : Result (U32 × U32) := +/- [constants::mk_pair0]: forward function -/ +def mk_pair0 (x : U32) (y : U32) : Result (U32 × U32) := Result.ret (x, y) /- [constants::Pair] -/ @@ -38,18 +38,18 @@ structure Pair (T1 T2 : Type) where pair_x : T1 pair_y : T2 -/- [constants::mk_pair1] -/ -def mk_pair1_fwd (x : U32) (y : U32) : Result (Pair U32 U32) := +/- [constants::mk_pair1]: forward function -/ +def mk_pair1 (x : U32) (y : U32) : Result (Pair U32 U32) := Result.ret { pair_x := x, pair_y := y } /- [constants::P0] -/ def p0_body : Result (U32 × U32) := - mk_pair0_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) + mk_pair0 (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) def p0_c : (U32 × U32) := eval_global p0_body (by simp) /- [constants::P1] -/ def p1_body : Result (Pair U32 U32) := - mk_pair1_fwd (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) + mk_pair1 (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) def p1_c : Pair U32 U32 := eval_global p1_body (by simp) /- [constants::P2] -/ @@ -67,32 +67,32 @@ def p3_c : Pair U32 U32 := eval_global p3_body (by simp) structure Wrap (T : Type) where wrap_val : T -/- [constants::Wrap::{0}::new] -/ -def Wrap.new_fwd (T : Type) (val : T) : Result (Wrap T) := +/- [constants::Wrap::{0}::new]: forward function -/ +def Wrap.new (T : Type) (val : T) : Result (Wrap T) := Result.ret { wrap_val := val } /- [constants::Y] -/ -def y_body : Result (Wrap I32) := Wrap.new_fwd I32 (I32.ofInt 2 (by intlit)) +def y_body : Result (Wrap I32) := Wrap.new I32 (I32.ofInt 2 (by intlit)) def y_c : Wrap I32 := eval_global y_body (by simp) -/- [constants::unwrap_y] -/ -def unwrap_y_fwd : Result I32 := +/- [constants::unwrap_y]: forward function -/ +def unwrap_y : Result I32 := Result.ret y_c.wrap_val /- [constants::YVAL] -/ -def yval_body : Result I32 := unwrap_y_fwd +def yval_body : Result I32 := unwrap_y def yval_c : I32 := eval_global yval_body (by simp) /- [constants::get_z1::Z1] -/ def get_z1_z1_body : Result I32 := Result.ret (I32.ofInt 3 (by intlit)) def get_z1_z1_c : I32 := eval_global get_z1_z1_body (by simp) -/- [constants::get_z1] -/ -def get_z1_fwd : Result I32 := +/- [constants::get_z1]: forward function -/ +def get_z1 : Result I32 := Result.ret get_z1_z1_c -/- [constants::add] -/ -def add_fwd (a : I32) (b : I32) : Result I32 := +/- [constants::add]: forward function -/ +def add (a : I32) (b : I32) : Result I32 := a + b /- [constants::Q1] -/ @@ -104,22 +104,22 @@ def q2_body : Result I32 := Result.ret q1_c def q2_c : I32 := eval_global q2_body (by simp) /- [constants::Q3] -/ -def q3_body : Result I32 := add_fwd q2_c (I32.ofInt 3 (by intlit)) +def q3_body : Result I32 := add q2_c (I32.ofInt 3 (by intlit)) def q3_c : I32 := eval_global q3_body (by simp) -/- [constants::get_z2] -/ -def get_z2_fwd : Result I32 := +/- [constants::get_z2]: forward function -/ +def get_z2 : Result I32 := do - let i ← get_z1_fwd - let i0 ← add_fwd i q3_c - add_fwd q1_c i0 + let i ← get_z1 + let i0 ← add i q3_c + add q1_c i0 /- [constants::S1] -/ def s1_body : Result U32 := Result.ret (U32.ofInt 6 (by intlit)) def s1_c : U32 := eval_global s1_body (by simp) /- [constants::S2] -/ -def s2_body : Result U32 := incr_fwd s1_c +def s2_body : Result U32 := incr s1_c def s2_c : U32 := eval_global s2_body (by simp) /- [constants::S3] -/ @@ -128,7 +128,7 @@ def s3_c : Pair U32 U32 := eval_global s3_body (by simp) /- [constants::S4] -/ def s4_body : Result (Pair U32 U32) := - mk_pair1_fwd (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) + mk_pair1 (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) def s4_c : Pair U32 U32 := eval_global s4_body (by simp) end constants diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index 3fc21d91..122f94da 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -6,81 +6,80 @@ import External.FunsExternal open Primitives namespace external -/- [external::swap] -/ -def swap_fwd - (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := +/- [external::swap]: forward function -/ +def swap (T : Type) (x : T) (y : T) (st : State) : Result (State × Unit) := do - let (st0, _) ← core.mem.swap_fwd T x y st + let (st0, _) ← core.mem.swap T x y st let (st1, _) ← core.mem.swap_back0 T x y st st0 let (st2, _) ← core.mem.swap_back1 T x y st st1 Result.ret (st2, ()) -/- [external::swap] -/ +/- [external::swap]: backward function 0 -/ def swap_back (T : Type) (x : T) (y : T) (st : State) (st0 : State) : Result (State × (T × T)) := do - let (st1, _) ← core.mem.swap_fwd T x y st + let (st1, _) ← core.mem.swap T x y st let (st2, x0) ← core.mem.swap_back0 T x y st st1 let (_, y0) ← core.mem.swap_back1 T x y st st2 Result.ret (st0, (x0, y0)) -/- [external::test_new_non_zero_u32] -/ -def test_new_non_zero_u32_fwd +/- [external::test_new_non_zero_u32]: forward function -/ +def test_new_non_zero_u32 (x : U32) (st : State) : Result (State × core.num.nonzero.NonZeroU32) := do - let (st0, opt) ← core.num.nonzero.NonZeroU32.new_fwd x st - core.option.Option.unwrap_fwd core.num.nonzero.NonZeroU32 opt st0 + let (st0, opt) ← core.num.nonzero.NonZeroU32.new x st + core.option.Option.unwrap core.num.nonzero.NonZeroU32 opt st0 -/- [external::test_vec] -/ -def test_vec_fwd : Result Unit := +/- [external::test_vec]: forward function -/ +def test_vec : Result Unit := do let v := Vec.new U32 let _ ← Vec.push U32 v (U32.ofInt 0 (by intlit)) Result.ret () /- Unit test for [external::test_vec] -/ -#assert (test_vec_fwd == .ret ()) +#assert (test_vec == .ret ()) -/- [external::custom_swap] -/ -def custom_swap_fwd +/- [external::custom_swap]: forward function -/ +def custom_swap (T : Type) (x : T) (y : T) (st : State) : Result (State × T) := do - let (st0, _) ← core.mem.swap_fwd T x y st + let (st0, _) ← core.mem.swap T x y st let (st1, x0) ← core.mem.swap_back0 T x y st st0 let (st2, _) ← core.mem.swap_back1 T x y st st1 Result.ret (st2, x0) -/- [external::custom_swap] -/ +/- [external::custom_swap]: backward function 0 -/ def custom_swap_back (T : Type) (x : T) (y : T) (st : State) (ret0 : T) (st0 : State) : Result (State × (T × T)) := do - let (st1, _) ← core.mem.swap_fwd T x y st + let (st1, _) ← core.mem.swap T x y st let (st2, _) ← core.mem.swap_back0 T x y st st1 let (_, y0) ← core.mem.swap_back1 T x y st st2 Result.ret (st0, (ret0, y0)) -/- [external::test_custom_swap] -/ -def test_custom_swap_fwd +/- [external::test_custom_swap]: forward function -/ +def test_custom_swap (x : U32) (y : U32) (st : State) : Result (State × Unit) := do - let (st0, _) ← custom_swap_fwd U32 x y st + let (st0, _) ← custom_swap U32 x y st Result.ret (st0, ()) -/- [external::test_custom_swap] -/ +/- [external::test_custom_swap]: backward function 0 -/ def test_custom_swap_back (x : U32) (y : U32) (st : State) (st0 : State) : Result (State × (U32 × U32)) := custom_swap_back U32 x y st (U32.ofInt 1 (by intlit)) st0 -/- [external::test_swap_non_zero] -/ -def test_swap_non_zero_fwd (x : U32) (st : State) : Result (State × U32) := +/- [external::test_swap_non_zero]: forward function -/ +def test_swap_non_zero (x : U32) (st : State) : Result (State × U32) := do - let (st0, _) ← swap_fwd U32 x (U32.ofInt 0 (by intlit)) st + let (st0, _) ← swap U32 x (U32.ofInt 0 (by intlit)) st let (st1, (x0, _)) ← swap_back U32 x (U32.ofInt 0 (by intlit)) st st0 if x0 = (U32.ofInt 0 (by intlit)) then Result.fail Error.panic diff --git a/tests/lean/External/FunsExternal.lean b/tests/lean/External/FunsExternal.lean index 5326dd77..aae11ba1 100644 --- a/tests/lean/External/FunsExternal.lean +++ b/tests/lean/External/FunsExternal.lean @@ -7,7 +7,7 @@ open external -- TODO: fill those bodies /- [core::mem::swap] -/ -def core.mem.swap_fwd +def core.mem.swap (T : Type) : T → T → State → Result (State × Unit) := fun _x _y s => .ret (s, ()) @@ -22,12 +22,12 @@ def core.mem.swap_back1 fun x _y _s0 s1 => .ret (s1, x) /- [core::num::nonzero::NonZeroU32::{14}::new] -/ -def core.num.nonzero.NonZeroU32.new_fwd +def core.num.nonzero.NonZeroU32.new : U32 → State → Result (State × (Option core_num_nonzero_non_zero_u32_t)) := fun _ _ => .fail .panic /- [core::option::Option::{0}::unwrap] -/ -def core.option.Option.unwrap_fwd +def core.option.Option.unwrap (T : Type) : Option T → State → Result (State × T) := fun _ _ => .fail .panic diff --git a/tests/lean/External/FunsExternal_Template.lean b/tests/lean/External/FunsExternal_Template.lean index 669fe91b..c8bc397f 100644 --- a/tests/lean/External/FunsExternal_Template.lean +++ b/tests/lean/External/FunsExternal_Template.lean @@ -6,23 +6,22 @@ import External.Types open Primitives open external -/- [core::mem::swap] -/ -axiom core.mem.swap_fwd - (T : Type) : T → T → State → Result (State × Unit) +/- [core::mem::swap]: forward function -/ +axiom core.mem.swap (T : Type) : T → T → State → Result (State × Unit) -/- [core::mem::swap] -/ +/- [core::mem::swap]: backward function 0 -/ axiom core.mem.swap_back0 (T : Type) : T → T → State → State → Result (State × T) -/- [core::mem::swap] -/ +/- [core::mem::swap]: backward function 1 -/ axiom core.mem.swap_back1 (T : Type) : T → T → State → State → Result (State × T) -/- [core::num::nonzero::NonZeroU32::{14}::new] -/ -axiom core.num.nonzero.NonZeroU32.new_fwd +/- [core::num::nonzero::NonZeroU32::{14}::new]: forward function -/ +axiom core.num.nonzero.NonZeroU32.new : U32 → State → Result (State × (Option core.num.nonzero.NonZeroU32)) -/- [core::option::Option::{0}::unwrap] -/ -axiom core.option.Option.unwrap_fwd +/- [core::option::Option::{0}::unwrap]: forward function -/ +axiom core.option.Option.unwrap (T : Type) : Option T → State → Result (State × T) diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 48038bfb..34ff1379 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -5,35 +5,35 @@ import Hashmap.Types open Primitives namespace hashmap -/- [hashmap::hash_key] -/ -def hash_key_fwd (k : Usize) : Result Usize := +/- [hashmap::hash_key]: forward function -/ +def hash_key (k : Usize) : Result Usize := Result.ret k -/- [hashmap::HashMap::{0}::allocate_slots] -/ -divergent def HashMap.allocate_slots_loop_fwd +/- [hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function -/ +divergent def HashMap.allocate_slots_loop (T : Type) (slots : Vec (List T)) (n : Usize) : Result (Vec (List T)) := if n > (Usize.ofInt 0 (by intlit)) then do let slots0 ← Vec.push (List T) slots List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) - HashMap.allocate_slots_loop_fwd T slots0 n0 + HashMap.allocate_slots_loop T slots0 n0 else Result.ret slots -/- [hashmap::HashMap::{0}::allocate_slots] -/ -def HashMap.allocate_slots_fwd +/- [hashmap::HashMap::{0}::allocate_slots]: forward function -/ +def HashMap.allocate_slots (T : Type) (slots : Vec (List T)) (n : Usize) : Result (Vec (List T)) := - HashMap.allocate_slots_loop_fwd T slots n + HashMap.allocate_slots_loop T slots n -/- [hashmap::HashMap::{0}::new_with_capacity] -/ -def HashMap.new_with_capacity_fwd +/- [hashmap::HashMap::{0}::new_with_capacity]: forward function -/ +def HashMap.new_with_capacity (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : Result (HashMap T) := do let v := Vec.new (List T) - let slots ← HashMap.allocate_slots_fwd T v capacity + let slots ← HashMap.allocate_slots T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor Result.ret @@ -44,13 +44,14 @@ def HashMap.new_with_capacity_fwd hash_map_slots := slots } -/- [hashmap::HashMap::{0}::new] -/ -def HashMap.new_fwd (T : Type) : Result (HashMap T) := - HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) +/- [hashmap::HashMap::{0}::new]: forward function -/ +def HashMap.new (T : Type) : Result (HashMap T) := + HashMap.new_with_capacity T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) -/- [hashmap::HashMap::{0}::clear] -/ -divergent def HashMap.clear_loop_fwd_back +/- [hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def HashMap.clear_loop (T : Type) (slots : Vec (List T)) (i : Usize) : Result (Vec (List T)) := let i0 := Vec.len (List T) slots if i < i0 @@ -58,16 +59,15 @@ divergent def HashMap.clear_loop_fwd_back do let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← Vec.index_mut_back (List T) slots i List.Nil - HashMap.clear_loop_fwd_back T slots0 i1 + HashMap.clear_loop T slots0 i1 else Result.ret slots -/- [hashmap::HashMap::{0}::clear] -/ -def HashMap.clear_fwd_back - (T : Type) (self : HashMap T) : Result (HashMap T) := +/- [hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.clear (T : Type) (self : HashMap T) : Result (HashMap T) := do let v ← - HashMap.clear_loop_fwd_back T self.hash_map_slots - (Usize.ofInt 0 (by intlit)) + HashMap.clear_loop T self.hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { self @@ -76,26 +76,26 @@ def HashMap.clear_fwd_back hash_map_slots := v } -/- [hashmap::HashMap::{0}::len] -/ -def HashMap.len_fwd (T : Type) (self : HashMap T) : Result Usize := +/- [hashmap::HashMap::{0}::len]: forward function -/ +def HashMap.len (T : Type) (self : HashMap T) : Result Usize := Result.ret self.hash_map_num_entries -/- [hashmap::HashMap::{0}::insert_in_list] -/ -divergent def HashMap.insert_in_list_loop_fwd +/- [hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function -/ +divergent def HashMap.insert_in_list_loop (T : Type) (key : Usize) (value : T) (ls : List T) : Result Bool := match ls with | List.Cons ckey cvalue tl => if ckey = key then Result.ret false - else HashMap.insert_in_list_loop_fwd T key value tl + else HashMap.insert_in_list_loop T key value tl | List.Nil => Result.ret true -/- [hashmap::HashMap::{0}::insert_in_list] -/ -def HashMap.insert_in_list_fwd +/- [hashmap::HashMap::{0}::insert_in_list]: forward function -/ +def HashMap.insert_in_list (T : Type) (key : Usize) (value : T) (ls : List T) : Result Bool := - HashMap.insert_in_list_loop_fwd T key value ls + HashMap.insert_in_list_loop T key value ls -/- [hashmap::HashMap::{0}::insert_in_list] -/ +/- [hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 -/ divergent def HashMap.insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : List T) : Result (List T) := match ls with @@ -109,22 +109,23 @@ divergent def HashMap.insert_in_list_loop_back | List.Nil => let l := List.Nil Result.ret (List.Cons key value l) -/- [hashmap::HashMap::{0}::insert_in_list] -/ +/- [hashmap::HashMap::{0}::insert_in_list]: backward function 0 -/ def HashMap.insert_in_list_back (T : Type) (key : Usize) (value : T) (ls : List T) : Result (List T) := HashMap.insert_in_list_loop_back T key value ls -/- [hashmap::HashMap::{0}::insert_no_resize] -/ -def HashMap.insert_no_resize_fwd_back +/- [hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.insert_no_resize (T : Type) (self : HashMap T) (key : Usize) (value : T) : Result (HashMap T) := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod - let inserted ← HashMap.insert_in_list_fwd T key value l + let inserted ← HashMap.insert_in_list T key value l if inserted then do @@ -144,23 +145,26 @@ def core_num_u32_max_body : Result U32 := Result.ret (U32.ofInt 4294967295 (by intlit)) def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) -/- [hashmap::HashMap::{0}::move_elements_from_list] -/ -divergent def HashMap.move_elements_from_list_loop_fwd_back +/- [hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def HashMap.move_elements_from_list_loop (T : Type) (ntable : HashMap T) (ls : List T) : Result (HashMap T) := match ls with | List.Cons k v tl => do - let ntable0 ← HashMap.insert_no_resize_fwd_back T ntable k v - HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl + let ntable0 ← HashMap.insert_no_resize T ntable k v + HashMap.move_elements_from_list_loop T ntable0 tl | List.Nil => Result.ret ntable -/- [hashmap::HashMap::{0}::move_elements_from_list] -/ -def HashMap.move_elements_from_list_fwd_back +/- [hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.move_elements_from_list (T : Type) (ntable : HashMap T) (ls : List T) : Result (HashMap T) := - HashMap.move_elements_from_list_loop_fwd_back T ntable ls + HashMap.move_elements_from_list_loop T ntable ls -/- [hashmap::HashMap::{0}::move_elements] -/ -divergent def HashMap.move_elements_loop_fwd_back +/- [hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def HashMap.move_elements_loop (T : Type) (ntable : HashMap T) (slots : Vec (List T)) (i : Usize) : Result ((HashMap T) × (Vec (List T))) := @@ -169,24 +173,25 @@ divergent def HashMap.move_elements_loop_fwd_back then do let l ← Vec.index_mut (List T) slots i - let ls := mem.replace_fwd (List T) l List.Nil - let ntable0 ← HashMap.move_elements_from_list_fwd_back T ntable ls + let ls := mem.replace (List T) l List.Nil + let ntable0 ← HashMap.move_elements_from_list T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) let l0 := mem.replace_back (List T) l List.Nil let slots0 ← Vec.index_mut_back (List T) slots i l0 - HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 + HashMap.move_elements_loop T ntable0 slots0 i1 else Result.ret (ntable, slots) -/- [hashmap::HashMap::{0}::move_elements] -/ -def HashMap.move_elements_fwd_back +/- [hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.move_elements (T : Type) (ntable : HashMap T) (slots : Vec (List T)) (i : Usize) : Result ((HashMap T) × (Vec (List T))) := - HashMap.move_elements_loop_fwd_back T ntable slots i + HashMap.move_elements_loop T ntable slots i -/- [hashmap::HashMap::{0}::try_resize] -/ -def HashMap.try_resize_fwd_back - (T : Type) (self : HashMap T) : Result (HashMap T) := +/- [hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.try_resize (T : Type) (self : HashMap T) : Result (HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c let capacity := Vec.len (List T) self.hash_map_slots @@ -197,9 +202,9 @@ def HashMap.try_resize_fwd_back then do let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← HashMap.new_with_capacity_fwd T i2 i i0 + let ntable ← HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - HashMap.move_elements_fwd_back T ntable self.hash_map_slots + HashMap.move_elements T ntable self.hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -210,83 +215,83 @@ def HashMap.try_resize_fwd_back } else Result.ret { self with hash_map_max_load_factor := (i, i0) } -/- [hashmap::HashMap::{0}::insert] -/ -def HashMap.insert_fwd_back +/- [hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def HashMap.insert (T : Type) (self : HashMap T) (key : Usize) (value : T) : Result (HashMap T) := do - let self0 ← HashMap.insert_no_resize_fwd_back T self key value - let i ← HashMap.len_fwd T self0 + let self0 ← HashMap.insert_no_resize T self key value + let i ← HashMap.len T self0 if i > self0.hash_map_max_load - then HashMap.try_resize_fwd_back T self0 + then HashMap.try_resize T self0 else Result.ret self0 -/- [hashmap::HashMap::{0}::contains_key_in_list] -/ -divergent def HashMap.contains_key_in_list_loop_fwd +/- [hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function -/ +divergent def HashMap.contains_key_in_list_loop (T : Type) (key : Usize) (ls : List T) : Result Bool := match ls with | List.Cons ckey t tl => if ckey = key then Result.ret true - else HashMap.contains_key_in_list_loop_fwd T key tl + else HashMap.contains_key_in_list_loop T key tl | List.Nil => Result.ret false -/- [hashmap::HashMap::{0}::contains_key_in_list] -/ -def HashMap.contains_key_in_list_fwd +/- [hashmap::HashMap::{0}::contains_key_in_list]: forward function -/ +def HashMap.contains_key_in_list (T : Type) (key : Usize) (ls : List T) : Result Bool := - HashMap.contains_key_in_list_loop_fwd T key ls + HashMap.contains_key_in_list_loop T key ls -/- [hashmap::HashMap::{0}::contains_key] -/ -def HashMap.contains_key_fwd +/- [hashmap::HashMap::{0}::contains_key]: forward function -/ +def HashMap.contains_key (T : Type) (self : HashMap T) (key : Usize) : Result Bool := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index (List T) self.hash_map_slots hash_mod - HashMap.contains_key_in_list_fwd T key l + HashMap.contains_key_in_list T key l -/- [hashmap::HashMap::{0}::get_in_list] -/ -divergent def HashMap.get_in_list_loop_fwd +/- [hashmap::HashMap::{0}::get_in_list]: loop 0: forward function -/ +divergent def HashMap.get_in_list_loop (T : Type) (key : Usize) (ls : List T) : Result T := match ls with | List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else HashMap.get_in_list_loop_fwd T key tl + else HashMap.get_in_list_loop T key tl | List.Nil => Result.fail Error.panic -/- [hashmap::HashMap::{0}::get_in_list] -/ -def HashMap.get_in_list_fwd - (T : Type) (key : Usize) (ls : List T) : Result T := - HashMap.get_in_list_loop_fwd T key ls +/- [hashmap::HashMap::{0}::get_in_list]: forward function -/ +def HashMap.get_in_list (T : Type) (key : Usize) (ls : List T) : Result T := + HashMap.get_in_list_loop T key ls -/- [hashmap::HashMap::{0}::get] -/ -def HashMap.get_fwd (T : Type) (self : HashMap T) (key : Usize) : Result T := +/- [hashmap::HashMap::{0}::get]: forward function -/ +def HashMap.get (T : Type) (self : HashMap T) (key : Usize) : Result T := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index (List T) self.hash_map_slots hash_mod - HashMap.get_in_list_fwd T key l + HashMap.get_in_list T key l -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def HashMap.get_mut_in_list_loop_fwd +/- [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function -/ +divergent def HashMap.get_mut_in_list_loop (T : Type) (ls : List T) (key : Usize) : Result T := match ls with | List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else HashMap.get_mut_in_list_loop_fwd T tl key + else HashMap.get_mut_in_list_loop T tl key | List.Nil => Result.fail Error.panic -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ -def HashMap.get_mut_in_list_fwd +/- [hashmap::HashMap::{0}::get_mut_in_list]: forward function -/ +def HashMap.get_mut_in_list (T : Type) (ls : List T) (key : Usize) : Result T := - HashMap.get_mut_in_list_loop_fwd T ls key + HashMap.get_mut_in_list_loop T ls key -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +/- [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 -/ divergent def HashMap.get_mut_in_list_loop_back (T : Type) (ls : List T) (key : Usize) (ret0 : T) : Result (List T) := match ls with @@ -299,28 +304,27 @@ divergent def HashMap.get_mut_in_list_loop_back Result.ret (List.Cons ckey cvalue tl0) | List.Nil => Result.fail Error.panic -/- [hashmap::HashMap::{0}::get_mut_in_list] -/ +/- [hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 -/ def HashMap.get_mut_in_list_back (T : Type) (ls : List T) (key : Usize) (ret0 : T) : Result (List T) := HashMap.get_mut_in_list_loop_back T ls key ret0 -/- [hashmap::HashMap::{0}::get_mut] -/ -def HashMap.get_mut_fwd - (T : Type) (self : HashMap T) (key : Usize) : Result T := +/- [hashmap::HashMap::{0}::get_mut]: forward function -/ +def HashMap.get_mut (T : Type) (self : HashMap T) (key : Usize) : Result T := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod - HashMap.get_mut_in_list_fwd T l key + HashMap.get_mut_in_list T l key -/- [hashmap::HashMap::{0}::get_mut] -/ +/- [hashmap::HashMap::{0}::get_mut]: backward function 0 -/ def HashMap.get_mut_back (T : Type) (self : HashMap T) (key : Usize) (ret0 : T) : Result (HashMap T) := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod @@ -328,33 +332,33 @@ def HashMap.get_mut_back let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 Result.ret { self with hash_map_slots := v } -/- [hashmap::HashMap::{0}::remove_from_list] -/ -divergent def HashMap.remove_from_list_loop_fwd +/- [hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function -/ +divergent def HashMap.remove_from_list_loop (T : Type) (key : Usize) (ls : List T) : Result (Option T) := match ls with | List.Cons ckey t tl => if ckey = key then - let mv_ls := mem.replace_fwd (List T) (List.Cons ckey t tl) List.Nil + let mv_ls := mem.replace (List T) (List.Cons ckey t tl) List.Nil match mv_ls with | List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | List.Nil => Result.fail Error.panic - else HashMap.remove_from_list_loop_fwd T key tl + else HashMap.remove_from_list_loop T key tl | List.Nil => Result.ret Option.none -/- [hashmap::HashMap::{0}::remove_from_list] -/ -def HashMap.remove_from_list_fwd +/- [hashmap::HashMap::{0}::remove_from_list]: forward function -/ +def HashMap.remove_from_list (T : Type) (key : Usize) (ls : List T) : Result (Option T) := - HashMap.remove_from_list_loop_fwd T key ls + HashMap.remove_from_list_loop T key ls -/- [hashmap::HashMap::{0}::remove_from_list] -/ +/- [hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 -/ divergent def HashMap.remove_from_list_loop_back (T : Type) (key : Usize) (ls : List T) : Result (List T) := match ls with | List.Cons ckey t tl => if ckey = key then - let mv_ls := mem.replace_fwd (List T) (List.Cons ckey t tl) List.Nil + let mv_ls := mem.replace (List T) (List.Cons ckey t tl) List.Nil match mv_ls with | List.Cons i cvalue tl0 => Result.ret tl0 | List.Nil => Result.fail Error.panic @@ -364,20 +368,20 @@ divergent def HashMap.remove_from_list_loop_back Result.ret (List.Cons ckey t tl0) | List.Nil => Result.ret List.Nil -/- [hashmap::HashMap::{0}::remove_from_list] -/ +/- [hashmap::HashMap::{0}::remove_from_list]: backward function 1 -/ def HashMap.remove_from_list_back (T : Type) (key : Usize) (ls : List T) : Result (List T) := HashMap.remove_from_list_loop_back T key ls -/- [hashmap::HashMap::{0}::remove] -/ -def HashMap.remove_fwd +/- [hashmap::HashMap::{0}::remove]: forward function -/ +def HashMap.remove (T : Type) (self : HashMap T) (key : Usize) : Result (Option T) := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod - let x ← HashMap.remove_from_list_fwd T key l + let x ← HashMap.remove_from_list T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => @@ -385,15 +389,15 @@ def HashMap.remove_fwd let _ ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) Result.ret (Option.some x0) -/- [hashmap::HashMap::{0}::remove] -/ +/- [hashmap::HashMap::{0}::remove]: backward function 0 -/ def HashMap.remove_back (T : Type) (self : HashMap T) (key : Usize) : Result (HashMap T) := do - let hash ← hash_key_fwd key + let hash ← hash_key key let i := Vec.len (List T) self.hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod - let x ← HashMap.remove_from_list_fwd T key l + let x ← HashMap.remove_from_list T key l match x with | Option.none => do @@ -408,23 +412,23 @@ def HashMap.remove_back Result.ret { self with hash_map_num_entries := i0, hash_map_slots := v } -/- [hashmap::test1] -/ -def test1_fwd : Result Unit := +/- [hashmap::test1]: forward function -/ +def test1 : Result Unit := do - let hm ← HashMap.new_fwd U64 + let hm ← HashMap.new U64 let hm0 ← - HashMap.insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + HashMap.insert U64 hm (Usize.ofInt 0 (by intlit)) (U64.ofInt 42 (by intlit)) let hm1 ← - HashMap.insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + HashMap.insert U64 hm0 (Usize.ofInt 128 (by intlit)) (U64.ofInt 18 (by intlit)) let hm2 ← - HashMap.insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + HashMap.insert U64 hm1 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 138 (by intlit)) let hm3 ← - HashMap.insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + HashMap.insert U64 hm2 (Usize.ofInt 1056 (by intlit)) (U64.ofInt 256 (by intlit)) - let i ← HashMap.get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + let i ← HashMap.get U64 hm3 (Usize.ofInt 128 (by intlit)) if not (i = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else @@ -432,12 +436,12 @@ def test1_fwd : Result Unit := let hm4 ← HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 56 (by intlit)) - let i0 ← HashMap.get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + let i0 ← HashMap.get U64 hm4 (Usize.ofInt 1024 (by intlit)) if not (i0 = (U64.ofInt 56 (by intlit))) then Result.fail Error.panic else do - let x ← HashMap.remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + let x ← HashMap.remove U64 hm4 (Usize.ofInt 1024 (by intlit)) match x with | Option.none => Result.fail Error.panic | Option.some x0 => @@ -447,26 +451,24 @@ def test1_fwd : Result Unit := do let hm5 ← HashMap.remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) - let i1 ← - HashMap.get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) + let i1 ← HashMap.get U64 hm5 (Usize.ofInt 0 (by intlit)) if not (i1 = (U64.ofInt 42 (by intlit))) then Result.fail Error.panic else do let i2 ← - HashMap.get_fwd U64 hm5 (Usize.ofInt 128 (by intlit)) + HashMap.get U64 hm5 (Usize.ofInt 128 (by intlit)) if not (i2 = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let i3 ← - HashMap.get_fwd U64 hm5 - (Usize.ofInt 1056 (by intlit)) + HashMap.get U64 hm5 (Usize.ofInt 1056 (by intlit)) if not (i3 = (U64.ofInt 256 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [hashmap::test1] -/ -#assert (test1_fwd == .ret ()) +#assert (test1 == .ret ()) end hashmap diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index 1a741a2d..b1afcd44 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -6,12 +6,12 @@ import HashmapMain.FunsExternal open Primitives namespace hashmap_main -/- [hashmap_main::hashmap::hash_key] -/ -def hashmap.hash_key_fwd (k : Usize) : Result Usize := +/- [hashmap_main::hashmap::hash_key]: forward function -/ +def hashmap.hash_key (k : Usize) : Result Usize := Result.ret k -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -divergent def hashmap.HashMap.allocate_slots_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function -/ +divergent def hashmap.HashMap.allocate_slots_loop (T : Type) (slots : Vec (hashmap.List T)) (n : Usize) : Result (Vec (hashmap.List T)) := @@ -20,25 +20,25 @@ divergent def hashmap.HashMap.allocate_slots_loop_fwd do let slots0 ← Vec.push (hashmap.List T) slots hashmap.List.Nil let n0 ← n - (Usize.ofInt 1 (by intlit)) - hashmap.HashMap.allocate_slots_loop_fwd T slots0 n0 + hashmap.HashMap.allocate_slots_loop T slots0 n0 else Result.ret slots -/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots] -/ -def hashmap.HashMap.allocate_slots_fwd +/- [hashmap_main::hashmap::HashMap::{0}::allocate_slots]: forward function -/ +def hashmap.HashMap.allocate_slots (T : Type) (slots : Vec (hashmap.List T)) (n : Usize) : Result (Vec (hashmap.List T)) := - hashmap.HashMap.allocate_slots_loop_fwd T slots n + hashmap.HashMap.allocate_slots_loop T slots n -/- [hashmap_main::hashmap::HashMap::{0}::new_with_capacity] -/ -def hashmap.HashMap.new_with_capacity_fwd +/- [hashmap_main::hashmap::HashMap::{0}::new_with_capacity]: forward function -/ +def hashmap.HashMap.new_with_capacity (T : Type) (capacity : Usize) (max_load_dividend : Usize) (max_load_divisor : Usize) : Result (hashmap.HashMap T) := do let v := Vec.new (hashmap.List T) - let slots ← hashmap.HashMap.allocate_slots_fwd T v capacity + let slots ← hashmap.HashMap.allocate_slots T v capacity let i ← capacity * max_load_dividend let i0 ← i / max_load_divisor Result.ret @@ -50,13 +50,14 @@ def hashmap.HashMap.new_with_capacity_fwd hashmap_hash_map_slots := slots } -/- [hashmap_main::hashmap::HashMap::{0}::new] -/ -def hashmap.HashMap.new_fwd (T : Type) : Result (hashmap.HashMap T) := - hashmap.HashMap.new_with_capacity_fwd T (Usize.ofInt 32 (by intlit)) +/- [hashmap_main::hashmap::HashMap::{0}::new]: forward function -/ +def hashmap.HashMap.new (T : Type) : Result (hashmap.HashMap T) := + hashmap.HashMap.new_with_capacity T (Usize.ofInt 32 (by intlit)) (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) -/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -divergent def hashmap.HashMap.clear_loop_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def hashmap.HashMap.clear_loop (T : Type) (slots : Vec (hashmap.List T)) (i : Usize) : Result (Vec (hashmap.List T)) := @@ -67,15 +68,16 @@ divergent def hashmap.HashMap.clear_loop_fwd_back let i1 ← i + (Usize.ofInt 1 (by intlit)) let slots0 ← Vec.index_mut_back (hashmap.List T) slots i hashmap.List.Nil - hashmap.HashMap.clear_loop_fwd_back T slots0 i1 + hashmap.HashMap.clear_loop T slots0 i1 else Result.ret slots -/- [hashmap_main::hashmap::HashMap::{0}::clear] -/ -def hashmap.HashMap.clear_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.clear (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let v ← - hashmap.HashMap.clear_loop_fwd_back T self.hashmap_hash_map_slots + hashmap.HashMap.clear_loop T self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) Result.ret { @@ -85,27 +87,26 @@ def hashmap.HashMap.clear_fwd_back hashmap_hash_map_slots := v } -/- [hashmap_main::hashmap::HashMap::{0}::len] -/ -def hashmap.HashMap.len_fwd - (T : Type) (self : hashmap.HashMap T) : Result Usize := +/- [hashmap_main::hashmap::HashMap::{0}::len]: forward function -/ +def hashmap.HashMap.len (T : Type) (self : hashmap.HashMap T) : Result Usize := Result.ret self.hashmap_hash_map_num_entries -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -divergent def hashmap.HashMap.insert_in_list_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function -/ +divergent def hashmap.HashMap.insert_in_list_loop (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result Bool := match ls with | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret false - else hashmap.HashMap.insert_in_list_loop_fwd T key value tl + else hashmap.HashMap.insert_in_list_loop T key value tl | hashmap.List.Nil => Result.ret true -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ -def hashmap.HashMap.insert_in_list_fwd +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: forward function -/ +def hashmap.HashMap.insert_in_list (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result Bool := - hashmap.HashMap.insert_in_list_loop_fwd T key value ls + hashmap.HashMap.insert_in_list_loop T key value ls -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: backward function 0 -/ divergent def hashmap.HashMap.insert_in_list_loop_back (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result (hashmap.List T) @@ -122,25 +123,26 @@ divergent def hashmap.HashMap.insert_in_list_loop_back let l := hashmap.List.Nil Result.ret (hashmap.List.Cons key value l) -/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: backward function 0 -/ def hashmap.HashMap.insert_in_list_back (T : Type) (key : Usize) (value : T) (ls : hashmap.List T) : Result (hashmap.List T) := hashmap.HashMap.insert_in_list_loop_back T key value ls -/- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize] -/ -def hashmap.HashMap.insert_no_resize_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::insert_no_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.insert_no_resize (T : Type) (self : hashmap.HashMap T) (key : Usize) (value : T) : Result (hashmap.HashMap T) := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod - let inserted ← hashmap.HashMap.insert_in_list_fwd T key value l + let inserted ← hashmap.HashMap.insert_in_list T key value l if inserted then do @@ -169,27 +171,30 @@ def core_num_u32_max_body : Result U32 := Result.ret (U32.ofInt 4294967295 (by intlit)) def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -divergent def hashmap.HashMap.move_elements_from_list_loop_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def hashmap.HashMap.move_elements_from_list_loop (T : Type) (ntable : hashmap.HashMap T) (ls : hashmap.List T) : Result (hashmap.HashMap T) := match ls with | hashmap.List.Cons k v tl => do - let ntable0 ← hashmap.HashMap.insert_no_resize_fwd_back T ntable k v - hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable0 tl + let ntable0 ← hashmap.HashMap.insert_no_resize T ntable k v + hashmap.HashMap.move_elements_from_list_loop T ntable0 tl | hashmap.List.Nil => Result.ret ntable -/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list] -/ -def hashmap.HashMap.move_elements_from_list_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.move_elements_from_list (T : Type) (ntable : hashmap.HashMap T) (ls : hashmap.List T) : Result (hashmap.HashMap T) := - hashmap.HashMap.move_elements_from_list_loop_fwd_back T ntable ls + hashmap.HashMap.move_elements_from_list_loop T ntable ls -/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -divergent def hashmap.HashMap.move_elements_loop_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def hashmap.HashMap.move_elements_loop (T : Type) (ntable : hashmap.HashMap T) (slots : Vec (hashmap.List T)) (i : Usize) : Result ((hashmap.HashMap T) × (Vec (hashmap.List T))) @@ -199,25 +204,26 @@ divergent def hashmap.HashMap.move_elements_loop_fwd_back then do let l ← Vec.index_mut (hashmap.List T) slots i - let ls := mem.replace_fwd (hashmap.List T) l hashmap.List.Nil - let ntable0 ← - hashmap.HashMap.move_elements_from_list_fwd_back T ntable ls + let ls := mem.replace (hashmap.List T) l hashmap.List.Nil + let ntable0 ← hashmap.HashMap.move_elements_from_list T ntable ls let i1 ← i + (Usize.ofInt 1 (by intlit)) let l0 := mem.replace_back (hashmap.List T) l hashmap.List.Nil let slots0 ← Vec.index_mut_back (hashmap.List T) slots i l0 - hashmap.HashMap.move_elements_loop_fwd_back T ntable0 slots0 i1 + hashmap.HashMap.move_elements_loop T ntable0 slots0 i1 else Result.ret (ntable, slots) -/- [hashmap_main::hashmap::HashMap::{0}::move_elements] -/ -def hashmap.HashMap.move_elements_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::move_elements]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.move_elements (T : Type) (ntable : hashmap.HashMap T) (slots : Vec (hashmap.List T)) (i : Usize) : Result ((hashmap.HashMap T) × (Vec (hashmap.List T))) := - hashmap.HashMap.move_elements_loop_fwd_back T ntable slots i + hashmap.HashMap.move_elements_loop T ntable slots i -/- [hashmap_main::hashmap::HashMap::{0}::try_resize] -/ -def hashmap.HashMap.try_resize_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::try_resize]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.try_resize (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c @@ -229,10 +235,10 @@ def hashmap.HashMap.try_resize_fwd_back then do let i2 ← capacity * (Usize.ofInt 2 (by intlit)) - let ntable ← hashmap.HashMap.new_with_capacity_fwd T i2 i i0 + let ntable ← hashmap.HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - hashmap.HashMap.move_elements_fwd_back T ntable - self.hashmap_hash_map_slots (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.move_elements T ntable self.hashmap_hash_map_slots + (Usize.ofInt 0 (by intlit)) Result.ret { ntable0 @@ -242,84 +248,85 @@ def hashmap.HashMap.try_resize_fwd_back } else Result.ret { self with hashmap_hash_map_max_load_factor := (i, i0) } -/- [hashmap_main::hashmap::HashMap::{0}::insert] -/ -def hashmap.HashMap.insert_fwd_back +/- [hashmap_main::hashmap::HashMap::{0}::insert]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def hashmap.HashMap.insert (T : Type) (self : hashmap.HashMap T) (key : Usize) (value : T) : Result (hashmap.HashMap T) := do - let self0 ← hashmap.HashMap.insert_no_resize_fwd_back T self key value - let i ← hashmap.HashMap.len_fwd T self0 + let self0 ← hashmap.HashMap.insert_no_resize T self key value + let i ← hashmap.HashMap.len T self0 if i > self0.hashmap_hash_map_max_load - then hashmap.HashMap.try_resize_fwd_back T self0 + then hashmap.HashMap.try_resize T self0 else Result.ret self0 -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -divergent def hashmap.HashMap.contains_key_in_list_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: loop 0: forward function -/ +divergent def hashmap.HashMap.contains_key_in_list_loop (T : Type) (key : Usize) (ls : hashmap.List T) : Result Bool := match ls with | hashmap.List.Cons ckey t tl => if ckey = key then Result.ret true - else hashmap.HashMap.contains_key_in_list_loop_fwd T key tl + else hashmap.HashMap.contains_key_in_list_loop T key tl | hashmap.List.Nil => Result.ret false -/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list] -/ -def hashmap.HashMap.contains_key_in_list_fwd +/- [hashmap_main::hashmap::HashMap::{0}::contains_key_in_list]: forward function -/ +def hashmap.HashMap.contains_key_in_list (T : Type) (key : Usize) (ls : hashmap.List T) : Result Bool := - hashmap.HashMap.contains_key_in_list_loop_fwd T key ls + hashmap.HashMap.contains_key_in_list_loop T key ls -/- [hashmap_main::hashmap::HashMap::{0}::contains_key] -/ -def hashmap.HashMap.contains_key_fwd +/- [hashmap_main::hashmap::HashMap::{0}::contains_key]: forward function -/ +def hashmap.HashMap.contains_key (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result Bool := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod - hashmap.HashMap.contains_key_in_list_fwd T key l + hashmap.HashMap.contains_key_in_list T key l -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -divergent def hashmap.HashMap.get_in_list_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: loop 0: forward function -/ +divergent def hashmap.HashMap.get_in_list_loop (T : Type) (key : Usize) (ls : hashmap.List T) : Result T := match ls with | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hashmap.HashMap.get_in_list_loop_fwd T key tl + else hashmap.HashMap.get_in_list_loop T key tl | hashmap.List.Nil => Result.fail Error.panic -/- [hashmap_main::hashmap::HashMap::{0}::get_in_list] -/ -def hashmap.HashMap.get_in_list_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: forward function -/ +def hashmap.HashMap.get_in_list (T : Type) (key : Usize) (ls : hashmap.List T) : Result T := - hashmap.HashMap.get_in_list_loop_fwd T key ls + hashmap.HashMap.get_in_list_loop T key ls -/- [hashmap_main::hashmap::HashMap::{0}::get] -/ -def hashmap.HashMap.get_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get]: forward function -/ +def hashmap.HashMap.get (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod - hashmap.HashMap.get_in_list_fwd T key l + hashmap.HashMap.get_in_list T key l -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -divergent def hashmap.HashMap.get_mut_in_list_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function -/ +divergent def hashmap.HashMap.get_mut_in_list_loop (T : Type) (ls : hashmap.List T) (key : Usize) : Result T := match ls with | hashmap.List.Cons ckey cvalue tl => if ckey = key then Result.ret cvalue - else hashmap.HashMap.get_mut_in_list_loop_fwd T tl key + else hashmap.HashMap.get_mut_in_list_loop T tl key | hashmap.List.Nil => Result.fail Error.panic -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ -def hashmap.HashMap.get_mut_in_list_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: forward function -/ +def hashmap.HashMap.get_mut_in_list (T : Type) (ls : hashmap.List T) (key : Usize) : Result T := - hashmap.HashMap.get_mut_in_list_loop_fwd T ls key + hashmap.HashMap.get_mut_in_list_loop T ls key -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: backward function 0 -/ divergent def hashmap.HashMap.get_mut_in_list_loop_back (T : Type) (ls : hashmap.List T) (key : Usize) (ret0 : T) : Result (hashmap.List T) @@ -334,31 +341,31 @@ divergent def hashmap.HashMap.get_mut_in_list_loop_back Result.ret (hashmap.List.Cons ckey cvalue tl0) | hashmap.List.Nil => Result.fail Error.panic -/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: backward function 0 -/ def hashmap.HashMap.get_mut_in_list_back (T : Type) (ls : hashmap.List T) (key : Usize) (ret0 : T) : Result (hashmap.List T) := hashmap.HashMap.get_mut_in_list_loop_back T ls key ret0 -/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ -def hashmap.HashMap.get_mut_fwd +/- [hashmap_main::hashmap::HashMap::{0}::get_mut]: forward function -/ +def hashmap.HashMap.get_mut (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod - hashmap.HashMap.get_mut_in_list_fwd T l key + hashmap.HashMap.get_mut_in_list T l key -/- [hashmap_main::hashmap::HashMap::{0}::get_mut] -/ +/- [hashmap_main::hashmap::HashMap::{0}::get_mut]: backward function 0 -/ def hashmap.HashMap.get_mut_back (T : Type) (self : hashmap.HashMap T) (key : Usize) (ret0 : T) : Result (hashmap.HashMap T) := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← @@ -369,28 +376,28 @@ def hashmap.HashMap.get_mut_back l0 Result.ret { self with hashmap_hash_map_slots := v } -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -divergent def hashmap.HashMap.remove_from_list_loop_fwd +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function -/ +divergent def hashmap.HashMap.remove_from_list_loop (T : Type) (key : Usize) (ls : hashmap.List T) : Result (Option T) := match ls with | hashmap.List.Cons ckey t tl => if ckey = key then let mv_ls := - mem.replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + mem.replace (hashmap.List T) (hashmap.List.Cons ckey t tl) hashmap.List.Nil match mv_ls with | hashmap.List.Cons i cvalue tl0 => Result.ret (Option.some cvalue) | hashmap.List.Nil => Result.fail Error.panic - else hashmap.HashMap.remove_from_list_loop_fwd T key tl + else hashmap.HashMap.remove_from_list_loop T key tl | hashmap.List.Nil => Result.ret Option.none -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ -def hashmap.HashMap.remove_from_list_fwd +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: forward function -/ +def hashmap.HashMap.remove_from_list (T : Type) (key : Usize) (ls : hashmap.List T) : Result (Option T) := - hashmap.HashMap.remove_from_list_loop_fwd T key ls + hashmap.HashMap.remove_from_list_loop T key ls -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: backward function 1 -/ divergent def hashmap.HashMap.remove_from_list_loop_back (T : Type) (key : Usize) (ls : hashmap.List T) : Result (hashmap.List T) := match ls with @@ -398,7 +405,7 @@ divergent def hashmap.HashMap.remove_from_list_loop_back if ckey = key then let mv_ls := - mem.replace_fwd (hashmap.List T) (hashmap.List.Cons ckey t tl) + mem.replace (hashmap.List T) (hashmap.List.Cons ckey t tl) hashmap.List.Nil match mv_ls with | hashmap.List.Cons i cvalue tl0 => Result.ret tl0 @@ -409,21 +416,21 @@ divergent def hashmap.HashMap.remove_from_list_loop_back Result.ret (hashmap.List.Cons ckey t tl0) | hashmap.List.Nil => Result.ret hashmap.List.Nil -/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list] -/ +/- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: backward function 1 -/ def hashmap.HashMap.remove_from_list_back (T : Type) (key : Usize) (ls : hashmap.List T) : Result (hashmap.List T) := hashmap.HashMap.remove_from_list_loop_back T key ls -/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ -def hashmap.HashMap.remove_fwd +/- [hashmap_main::hashmap::HashMap::{0}::remove]: forward function -/ +def hashmap.HashMap.remove (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result (Option T) := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap.HashMap.remove_from_list_fwd T key l + let x ← hashmap.HashMap.remove_from_list T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => @@ -432,18 +439,18 @@ def hashmap.HashMap.remove_fwd (Usize.ofInt 1 (by intlit)) Result.ret (Option.some x0) -/- [hashmap_main::hashmap::HashMap::{0}::remove] -/ +/- [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 -/ def hashmap.HashMap.remove_back (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result (hashmap.HashMap T) := do - let hash ← hashmap.hash_key_fwd key + let hash ← hashmap.hash_key key let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots let hash_mod ← hash % i let l ← Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod - let x ← hashmap.HashMap.remove_from_list_fwd T key l + let x ← hashmap.HashMap.remove_from_list T key l match x with | Option.none => do @@ -467,23 +474,23 @@ def hashmap.HashMap.remove_back hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v } -/- [hashmap_main::hashmap::test1] -/ -def hashmap.test1_fwd : Result Unit := +/- [hashmap_main::hashmap::test1]: forward function -/ +def hashmap.test1 : Result Unit := do - let hm ← hashmap.HashMap.new_fwd U64 + let hm ← hashmap.HashMap.new U64 let hm0 ← - hashmap.HashMap.insert_fwd_back U64 hm (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.insert U64 hm (Usize.ofInt 0 (by intlit)) (U64.ofInt 42 (by intlit)) let hm1 ← - hashmap.HashMap.insert_fwd_back U64 hm0 (Usize.ofInt 128 (by intlit)) + hashmap.HashMap.insert U64 hm0 (Usize.ofInt 128 (by intlit)) (U64.ofInt 18 (by intlit)) let hm2 ← - hashmap.HashMap.insert_fwd_back U64 hm1 (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.insert U64 hm1 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 138 (by intlit)) let hm3 ← - hashmap.HashMap.insert_fwd_back U64 hm2 (Usize.ofInt 1056 (by intlit)) + hashmap.HashMap.insert U64 hm2 (Usize.ofInt 1056 (by intlit)) (U64.ofInt 256 (by intlit)) - let i ← hashmap.HashMap.get_fwd U64 hm3 (Usize.ofInt 128 (by intlit)) + let i ← hashmap.HashMap.get U64 hm3 (Usize.ofInt 128 (by intlit)) if not (i = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else @@ -491,14 +498,13 @@ def hashmap.test1_fwd : Result Unit := let hm4 ← hashmap.HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) (U64.ofInt 56 (by intlit)) - let i0 ← - hashmap.HashMap.get_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + let i0 ← hashmap.HashMap.get U64 hm4 (Usize.ofInt 1024 (by intlit)) if not (i0 = (U64.ofInt 56 (by intlit))) then Result.fail Error.panic else do let x ← - hashmap.HashMap.remove_fwd U64 hm4 (Usize.ofInt 1024 (by intlit)) + hashmap.HashMap.remove U64 hm4 (Usize.ofInt 1024 (by intlit)) match x with | Option.none => Result.fail Error.panic | Option.some x0 => @@ -510,42 +516,42 @@ def hashmap.test1_fwd : Result Unit := hashmap.HashMap.remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) let i1 ← - hashmap.HashMap.get_fwd U64 hm5 (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.get U64 hm5 (Usize.ofInt 0 (by intlit)) if not (i1 = (U64.ofInt 42 (by intlit))) then Result.fail Error.panic else do let i2 ← - hashmap.HashMap.get_fwd U64 hm5 + hashmap.HashMap.get U64 hm5 (Usize.ofInt 128 (by intlit)) if not (i2 = (U64.ofInt 18 (by intlit))) then Result.fail Error.panic else do let i3 ← - hashmap.HashMap.get_fwd U64 hm5 + hashmap.HashMap.get U64 hm5 (Usize.ofInt 1056 (by intlit)) if not (i3 = (U64.ofInt 256 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [hashmap_main::hashmap::test1] -/ -#assert (hashmap.test1_fwd == .ret ()) +#assert (hashmap.test1 == .ret ()) -/- [hashmap_main::insert_on_disk] -/ -def insert_on_disk_fwd +/- [hashmap_main::insert_on_disk]: forward function -/ +def insert_on_disk (key : Usize) (value : U64) (st : State) : Result (State × Unit) := do - let (st0, hm) ← hashmap_utils.deserialize_fwd st - let hm0 ← hashmap.HashMap.insert_fwd_back U64 hm key value - let (st1, _) ← hashmap_utils.serialize_fwd hm0 st0 + let (st0, hm) ← hashmap_utils.deserialize st + let hm0 ← hashmap.HashMap.insert U64 hm key value + let (st1, _) ← hashmap_utils.serialize hm0 st0 Result.ret (st1, ()) -/- [hashmap_main::main] -/ -def main_fwd : Result Unit := +/- [hashmap_main::main]: forward function -/ +def main : Result Unit := Result.ret () /- Unit test for [hashmap_main::main] -/ -#assert (main_fwd == .ret ()) +#assert (main == .ret ()) end hashmap_main diff --git a/tests/lean/HashmapMain/FunsExternal.lean b/tests/lean/HashmapMain/FunsExternal.lean index 3689dd45..b394b32b 100644 --- a/tests/lean/HashmapMain/FunsExternal.lean +++ b/tests/lean/HashmapMain/FunsExternal.lean @@ -7,11 +7,11 @@ open hashmap_main -- TODO: fill those bodies /- [hashmap_main::hashmap_utils::deserialize] -/ -def hashmap_utils.deserialize_fwd +def hashmap_utils.deserialize : State → Result (State × (hashmap.HashMap U64)) := fun _ => .fail .panic /- [hashmap_main::hashmap_utils::serialize] -/ -def hashmap_utils.serialize_fwd +def hashmap_utils.serialize : hashmap.HashMap U64 → State → Result (State × Unit) := fun _ _ => .fail .panic diff --git a/tests/lean/HashmapMain/FunsExternal_Template.lean b/tests/lean/HashmapMain/FunsExternal_Template.lean index 8853b7fc..f537fc8f 100644 --- a/tests/lean/HashmapMain/FunsExternal_Template.lean +++ b/tests/lean/HashmapMain/FunsExternal_Template.lean @@ -6,11 +6,11 @@ import HashmapMain.Types open Primitives open hashmap_main -/- [hashmap_main::hashmap_utils::deserialize] -/ -axiom hashmap_utils.deserialize_fwd +/- [hashmap_main::hashmap_utils::deserialize]: forward function -/ +axiom hashmap_utils.deserialize : State → Result (State × (hashmap.HashMap U64)) -/- [hashmap_main::hashmap_utils::serialize] -/ -axiom hashmap_utils.serialize_fwd +/- [hashmap_main::hashmap_utils::serialize]: forward function -/ +axiom hashmap_utils.serialize : hashmap.HashMap U64 → State → Result (State × Unit) diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 6e6eef3b..8cac7ac0 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -5,82 +5,83 @@ import Loops.Types open Primitives namespace loops -/- [loops::sum] -/ -divergent def sum_loop_fwd (max : U32) (i : U32) (s : U32) : Result U32 := +/- [loops::sum]: loop 0: forward function -/ +divergent def sum_loop (max : U32) (i : U32) (s : U32) : Result U32 := if i < max then do let s0 ← s + i let i0 ← i + (U32.ofInt 1 (by intlit)) - sum_loop_fwd max i0 s0 + sum_loop max i0 s0 else s * (U32.ofInt 2 (by intlit)) -/- [loops::sum] -/ -def sum_fwd (max : U32) : Result U32 := - sum_loop_fwd max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) +/- [loops::sum]: forward function -/ +def sum (max : U32) : Result U32 := + sum_loop max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) -/- [loops::sum_with_mut_borrows] -/ -divergent def sum_with_mut_borrows_loop_fwd +/- [loops::sum_with_mut_borrows]: loop 0: forward function -/ +divergent def sum_with_mut_borrows_loop (max : U32) (mi : U32) (ms : U32) : Result U32 := if mi < max then do let ms0 ← ms + mi let mi0 ← mi + (U32.ofInt 1 (by intlit)) - sum_with_mut_borrows_loop_fwd max mi0 ms0 + sum_with_mut_borrows_loop max mi0 ms0 else ms * (U32.ofInt 2 (by intlit)) -/- [loops::sum_with_mut_borrows] -/ -def sum_with_mut_borrows_fwd (max : U32) : Result U32 := - sum_with_mut_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) +/- [loops::sum_with_mut_borrows]: forward function -/ +def sum_with_mut_borrows (max : U32) : Result U32 := + sum_with_mut_borrows_loop max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) -/- [loops::sum_with_shared_borrows] -/ -divergent def sum_with_shared_borrows_loop_fwd +/- [loops::sum_with_shared_borrows]: loop 0: forward function -/ +divergent def sum_with_shared_borrows_loop (max : U32) (i : U32) (s : U32) : Result U32 := if i < max then do let i0 ← i + (U32.ofInt 1 (by intlit)) let s0 ← s + i0 - sum_with_shared_borrows_loop_fwd max i0 s0 + sum_with_shared_borrows_loop max i0 s0 else s * (U32.ofInt 2 (by intlit)) -/- [loops::sum_with_shared_borrows] -/ -def sum_with_shared_borrows_fwd (max : U32) : Result U32 := - sum_with_shared_borrows_loop_fwd max (U32.ofInt 0 (by intlit)) +/- [loops::sum_with_shared_borrows]: forward function -/ +def sum_with_shared_borrows (max : U32) : Result U32 := + sum_with_shared_borrows_loop max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) -/- [loops::clear] -/ -divergent def clear_loop_fwd_back - (v : Vec U32) (i : Usize) : Result (Vec U32) := +/- [loops::clear]: loop 0: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +divergent def clear_loop (v : Vec U32) (i : Usize) : Result (Vec U32) := let i0 := Vec.len U32 v if i < i0 then do let i1 ← i + (Usize.ofInt 1 (by intlit)) let v0 ← Vec.index_mut_back U32 v i (U32.ofInt 0 (by intlit)) - clear_loop_fwd_back v0 i1 + clear_loop v0 i1 else Result.ret v -/- [loops::clear] -/ -def clear_fwd_back (v : Vec U32) : Result (Vec U32) := - clear_loop_fwd_back v (Usize.ofInt 0 (by intlit)) +/- [loops::clear]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def clear (v : Vec U32) : Result (Vec U32) := + clear_loop v (Usize.ofInt 0 (by intlit)) -/- [loops::list_mem] -/ -divergent def list_mem_loop_fwd (x : U32) (ls : List U32) : Result Bool := +/- [loops::list_mem]: loop 0: forward function -/ +divergent def list_mem_loop (x : U32) (ls : List U32) : Result Bool := match ls with | List.Cons y tl => if y = x then Result.ret true - else list_mem_loop_fwd x tl + else list_mem_loop x tl | List.Nil => Result.ret false -/- [loops::list_mem] -/ -def list_mem_fwd (x : U32) (ls : List U32) : Result Bool := - list_mem_loop_fwd x ls +/- [loops::list_mem]: forward function -/ +def list_mem (x : U32) (ls : List U32) : Result Bool := + list_mem_loop x ls -/- [loops::list_nth_mut_loop] -/ -divergent def list_nth_mut_loop_loop_fwd +/- [loops::list_nth_mut_loop]: loop 0: forward function -/ +divergent def list_nth_mut_loop_loop (T : Type) (ls : List T) (i : U32) : Result T := match ls with | List.Cons x tl => @@ -89,14 +90,14 @@ divergent def list_nth_mut_loop_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_loop_fwd T tl i0 + list_nth_mut_loop_loop T tl i0 | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop] -/ -def list_nth_mut_loop_fwd (T : Type) (ls : List T) (i : U32) : Result T := - list_nth_mut_loop_loop_fwd T ls i +/- [loops::list_nth_mut_loop]: forward function -/ +def list_nth_mut_loop (T : Type) (ls : List T) (i : U32) : Result T := + list_nth_mut_loop_loop T ls i -/- [loops::list_nth_mut_loop] -/ +/- [loops::list_nth_mut_loop]: loop 0: backward function 0 -/ divergent def list_nth_mut_loop_loop_back (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := match ls with @@ -110,13 +111,13 @@ divergent def list_nth_mut_loop_loop_back Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop] -/ +/- [loops::list_nth_mut_loop]: backward function 0 -/ def list_nth_mut_loop_back (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_loop_loop_back T ls i ret0 -/- [loops::list_nth_shared_loop] -/ -divergent def list_nth_shared_loop_loop_fwd +/- [loops::list_nth_shared_loop]: loop 0: forward function -/ +divergent def list_nth_shared_loop_loop (T : Type) (ls : List T) (i : U32) : Result T := match ls with | List.Cons x tl => @@ -125,30 +126,28 @@ divergent def list_nth_shared_loop_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_loop_fwd T tl i0 + list_nth_shared_loop_loop T tl i0 | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_loop] -/ -def list_nth_shared_loop_fwd (T : Type) (ls : List T) (i : U32) : Result T := - list_nth_shared_loop_loop_fwd T ls i +/- [loops::list_nth_shared_loop]: forward function -/ +def list_nth_shared_loop (T : Type) (ls : List T) (i : U32) : Result T := + list_nth_shared_loop_loop T ls i -/- [loops::get_elem_mut] -/ -divergent def get_elem_mut_loop_fwd - (x : Usize) (ls : List Usize) : Result Usize := +/- [loops::get_elem_mut]: loop 0: forward function -/ +divergent def get_elem_mut_loop (x : Usize) (ls : List Usize) : Result Usize := match ls with - | List.Cons y tl => - if y = x - then Result.ret y - else get_elem_mut_loop_fwd x tl + | List.Cons y tl => if y = x + then Result.ret y + else get_elem_mut_loop x tl | List.Nil => Result.fail Error.panic -/- [loops::get_elem_mut] -/ -def get_elem_mut_fwd (slots : Vec (List Usize)) (x : Usize) : Result Usize := +/- [loops::get_elem_mut]: forward function -/ +def get_elem_mut (slots : Vec (List Usize)) (x : Usize) : Result Usize := do let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0 (by intlit)) - get_elem_mut_loop_fwd x l + get_elem_mut_loop x l -/- [loops::get_elem_mut] -/ +/- [loops::get_elem_mut]: loop 0: backward function 0 -/ divergent def get_elem_mut_loop_back (x : Usize) (ls : List Usize) (ret0 : Usize) : Result (List Usize) := match ls with @@ -161,7 +160,7 @@ divergent def get_elem_mut_loop_back Result.ret (List.Cons y tl0) | List.Nil => Result.fail Error.panic -/- [loops::get_elem_mut] -/ +/- [loops::get_elem_mut]: backward function 0 -/ def get_elem_mut_back (slots : Vec (List Usize)) (x : Usize) (ret0 : Usize) : Result (Vec (List Usize)) @@ -171,37 +170,35 @@ def get_elem_mut_back let l0 ← get_elem_mut_loop_back x l ret0 Vec.index_mut_back (List Usize) slots (Usize.ofInt 0 (by intlit)) l0 -/- [loops::get_elem_shared] -/ -divergent def get_elem_shared_loop_fwd +/- [loops::get_elem_shared]: loop 0: forward function -/ +divergent def get_elem_shared_loop (x : Usize) (ls : List Usize) : Result Usize := match ls with - | List.Cons y tl => - if y = x - then Result.ret y - else get_elem_shared_loop_fwd x tl + | List.Cons y tl => if y = x + then Result.ret y + else get_elem_shared_loop x tl | List.Nil => Result.fail Error.panic -/- [loops::get_elem_shared] -/ -def get_elem_shared_fwd - (slots : Vec (List Usize)) (x : Usize) : Result Usize := +/- [loops::get_elem_shared]: forward function -/ +def get_elem_shared (slots : Vec (List Usize)) (x : Usize) : Result Usize := do let l ← Vec.index (List Usize) slots (Usize.ofInt 0 (by intlit)) - get_elem_shared_loop_fwd x l + get_elem_shared_loop x l -/- [loops::id_mut] -/ -def id_mut_fwd (T : Type) (ls : List T) : Result (List T) := +/- [loops::id_mut]: forward function -/ +def id_mut (T : Type) (ls : List T) : Result (List T) := Result.ret ls -/- [loops::id_mut] -/ +/- [loops::id_mut]: backward function 0 -/ def id_mut_back (T : Type) (ls : List T) (ret0 : List T) : Result (List T) := Result.ret ret0 -/- [loops::id_shared] -/ -def id_shared_fwd (T : Type) (ls : List T) : Result (List T) := +/- [loops::id_shared]: forward function -/ +def id_shared (T : Type) (ls : List T) : Result (List T) := Result.ret ls -/- [loops::list_nth_mut_loop_with_id] -/ -divergent def list_nth_mut_loop_with_id_loop_fwd +/- [loops::list_nth_mut_loop_with_id]: loop 0: forward function -/ +divergent def list_nth_mut_loop_with_id_loop (T : Type) (i : U32) (ls : List T) : Result T := match ls with | List.Cons x tl => @@ -210,17 +207,16 @@ divergent def list_nth_mut_loop_with_id_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_with_id_loop_fwd T i0 tl + list_nth_mut_loop_with_id_loop T i0 tl | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_with_id] -/ -def list_nth_mut_loop_with_id_fwd - (T : Type) (ls : List T) (i : U32) : Result T := +/- [loops::list_nth_mut_loop_with_id]: forward function -/ +def list_nth_mut_loop_with_id (T : Type) (ls : List T) (i : U32) : Result T := do - let ls0 ← id_mut_fwd T ls - list_nth_mut_loop_with_id_loop_fwd T i ls0 + let ls0 ← id_mut T ls + list_nth_mut_loop_with_id_loop T i ls0 -/- [loops::list_nth_mut_loop_with_id] -/ +/- [loops::list_nth_mut_loop_with_id]: loop 0: backward function 0 -/ divergent def list_nth_mut_loop_with_id_loop_back (T : Type) (i : U32) (ls : List T) (ret0 : T) : Result (List T) := match ls with @@ -234,16 +230,16 @@ divergent def list_nth_mut_loop_with_id_loop_back Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_with_id] -/ +/- [loops::list_nth_mut_loop_with_id]: backward function 0 -/ def list_nth_mut_loop_with_id_back (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := do - let ls0 ← id_mut_fwd T ls + let ls0 ← id_mut T ls let l ← list_nth_mut_loop_with_id_loop_back T i ls0 ret0 id_mut_back T ls l -/- [loops::list_nth_shared_loop_with_id] -/ -divergent def list_nth_shared_loop_with_id_loop_fwd +/- [loops::list_nth_shared_loop_with_id]: loop 0: forward function -/ +divergent def list_nth_shared_loop_with_id_loop (T : Type) (i : U32) (ls : List T) : Result T := match ls with | List.Cons x tl => @@ -252,18 +248,18 @@ divergent def list_nth_shared_loop_with_id_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_with_id_loop_fwd T i0 tl + list_nth_shared_loop_with_id_loop T i0 tl | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_loop_with_id] -/ -def list_nth_shared_loop_with_id_fwd +/- [loops::list_nth_shared_loop_with_id]: forward function -/ +def list_nth_shared_loop_with_id (T : Type) (ls : List T) (i : U32) : Result T := do - let ls0 ← id_shared_fwd T ls - list_nth_shared_loop_with_id_loop_fwd T i ls0 + let ls0 ← id_shared T ls + list_nth_shared_loop_with_id_loop T i ls0 -/- [loops::list_nth_mut_loop_pair] -/ -divergent def list_nth_mut_loop_pair_loop_fwd +/- [loops::list_nth_mut_loop_pair]: loop 0: forward function -/ +divergent def list_nth_mut_loop_pair_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -274,16 +270,16 @@ divergent def list_nth_mut_loop_pair_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_pair_loop_fwd T tl0 tl1 i0 + list_nth_mut_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_pair] -/ -def list_nth_mut_loop_pair_fwd +/- [loops::list_nth_mut_loop_pair]: forward function -/ +def list_nth_mut_loop_pair (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_mut_loop_pair_loop_fwd T ls0 ls1 i + list_nth_mut_loop_pair_loop T ls0 ls1 i -/- [loops::list_nth_mut_loop_pair] -/ +/- [loops::list_nth_mut_loop_pair]: loop 0: backward function 0 -/ divergent def list_nth_mut_loop_pair_loop_back'a (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -302,14 +298,14 @@ divergent def list_nth_mut_loop_pair_loop_back'a | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_pair] -/ +/- [loops::list_nth_mut_loop_pair]: backward function 0 -/ def list_nth_mut_loop_pair_back'a (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_loop_pair_loop_back'a T ls0 ls1 i ret0 -/- [loops::list_nth_mut_loop_pair] -/ +/- [loops::list_nth_mut_loop_pair]: loop 0: backward function 1 -/ divergent def list_nth_mut_loop_pair_loop_back'b (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -328,15 +324,15 @@ divergent def list_nth_mut_loop_pair_loop_back'b | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_pair] -/ +/- [loops::list_nth_mut_loop_pair]: backward function 1 -/ def list_nth_mut_loop_pair_back'b (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_loop_pair_loop_back'b T ls0 ls1 i ret0 -/- [loops::list_nth_shared_loop_pair] -/ -divergent def list_nth_shared_loop_pair_loop_fwd +/- [loops::list_nth_shared_loop_pair]: loop 0: forward function -/ +divergent def list_nth_shared_loop_pair_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -347,17 +343,17 @@ divergent def list_nth_shared_loop_pair_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_pair_loop_fwd T tl0 tl1 i0 + list_nth_shared_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_loop_pair] -/ -def list_nth_shared_loop_pair_fwd +/- [loops::list_nth_shared_loop_pair]: forward function -/ +def list_nth_shared_loop_pair (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_shared_loop_pair_loop_fwd T ls0 ls1 i + list_nth_shared_loop_pair_loop T ls0 ls1 i -/- [loops::list_nth_mut_loop_pair_merge] -/ -divergent def list_nth_mut_loop_pair_merge_loop_fwd +/- [loops::list_nth_mut_loop_pair_merge]: loop 0: forward function -/ +divergent def list_nth_mut_loop_pair_merge_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -368,16 +364,16 @@ divergent def list_nth_mut_loop_pair_merge_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 + list_nth_mut_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_pair_merge] -/ -def list_nth_mut_loop_pair_merge_fwd +/- [loops::list_nth_mut_loop_pair_merge]: forward function -/ +def list_nth_mut_loop_pair_merge (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_mut_loop_pair_merge_loop_fwd T ls0 ls1 i + list_nth_mut_loop_pair_merge_loop T ls0 ls1 i -/- [loops::list_nth_mut_loop_pair_merge] -/ +/- [loops::list_nth_mut_loop_pair_merge]: loop 0: backward function 0 -/ divergent def list_nth_mut_loop_pair_merge_loop_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : (T × T)) : Result ((List T) × (List T)) @@ -398,15 +394,15 @@ divergent def list_nth_mut_loop_pair_merge_loop_back | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_loop_pair_merge] -/ +/- [loops::list_nth_mut_loop_pair_merge]: backward function 0 -/ def list_nth_mut_loop_pair_merge_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : (T × T)) : Result ((List T) × (List T)) := list_nth_mut_loop_pair_merge_loop_back T ls0 ls1 i ret0 -/- [loops::list_nth_shared_loop_pair_merge] -/ -divergent def list_nth_shared_loop_pair_merge_loop_fwd +/- [loops::list_nth_shared_loop_pair_merge]: loop 0: forward function -/ +divergent def list_nth_shared_loop_pair_merge_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -417,17 +413,17 @@ divergent def list_nth_shared_loop_pair_merge_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 + list_nth_shared_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_loop_pair_merge] -/ -def list_nth_shared_loop_pair_merge_fwd +/- [loops::list_nth_shared_loop_pair_merge]: forward function -/ +def list_nth_shared_loop_pair_merge (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_shared_loop_pair_merge_loop_fwd T ls0 ls1 i + list_nth_shared_loop_pair_merge_loop T ls0 ls1 i -/- [loops::list_nth_mut_shared_loop_pair] -/ -divergent def list_nth_mut_shared_loop_pair_loop_fwd +/- [loops::list_nth_mut_shared_loop_pair]: loop 0: forward function -/ +divergent def list_nth_mut_shared_loop_pair_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -438,16 +434,16 @@ divergent def list_nth_mut_shared_loop_pair_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_shared_loop_pair_loop_fwd T tl0 tl1 i0 + list_nth_mut_shared_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_shared_loop_pair] -/ -def list_nth_mut_shared_loop_pair_fwd +/- [loops::list_nth_mut_shared_loop_pair]: forward function -/ +def list_nth_mut_shared_loop_pair (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_mut_shared_loop_pair_loop_fwd T ls0 ls1 i + list_nth_mut_shared_loop_pair_loop T ls0 ls1 i -/- [loops::list_nth_mut_shared_loop_pair] -/ +/- [loops::list_nth_mut_shared_loop_pair]: loop 0: backward function 0 -/ divergent def list_nth_mut_shared_loop_pair_loop_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -467,15 +463,15 @@ divergent def list_nth_mut_shared_loop_pair_loop_back | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_shared_loop_pair] -/ +/- [loops::list_nth_mut_shared_loop_pair]: backward function 0 -/ def list_nth_mut_shared_loop_pair_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_shared_loop_pair_loop_back T ls0 ls1 i ret0 -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -divergent def list_nth_mut_shared_loop_pair_merge_loop_fwd +/- [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: forward function -/ +divergent def list_nth_mut_shared_loop_pair_merge_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -486,16 +482,16 @@ divergent def list_nth_mut_shared_loop_pair_merge_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_shared_loop_pair_merge_loop_fwd T tl0 tl1 i0 + list_nth_mut_shared_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ -def list_nth_mut_shared_loop_pair_merge_fwd +/- [loops::list_nth_mut_shared_loop_pair_merge]: forward function -/ +def list_nth_mut_shared_loop_pair_merge (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_mut_shared_loop_pair_merge_loop_fwd T ls0 ls1 i + list_nth_mut_shared_loop_pair_merge_loop T ls0 ls1 i -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +/- [loops::list_nth_mut_shared_loop_pair_merge]: loop 0: backward function 0 -/ divergent def list_nth_mut_shared_loop_pair_merge_loop_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -515,15 +511,15 @@ divergent def list_nth_mut_shared_loop_pair_merge_loop_back | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_mut_shared_loop_pair_merge] -/ +/- [loops::list_nth_mut_shared_loop_pair_merge]: backward function 0 -/ def list_nth_mut_shared_loop_pair_merge_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_mut_shared_loop_pair_merge_loop_back T ls0 ls1 i ret0 -/- [loops::list_nth_shared_mut_loop_pair] -/ -divergent def list_nth_shared_mut_loop_pair_loop_fwd +/- [loops::list_nth_shared_mut_loop_pair]: loop 0: forward function -/ +divergent def list_nth_shared_mut_loop_pair_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -534,16 +530,16 @@ divergent def list_nth_shared_mut_loop_pair_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_mut_loop_pair_loop_fwd T tl0 tl1 i0 + list_nth_shared_mut_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_mut_loop_pair] -/ -def list_nth_shared_mut_loop_pair_fwd +/- [loops::list_nth_shared_mut_loop_pair]: forward function -/ +def list_nth_shared_mut_loop_pair (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_shared_mut_loop_pair_loop_fwd T ls0 ls1 i + list_nth_shared_mut_loop_pair_loop T ls0 ls1 i -/- [loops::list_nth_shared_mut_loop_pair] -/ +/- [loops::list_nth_shared_mut_loop_pair]: loop 0: backward function 1 -/ divergent def list_nth_shared_mut_loop_pair_loop_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -563,15 +559,15 @@ divergent def list_nth_shared_mut_loop_pair_loop_back | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_mut_loop_pair] -/ +/- [loops::list_nth_shared_mut_loop_pair]: backward function 1 -/ def list_nth_shared_mut_loop_pair_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) := list_nth_shared_mut_loop_pair_loop_back T ls0 ls1 i ret0 -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -divergent def list_nth_shared_mut_loop_pair_merge_loop_fwd +/- [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: forward function -/ +divergent def list_nth_shared_mut_loop_pair_merge_loop (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := match ls0 with | List.Cons x0 tl0 => @@ -582,16 +578,16 @@ divergent def list_nth_shared_mut_loop_pair_merge_loop_fwd else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_mut_loop_pair_merge_loop_fwd T tl0 tl1 i0 + list_nth_shared_mut_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ -def list_nth_shared_mut_loop_pair_merge_fwd +/- [loops::list_nth_shared_mut_loop_pair_merge]: forward function -/ +def list_nth_shared_mut_loop_pair_merge (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) : Result (T × T) := - list_nth_shared_mut_loop_pair_merge_loop_fwd T ls0 ls1 i + list_nth_shared_mut_loop_pair_merge_loop T ls0 ls1 i -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +/- [loops::list_nth_shared_mut_loop_pair_merge]: loop 0: backward function 0 -/ divergent def list_nth_shared_mut_loop_pair_merge_loop_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) @@ -611,7 +607,7 @@ divergent def list_nth_shared_mut_loop_pair_merge_loop_back | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic -/- [loops::list_nth_shared_mut_loop_pair_merge] -/ +/- [loops::list_nth_shared_mut_loop_pair_merge]: backward function 0 -/ def list_nth_shared_mut_loop_pair_merge_back (T : Type) (ls0 : List T) (ls1 : List T) (i : U32) (ret0 : T) : Result (List T) diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index e4fa7612..dc744a29 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -35,64 +35,64 @@ inductive Sum (T1 T2 : Type) := | Left : T1 → Sum T1 T2 | Right : T2 → Sum T1 T2 -/- [no_nested_borrows::neg_test] -/ -def neg_test_fwd (x : I32) : Result I32 := +/- [no_nested_borrows::neg_test]: forward function -/ +def neg_test (x : I32) : Result I32 := - x -/- [no_nested_borrows::add_test] -/ -def add_test_fwd (x : U32) (y : U32) : Result U32 := +/- [no_nested_borrows::add_test]: forward function -/ +def add_test (x : U32) (y : U32) : Result U32 := x + y -/- [no_nested_borrows::subs_test] -/ -def subs_test_fwd (x : U32) (y : U32) : Result U32 := +/- [no_nested_borrows::subs_test]: forward function -/ +def subs_test (x : U32) (y : U32) : Result U32 := x - y -/- [no_nested_borrows::div_test] -/ -def div_test_fwd (x : U32) (y : U32) : Result U32 := +/- [no_nested_borrows::div_test]: forward function -/ +def div_test (x : U32) (y : U32) : Result U32 := x / y -/- [no_nested_borrows::div_test1] -/ -def div_test1_fwd (x : U32) : Result U32 := +/- [no_nested_borrows::div_test1]: forward function -/ +def div_test1 (x : U32) : Result U32 := x / (U32.ofInt 2 (by intlit)) -/- [no_nested_borrows::rem_test] -/ -def rem_test_fwd (x : U32) (y : U32) : Result U32 := +/- [no_nested_borrows::rem_test]: forward function -/ +def rem_test (x : U32) (y : U32) : Result U32 := x % y -/- [no_nested_borrows::cast_test] -/ -def cast_test_fwd (x : U32) : Result I32 := +/- [no_nested_borrows::cast_test]: forward function -/ +def cast_test (x : U32) : Result I32 := Scalar.cast .I32 x -/- [no_nested_borrows::test2] -/ -def test2_fwd : Result Unit := +/- [no_nested_borrows::test2]: forward function -/ +def test2 : Result Unit := do let _ ← (U32.ofInt 23 (by intlit)) + (U32.ofInt 44 (by intlit)) Result.ret () /- Unit test for [no_nested_borrows::test2] -/ -#assert (test2_fwd == .ret ()) +#assert (test2 == .ret ()) -/- [no_nested_borrows::get_max] -/ -def get_max_fwd (x : U32) (y : U32) : Result U32 := +/- [no_nested_borrows::get_max]: forward function -/ +def get_max (x : U32) (y : U32) : Result U32 := if x >= y then Result.ret x else Result.ret y -/- [no_nested_borrows::test3] -/ -def test3_fwd : Result Unit := +/- [no_nested_borrows::test3]: forward function -/ +def test3 : Result Unit := do - let x ← get_max_fwd (U32.ofInt 4 (by intlit)) (U32.ofInt 3 (by intlit)) - let y ← get_max_fwd (U32.ofInt 10 (by intlit)) (U32.ofInt 11 (by intlit)) + let x ← get_max (U32.ofInt 4 (by intlit)) (U32.ofInt 3 (by intlit)) + let y ← get_max (U32.ofInt 10 (by intlit)) (U32.ofInt 11 (by intlit)) let z ← x + y if not (z = (U32.ofInt 15 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test3] -/ -#assert (test3_fwd == .ret ()) +#assert (test3 == .ret ()) -/- [no_nested_borrows::test_neg1] -/ -def test_neg1_fwd : Result Unit := +/- [no_nested_borrows::test_neg1]: forward function -/ +def test_neg1 : Result Unit := do let y ← - (I32.ofInt 3 (by intlit)) if not (y = (I32.ofInt (-(3:Int)) (by intlit))) @@ -100,19 +100,19 @@ def test_neg1_fwd : Result Unit := else Result.ret () /- Unit test for [no_nested_borrows::test_neg1] -/ -#assert (test_neg1_fwd == .ret ()) +#assert (test_neg1 == .ret ()) -/- [no_nested_borrows::refs_test1] -/ -def refs_test1_fwd : Result Unit := +/- [no_nested_borrows::refs_test1]: forward function -/ +def refs_test1 : Result Unit := if not ((I32.ofInt 1 (by intlit)) = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::refs_test1] -/ -#assert (refs_test1_fwd == .ret ()) +#assert (refs_test1 == .ret ()) -/- [no_nested_borrows::refs_test2] -/ -def refs_test2_fwd : Result Unit := +/- [no_nested_borrows::refs_test2]: forward function -/ +def refs_test2 : Result Unit := if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) then Result.fail Error.panic else @@ -127,17 +127,17 @@ def refs_test2_fwd : Result Unit := else Result.ret () /- Unit test for [no_nested_borrows::refs_test2] -/ -#assert (refs_test2_fwd == .ret ()) +#assert (refs_test2 == .ret ()) -/- [no_nested_borrows::test_list1] -/ -def test_list1_fwd : Result Unit := +/- [no_nested_borrows::test_list1]: forward function -/ +def test_list1 : Result Unit := Result.ret () /- Unit test for [no_nested_borrows::test_list1] -/ -#assert (test_list1_fwd == .ret ()) +#assert (test_list1 == .ret ()) -/- [no_nested_borrows::test_box1] -/ -def test_box1_fwd : Result Unit := +/- [no_nested_borrows::test_box1]: forward function -/ +def test_box1 : Result Unit := let b := (I32.ofInt 1 (by intlit)) let x := b if not (x = (I32.ofInt 1 (by intlit))) @@ -145,90 +145,90 @@ def test_box1_fwd : Result Unit := else Result.ret () /- Unit test for [no_nested_borrows::test_box1] -/ -#assert (test_box1_fwd == .ret ()) +#assert (test_box1 == .ret ()) -/- [no_nested_borrows::copy_int] -/ -def copy_int_fwd (x : I32) : Result I32 := +/- [no_nested_borrows::copy_int]: forward function -/ +def copy_int (x : I32) : Result I32 := Result.ret x -/- [no_nested_borrows::test_unreachable] -/ -def test_unreachable_fwd (b : Bool) : Result Unit := +/- [no_nested_borrows::test_unreachable]: forward function -/ +def test_unreachable (b : Bool) : Result Unit := if b then Result.fail Error.panic else Result.ret () -/- [no_nested_borrows::test_panic] -/ -def test_panic_fwd (b : Bool) : Result Unit := +/- [no_nested_borrows::test_panic]: forward function -/ +def test_panic (b : Bool) : Result Unit := if b then Result.fail Error.panic else Result.ret () -/- [no_nested_borrows::test_copy_int] -/ -def test_copy_int_fwd : Result Unit := +/- [no_nested_borrows::test_copy_int]: forward function -/ +def test_copy_int : Result Unit := do - let y ← copy_int_fwd (I32.ofInt 0 (by intlit)) + let y ← copy_int (I32.ofInt 0 (by intlit)) if not ((I32.ofInt 0 (by intlit)) = y) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test_copy_int] -/ -#assert (test_copy_int_fwd == .ret ()) +#assert (test_copy_int == .ret ()) -/- [no_nested_borrows::is_cons] -/ -def is_cons_fwd (T : Type) (l : List T) : Result Bool := +/- [no_nested_borrows::is_cons]: forward function -/ +def is_cons (T : Type) (l : List T) : Result Bool := match l with | List.Cons t l0 => Result.ret true | List.Nil => Result.ret false -/- [no_nested_borrows::test_is_cons] -/ -def test_is_cons_fwd : Result Unit := +/- [no_nested_borrows::test_is_cons]: forward function -/ +def test_is_cons : Result Unit := do let l := List.Nil - let b ← is_cons_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l) + let b ← is_cons I32 (List.Cons (I32.ofInt 0 (by intlit)) l) if not b then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test_is_cons] -/ -#assert (test_is_cons_fwd == .ret ()) +#assert (test_is_cons == .ret ()) -/- [no_nested_borrows::split_list] -/ -def split_list_fwd (T : Type) (l : List T) : Result (T × (List T)) := +/- [no_nested_borrows::split_list]: forward function -/ +def split_list (T : Type) (l : List T) : Result (T × (List T)) := match l with | List.Cons hd tl => Result.ret (hd, tl) | List.Nil => Result.fail Error.panic -/- [no_nested_borrows::test_split_list] -/ -def test_split_list_fwd : Result Unit := +/- [no_nested_borrows::test_split_list]: forward function -/ +def test_split_list : Result Unit := do let l := List.Nil - let p ← split_list_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l) + let p ← split_list I32 (List.Cons (I32.ofInt 0 (by intlit)) l) let (hd, _) := p if not (hd = (I32.ofInt 0 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test_split_list] -/ -#assert (test_split_list_fwd == .ret ()) +#assert (test_split_list == .ret ()) -/- [no_nested_borrows::choose] -/ -def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := +/- [no_nested_borrows::choose]: forward function -/ +def choose (T : Type) (b : Bool) (x : T) (y : T) : Result T := if b then Result.ret x else Result.ret y -/- [no_nested_borrows::choose] -/ +/- [no_nested_borrows::choose]: backward function 0 -/ def choose_back (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := if b then Result.ret (ret0, y) else Result.ret (x, ret0) -/- [no_nested_borrows::choose_test] -/ -def choose_test_fwd : Result Unit := +/- [no_nested_borrows::choose_test]: forward function -/ +def choose_test : Result Unit := do let z ← - choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) + choose I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) let z0 ← z + (I32.ofInt 1 (by intlit)) if not (z0 = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic @@ -245,10 +245,10 @@ def choose_test_fwd : Result Unit := else Result.ret () /- Unit test for [no_nested_borrows::choose_test] -/ -#assert (choose_test_fwd == .ret ()) +#assert (choose_test == .ret ()) -/- [no_nested_borrows::test_char] -/ -def test_char_fwd : Result Char := +/- [no_nested_borrows::test_char]: forward function -/ +def test_char : Result Char := Result.ret 'a' mutual @@ -265,40 +265,38 @@ inductive Tree (T : Type) := end -/- [no_nested_borrows::list_length] -/ -divergent def list_length_fwd (T : Type) (l : List T) : Result U32 := +/- [no_nested_borrows::list_length]: forward function -/ +divergent def list_length (T : Type) (l : List T) : Result U32 := match l with | List.Cons t l1 => do - let i ← list_length_fwd T l1 + let i ← list_length T l1 (U32.ofInt 1 (by intlit)) + i | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) -/- [no_nested_borrows::list_nth_shared] -/ -divergent def list_nth_shared_fwd - (T : Type) (l : List T) (i : U32) : Result T := +/- [no_nested_borrows::list_nth_shared]: forward function -/ +divergent def list_nth_shared (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_fwd T tl i0 + else do + let i0 ← i - (U32.ofInt 1 (by intlit)) + list_nth_shared T tl i0 | List.Nil => Result.fail Error.panic -/- [no_nested_borrows::list_nth_mut] -/ -divergent def list_nth_mut_fwd (T : Type) (l : List T) (i : U32) : Result T := +/- [no_nested_borrows::list_nth_mut]: forward function -/ +divergent def list_nth_mut (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_fwd T tl i0 + list_nth_mut T tl i0 | List.Nil => Result.fail Error.panic -/- [no_nested_borrows::list_nth_mut] -/ +/- [no_nested_borrows::list_nth_mut]: backward function 0 -/ divergent def list_nth_mut_back (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with @@ -312,46 +310,47 @@ divergent def list_nth_mut_back Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic -/- [no_nested_borrows::list_rev_aux] -/ -divergent def list_rev_aux_fwd +/- [no_nested_borrows::list_rev_aux]: forward function -/ +divergent def list_rev_aux (T : Type) (li : List T) (lo : List T) : Result (List T) := match li with - | List.Cons hd tl => list_rev_aux_fwd T tl (List.Cons hd lo) + | List.Cons hd tl => list_rev_aux T tl (List.Cons hd lo) | List.Nil => Result.ret lo -/- [no_nested_borrows::list_rev] -/ -def list_rev_fwd_back (T : Type) (l : List T) : Result (List T) := - let li := mem.replace_fwd (List T) l List.Nil - list_rev_aux_fwd T li List.Nil +/- [no_nested_borrows::list_rev]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def list_rev (T : Type) (l : List T) : Result (List T) := + let li := mem.replace (List T) l List.Nil + list_rev_aux T li List.Nil -/- [no_nested_borrows::test_list_functions] -/ -def test_list_functions_fwd : Result Unit := +/- [no_nested_borrows::test_list_functions]: forward function -/ +def test_list_functions : Result Unit := do let l := List.Nil let l0 := List.Cons (I32.ofInt 2 (by intlit)) l let l1 := List.Cons (I32.ofInt 1 (by intlit)) l0 - let i ← list_length_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) + let i ← list_length I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) if not (i = (U32.ofInt 3 (by intlit))) then Result.fail Error.panic else do let i0 ← - list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) + list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 0 (by intlit)) if not (i0 = (I32.ofInt 0 (by intlit))) then Result.fail Error.panic else do let i1 ← - list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) + list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) if not (i1 = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic else do let i2 ← - list_nth_shared_fwd I32 (List.Cons (I32.ofInt 0 (by intlit)) - l1) (U32.ofInt 2 (by intlit)) + list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) + (U32.ofInt 2 (by intlit)) if not (i2 = (I32.ofInt 2 (by intlit))) then Result.fail Error.panic else @@ -360,74 +359,72 @@ def test_list_functions_fwd : Result Unit := list_nth_mut_back I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) (I32.ofInt 3 (by intlit)) - let i3 ← - list_nth_shared_fwd I32 ls (U32.ofInt 0 (by intlit)) + let i3 ← list_nth_shared I32 ls (U32.ofInt 0 (by intlit)) if not (i3 = (I32.ofInt 0 (by intlit))) then Result.fail Error.panic else do let i4 ← - list_nth_shared_fwd I32 ls (U32.ofInt 1 (by intlit)) + list_nth_shared I32 ls (U32.ofInt 1 (by intlit)) if not (i4 = (I32.ofInt 3 (by intlit))) then Result.fail Error.panic else do let i5 ← - list_nth_shared_fwd I32 ls - (U32.ofInt 2 (by intlit)) + list_nth_shared I32 ls (U32.ofInt 2 (by intlit)) if not (i5 = (I32.ofInt 2 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test_list_functions] -/ -#assert (test_list_functions_fwd == .ret ()) +#assert (test_list_functions == .ret ()) -/- [no_nested_borrows::id_mut_pair1] -/ -def id_mut_pair1_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := +/- [no_nested_borrows::id_mut_pair1]: forward function -/ +def id_mut_pair1 (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := Result.ret (x, y) -/- [no_nested_borrows::id_mut_pair1] -/ +/- [no_nested_borrows::id_mut_pair1]: backward function 0 -/ def id_mut_pair1_back (T1 T2 : Type) (x : T1) (y : T2) (ret0 : (T1 × T2)) : Result (T1 × T2) := let (t, t0) := ret0 Result.ret (t, t0) -/- [no_nested_borrows::id_mut_pair2] -/ -def id_mut_pair2_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := +/- [no_nested_borrows::id_mut_pair2]: forward function -/ +def id_mut_pair2 (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := let (t, t0) := p Result.ret (t, t0) -/- [no_nested_borrows::id_mut_pair2] -/ +/- [no_nested_borrows::id_mut_pair2]: backward function 0 -/ def id_mut_pair2_back (T1 T2 : Type) (p : (T1 × T2)) (ret0 : (T1 × T2)) : Result (T1 × T2) := let (t, t0) := ret0 Result.ret (t, t0) -/- [no_nested_borrows::id_mut_pair3] -/ -def id_mut_pair3_fwd (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := +/- [no_nested_borrows::id_mut_pair3]: forward function -/ +def id_mut_pair3 (T1 T2 : Type) (x : T1) (y : T2) : Result (T1 × T2) := Result.ret (x, y) -/- [no_nested_borrows::id_mut_pair3] -/ +/- [no_nested_borrows::id_mut_pair3]: backward function 0 -/ def id_mut_pair3_back'a (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T1) : Result T1 := Result.ret ret0 -/- [no_nested_borrows::id_mut_pair3] -/ +/- [no_nested_borrows::id_mut_pair3]: backward function 1 -/ def id_mut_pair3_back'b (T1 T2 : Type) (x : T1) (y : T2) (ret0 : T2) : Result T2 := Result.ret ret0 -/- [no_nested_borrows::id_mut_pair4] -/ -def id_mut_pair4_fwd (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := +/- [no_nested_borrows::id_mut_pair4]: forward function -/ +def id_mut_pair4 (T1 T2 : Type) (p : (T1 × T2)) : Result (T1 × T2) := let (t, t0) := p Result.ret (t, t0) -/- [no_nested_borrows::id_mut_pair4] -/ +/- [no_nested_borrows::id_mut_pair4]: backward function 0 -/ def id_mut_pair4_back'a (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T1) : Result T1 := Result.ret ret0 -/- [no_nested_borrows::id_mut_pair4] -/ +/- [no_nested_borrows::id_mut_pair4]: backward function 1 -/ def id_mut_pair4_back'b (T1 T2 : Type) (p : (T1 × T2)) (ret0 : T2) : Result T2 := Result.ret ret0 @@ -436,24 +433,24 @@ def id_mut_pair4_back'b structure StructWithTuple (T1 T2 : Type) where struct_with_tuple_p : (T1 × T2) -/- [no_nested_borrows::new_tuple1] -/ -def new_tuple1_fwd : Result (StructWithTuple U32 U32) := +/- [no_nested_borrows::new_tuple1]: forward function -/ +def new_tuple1 : Result (StructWithTuple U32 U32) := Result.ret { struct_with_tuple_p := ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) } -/- [no_nested_borrows::new_tuple2] -/ -def new_tuple2_fwd : Result (StructWithTuple I16 I16) := +/- [no_nested_borrows::new_tuple2]: forward function -/ +def new_tuple2 : Result (StructWithTuple I16 I16) := Result.ret { struct_with_tuple_p := ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) } -/- [no_nested_borrows::new_tuple3] -/ -def new_tuple3_fwd : Result (StructWithTuple U64 I64) := +/- [no_nested_borrows::new_tuple3]: forward function -/ +def new_tuple3 : Result (StructWithTuple U64 I64) := Result.ret { struct_with_tuple_p := @@ -464,8 +461,8 @@ def new_tuple3_fwd : Result (StructWithTuple U64 I64) := structure StructWithPair (T1 T2 : Type) where struct_with_pair_p : Pair T1 T2 -/- [no_nested_borrows::new_pair1] -/ -def new_pair1_fwd : Result (StructWithPair U32 U32) := +/- [no_nested_borrows::new_pair1]: forward function -/ +def new_pair1 : Result (StructWithPair U32 U32) := Result.ret { struct_with_pair_p := @@ -475,68 +472,69 @@ def new_pair1_fwd : Result (StructWithPair U32 U32) := } } -/- [no_nested_borrows::test_constants] -/ -def test_constants_fwd : Result Unit := +/- [no_nested_borrows::test_constants]: forward function -/ +def test_constants : Result Unit := do - let swt ← new_tuple1_fwd + let swt ← new_tuple1 let (i, _) := swt.struct_with_tuple_p if not (i = (U32.ofInt 1 (by intlit))) then Result.fail Error.panic else do - let swt0 ← new_tuple2_fwd + let swt0 ← new_tuple2 let (i0, _) := swt0.struct_with_tuple_p if not (i0 = (I16.ofInt 1 (by intlit))) then Result.fail Error.panic else do - let swt1 ← new_tuple3_fwd + let swt1 ← new_tuple3 let (i1, _) := swt1.struct_with_tuple_p if not (i1 = (U64.ofInt 1 (by intlit))) then Result.fail Error.panic else do - let swp ← new_pair1_fwd + let swp ← new_pair1 if not (swp.struct_with_pair_p.pair_x = (U32.ofInt 1 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [no_nested_borrows::test_constants] -/ -#assert (test_constants_fwd == .ret ()) +#assert (test_constants == .ret ()) -/- [no_nested_borrows::test_weird_borrows1] -/ -def test_weird_borrows1_fwd : Result Unit := +/- [no_nested_borrows::test_weird_borrows1]: forward function -/ +def test_weird_borrows1 : Result Unit := Result.ret () /- Unit test for [no_nested_borrows::test_weird_borrows1] -/ -#assert (test_weird_borrows1_fwd == .ret ()) +#assert (test_weird_borrows1 == .ret ()) -/- [no_nested_borrows::test_mem_replace] -/ -def test_mem_replace_fwd_back (px : U32) : Result U32 := - let y := mem.replace_fwd U32 px (U32.ofInt 1 (by intlit)) +/- [no_nested_borrows::test_mem_replace]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def test_mem_replace (px : U32) : Result U32 := + let y := mem.replace U32 px (U32.ofInt 1 (by intlit)) if not (y = (U32.ofInt 0 (by intlit))) then Result.fail Error.panic else Result.ret (U32.ofInt 2 (by intlit)) -/- [no_nested_borrows::test_shared_borrow_bool1] -/ -def test_shared_borrow_bool1_fwd (b : Bool) : Result U32 := +/- [no_nested_borrows::test_shared_borrow_bool1]: forward function -/ +def test_shared_borrow_bool1 (b : Bool) : Result U32 := if b then Result.ret (U32.ofInt 0 (by intlit)) else Result.ret (U32.ofInt 1 (by intlit)) -/- [no_nested_borrows::test_shared_borrow_bool2] -/ -def test_shared_borrow_bool2_fwd : Result U32 := +/- [no_nested_borrows::test_shared_borrow_bool2]: forward function -/ +def test_shared_borrow_bool2 : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) -/- [no_nested_borrows::test_shared_borrow_enum1] -/ -def test_shared_borrow_enum1_fwd (l : List U32) : Result U32 := +/- [no_nested_borrows::test_shared_borrow_enum1]: forward function -/ +def test_shared_borrow_enum1 (l : List U32) : Result U32 := match l with | List.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) -/- [no_nested_borrows::test_shared_borrow_enum2] -/ -def test_shared_borrow_enum2_fwd : Result U32 := +/- [no_nested_borrows::test_shared_borrow_enum2]: forward function -/ +def test_shared_borrow_enum2 : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) end no_nested_borrows diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean index 9f63b460..ade65656 100644 --- a/tests/lean/Paper.lean +++ b/tests/lean/Paper.lean @@ -4,39 +4,40 @@ import Base open Primitives namespace paper -/- [paper::ref_incr] -/ -def ref_incr_fwd_back (x : I32) : Result I32 := +/- [paper::ref_incr]: merged forward/backward function + (there is a single backward function, and the forward function returns ()) -/ +def ref_incr (x : I32) : Result I32 := x + (I32.ofInt 1 (by intlit)) -/- [paper::test_incr] -/ -def test_incr_fwd : Result Unit := +/- [paper::test_incr]: forward function -/ +def test_incr : Result Unit := do - let x ← ref_incr_fwd_back (I32.ofInt 0 (by intlit)) + let x ← ref_incr (I32.ofInt 0 (by intlit)) if not (x = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [paper::test_incr] -/ -#assert (test_incr_fwd == .ret ()) +#assert (test_incr == .ret ()) -/- [paper::choose] -/ -def choose_fwd (T : Type) (b : Bool) (x : T) (y : T) : Result T := +/- [paper::choose]: forward function -/ +def choose (T : Type) (b : Bool) (x : T) (y : T) : Result T := if b then Result.ret x else Result.ret y -/- [paper::choose] -/ +/- [paper::choose]: backward function 0 -/ def choose_back (T : Type) (b : Bool) (x : T) (y : T) (ret0 : T) : Result (T × T) := if b then Result.ret (ret0, y) else Result.ret (x, ret0) -/- [paper::test_choose] -/ -def test_choose_fwd : Result Unit := +/- [paper::test_choose]: forward function -/ +def test_choose : Result Unit := do let z ← - choose_fwd I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) + choose I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) let z0 ← z + (I32.ofInt 1 (by intlit)) if not (z0 = (I32.ofInt 1 (by intlit))) then Result.fail Error.panic @@ -53,25 +54,25 @@ def test_choose_fwd : Result Unit := else Result.ret () /- Unit test for [paper::test_choose] -/ -#assert (test_choose_fwd == .ret ()) +#assert (test_choose == .ret ()) /- [paper::List] -/ inductive List (T : Type) := | Cons : T → List T → List T | Nil : List T -/- [paper::list_nth_mut] -/ -divergent def list_nth_mut_fwd (T : Type) (l : List T) (i : U32) : Result T := +/- [paper::list_nth_mut]: forward function -/ +divergent def list_nth_mut (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => if i = (U32.ofInt 0 (by intlit)) then Result.ret x else do let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_fwd T tl i0 + list_nth_mut T tl i0 | List.Nil => Result.fail Error.panic -/- [paper::list_nth_mut] -/ +/- [paper::list_nth_mut]: backward function 0 -/ divergent def list_nth_mut_back (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with @@ -85,40 +86,40 @@ divergent def list_nth_mut_back Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic -/- [paper::sum] -/ -divergent def sum_fwd (l : List I32) : Result I32 := +/- [paper::sum]: forward function -/ +divergent def sum (l : List I32) : Result I32 := match l with | List.Cons x tl => do - let i ← sum_fwd tl + let i ← sum tl x + i | List.Nil => Result.ret (I32.ofInt 0 (by intlit)) -/- [paper::test_nth] -/ -def test_nth_fwd : Result Unit := +/- [paper::test_nth]: forward function -/ +def test_nth : Result Unit := do let l := List.Nil let l0 := List.Cons (I32.ofInt 3 (by intlit)) l let l1 := List.Cons (I32.ofInt 2 (by intlit)) l0 let x ← - list_nth_mut_fwd I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) + list_nth_mut I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) (U32.ofInt 2 (by intlit)) let x0 ← x + (I32.ofInt 1 (by intlit)) let l2 ← list_nth_mut_back I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) (U32.ofInt 2 (by intlit)) x0 - let i ← sum_fwd l2 + let i ← sum l2 if not (i = (I32.ofInt 7 (by intlit))) then Result.fail Error.panic else Result.ret () /- Unit test for [paper::test_nth] -/ -#assert (test_nth_fwd == .ret ()) +#assert (test_nth == .ret ()) -/- [paper::call_choose] -/ -def call_choose_fwd (p : (U32 × U32)) : Result U32 := +/- [paper::call_choose]: forward function -/ +def call_choose (p : (U32 × U32)) : Result U32 := do let (px, py) := p - let pz ← choose_fwd U32 true px py + let pz ← choose U32 true px py let pz0 ← pz + (U32.ofInt 1 (by intlit)) let (px0, _) ← choose_back U32 true px py pz0 Result.ret px0 diff --git a/tests/lean/PoloniusList.lean b/tests/lean/PoloniusList.lean index 1d7ec99b..1453c275 100644 --- a/tests/lean/PoloniusList.lean +++ b/tests/lean/PoloniusList.lean @@ -9,17 +9,16 @@ inductive List (T : Type) := | Cons : T → List T → List T | Nil : List T -/- [polonius_list::get_list_at_x] -/ -divergent def get_list_at_x_fwd - (ls : List U32) (x : U32) : Result (List U32) := +/- [polonius_list::get_list_at_x]: forward function -/ +divergent def get_list_at_x (ls : List U32) (x : U32) : Result (List U32) := match ls with | List.Cons hd tl => if hd = x then Result.ret (List.Cons hd tl) - else get_list_at_x_fwd tl x + else get_list_at_x tl x | List.Nil => Result.ret List.Nil -/- [polonius_list::get_list_at_x] -/ +/- [polonius_list::get_list_at_x]: backward function 0 -/ divergent def get_list_at_x_back (ls : List U32) (x : U32) (ret0 : List U32) : Result (List U32) := match ls with -- cgit v1.2.3 From 36c3348bacf7127d3736f9aac16a430a30424020 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 6 Jul 2023 13:46:26 +0200 Subject: Use short names for the structure fields in Lean --- compiler/Config.ml | 11 ++++ compiler/Driver.ml | 4 +- compiler/Extract.ml | 13 +++-- compiler/ExtractBase.ml | 68 +++++++++++++++++----- compiler/Translate.ml | 1 + tests/lean/BetreeMain/Funs.lean | 106 +++++++++++++--------------------- tests/lean/BetreeMain/Types.lean | 16 +++--- tests/lean/Constants.lean | 15 +++-- tests/lean/Hashmap/Funs.lean | 90 +++++++++++++---------------- tests/lean/Hashmap/Types.lean | 8 +-- tests/lean/HashmapMain/Funs.lean | 116 +++++++++++++------------------------- tests/lean/HashmapMain/Types.lean | 8 +-- tests/lean/NoNestedBorrows.lean | 43 ++++---------- 13 files changed, 232 insertions(+), 267 deletions(-) diff --git a/compiler/Config.ml b/compiler/Config.ml index f58ba89b..0475899c 100644 --- a/compiler/Config.ml +++ b/compiler/Config.ml @@ -304,3 +304,14 @@ let filter_useless_functions = ref true called opaque_defs, of type OpaqueDefs. *) let wrap_opaque_in_sig = ref false + +(** Use short names for the record fields. + + Some backends can't disambiguate records when their field names have collisions. + When this happens, we use long names, by which we concatenate the record + names with the field names, and check whether there are name collisions. + + For backends which can disambiguate records (typically by using the typing + information), we use short names (i.e., the original field names). + *) +let record_fields_short_names = ref false diff --git a/compiler/Driver.ml b/compiler/Driver.ml index f935a717..166ef11b 100644 --- a/compiler/Driver.ml +++ b/compiler/Driver.ml @@ -163,7 +163,9 @@ let () = (* We don't support fuel for the Lean backend *) if !use_fuel then ( log#error "The Lean backend doesn't support the -use-fuel option"; - fail ()) + fail ()); + (* Lean can disambiguate the field names *) + record_fields_short_names := true | HOL4 -> (* We don't support fuel for the HOL4 backend *) if !use_fuel then ( diff --git a/compiler/Extract.ml b/compiler/Extract.ml index cacb9b96..558a981d 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -625,10 +625,15 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) in let field_name (def_name : name) (field_id : FieldId.id) (field_name : string option) : string = - let def_name = type_name_to_snake_case def_name ^ "_" in - match field_name with - | Some field_name -> def_name ^ field_name - | None -> def_name ^ FieldId.to_string field_id + let field_name = + match field_name with + | Some field_name -> field_name + | None -> FieldId.to_string field_id + in + if !Config.record_fields_short_names then field_name + else + let def_name = type_name_to_snake_case def_name ^ "_" in + def_name ^ field_name in let variant_name (def_name : name) (variant : string) : string = match !backend with diff --git a/compiler/ExtractBase.ml b/compiler/ExtractBase.ml index ede7af29..655bb033 100644 --- a/compiler/ExtractBase.ml +++ b/compiler/ExtractBase.ml @@ -416,7 +416,7 @@ module IdSet = Collections.MakeSet (IdOrderedType) We use it for lookups (during the translation) and to check for name clashes. - [id_to_string] is for debugging. + [id_to_name] is for debugging. *) type names_map = { id_to_name : string IdMap.t; @@ -427,7 +427,9 @@ type names_map = { *) names_set : StringSet.t; opaque_ids : IdSet.t; - (** The set of opaque definitions. + (** TODO: this is obsolete. Remove. + + The set of opaque definitions. See {!formatter.opaque_pre} for detailed explanations about why we need to know which definitions are opaque to compute names. @@ -488,6 +490,20 @@ let names_map_add_function (id_to_string : id -> string) (is_opaque : bool) (fid : fun_id) (name : string) (nm : names_map) : names_map = names_map_add id_to_string is_opaque (FunId fid) name nm +(** The unsafe names map stores mappings from identifiers to names which might + collide. For some backends and some names, it might be acceptable to have + collisions. For instance, in Lean, different records can have fields with + the same name because Lean uses the typing information to resolve the + ambiguities. + + This map complements the {!names_map}, which checks for collisions. + *) +type unsafe_names_map = { id_to_name : string IdMap.t } + +let unsafe_names_map_add (id : id) (name : string) (nm : unsafe_names_map) : + unsafe_names_map = + { id_to_name = IdMap.add id name nm.id_to_name } + (** Make a (variable) basename unique (by adding an index). We do this in an inefficient manner (by testing all indices starting from @@ -532,6 +548,11 @@ type fun_name_info = { keep_fwd : bool; num_backs : int } type extraction_ctx = { trans_ctx : trans_ctx; names_map : names_map; + (** The map for id to names, where we forbid name collisions + (ex.: we always forbid function name collisions). *) + unsafe_names_map : unsafe_names_map; + (** The map for id to names, where we allow name collisions + (ex.: we might allow record field name collisions). *) fmt : formatter; indent_incr : int; (** The indent increment we insert whenever we need to indent more *) @@ -690,23 +711,42 @@ let id_to_string (id : id) (ctx : extraction_ctx) : string = | TypeVarId id -> "type_var_id: " ^ TypeVarId.to_string id | VarId id -> "var_id: " ^ VarId.to_string id +(** We might not check for collisions for some specific ids (ex.: field names) *) +let allow_collisions (id : id) : bool = + match id with + | FieldId (_, _) -> !Config.record_fields_short_names + | _ -> false + let ctx_add (is_opaque : bool) (id : id) (name : string) (ctx : extraction_ctx) : extraction_ctx = - (* The id_to_string function to print nice debugging messages if there are - * collisions *) - let id_to_string (id : id) : string = id_to_string id ctx in - let names_map = names_map_add id_to_string is_opaque id name ctx.names_map in - { ctx with names_map } + (* We do not use the same name map if we allow/disallow collisions *) + if allow_collisions id then ( + assert (not is_opaque); + { + ctx with + unsafe_names_map = unsafe_names_map_add id name ctx.unsafe_names_map; + }) + else + (* The id_to_string function to print nice debugging messages if there are + * collisions *) + let id_to_string (id : id) : string = id_to_string id ctx in + let names_map = + names_map_add id_to_string is_opaque id name ctx.names_map + in + { ctx with names_map } (** [with_opaque_pre]: if [true] and the definition is opaque, add the opaque prefix *) let ctx_get (with_opaque_pre : bool) (id : id) (ctx : extraction_ctx) : string = - match IdMap.find_opt id ctx.names_map.id_to_name with - | Some s -> - let is_opaque = IdSet.mem id ctx.names_map.opaque_ids in - if with_opaque_pre && is_opaque then ctx.fmt.opaque_pre () ^ s else s - | None -> - log#serror ("Could not find: " ^ id_to_string id ctx); - raise Not_found + (* We do not use the same name map if we allow/disallow collisions *) + if allow_collisions id then IdMap.find id ctx.unsafe_names_map.id_to_name + else + match IdMap.find_opt id ctx.names_map.id_to_name with + | Some s -> + let is_opaque = IdSet.mem id ctx.names_map.opaque_ids in + if with_opaque_pre && is_opaque then ctx.fmt.opaque_pre () ^ s else s + | None -> + log#serror ("Could not find: " ^ id_to_string id ctx); + raise Not_found let ctx_get_global (with_opaque_pre : bool) (id : A.GlobalDeclId.id) (ctx : extraction_ctx) : string = diff --git a/compiler/Translate.ml b/compiler/Translate.ml index 444642c0..c5f7df92 100644 --- a/compiler/Translate.ml +++ b/compiler/Translate.ml @@ -922,6 +922,7 @@ let translate_crate (filename : string) (dest_dir : string) (crate : A.crate) : { ExtractBase.trans_ctx; names_map; + unsafe_names_map = { id_to_name = ExtractBase.IdMap.empty }; fmt; indent_incr = 2; use_opaque_pre = !Config.split_files; diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index 41e4349e..b0939155 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -48,23 +48,20 @@ def betree.fresh_node_id_back (counter : U64) : Result U64 := /- [betree_main::betree::NodeIdCounter::{0}::new]: forward function -/ def betree.NodeIdCounter.new : Result betree.NodeIdCounter := - Result.ret - { betree_node_id_counter_next_node_id := (U64.ofInt 0 (by intlit)) } + Result.ret { next_node_id := (U64.ofInt 0 (by intlit)) } /- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function -/ def betree.NodeIdCounter.fresh_id (self : betree.NodeIdCounter) : Result U64 := do - let _ ← self.betree_node_id_counter_next_node_id + - (U64.ofInt 1 (by intlit)) - Result.ret self.betree_node_id_counter_next_node_id + let _ ← self.next_node_id + (U64.ofInt 1 (by intlit)) + Result.ret self.next_node_id /- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 -/ def betree.NodeIdCounter.fresh_id_back (self : betree.NodeIdCounter) : Result betree.NodeIdCounter := do - let i ← self.betree_node_id_counter_next_node_id + - (U64.ofInt 1 (by intlit)) - Result.ret { betree_node_id_counter_next_node_id := i } + let i ← self.next_node_id + (U64.ofInt 1 (by intlit)) + Result.ret { next_node_id := i } /- [core::num::u64::{10}::MAX] -/ def core_num_u64_max_body : Result U64 := @@ -181,8 +178,7 @@ def betree.Leaf.split Result (State × betree.Internal) := do - let p ← - betree.List.split_at (U64 × U64) content params.betree_params_split_size + let p ← betree.List.split_at (U64 × U64) content params.split_size let (content0, content1) := p let p0 ← betree.List.hd (U64 × U64) content1 let (pivot, _) := p0 @@ -191,17 +187,9 @@ def betree.Leaf.split let id1 ← betree.NodeIdCounter.fresh_id node_id_cnt0 let (st0, _) ← betree.store_leaf_node id0 content0 st let (st1, _) ← betree.store_leaf_node id1 content1 st0 - let n := betree.Node.Leaf - { - betree_leaf_id := id0, - betree_leaf_size := params.betree_params_split_size - } - let n0 := betree.Node.Leaf - { - betree_leaf_id := id1, - betree_leaf_size := params.betree_params_split_size - } - Result.ret (st1, betree.Internal.mk self.betree_leaf_id pivot n n0) + let n := betree.Node.Leaf { id := id0, size := params.split_size } + let n0 := betree.Node.Leaf { id := id1, size := params.split_size } + Result.ret (st1, betree.Internal.mk self.id pivot n n0) /- [betree_main::betree::Leaf::{3}::split]: backward function 2 -/ def betree.Leaf.split_back @@ -210,8 +198,7 @@ def betree.Leaf.split_back Result betree.NodeIdCounter := do - let p ← - betree.List.split_at (U64 × U64) content params.betree_params_split_size + let p ← betree.List.split_at (U64 × U64) content params.split_size let (content0, content1) := p let _ ← betree.List.hd (U64 × U64) content1 let id0 ← betree.NodeIdCounter.fresh_id node_id_cnt @@ -392,7 +379,7 @@ mutual divergent def betree.Node.lookup Result.ret (st1, opt) | betree.Node.Leaf node => do - let (st0, bindings) ← betree.load_leaf_node node.betree_leaf_id st + let (st0, bindings) ← betree.load_leaf_node node.id st let opt ← betree.Node.lookup_in_bindings key bindings Result.ret (st0, opt) @@ -463,7 +450,7 @@ divergent def betree.Node.lookup_back Result.ret (betree.Node.Internal node0) | betree.Node.Leaf node => do - let (_, bindings) ← betree.load_leaf_node node.betree_leaf_id st + let (_, bindings) ← betree.load_leaf_node node.id st let _ ← betree.Node.lookup_in_bindings key bindings Result.ret (betree.Node.Leaf node) @@ -732,7 +719,7 @@ mutual divergent def betree.Node.apply_messages let (st0, content) ← betree.load_internal_node i st let content0 ← betree.Node.apply_messages_to_internal content msgs let num_msgs ← betree.List.len (U64 × betree.Message) content0 - if num_msgs >= params.betree_params_min_flush_size + if num_msgs >= params.min_flush_size then do let (st1, content1) ← @@ -750,22 +737,20 @@ mutual divergent def betree.Node.apply_messages Result.ret (st1, ()) | betree.Node.Leaf node => do - let (st0, content) ← betree.load_leaf_node node.betree_leaf_id st + let (st0, content) ← betree.load_leaf_node node.id st let content0 ← betree.Node.apply_messages_to_leaf content msgs let len ← betree.List.len (U64 × U64) content0 - let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size + let i ← (U64.ofInt 2 (by intlit)) * params.split_size if len >= i then do let (st1, _) ← betree.Leaf.split node content0 params node_id_cnt st0 - let (st2, _) ← - betree.store_leaf_node node.betree_leaf_id betree.List.Nil st1 + let (st2, _) ← betree.store_leaf_node node.id betree.List.Nil st1 Result.ret (st2, ()) else do - let (st1, _) ← - betree.store_leaf_node node.betree_leaf_id content0 st0 + let (st1, _) ← betree.store_leaf_node node.id content0 st0 Result.ret (st1, ()) /- [betree_main::betree::Node::{5}::apply_messages]: backward function 0 -/ @@ -782,7 +767,7 @@ divergent def betree.Node.apply_messages_back let (st0, content) ← betree.load_internal_node i st let content0 ← betree.Node.apply_messages_to_internal content msgs let num_msgs ← betree.List.len (U64 × betree.Message) content0 - if num_msgs >= params.betree_params_min_flush_size + if num_msgs >= params.min_flush_size then do let (st1, content1) ← @@ -802,25 +787,23 @@ divergent def betree.Node.apply_messages_back node_id_cnt) | betree.Node.Leaf node => do - let (st0, content) ← betree.load_leaf_node node.betree_leaf_id st + let (st0, content) ← betree.load_leaf_node node.id st let content0 ← betree.Node.apply_messages_to_leaf content msgs let len ← betree.List.len (U64 × U64) content0 - let i ← (U64.ofInt 2 (by intlit)) * params.betree_params_split_size + let i ← (U64.ofInt 2 (by intlit)) * params.split_size if len >= i then do let (st1, new_node) ← betree.Leaf.split node content0 params node_id_cnt st0 - let _ ← - betree.store_leaf_node node.betree_leaf_id betree.List.Nil st1 + let _ ← betree.store_leaf_node node.id betree.List.Nil st1 let node_id_cnt0 ← betree.Leaf.split_back node content0 params node_id_cnt st0 Result.ret (betree.Node.Internal new_node, node_id_cnt0) else do - let _ ← betree.store_leaf_node node.betree_leaf_id content0 st0 - Result.ret (betree.Node.Leaf { node with betree_leaf_size := len }, - node_id_cnt) + let _ ← betree.store_leaf_node node.id content0 st0 + Result.ret (betree.Node.Leaf { node with size := len }, node_id_cnt) /- [betree_main::betree::Internal::{4}::flush]: forward function -/ divergent def betree.Internal.flush @@ -834,7 +817,7 @@ divergent def betree.Internal.flush let p ← betree.List.partition_at_pivot betree.Message content i let (msgs_left, msgs_right) := p let len_left ← betree.List.len (U64 × betree.Message) msgs_left - if len_left >= params.betree_params_min_flush_size + if len_left >= params.min_flush_size then do let (st0, _) ← @@ -842,7 +825,7 @@ divergent def betree.Internal.flush let (_, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← betree.List.len (U64 × betree.Message) msgs_right - if len_right >= params.betree_params_min_flush_size + if len_right >= params.min_flush_size then do let (st1, _) ← @@ -872,7 +855,7 @@ divergent def betree.Internal.flush_back let p ← betree.List.partition_at_pivot betree.Message content i0 let (msgs_left, msgs_right) := p let len_left ← betree.List.len (U64 × betree.Message) msgs_left - if len_left >= params.betree_params_min_flush_size + if len_left >= params.min_flush_size then do let (st0, _) ← @@ -880,7 +863,7 @@ divergent def betree.Internal.flush_back let (n1, node_id_cnt0) ← betree.Node.apply_messages_back n params node_id_cnt msgs_left st let len_right ← betree.List.len (U64 × betree.Message) msgs_right - if len_right >= params.betree_params_min_flush_size + if len_right >= params.min_flush_size then do let (n2, node_id_cnt1) ← @@ -936,18 +919,11 @@ def betree.BeTree.new let node_id_cnt0 ← betree.NodeIdCounter.fresh_id_back node_id_cnt Result.ret (st0, { - betree_be_tree_params := - { - betree_params_min_flush_size := min_flush_size, - betree_params_split_size := split_size - }, - betree_be_tree_node_id_cnt := node_id_cnt0, - betree_be_tree_root := - (betree.Node.Leaf - { - betree_leaf_id := id, - betree_leaf_size := (U64.ofInt 0 (by intlit)) - }) + params := + { min_flush_size := min_flush_size, split_size := split_size }, + node_id_cnt := node_id_cnt0, + root := + (betree.Node.Leaf { id := id, size := (U64.ofInt 0 (by intlit)) }) }) /- [betree_main::betree::BeTree::{6}::apply]: forward function -/ @@ -957,11 +933,9 @@ def betree.BeTree.apply := do let (st0, _) ← - betree.Node.apply self.betree_be_tree_root self.betree_be_tree_params - self.betree_be_tree_node_id_cnt key msg st + betree.Node.apply self.root self.params self.node_id_cnt key msg st let _ ← - betree.Node.apply_back self.betree_be_tree_root - self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st + betree.Node.apply_back self.root self.params self.node_id_cnt key msg st Result.ret (st0, ()) /- [betree_main::betree::BeTree::{6}::apply]: backward function 0 -/ @@ -971,10 +945,8 @@ def betree.BeTree.apply_back := do let (n, nic) ← - betree.Node.apply_back self.betree_be_tree_root - self.betree_be_tree_params self.betree_be_tree_node_id_cnt key msg st - Result.ret - { self with betree_be_tree_node_id_cnt := nic, betree_be_tree_root := n } + betree.Node.apply_back self.root self.params self.node_id_cnt key msg st + Result.ret { self with node_id_cnt := nic, root := n } /- [betree_main::betree::BeTree::{6}::insert]: forward function -/ def betree.BeTree.insert @@ -1033,14 +1005,14 @@ def betree.BeTree.lookup (self : betree.BeTree) (key : U64) (st : State) : Result (State × (Option U64)) := - betree.Node.lookup self.betree_be_tree_root key st + betree.Node.lookup self.root key st /- [betree_main::betree::BeTree::{6}::lookup]: backward function 0 -/ def betree.BeTree.lookup_back (self : betree.BeTree) (key : U64) (st : State) : Result betree.BeTree := do - let n ← betree.Node.lookup_back self.betree_be_tree_root key st - Result.ret { self with betree_be_tree_root := n } + let n ← betree.Node.lookup_back self.root key st + Result.ret { self with root := n } /- [betree_main::main]: forward function -/ def main : Result Unit := diff --git a/tests/lean/BetreeMain/Types.lean b/tests/lean/BetreeMain/Types.lean index afbdac9a..783ade64 100644 --- a/tests/lean/BetreeMain/Types.lean +++ b/tests/lean/BetreeMain/Types.lean @@ -22,8 +22,8 @@ inductive betree.Message := /- [betree_main::betree::Leaf] -/ structure betree.Leaf where - betree_leaf_id : U64 - betree_leaf_size : U64 + id : U64 + size : U64 mutual @@ -40,18 +40,18 @@ end /- [betree_main::betree::Params] -/ structure betree.Params where - betree_params_min_flush_size : U64 - betree_params_split_size : U64 + min_flush_size : U64 + split_size : U64 /- [betree_main::betree::NodeIdCounter] -/ structure betree.NodeIdCounter where - betree_node_id_counter_next_node_id : U64 + next_node_id : U64 /- [betree_main::betree::BeTree] -/ structure betree.BeTree where - betree_be_tree_params : betree.Params - betree_be_tree_node_id_cnt : betree.NodeIdCounter - betree_be_tree_root : betree.Node + params : betree.Params + node_id_cnt : betree.NodeIdCounter + root : betree.Node /- The state type used in the state-error monad -/ axiom State : Type diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index f37c9204..8f22bfba 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -35,12 +35,12 @@ def mk_pair0 (x : U32) (y : U32) : Result (U32 × U32) := /- [constants::Pair] -/ structure Pair (T1 T2 : Type) where - pair_x : T1 - pair_y : T2 + x : T1 + y : T2 /- [constants::mk_pair1]: forward function -/ def mk_pair1 (x : U32) (y : U32) : Result (Pair U32 U32) := - Result.ret { pair_x := x, pair_y := y } + Result.ret { x := x, y := y } /- [constants::P0] -/ def p0_body : Result (U32 × U32) := @@ -59,17 +59,16 @@ def p2_c : (U32 × U32) := eval_global p2_body (by simp) /- [constants::P3] -/ def p3_body : Result (Pair U32 U32) := - Result.ret - { pair_x := (U32.ofInt 0 (by intlit)), pair_y := (U32.ofInt 1 (by intlit)) } + Result.ret { x := (U32.ofInt 0 (by intlit)), y := (U32.ofInt 1 (by intlit)) } def p3_c : Pair U32 U32 := eval_global p3_body (by simp) /- [constants::Wrap] -/ structure Wrap (T : Type) where - wrap_val : T + val : T /- [constants::Wrap::{0}::new]: forward function -/ def Wrap.new (T : Type) (val : T) : Result (Wrap T) := - Result.ret { wrap_val := val } + Result.ret { val := val } /- [constants::Y] -/ def y_body : Result (Wrap I32) := Wrap.new I32 (I32.ofInt 2 (by intlit)) @@ -77,7 +76,7 @@ def y_c : Wrap I32 := eval_global y_body (by simp) /- [constants::unwrap_y]: forward function -/ def unwrap_y : Result I32 := - Result.ret y_c.wrap_val + Result.ret y_c.val /- [constants::YVAL] -/ def yval_body : Result I32 := unwrap_y diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 34ff1379..5e11ffdd 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -38,10 +38,10 @@ def HashMap.new_with_capacity let i0 ← i / max_load_divisor Result.ret { - hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hash_map_max_load_factor := (max_load_dividend, max_load_divisor), - hash_map_max_load := i0, - hash_map_slots := slots + num_entries := (Usize.ofInt 0 (by intlit)), + max_load_factor := (max_load_dividend, max_load_divisor), + max_load := i0, + slots := slots } /- [hashmap::HashMap::{0}::new]: forward function -/ @@ -66,19 +66,13 @@ divergent def HashMap.clear_loop (there is a single backward function, and the forward function returns ()) -/ def HashMap.clear (T : Type) (self : HashMap T) : Result (HashMap T) := do - let v ← - HashMap.clear_loop T self.hash_map_slots (Usize.ofInt 0 (by intlit)) + let v ← HashMap.clear_loop T self.slots (Usize.ofInt 0 (by intlit)) Result.ret - { - self - with - hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hash_map_slots := v - } + { self with num_entries := (Usize.ofInt 0 (by intlit)), slots := v } /- [hashmap::HashMap::{0}::len]: forward function -/ def HashMap.len (T : Type) (self : HashMap T) : Result Usize := - Result.ret self.hash_map_num_entries + Result.ret self.num_entries /- [hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function -/ divergent def HashMap.insert_in_list_loop @@ -122,23 +116,22 @@ def HashMap.insert_no_resize := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.slots hash_mod let inserted ← HashMap.insert_in_list T key value l if inserted then do - let i0 ← self.hash_map_num_entries + (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries + (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.insert_in_list_back T key value l - let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 - Result.ret - { self with hash_map_num_entries := i0, hash_map_slots := v } + let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 + Result.ret { self with num_entries := i0, slots := v } else do let l0 ← HashMap.insert_in_list_back T key value l - let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } + let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 + Result.ret { self with slots := v } /- [core::num::u32::{9}::MAX] -/ def core_num_u32_max_body : Result U32 := @@ -194,9 +187,9 @@ def HashMap.move_elements def HashMap.try_resize (T : Type) (self : HashMap T) : Result (HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := Vec.len (List T) self.hash_map_slots + let capacity := Vec.len (List T) self.slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) - let (i, i0) := self.hash_map_max_load_factor + let (i, i0) := self.max_load_factor let i1 ← n1 / i if capacity <= i1 then @@ -204,16 +197,14 @@ def HashMap.try_resize (T : Type) (self : HashMap T) : Result (HashMap T) := let i2 ← capacity * (Usize.ofInt 2 (by intlit)) let ntable ← HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - HashMap.move_elements T ntable self.hash_map_slots - (Usize.ofInt 0 (by intlit)) + HashMap.move_elements T ntable self.slots (Usize.ofInt 0 (by intlit)) Result.ret { ntable0 with - hash_map_num_entries := self.hash_map_num_entries, - hash_map_max_load_factor := (i, i0) + num_entries := self.num_entries, max_load_factor := (i, i0) } - else Result.ret { self with hash_map_max_load_factor := (i, i0) } + else Result.ret { self with max_load_factor := (i, i0) } /- [hashmap::HashMap::{0}::insert]: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ @@ -224,7 +215,7 @@ def HashMap.insert do let self0 ← HashMap.insert_no_resize T self key value let i ← HashMap.len T self0 - if i > self0.hash_map_max_load + if i > self0.max_load then HashMap.try_resize T self0 else Result.ret self0 @@ -248,9 +239,9 @@ def HashMap.contains_key (T : Type) (self : HashMap T) (key : Usize) : Result Bool := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index (List T) self.hash_map_slots hash_mod + let l ← Vec.index (List T) self.slots hash_mod HashMap.contains_key_in_list T key l /- [hashmap::HashMap::{0}::get_in_list]: loop 0: forward function -/ @@ -271,9 +262,9 @@ def HashMap.get_in_list (T : Type) (key : Usize) (ls : List T) : Result T := def HashMap.get (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index (List T) self.hash_map_slots hash_mod + let l ← Vec.index (List T) self.slots hash_mod HashMap.get_in_list T key l /- [hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function -/ @@ -313,9 +304,9 @@ def HashMap.get_mut_in_list_back def HashMap.get_mut (T : Type) (self : HashMap T) (key : Usize) : Result T := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.slots hash_mod HashMap.get_mut_in_list T l key /- [hashmap::HashMap::{0}::get_mut]: backward function 0 -/ @@ -325,12 +316,12 @@ def HashMap.get_mut_back := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.slots hash_mod let l0 ← HashMap.get_mut_in_list_back T l key ret0 - let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } + let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 + Result.ret { self with slots := v } /- [hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function -/ divergent def HashMap.remove_from_list_loop @@ -378,15 +369,15 @@ def HashMap.remove (T : Type) (self : HashMap T) (key : Usize) : Result (Option T) := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.slots hash_mod let x ← HashMap.remove_from_list T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => do - let _ ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) + let _ ← self.num_entries - (Usize.ofInt 1 (by intlit)) Result.ret (Option.some x0) /- [hashmap::HashMap::{0}::remove]: backward function 0 -/ @@ -394,23 +385,22 @@ def HashMap.remove_back (T : Type) (self : HashMap T) (key : Usize) : Result (HashMap T) := do let hash ← hash_key key - let i := Vec.len (List T) self.hash_map_slots + let i := Vec.len (List T) self.slots let hash_mod ← hash % i - let l ← Vec.index_mut (List T) self.hash_map_slots hash_mod + let l ← Vec.index_mut (List T) self.slots hash_mod let x ← HashMap.remove_from_list T key l match x with | Option.none => do let l0 ← HashMap.remove_from_list_back T key l - let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 - Result.ret { self with hash_map_slots := v } + let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 + Result.ret { self with slots := v } | Option.some x0 => do - let i0 ← self.hash_map_num_entries - (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries - (Usize.ofInt 1 (by intlit)) let l0 ← HashMap.remove_from_list_back T key l - let v ← Vec.index_mut_back (List T) self.hash_map_slots hash_mod l0 - Result.ret - { self with hash_map_num_entries := i0, hash_map_slots := v } + let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 + Result.ret { self with num_entries := i0, slots := v } /- [hashmap::test1]: forward function -/ def test1 : Result Unit := diff --git a/tests/lean/Hashmap/Types.lean b/tests/lean/Hashmap/Types.lean index 7530f3b9..6606cf9e 100644 --- a/tests/lean/Hashmap/Types.lean +++ b/tests/lean/Hashmap/Types.lean @@ -11,9 +11,9 @@ inductive List (T : Type) := /- [hashmap::HashMap] -/ structure HashMap (T : Type) where - hash_map_num_entries : Usize - hash_map_max_load_factor : (Usize × Usize) - hash_map_max_load : Usize - hash_map_slots : Vec (List T) + num_entries : Usize + max_load_factor : (Usize × Usize) + max_load : Usize + slots : Vec (List T) end hashmap diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index b1afcd44..e82cc9b2 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -43,11 +43,10 @@ def hashmap.HashMap.new_with_capacity let i0 ← i / max_load_divisor Result.ret { - hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hashmap_hash_map_max_load_factor := - (max_load_dividend, max_load_divisor), - hashmap_hash_map_max_load := i0, - hashmap_hash_map_slots := slots + num_entries := (Usize.ofInt 0 (by intlit)), + max_load_factor := (max_load_dividend, max_load_divisor), + max_load := i0, + slots := slots } /- [hashmap_main::hashmap::HashMap::{0}::new]: forward function -/ @@ -77,19 +76,13 @@ def hashmap.HashMap.clear (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let v ← - hashmap.HashMap.clear_loop T self.hashmap_hash_map_slots - (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.clear_loop T self.slots (Usize.ofInt 0 (by intlit)) Result.ret - { - self - with - hashmap_hash_map_num_entries := (Usize.ofInt 0 (by intlit)), - hashmap_hash_map_slots := v - } + { self with num_entries := (Usize.ofInt 0 (by intlit)), slots := v } /- [hashmap_main::hashmap::HashMap::{0}::len]: forward function -/ def hashmap.HashMap.len (T : Type) (self : hashmap.HashMap T) : Result Usize := - Result.ret self.hashmap_hash_map_num_entries + Result.ret self.num_entries /- [hashmap_main::hashmap::HashMap::{0}::insert_in_list]: loop 0: forward function -/ divergent def hashmap.HashMap.insert_in_list_loop @@ -138,33 +131,22 @@ def hashmap.HashMap.insert_no_resize := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← - Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index_mut (hashmap.List T) self.slots hash_mod let inserted ← hashmap.HashMap.insert_in_list T key value l if inserted then do - let i0 ← self.hashmap_hash_map_num_entries + - (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries + (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.insert_in_list_back T key value l - let v ← - Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret - { - self - with - hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v - } + let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 + Result.ret { self with num_entries := i0, slots := v } else do let l0 ← hashmap.HashMap.insert_in_list_back T key value l - let v ← - Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret { self with hashmap_hash_map_slots := v } + let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 + Result.ret { self with slots := v } /- [core::num::u32::{9}::MAX] -/ def core_num_u32_max_body : Result U32 := @@ -227,9 +209,9 @@ def hashmap.HashMap.try_resize (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c - let capacity := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let capacity := Vec.len (hashmap.List T) self.slots let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) - let (i, i0) := self.hashmap_hash_map_max_load_factor + let (i, i0) := self.max_load_factor let i1 ← n1 / i if capacity <= i1 then @@ -237,16 +219,15 @@ def hashmap.HashMap.try_resize let i2 ← capacity * (Usize.ofInt 2 (by intlit)) let ntable ← hashmap.HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - hashmap.HashMap.move_elements T ntable self.hashmap_hash_map_slots + hashmap.HashMap.move_elements T ntable self.slots (Usize.ofInt 0 (by intlit)) Result.ret { ntable0 with - hashmap_hash_map_num_entries := self.hashmap_hash_map_num_entries, - hashmap_hash_map_max_load_factor := (i, i0) + num_entries := self.num_entries, max_load_factor := (i, i0) } - else Result.ret { self with hashmap_hash_map_max_load_factor := (i, i0) } + else Result.ret { self with max_load_factor := (i, i0) } /- [hashmap_main::hashmap::HashMap::{0}::insert]: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ @@ -257,7 +238,7 @@ def hashmap.HashMap.insert do let self0 ← hashmap.HashMap.insert_no_resize T self key value let i ← hashmap.HashMap.len T self0 - if i > self0.hashmap_hash_map_max_load + if i > self0.max_load then hashmap.HashMap.try_resize T self0 else Result.ret self0 @@ -281,9 +262,9 @@ def hashmap.HashMap.contains_key (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result Bool := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index (hashmap.List T) self.slots hash_mod hashmap.HashMap.contains_key_in_list T key l /- [hashmap_main::hashmap::HashMap::{0}::get_in_list]: loop 0: forward function -/ @@ -306,9 +287,9 @@ def hashmap.HashMap.get (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← Vec.index (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index (hashmap.List T) self.slots hash_mod hashmap.HashMap.get_in_list T key l /- [hashmap_main::hashmap::HashMap::{0}::get_mut_in_list]: loop 0: forward function -/ @@ -353,10 +334,9 @@ def hashmap.HashMap.get_mut (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result T := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← - Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index_mut (hashmap.List T) self.slots hash_mod hashmap.HashMap.get_mut_in_list T l key /- [hashmap_main::hashmap::HashMap::{0}::get_mut]: backward function 0 -/ @@ -366,15 +346,12 @@ def hashmap.HashMap.get_mut_back := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← - Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index_mut (hashmap.List T) self.slots hash_mod let l0 ← hashmap.HashMap.get_mut_in_list_back T l key ret0 - let v ← - Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots hash_mod - l0 - Result.ret { self with hashmap_hash_map_slots := v } + let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 + Result.ret { self with slots := v } /- [hashmap_main::hashmap::HashMap::{0}::remove_from_list]: loop 0: forward function -/ divergent def hashmap.HashMap.remove_from_list_loop @@ -426,17 +403,15 @@ def hashmap.HashMap.remove (T : Type) (self : hashmap.HashMap T) (key : Usize) : Result (Option T) := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← - Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index_mut (hashmap.List T) self.slots hash_mod let x ← hashmap.HashMap.remove_from_list T key l match x with | Option.none => Result.ret Option.none | Option.some x0 => do - let _ ← self.hashmap_hash_map_num_entries - - (Usize.ofInt 1 (by intlit)) + let _ ← self.num_entries - (Usize.ofInt 1 (by intlit)) Result.ret (Option.some x0) /- [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 -/ @@ -446,33 +421,22 @@ def hashmap.HashMap.remove_back := do let hash ← hashmap.hash_key key - let i := Vec.len (hashmap.List T) self.hashmap_hash_map_slots + let i := Vec.len (hashmap.List T) self.slots let hash_mod ← hash % i - let l ← - Vec.index_mut (hashmap.List T) self.hashmap_hash_map_slots hash_mod + let l ← Vec.index_mut (hashmap.List T) self.slots hash_mod let x ← hashmap.HashMap.remove_from_list T key l match x with | Option.none => do let l0 ← hashmap.HashMap.remove_from_list_back T key l - let v ← - Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret { self with hashmap_hash_map_slots := v } + let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 + Result.ret { self with slots := v } | Option.some x0 => do - let i0 ← self.hashmap_hash_map_num_entries - - (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries - (Usize.ofInt 1 (by intlit)) let l0 ← hashmap.HashMap.remove_from_list_back T key l - let v ← - Vec.index_mut_back (hashmap.List T) self.hashmap_hash_map_slots - hash_mod l0 - Result.ret - { - self - with - hashmap_hash_map_num_entries := i0, hashmap_hash_map_slots := v - } + let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 + Result.ret { self with num_entries := i0, slots := v } /- [hashmap_main::hashmap::test1]: forward function -/ def hashmap.test1 : Result Unit := diff --git a/tests/lean/HashmapMain/Types.lean b/tests/lean/HashmapMain/Types.lean index ac195e3d..3b3d0d7c 100644 --- a/tests/lean/HashmapMain/Types.lean +++ b/tests/lean/HashmapMain/Types.lean @@ -11,10 +11,10 @@ inductive hashmap.List (T : Type) := /- [hashmap_main::hashmap::HashMap] -/ structure hashmap.HashMap (T : Type) where - hashmap_hash_map_num_entries : Usize - hashmap_hash_map_max_load_factor : (Usize × Usize) - hashmap_hash_map_max_load : Usize - hashmap_hash_map_slots : Vec (hashmap.List T) + num_entries : Usize + max_load_factor : (Usize × Usize) + max_load : Usize + slots : Vec (hashmap.List T) /- The state type used in the state-error monad -/ axiom State : Type diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index dc744a29..1c6421bb 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -6,8 +6,8 @@ namespace no_nested_borrows /- [no_nested_borrows::Pair] -/ structure Pair (T1 T2 : Type) where - pair_x : T1 - pair_y : T2 + x : T1 + y : T2 /- [no_nested_borrows::List] -/ inductive List (T : Type) := @@ -431,71 +431,52 @@ def id_mut_pair4_back'b /- [no_nested_borrows::StructWithTuple] -/ structure StructWithTuple (T1 T2 : Type) where - struct_with_tuple_p : (T1 × T2) + p : (T1 × T2) /- [no_nested_borrows::new_tuple1]: forward function -/ def new_tuple1 : Result (StructWithTuple U32 U32) := - Result.ret - { - struct_with_tuple_p := - ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) - } + Result.ret { p := ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) } /- [no_nested_borrows::new_tuple2]: forward function -/ def new_tuple2 : Result (StructWithTuple I16 I16) := - Result.ret - { - struct_with_tuple_p := - ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) - } + Result.ret { p := ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) } /- [no_nested_borrows::new_tuple3]: forward function -/ def new_tuple3 : Result (StructWithTuple U64 I64) := - Result.ret - { - struct_with_tuple_p := - ((U64.ofInt 1 (by intlit)), (I64.ofInt 2 (by intlit))) - } + Result.ret { p := ((U64.ofInt 1 (by intlit)), (I64.ofInt 2 (by intlit))) } /- [no_nested_borrows::StructWithPair] -/ structure StructWithPair (T1 T2 : Type) where - struct_with_pair_p : Pair T1 T2 + p : Pair T1 T2 /- [no_nested_borrows::new_pair1]: forward function -/ def new_pair1 : Result (StructWithPair U32 U32) := Result.ret - { - struct_with_pair_p := - { - pair_x := (U32.ofInt 1 (by intlit)), - pair_y := (U32.ofInt 2 (by intlit)) - } - } + { p := { x := (U32.ofInt 1 (by intlit)), y := (U32.ofInt 2 (by intlit)) } } /- [no_nested_borrows::test_constants]: forward function -/ def test_constants : Result Unit := do let swt ← new_tuple1 - let (i, _) := swt.struct_with_tuple_p + let (i, _) := swt.p if not (i = (U32.ofInt 1 (by intlit))) then Result.fail Error.panic else do let swt0 ← new_tuple2 - let (i0, _) := swt0.struct_with_tuple_p + let (i0, _) := swt0.p if not (i0 = (I16.ofInt 1 (by intlit))) then Result.fail Error.panic else do let swt1 ← new_tuple3 - let (i1, _) := swt1.struct_with_tuple_p + let (i1, _) := swt1.p if not (i1 = (U64.ofInt 1 (by intlit))) then Result.fail Error.panic else do let swp ← new_pair1 - if not (swp.struct_with_pair_p.pair_x = - (U32.ofInt 1 (by intlit))) + if not (swp.p.x = (U32.ofInt 1 (by intlit))) then Result.fail Error.panic else Result.ret () -- cgit v1.2.3 From 2496a08691809683e256af7c479588a2fae8e3d7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 6 Jul 2023 14:23:21 +0200 Subject: Register the unfolding theorems in the Lean equation compilers and solve a "unused variable" warning --- backends/lean/Base/Diverge/Elab.lean | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 1af06fea..e5b39440 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -843,6 +843,8 @@ partial def proveUnfoldingThms (isValidThm : Expr) (inOutTys : Array (Expr × Ex all := [name] } addDecl decl + -- Add the unfolding theorem to the equation compiler + eqnsAttribute.add preDef.declName #[name] trace[Diverge.def.unfold] "proveUnfoldingThms: added thm: {name}:\n{thmTy}" let rec prove (i : Nat) : MetaM Unit := do if i = preDefs.size then pure () @@ -1011,6 +1013,13 @@ def Term.elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM U withFunLocalDecls headers fun funFVars => do for view in views, funFVar in funFVars do addLocalVarInfo view.declId funFVar + -- Add fake use site to prevent "unused variable" warning (if the + -- function is actually not recursive, Lean would print this warning). + -- Remark: we could detect this case and encode the function without + -- using the fixed-point. In practice it shouldn't happen however: + -- we define non-recursive functions with the `divergent` keyword + -- only for testing purposes. + addTermInfo' view.declId funFVar let values ← try let values ← elabFunValues headers @@ -1091,7 +1100,8 @@ namespace Tests . intro i hpos h; simp at h; linarith . rename_i hd tl ih intro i hpos h - rw [list_nth.unfold]; simp + -- We can directly use `rw [list_nth]`! + rw [list_nth]; simp split <;> simp [*] . tauto . -- TODO: we shouldn't have to do that @@ -1147,7 +1157,7 @@ namespace Tests let ls1 := ls match ls1 with | [] => Result.ret False - | x :: tl => Result.ret True + | _ :: _ => Result.ret True #check isCons.unfold -- cgit v1.2.3 From 9515bbad5b58ed1c51ac6d9fc9d7a4e5884b6273 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 6 Jul 2023 15:23:53 +0200 Subject: Reorganize a bit the lean backend files --- backends/lean/Base/Diverge/Elab.lean | 2 + backends/lean/Base/Utils.lean | 119 +++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 backends/lean/Base/Utils.lean diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index e5b39440..96f7abc0 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -2,6 +2,7 @@ import Lean import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd +import Base.Utils import Base.Diverge.Base import Base.Diverge.ElabBase @@ -13,6 +14,7 @@ namespace Diverge syntax (name := divergentDef) declModifiers "divergent" "def" declId ppIndent(optDeclSig) declVal : command +open Utils open Lean Elab Term Meta Primitives Lean.Meta /- The following was copied from the `wfRecursion` function. -/ diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean new file mode 100644 index 00000000..161b9ddb --- /dev/null +++ b/backends/lean/Base/Utils.lean @@ -0,0 +1,119 @@ +import Lean + +namespace Utils + +open Lean Elab Term Meta + +-- Useful helper to explore definitions and figure out the variant +-- of their sub-expressions. +def explore_term (incr : String) (e : Expr) : MetaM Unit := + match e with + | .bvar _ => do logInfo m!"{incr}bvar: {e}"; return () + | .fvar _ => do logInfo m!"{incr}fvar: {e}"; return () + | .mvar _ => do logInfo m!"{incr}mvar: {e}"; return () + | .sort _ => do logInfo m!"{incr}sort: {e}"; return () + | .const _ _ => do logInfo m!"{incr}const: {e}"; return () + | .app fn arg => do + logInfo m!"{incr}app: {e}" + explore_term (incr ++ " ") fn + explore_term (incr ++ " ") arg + | .lam _bName bTy body _binfo => do + logInfo m!"{incr}lam: {e}" + explore_term (incr ++ " ") bTy + explore_term (incr ++ " ") body + | .forallE _bName bTy body _bInfo => do + logInfo m!"{incr}forallE: {e}" + explore_term (incr ++ " ") bTy + explore_term (incr ++ " ") body + | .letE _dName ty val body _nonDep => do + logInfo m!"{incr}letE: {e}" + explore_term (incr ++ " ") ty + explore_term (incr ++ " ") val + explore_term (incr ++ " ") body + | .lit _ => do logInfo m!"{incr}lit: {e}"; return () + | .mdata _ e => do + logInfo m!"{incr}mdata: {e}" + explore_term (incr ++ " ") e + | .proj _ _ struct => do + logInfo m!"{incr}proj: {e}" + explore_term (incr ++ " ") struct + +def explore_decl (n : Name) : TermElabM Unit := do + logInfo m!"Name: {n}" + let env ← getEnv + let decl := env.constants.find! n + match decl with + | .defnInfo val => + logInfo m!"About to explore defn: {decl.name}" + logInfo m!"# Type:" + explore_term "" val.type + logInfo m!"# Value:" + explore_term "" val.value + | .axiomInfo _ => throwError m!"axiom: {n}" + | .thmInfo _ => throwError m!"thm: {n}" + | .opaqueInfo _ => throwError m!"opaque: {n}" + | .quotInfo _ => throwError m!"quot: {n}" + | .inductInfo _ => throwError m!"induct: {n}" + | .ctorInfo _ => throwError m!"ctor: {n}" + | .recInfo _ => throwError m!"rec: {n}" + +syntax (name := printDecl) "print_decl " ident : command + +open Lean.Elab.Command + +@[command_elab printDecl] def elabPrintDecl : CommandElab := fun stx => do + liftTermElabM do + let id := stx[1] + addCompletionInfo <| CompletionInfo.id id id.getId (danglingDot := false) {} none + let cs ← resolveGlobalConstWithInfos id + explore_decl cs[0]! + +private def test1 : Nat := 0 +private def test2 (x : Nat) : Nat := x + +print_decl test1 +print_decl test2 + +-- A map visitor function for expressions (adapted from `AbstractNestedProofs.visit`) +-- The continuation takes as parameters: +-- - the current depth of the expression (useful for printing/debugging) +-- - the expression to explore +partial def mapVisit (k : Nat → Expr → MetaM Expr) (e : Expr) : MetaM Expr := do + let mapVisitBinders (xs : Array Expr) (k2 : MetaM Expr) : MetaM Expr := do + let localInstances ← getLocalInstances + let mut lctx ← getLCtx + for x in xs do + let xFVarId := x.fvarId! + let localDecl ← xFVarId.getDecl + let type ← mapVisit k localDecl.type + let localDecl := localDecl.setType type + let localDecl ← match localDecl.value? with + | some value => let value ← mapVisit k value; pure <| localDecl.setValue value + | none => pure localDecl + lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl + withLCtx lctx localInstances k2 + -- TODO: use a cache? (Lean.checkCache) + let rec visit (i : Nat) (e : Expr) : MetaM Expr := do + -- Explore + let e ← k i e + match e with + | .bvar _ + | .fvar _ + | .mvar _ + | .sort _ + | .lit _ + | .const _ _ => pure e + | .app .. => do e.withApp fun f args => return mkAppN f (← args.mapM (visit (i + 1))) + | .lam .. => + lambdaLetTelescope e fun xs b => + mapVisitBinders xs do mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) + | .forallE .. => do + forallTelescope e fun xs b => mapVisitBinders xs do mkForallFVars xs (← visit (i + 1) b) + | .letE .. => do + lambdaLetTelescope e fun xs b => mapVisitBinders xs do + mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) + | .mdata _ b => return e.updateMData! (← visit (i + 1) b) + | .proj _ _ b => return e.updateProj! (← visit (i + 1) b) + visit 0 e + +end Utils -- cgit v1.2.3 From 0d1ac53f88f947ae94f6afb57b2a7e18a77460a7 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Sun, 9 Jul 2023 10:11:13 +0200 Subject: Make progress on the int tactic --- backends/lean/Base/Arith.lean | 413 +++++++++++++++++++------------ backends/lean/Base/ArithBase.lean | 10 + backends/lean/Base/Diverge/ElabBase.lean | 112 --------- 3 files changed, 267 insertions(+), 268 deletions(-) create mode 100644 backends/lean/Base/ArithBase.lean diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index bb776b55..df48a6a2 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -8,6 +8,7 @@ import Mathlib.Tactic.Linarith -- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet --import Mathlib.Tactic.Omega import Base.Primitives +import Base.ArithBase /- Mathlib tactics: @@ -53,9 +54,24 @@ namespace Arith open Primitives ---set_option pp.explicit true ---set_option pp.notation false ---set_option pp.coercions false +-- TODO: move? +theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by + cases h: x <;> simp_all + . rename_i n; + cases n <;> simp_all + . apply Int.negSucc_lt_zero + +-- TODO: move? +theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by + have hne : x - y ≠ 0 := by + simp + intro h + have: x = y := by linarith + simp_all + have h := ne_zero_is_lt_or_gt hne + match h with + | .inl _ => left; linarith + | .inr _ => right; linarith -- TODO: move instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val @@ -71,17 +87,9 @@ instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val -/ def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val --- We use this type-class to test if an expression is a scalar (if we manage --- to lookup an instance of this type-class, then it is) -class IsScalar (a : Type) where - -instance (ty : ScalarTy) : IsScalar (Scalar ty) where - -example (ty : ScalarTy) : IsScalar (Scalar ty) := inferInstance - -- Remark: I tried a version of the shape `HasProp {a : Type} (x : a)` -- but the lookup didn't work -class HasProp (a : Type) where +class HasProp (a : Sort u) where prop_ty : a → Prop prop : ∀ x:a, prop_ty x @@ -93,73 +101,50 @@ instance (a : Type) : HasProp (Vec a) where prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize prop := λ ⟨ _, l ⟩ => l -open Lean Lean.Elab Command Term Lean.Meta - --- Return true if the expression is a scalar expression -def isScalarExpr (e : Expr) : MetaM Bool := do - -- Try to convert the expression to a scalar - -- TODO: I tried to do it with Lean.Meta.mkAppM but it didn't work: how - -- do we allow Lean to perform (controlled) unfoldings for instantiation - -- purposes? - let r ← Lean.observing? do - let ty ← Lean.Meta.inferType e - let isScalar ← mkAppM `Arith.IsScalar #[ty] - let isScalar ← trySynthInstance isScalar - match isScalar with - | LOption.some x => some x - | _ => none - match r with - | .some _ => pure true - | _ => pure false +class PropHasImp (x : Prop) where + concl : Prop + prop : x → concl --- Return an instance of `HasProp` for `e` if it has some -def lookupHasProp (e : Expr) : MetaM (Option Expr) := do - logInfo f!"lookupHasProp" - -- TODO: do we need Lean.observing? - -- This actually eliminates the error messages - Lean.observing? do - logInfo f!"lookupHasProp: observing" - let ty ← Lean.Meta.inferType e - let hasProp ← mkAppM ``Arith.HasProp #[ty] - let hasPropInst ← trySynthInstance hasProp - match hasPropInst with - | LOption.some i => - logInfo m!"Found HasProp instance" - let i_prop ← mkProjection i `prop - some (← mkAppM' i_prop #[e]) - | _ => none +-- This also works for `x ≠ y` because this expression reduces to `¬ x = y` +-- and `Ne` is marked as `reducible` +instance (x y : Int) : PropHasImp (¬ x = y) where + concl := x < y ∨ x > y + prop := λ (h:x ≠ y) => ne_is_lt_or_gt h --- Auxiliary function for `collectHasPropInstances` -private partial def collectHasPropInstancesAux (hs : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do - -- We do it in a very simpler manner: we deconstruct applications, - -- and recursively explore the sub-expressions. Note that we do - -- not go inside foralls and abstractions (should we?). - e.withApp fun f args => do - let hasPropInst ← lookupHasProp f - let hs := Option.getD (hasPropInst.map hs.insert) hs - let hs ← args.foldlM collectHasPropInstancesAux hs - pure hs +open Lean Lean.Elab Command Term Lean.Meta --- Explore a term and return the instances of `HasProp` found for the sub-expressions -def collectHasPropInstances (e : Expr) : MetaM (HashSet Expr) := - collectHasPropInstancesAux HashSet.empty e +-- Small utility: print all the declarations in the context +elab "print_all_decls" : tactic => do + let ctx ← Lean.MonadLCtx.getLCtx + for decl in ← ctx.getDecls do + let ty ← Lean.Meta.inferType decl.toExpr + logInfo m!"{decl.toExpr} : {ty}" + pure () --- Explore a term and return the set of scalar expressions found inside -partial def collectScalarExprsAux (hs : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do +-- Explore a term by decomposing the applications (we explore the applied +-- functions and their arguments, but ignore lambdas, forall, etc. - +-- should we go inside?). +partial def foldTermApps (k : α → Expr → MetaM α) (s : α) (e : Expr) : MetaM α := do -- We do it in a very simpler manner: we deconstruct applications, -- and recursively explore the sub-expressions. Note that we do -- not go inside foralls and abstractions (should we?). e.withApp fun f args => do - let hs ← if ← isScalarExpr f then pure (hs.insert f) else pure hs - let hs ← args.foldlM collectScalarExprsAux hs - pure hs - --- Explore a term and return the list of scalar expressions found inside -def collectScalarExprs (e : Expr) : MetaM (HashSet Expr) := - collectScalarExprsAux HashSet.empty e - --- Collect the scalar expressions in the context -def getScalarExprsFromMainCtx : Tactic.TacticM (HashSet Expr) := do + let s ← k s f + args.foldlM (foldTermApps k) s + +-- Provided a function `k` which lookups type class instances on an expression, +-- collect all the instances lookuped by applying `k` on the sub-expressions of `e`. +def collectInstances + (k : Expr → MetaM (Option Expr)) (s : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do + let k s e := do + match ← k e with + | none => pure s + | some i => pure (s.insert i) + foldTermApps k s e + +-- Similar to `collectInstances`, but explores all the local declarations in the +-- main context. +def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do Lean.Elab.Tactic.withMainContext do -- Get the local context let ctx ← Lean.MonadLCtx.getLCtx @@ -169,40 +154,37 @@ def getScalarExprsFromMainCtx : Tactic.TacticM (HashSet Expr) := do let hs := HashSet.empty -- Explore the declarations let decls ← ctx.getDecls - let hs ← decls.foldlM (fun hs d => collectScalarExprsAux hs d.toExpr) hs - -- Return - pure hs + decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs + +-- Return an instance of `HasProp` for `e` if it has some +def lookupHasProp (e : Expr) : MetaM (Option Expr) := do + trace[Arith] "lookupHasProp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] "lookupHasProp: observing" + let ty ← Lean.Meta.inferType e + let hasProp ← mkAppM ``HasProp #[ty] + let hasPropInst ← trySynthInstance hasProp + match hasPropInst with + | LOption.some i => + trace[Arith] "Found HasProp instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none -- Collect the instances of `HasProp` for the subexpressions in the context -def getHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - Lean.Elab.Tactic.withMainContext do - -- Get the local context - let ctx ← Lean.MonadLCtx.getLCtx - -- Just a matter of precaution - let ctx ← instantiateLCtxMVars ctx - -- Initialize the hashset - let hs := HashSet.empty - -- Explore the declarations - let decls ← ctx.getDecls - let hs ← decls.foldlM (fun hs d => collectHasPropInstancesAux hs d.toExpr) hs - -- Return - pure hs +def collectHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupHasProp -elab "list_scalar_exprs" : tactic => do - logInfo m!"Listing scalar expressions" - let hs ← getScalarExprsFromMainCtx +elab "display_has_prop_instances" : tactic => do + trace[Arith] "Displaying the HasProp instances" + let hs ← collectHasPropInstancesFromMainCtx hs.forM fun e => do - logInfo m!"+ Scalar expression: {e}" + trace[Arith] "+ HasProp instance: {e}" -example (x y : U32) (z : Usize) : True := by - list_scalar_exprs - simp -elab "display_has_prop_instances" : tactic => do - logInfo m!"Displaying the HasProp instances" - let hs ← getHasPropInstancesFromMainCtx - hs.forM fun e => do - logInfo m!"+ HasProp instance: {e}" +set_option trace.Arith true example (x : U32) : True := by let i : HasProp U32 := inferInstance @@ -211,34 +193,45 @@ example (x : U32) : True := by display_has_prop_instances simp -elab "list_local_decls_1" : tactic => - Lean.Elab.Tactic.withMainContext do - -- Get the local context - let ctx ← Lean.MonadLCtx.getLCtx - let ctx ← instantiateLCtxMVars ctx - let decls ← ctx.getDecls - -- Filter the scalar expressions - let decls ← decls.filterMapM fun decl: Lean.LocalDecl => do - let declExpr := decl.toExpr - let declName := decl.userName - let declType ← Lean.Meta.inferType declExpr - dbg_trace f!"+ local decl: name: {declName} | expr: {declExpr} | ty: {declType}" - -- Try to convert the expression to a scalar - -- TODO: I tried to do it with Lean.Meta.mkAppM but it didn't work: how - -- do we allow Lean to perform (controlled) unfoldings for instantiation - -- purposes? - let r ← Lean.observing? do - let isScalar ← mkAppM `Arith.IsScalar #[declType] - let isScalar ← trySynthInstance isScalar - match isScalar with - | LOption.some x => some x - | _ => none - match r with - | .some _ => dbg_trace f!" Scalar expression"; pure r - | _ => dbg_trace f!" Not a scalar"; pure .none - pure () +set_option trace.Arith false -def evalAddDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool := false) : Tactic.TacticM Unit := +-- Return an instance of `PropHasImp` for `e` if it has some +def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do + trace[Arith] "lookupPropHasImp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] "lookupPropHasImp: observing" + let ty ← Lean.Meta.inferType e + trace[Arith] "lookupPropHasImp: ty: {ty}" + let cl ← mkAppM ``PropHasImp #[ty] + let inst ← trySynthInstance cl + match inst with + | LOption.some i => + trace[Arith] "Found PropHasImp instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Collect the instances of `PropHasImp` for the subexpressions in the context +def collectPropHasImpInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupPropHasImp + +elab "display_prop_has_imp_instances" : tactic => do + trace[Arith] "Displaying the PropHasImp instances" + let hs ← collectPropHasImpInstancesFromMainCtx + hs.forM fun e => do + trace[Arith] "+ PropHasImp instance: {e}" + +set_option trace.Arith true + +example (x y : Int) (h0 : x ≠ y) (h1 : ¬ x = y) : True := by + display_prop_has_imp_instances + simp + +set_option trace.Arith false + +def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := -- I don't think we need that Lean.Elab.Tactic.withMainContext do -- Insert the new declaration @@ -248,8 +241,7 @@ def evalAddDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool := false) let lctx ← Lean.MonadLCtx.getLCtx let fid := nval.fvarId! let decl := lctx.get! fid - -- Remark: logInfo instantiates the mvars (contrary to dbg_trace): - logInfo m!" new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" + trace[Arith] " new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" -- -- Tranform the main goal `?m0` to `let x = nval in ?m1` let mvarId ← Tactic.getMainGoal @@ -260,17 +252,14 @@ def evalAddDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool := false) -- - asLet is false: ewVal is `λ $name => $newMVar` -- We need to apply it to `val` let newVal := if asLet then newVal else mkAppN newVal #[val] - -- Focus on the current goal - Tactic.focus do - -- Assign the main goal. - -- We must do this *after* we focused on the current goal, because - -- after we assigned the meta variable the goal is considered as solved + -- Assign the main goal and update the current goal mvarId.assign newVal - -- Replace the list of goals with the new goal - we can do this because - -- we focused on the current goal - Lean.Elab.Tactic.setGoals [newMVar.mvarId!] + let goals ← Tactic.getUnsolvedGoals + Lean.Elab.Tactic.setGoals (newMVar.mvarId! :: goals) + -- Call the continuation + k nval -def evalAddDeclSyntax (name : Name) (val : Syntax) (asLet : Bool := false) : Tactic.TacticM Unit := +def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := -- I don't think we need that Lean.Elab.Tactic.withMainContext do -- @@ -281,13 +270,13 @@ def evalAddDeclSyntax (name : Name) (val : Syntax) (asLet : Bool := false) : Tac -- not choose): we force the instantiation of the meta-variable synthesizeSyntheticMVarsUsingDefault -- - evalAddDecl name val type asLet + addDecl name val type asLet k elab "custom_let " n:ident " := " v:term : tactic => - evalAddDeclSyntax n.getId v (asLet := true) + addDeclSyntax n.getId v (asLet := true) (λ _ => pure ()) elab "custom_have " n:ident " := " v:term : tactic => - evalAddDeclSyntax n.getId v (asLet := false) + addDeclSyntax n.getId v (asLet := false) (λ _ => pure ()) example : Nat := by custom_let x := 4 @@ -297,26 +286,32 @@ example : Nat := by example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x --- Lookup the instances of `HasProp for all the sub-expressions in the context, --- and introduce the corresponding assumptions -elab "intro_has_prop_instances" : tactic => do - logInfo m!"Introducing the HasProp instances" - let hs ← getHasPropInstancesFromMainCtx +-- Lookup instances in a context and introduce them with additional declarations. +def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := do + let hs ← collectInstancesFromMainCtx lookup hs.forM fun e => do let type ← inferType e - let name := `h - evalAddDecl name e type (asLet := false) - -- Simplify to unfold the `prop_ty` projector + let name ← mkFreshUserName `h + -- Add a declaration + addDecl name e type (asLet := false) λ nval => do + -- Simplify to unfold the declaration to unfold (i.e., the projector) let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) - -- Add the equational theorem for `HashProp'.prop_ty` - let simpTheorems ← simpTheorems.addDeclToUnfold ``HasProp.prop_ty + -- Add the equational theorem for the decl to unfold + let simpTheorems ← simpTheorems.addDeclToUnfold declToUnfold let congrTheorems ← getSimpCongrTheorems let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } -- Where to apply the simplifier let loc := Tactic.Location.targets #[mkIdent name] false -- Apply the simplifier let _ ← Tactic.simpLocation ctx (discharge? := .none) loc - pure () + -- Call the continuation + k nval + +-- Lookup the instances of `HasProp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_has_prop_instances" : tactic => do + trace[Arith] "Introducing the HasProp instances" + introInstances ``HasProp.prop_ty lookupHasProp (fun _ => pure ()) example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by intro_has_prop_instances @@ -326,23 +321,129 @@ example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by intro_has_prop_instances simp_all [Scalar.max, Scalar.min] --- A tactic to solve linear arithmetic goals -syntax "int_tac" : tactic +-- Tactic to split on a disjunction +def splitDisj (h : Expr) : Tactic.TacticM Unit := do + trace[Arith] "assumption on which to split: {h}" + -- Retrieve the main goal + Lean.Elab.Tactic.withMainContext do + let goalType ← Lean.Elab.Tactic.getMainTarget + -- Case disjunction + let hTy ← inferType h + hTy.withApp fun f xs => do + trace[Arith] "as app: {f} {xs}" + -- Sanity check + if ¬ (f.isConstOf ``Or ∧ xs.size = 2) then throwError "Invalid argument to splitDisj" + let a := xs.get! 0 + let b := xs.get! 1 + -- Introduce the new goals + -- Returns: + -- - the match branch + -- - a fresh new mvar id + let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do + -- Introduce a variable for the assumption (`a` or `b`) + let asmName ← mkFreshUserName `h + withLocalDeclD asmName hTy fun var => do + -- The new goal + let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) + -- The branch expression + let branch ← mkLambdaFVars #[var] mgoal + pure (branch, mgoal.mvarId!) + let (inl, mleft) ← mkGoal a "left" + let (inr, mright) ← mkGoal b "right" + trace[Arith] "left: {inl}: {mleft}" + trace[Arith] "right: {inr}: {mright}" + -- Create the match expression + withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do + let motive ← mkLambdaFVars #[hVar] goalType + let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] + let mgoal ← Tactic.getMainGoal + trace[Arith] "goals: {← Tactic.getUnsolvedGoals}" + trace[Arith] "main goal: {mgoal}" + mgoal.assign casesExpr + let goals ← Tactic.getUnsolvedGoals + Tactic.setGoals (mleft :: mright :: goals) + trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" + +elab "split_disj " n:ident : tactic => do + Lean.Elab.Tactic.withMainContext do + let decl ← Lean.Meta.getLocalDeclFromUserName n.getId + let fvar := mkFVar decl.fvarId + splitDisj fvar + +example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by + split_disj h0 + . left; assumption + . right; assumption + +-- Lookup the instances of `PropHasImp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_prop_has_imp_instances" : tactic => do + trace[Arith] "Introducing the PropHasImp instances" + introInstances ``PropHasImp.concl lookupPropHasImp (fun _ => pure ()) + +example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by + intro_prop_has_imp_instances + rename_i h + split_disj h + . linarith + . linarith + +syntax "int_tac_preprocess" : tactic + +/- Boosting a bit the linarith tac. + + We do the following: + - for all the assumptions of the shape `(x : Int) ≠ y` or `¬ (x = y), we + introduce two goals with the assumptions `x < y` and `x > y` + TODO: we could create a PR for mathlib. + -/ +def intTacPreprocess : Tactic.TacticM Unit := do + Lean.Elab.Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + -- Just a matter of precaution + let ctx ← instantiateLCtxMVars ctx + -- Explore the declarations - Remark: we don't explore the subexpressions + -- (we could, but it is rarely necessary, because terms of the shape `x ≠ y` + -- are often introduced because of branchings in the code, and using `split` + -- introduces exactly the assumptions `x = y` and `x ≠ y`). + let decls ← ctx.getDecls + for decl in decls do + let ty ← Lean.Meta.inferType decl.toExpr + ty.withApp fun f args => do + trace[Arith] "decl: {f} {args}" + -- Check if this is an inequality between integers + pure () + +-- TODO: int_tac + +elab "int_tac_preprocess" : tactic => + intTacPreprocess + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac_preprocess + simp_all + int_tac_preprocess + +-- A tactic to solve linear arithmetic goals in the presence of scalars +syntax "scalar_tac" : tactic macro_rules - | `(tactic| int_tac) => + | `(tactic| scalar_tac) => `(tactic| intro_has_prop_instances; have := Scalar.cMin_bound ScalarTy.Usize; have := Scalar.cMin_bound ScalarTy.Isize; have := Scalar.cMax_bound ScalarTy.Usize; have := Scalar.cMax_bound ScalarTy.Isize; + -- TODO: not too sure about that simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; + -- TODO: use int_tac linarith) example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by - int_tac + scalar_tac example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - int_tac + scalar_tac end Arith diff --git a/backends/lean/Base/ArithBase.lean b/backends/lean/Base/ArithBase.lean new file mode 100644 index 00000000..ddd2dc24 --- /dev/null +++ b/backends/lean/Base/ArithBase.lean @@ -0,0 +1,10 @@ +import Lean + +namespace Arith + +open Lean Elab Term Meta + +-- We can't define and use trace classes in the same file +initialize registerTraceClass `Arith + +end Arith diff --git a/backends/lean/Base/Diverge/ElabBase.lean b/backends/lean/Base/Diverge/ElabBase.lean index aaaea6f7..fedb1c74 100644 --- a/backends/lean/Base/Diverge/ElabBase.lean +++ b/backends/lean/Base/Diverge/ElabBase.lean @@ -12,116 +12,4 @@ initialize registerTraceClass `Diverge.def.genBody initialize registerTraceClass `Diverge.def.valid initialize registerTraceClass `Diverge.def.unfold --- Useful helper to explore definitions and figure out the variant --- of their sub-expressions. -def explore_term (incr : String) (e : Expr) : MetaM Unit := - match e with - | .bvar _ => do logInfo m!"{incr}bvar: {e}"; return () - | .fvar _ => do logInfo m!"{incr}fvar: {e}"; return () - | .mvar _ => do logInfo m!"{incr}mvar: {e}"; return () - | .sort _ => do logInfo m!"{incr}sort: {e}"; return () - | .const _ _ => do logInfo m!"{incr}const: {e}"; return () - | .app fn arg => do - logInfo m!"{incr}app: {e}" - explore_term (incr ++ " ") fn - explore_term (incr ++ " ") arg - | .lam _bName bTy body _binfo => do - logInfo m!"{incr}lam: {e}" - explore_term (incr ++ " ") bTy - explore_term (incr ++ " ") body - | .forallE _bName bTy body _bInfo => do - logInfo m!"{incr}forallE: {e}" - explore_term (incr ++ " ") bTy - explore_term (incr ++ " ") body - | .letE _dName ty val body _nonDep => do - logInfo m!"{incr}letE: {e}" - explore_term (incr ++ " ") ty - explore_term (incr ++ " ") val - explore_term (incr ++ " ") body - | .lit _ => do logInfo m!"{incr}lit: {e}"; return () - | .mdata _ e => do - logInfo m!"{incr}mdata: {e}" - explore_term (incr ++ " ") e - | .proj _ _ struct => do - logInfo m!"{incr}proj: {e}" - explore_term (incr ++ " ") struct - -def explore_decl (n : Name) : TermElabM Unit := do - logInfo m!"Name: {n}" - let env ← getEnv - let decl := env.constants.find! n - match decl with - | .defnInfo val => - logInfo m!"About to explore defn: {decl.name}" - logInfo m!"# Type:" - explore_term "" val.type - logInfo m!"# Value:" - explore_term "" val.value - | .axiomInfo _ => throwError m!"axiom: {n}" - | .thmInfo _ => throwError m!"thm: {n}" - | .opaqueInfo _ => throwError m!"opaque: {n}" - | .quotInfo _ => throwError m!"quot: {n}" - | .inductInfo _ => throwError m!"induct: {n}" - | .ctorInfo _ => throwError m!"ctor: {n}" - | .recInfo _ => throwError m!"rec: {n}" - -syntax (name := printDecl) "print_decl " ident : command - -open Lean.Elab.Command - -@[command_elab printDecl] def elabPrintDecl : CommandElab := fun stx => do - liftTermElabM do - let id := stx[1] - addCompletionInfo <| CompletionInfo.id id id.getId (danglingDot := false) {} none - let cs ← resolveGlobalConstWithInfos id - explore_decl cs[0]! - -private def test1 : Nat := 0 -private def test2 (x : Nat) : Nat := x - -print_decl test1 -print_decl test2 - --- A map visitor function for expressions (adapted from `AbstractNestedProofs.visit`) --- The continuation takes as parameters: --- - the current depth of the expression (useful for printing/debugging) --- - the expression to explore -partial def mapVisit (k : Nat → Expr → MetaM Expr) (e : Expr) : MetaM Expr := do - let mapVisitBinders (xs : Array Expr) (k2 : MetaM Expr) : MetaM Expr := do - let localInstances ← getLocalInstances - let mut lctx ← getLCtx - for x in xs do - let xFVarId := x.fvarId! - let localDecl ← xFVarId.getDecl - let type ← mapVisit k localDecl.type - let localDecl := localDecl.setType type - let localDecl ← match localDecl.value? with - | some value => let value ← mapVisit k value; pure <| localDecl.setValue value - | none => pure localDecl - lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl - withLCtx lctx localInstances k2 - -- TODO: use a cache? (Lean.checkCache) - let rec visit (i : Nat) (e : Expr) : MetaM Expr := do - -- Explore - let e ← k i e - match e with - | .bvar _ - | .fvar _ - | .mvar _ - | .sort _ - | .lit _ - | .const _ _ => pure e - | .app .. => do e.withApp fun f args => return mkAppN f (← args.mapM (visit (i + 1))) - | .lam .. => - lambdaLetTelescope e fun xs b => - mapVisitBinders xs do mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) - | .forallE .. => do - forallTelescope e fun xs b => mapVisitBinders xs do mkForallFVars xs (← visit (i + 1) b) - | .letE .. => do - lambdaLetTelescope e fun xs b => mapVisitBinders xs do - mkLambdaFVars xs (← visit (i + 1) b) (usedLetOnly := false) - | .mdata _ b => return e.updateMData! (← visit (i + 1) b) - | .proj _ _ b => return e.updateProj! (← visit (i + 1) b) - visit 0 e - end Diverge -- cgit v1.2.3 From 1c251c13b1e6698f3c7c974ea88c2c8a28777cc1 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Sun, 9 Jul 2023 10:50:50 +0200 Subject: Implement a first working version of int_tac --- backends/lean/Base/Arith.lean | 96 ++++++++++++++++++++++++++----------------- 1 file changed, 58 insertions(+), 38 deletions(-) diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index df48a6a2..8cdf75a3 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -231,7 +231,7 @@ example (x y : Int) (h0 : x ≠ y) (h1 : ¬ x = y) : True := by set_option trace.Arith false -def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := +def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.TacticM Expr := -- I don't think we need that Lean.Elab.Tactic.withMainContext do -- Insert the new declaration @@ -256,10 +256,11 @@ def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) (k : Expr mvarId.assign newVal let goals ← Tactic.getUnsolvedGoals Lean.Elab.Tactic.setGoals (newMVar.mvarId! :: goals) - -- Call the continuation - k nval + -- Return the new value - note: we are in the *new* context, created + -- after the declaration was added, so it will persist + pure nval -def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := +def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) : Tactic.TacticM Unit := -- I don't think we need that Lean.Elab.Tactic.withMainContext do -- @@ -270,13 +271,13 @@ def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) (k : Expr → Tact -- not choose): we force the instantiation of the meta-variable synthesizeSyntheticMVarsUsingDefault -- - addDecl name val type asLet k + let _ ← addDecl name val type asLet -elab "custom_let " n:ident " := " v:term : tactic => - addDeclSyntax n.getId v (asLet := true) (λ _ => pure ()) +elab "custom_let " n:ident " := " v:term : tactic => do + addDeclSyntax n.getId v (asLet := true) elab "custom_have " n:ident " := " v:term : tactic => - addDeclSyntax n.getId v (asLet := false) (λ _ => pure ()) + addDeclSyntax n.getId v (asLet := false) example : Nat := by custom_let x := 4 @@ -287,13 +288,13 @@ example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x -- Lookup instances in a context and introduce them with additional declarations. -def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) (k : Expr → Tactic.TacticM Unit) : Tactic.TacticM Unit := do +def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) : Tactic.TacticM (Array Expr) := do let hs ← collectInstancesFromMainCtx lookup - hs.forM fun e => do + hs.toArray.mapM fun e => do let type ← inferType e let name ← mkFreshUserName `h -- Add a declaration - addDecl name e type (asLet := false) λ nval => do + let nval ← addDecl name e type (asLet := false) -- Simplify to unfold the declaration to unfold (i.e., the projector) let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) -- Add the equational theorem for the decl to unfold @@ -304,14 +305,14 @@ def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) let loc := Tactic.Location.targets #[mkIdent name] false -- Apply the simplifier let _ ← Tactic.simpLocation ctx (discharge? := .none) loc - -- Call the continuation - k nval + -- Return the new value + pure nval -- Lookup the instances of `HasProp for all the sub-expressions in the context, -- and introduce the corresponding assumptions elab "intro_has_prop_instances" : tactic => do trace[Arith] "Introducing the HasProp instances" - introInstances ``HasProp.prop_ty lookupHasProp (fun _ => pure ()) + let _ ← introInstances ``HasProp.prop_ty lookupHasProp example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by intro_has_prop_instances @@ -322,7 +323,7 @@ example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by simp_all [Scalar.max, Scalar.min] -- Tactic to split on a disjunction -def splitDisj (h : Expr) : Tactic.TacticM Unit := do +def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do trace[Arith] "assumption on which to split: {h}" -- Retrieve the main goal Lean.Elab.Tactic.withMainContext do @@ -361,14 +362,23 @@ def splitDisj (h : Expr) : Tactic.TacticM Unit := do trace[Arith] "main goal: {mgoal}" mgoal.assign casesExpr let goals ← Tactic.getUnsolvedGoals - Tactic.setGoals (mleft :: mright :: goals) + -- Focus on the left + Tactic.setGoals [mleft] + kleft + let leftGoals ← Tactic.getUnsolvedGoals + -- Focus on the right + Tactic.setGoals [mright] + kright + let rightGoals ← Tactic.getUnsolvedGoals + -- Put all the goals back + Tactic.setGoals (leftGoals ++ rightGoals ++ goals) trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" elab "split_disj " n:ident : tactic => do Lean.Elab.Tactic.withMainContext do let decl ← Lean.Meta.getLocalDeclFromUserName n.getId let fvar := mkFVar decl.fvarId - splitDisj fvar + splitDisj fvar (fun _ => pure ()) (fun _ => pure ()) example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by split_disj h0 @@ -379,7 +389,7 @@ example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by -- and introduce the corresponding assumptions elab "intro_prop_has_imp_instances" : tactic => do trace[Arith] "Introducing the PropHasImp instances" - introInstances ``PropHasImp.concl lookupPropHasImp (fun _ => pure ()) + let _ ← introInstances ``PropHasImp.concl lookupPropHasImp example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by intro_prop_has_imp_instances @@ -388,7 +398,7 @@ example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by . linarith . linarith -syntax "int_tac_preprocess" : tactic +--syntax "int_tac_preprocess" : tactic /- Boosting a bit the linarith tac. @@ -399,31 +409,41 @@ syntax "int_tac_preprocess" : tactic -/ def intTacPreprocess : Tactic.TacticM Unit := do Lean.Elab.Tactic.withMainContext do - -- Get the local context - let ctx ← Lean.MonadLCtx.getLCtx - -- Just a matter of precaution - let ctx ← instantiateLCtxMVars ctx - -- Explore the declarations - Remark: we don't explore the subexpressions - -- (we could, but it is rarely necessary, because terms of the shape `x ≠ y` - -- are often introduced because of branchings in the code, and using `split` - -- introduces exactly the assumptions `x = y` and `x ≠ y`). - let decls ← ctx.getDecls - for decl in decls do - let ty ← Lean.Meta.inferType decl.toExpr - ty.withApp fun f args => do - trace[Arith] "decl: {f} {args}" - -- Check if this is an inequality between integers - pure () - --- TODO: int_tac + -- Lookup the instances of PropHasImp (this is how we detect assumptions + -- of the proper shape), introduce assumptions in the context and split + -- on those + -- TODO: get rid of the assumption that we split + let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := + match asms with + | [] => pure () + | asm :: asms => + let k := splitOnAsms asms + splitDisj asm k k + -- Introduce + let asms ← introInstances ``PropHasImp.concl lookupPropHasImp + -- Split + splitOnAsms asms.toList elab "int_tac_preprocess" : tactic => intTacPreprocess example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac_preprocess - simp_all - int_tac_preprocess + linarith + linarith + +syntax "int_tac" : tactic +macro_rules + | `(tactic| int_tac) => + `(tactic| + int_tac_preprocess <;> + linarith) + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac + +-- Checking that things append correctly when there are several disjunctions +example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by + int_tac_preprocess <;> apply And.intro <;> linarith -- A tactic to solve linear arithmetic goals in the presence of scalars syntax "scalar_tac" : tactic -- cgit v1.2.3 From d9a11b312ef0df13795d9a1982ca1cd2eba0e124 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Sun, 9 Jul 2023 22:27:44 +0200 Subject: Improve int_tac --- backends/lean/Base/Arith.lean | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index 8cdf75a3..364447ed 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -183,9 +183,6 @@ elab "display_has_prop_instances" : tactic => do hs.forM fun e => do trace[Arith] "+ HasProp instance: {e}" - -set_option trace.Arith true - example (x : U32) : True := by let i : HasProp U32 := inferInstance have p := @HasProp.prop _ i x @@ -193,8 +190,6 @@ example (x : U32) : True := by display_has_prop_instances simp -set_option trace.Arith false - -- Return an instance of `PropHasImp` for `e` if it has some def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do trace[Arith] "lookupPropHasImp" @@ -223,14 +218,10 @@ elab "display_prop_has_imp_instances" : tactic => do hs.forM fun e => do trace[Arith] "+ PropHasImp instance: {e}" -set_option trace.Arith true - -example (x y : Int) (h0 : x ≠ y) (h1 : ¬ x = y) : True := by +example (x y : Int) (_ : x ≠ y) (_ : ¬ x = y) : True := by display_prop_has_imp_instances simp -set_option trace.Arith false - def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.TacticM Expr := -- I don't think we need that Lean.Elab.Tactic.withMainContext do @@ -322,12 +313,15 @@ example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by intro_has_prop_instances simp_all [Scalar.max, Scalar.min] --- Tactic to split on a disjunction +-- Tactic to split on a disjunction. +-- The expression `h` should be an fvar. def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do trace[Arith] "assumption on which to split: {h}" -- Retrieve the main goal Lean.Elab.Tactic.withMainContext do let goalType ← Lean.Elab.Tactic.getMainTarget + let hDecl := (← getLCtx).get! h.fvarId! + let hName := hDecl.userName -- Case disjunction let hTy ← inferType h hTy.withApp fun f xs => do @@ -341,14 +335,16 @@ def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM U -- - the match branch -- - a fresh new mvar id let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do - -- Introduce a variable for the assumption (`a` or `b`) - let asmName ← mkFreshUserName `h - withLocalDeclD asmName hTy fun var => do + -- Introduce a variable for the assumption (`a` or `b`). Note that we reuse + -- the name of the assumption we split. + withLocalDeclD hName hTy fun var => do -- The new goal let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) + -- Clear the assumption that we split + let mgoal ← mgoal.mvarId!.tryClearMany #[h.fvarId!] -- The branch expression - let branch ← mkLambdaFVars #[var] mgoal - pure (branch, mgoal.mvarId!) + let branch ← mkLambdaFVars #[var] (mkMVar mgoal) + pure (branch, mgoal) let (inl, mleft) ← mkGoal a "left" let (inr, mright) ← mkGoal b "right" trace[Arith] "left: {inl}: {mleft}" @@ -398,8 +394,6 @@ example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by . linarith . linarith ---syntax "int_tac_preprocess" : tactic - /- Boosting a bit the linarith tac. We do the following: @@ -412,7 +406,7 @@ def intTacPreprocess : Tactic.TacticM Unit := do -- Lookup the instances of PropHasImp (this is how we detect assumptions -- of the proper shape), introduce assumptions in the context and split -- on those - -- TODO: get rid of the assumption that we split + -- TODO: get rid of the assumptions that we split let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := match asms with | [] => pure () @@ -436,14 +430,16 @@ syntax "int_tac" : tactic macro_rules | `(tactic| int_tac) => `(tactic| + (repeat (apply And.intro)) <;> -- TODO: improve this int_tac_preprocess <;> linarith) -example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac -- Checking that things append correctly when there are several disjunctions example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by - int_tac_preprocess <;> apply And.intro <;> linarith + int_tac -- A tactic to solve linear arithmetic goals in the presence of scalars syntax "scalar_tac" : tactic @@ -457,8 +453,7 @@ macro_rules have := Scalar.cMax_bound ScalarTy.Isize; -- TODO: not too sure about that simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; - -- TODO: use int_tac - linarith) + int_tac) example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by scalar_tac -- cgit v1.2.3 From 7206b48a73d6204baea99f4f4675be2518a8f8c2 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 10 Jul 2023 15:06:12 +0200 Subject: Start working on the progress tactic --- backends/lean/Base.lean | 2 + backends/lean/Base/Arith.lean | 464 ----------------------------------- backends/lean/Base/Arith/Arith.lean | 409 ++++++++++++++++++++++++++++++ backends/lean/Base/Arith/Base.lean | 10 + backends/lean/Base/ArithBase.lean | 10 - backends/lean/Base/Diverge/Elab.lean | 17 +- backends/lean/Base/Utils.lean | 95 +++++++ 7 files changed, 517 insertions(+), 490 deletions(-) delete mode 100644 backends/lean/Base/Arith.lean create mode 100644 backends/lean/Base/Arith/Arith.lean create mode 100644 backends/lean/Base/Arith/Base.lean delete mode 100644 backends/lean/Base/ArithBase.lean diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index 1f8cbc8e..51211704 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -1,3 +1,5 @@ +import Base.Utils import Base.Primitives import Base.Diverge import Base.Arith +import Base.Progress diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean deleted file mode 100644 index 364447ed..00000000 --- a/backends/lean/Base/Arith.lean +++ /dev/null @@ -1,464 +0,0 @@ -/- This file contains tactics to solve arithmetic goals -/ - -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd -import Mathlib.Tactic.Linarith --- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet ---import Mathlib.Tactic.Omega -import Base.Primitives -import Base.ArithBase - -/- -Mathlib tactics: -- rcases: https://leanprover-community.github.io/mathlib_docs/tactics.html#rcases -- split_ifs: https://leanprover-community.github.io/mathlib_docs/tactics.html#split_ifs -- norm_num: https://leanprover-community.github.io/mathlib_docs/tactics.html#norm_num -- should we use linarith or omega? -- hint: https://leanprover-community.github.io/mathlib_docs/tactics.html#hint -- classical: https://leanprover-community.github.io/mathlib_docs/tactics.html#classical --/ - -namespace List - - -- TODO: I could not find this function?? - @[simp] def flatten {a : Type u} : List (List a) → List a - | [] => [] - | x :: ls => x ++ flatten ls - -end List - -namespace Lean - -namespace LocalContext - - open Lean Lean.Elab Command Term Lean.Meta - - -- Small utility: return the list of declarations in the context, from - -- the last to the first. - def getAllDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := - lctx.foldrM (fun d ls => do let d ← instantiateLocalDeclMVars d; pure (d :: ls)) [] - - -- Return the list of declarations in the context, but filter the - -- declarations which are considered as implementation details - def getDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := do - let ls ← lctx.getAllDecls - pure (ls.filter (fun d => not d.isImplementationDetail)) - -end LocalContext - -end Lean - -namespace Arith - -open Primitives - --- TODO: move? -theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by - cases h: x <;> simp_all - . rename_i n; - cases n <;> simp_all - . apply Int.negSucc_lt_zero - --- TODO: move? -theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by - have hne : x - y ≠ 0 := by - simp - intro h - have: x = y := by linarith - simp_all - have h := ne_zero_is_lt_or_gt hne - match h with - | .inl _ => left; linarith - | .inr _ => right; linarith - --- TODO: move -instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val - --- TODO: move -/- Remark: we can't write the following instance because of restrictions about - the type class parameters (`ty` doesn't appear in the return type, which is - forbidden): - - ``` - instance Scalar.cast (ty : ScalarTy) : Coe (Scalar ty) Int where coe := λ v => v.val - ``` - -/ -def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val - --- Remark: I tried a version of the shape `HasProp {a : Type} (x : a)` --- but the lookup didn't work -class HasProp (a : Sort u) where - prop_ty : a → Prop - prop : ∀ x:a, prop_ty x - -instance (ty : ScalarTy) : HasProp (Scalar ty) where - -- prop_ty is inferred - prop := λ x => And.intro x.hmin x.hmax - -instance (a : Type) : HasProp (Vec a) where - prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize - prop := λ ⟨ _, l ⟩ => l - -class PropHasImp (x : Prop) where - concl : Prop - prop : x → concl - --- This also works for `x ≠ y` because this expression reduces to `¬ x = y` --- and `Ne` is marked as `reducible` -instance (x y : Int) : PropHasImp (¬ x = y) where - concl := x < y ∨ x > y - prop := λ (h:x ≠ y) => ne_is_lt_or_gt h - -open Lean Lean.Elab Command Term Lean.Meta - --- Small utility: print all the declarations in the context -elab "print_all_decls" : tactic => do - let ctx ← Lean.MonadLCtx.getLCtx - for decl in ← ctx.getDecls do - let ty ← Lean.Meta.inferType decl.toExpr - logInfo m!"{decl.toExpr} : {ty}" - pure () - --- Explore a term by decomposing the applications (we explore the applied --- functions and their arguments, but ignore lambdas, forall, etc. - --- should we go inside?). -partial def foldTermApps (k : α → Expr → MetaM α) (s : α) (e : Expr) : MetaM α := do - -- We do it in a very simpler manner: we deconstruct applications, - -- and recursively explore the sub-expressions. Note that we do - -- not go inside foralls and abstractions (should we?). - e.withApp fun f args => do - let s ← k s f - args.foldlM (foldTermApps k) s - --- Provided a function `k` which lookups type class instances on an expression, --- collect all the instances lookuped by applying `k` on the sub-expressions of `e`. -def collectInstances - (k : Expr → MetaM (Option Expr)) (s : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do - let k s e := do - match ← k e with - | none => pure s - | some i => pure (s.insert i) - foldTermApps k s e - --- Similar to `collectInstances`, but explores all the local declarations in the --- main context. -def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do - Lean.Elab.Tactic.withMainContext do - -- Get the local context - let ctx ← Lean.MonadLCtx.getLCtx - -- Just a matter of precaution - let ctx ← instantiateLCtxMVars ctx - -- Initialize the hashset - let hs := HashSet.empty - -- Explore the declarations - let decls ← ctx.getDecls - decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs - --- Return an instance of `HasProp` for `e` if it has some -def lookupHasProp (e : Expr) : MetaM (Option Expr) := do - trace[Arith] "lookupHasProp" - -- TODO: do we need Lean.observing? - -- This actually eliminates the error messages - Lean.observing? do - trace[Arith] "lookupHasProp: observing" - let ty ← Lean.Meta.inferType e - let hasProp ← mkAppM ``HasProp #[ty] - let hasPropInst ← trySynthInstance hasProp - match hasPropInst with - | LOption.some i => - trace[Arith] "Found HasProp instance" - let i_prop ← mkProjection i (Name.mkSimple "prop") - some (← mkAppM' i_prop #[e]) - | _ => none - --- Collect the instances of `HasProp` for the subexpressions in the context -def collectHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupHasProp - -elab "display_has_prop_instances" : tactic => do - trace[Arith] "Displaying the HasProp instances" - let hs ← collectHasPropInstancesFromMainCtx - hs.forM fun e => do - trace[Arith] "+ HasProp instance: {e}" - -example (x : U32) : True := by - let i : HasProp U32 := inferInstance - have p := @HasProp.prop _ i x - simp only [HasProp.prop_ty] at p - display_has_prop_instances - simp - --- Return an instance of `PropHasImp` for `e` if it has some -def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do - trace[Arith] "lookupPropHasImp" - -- TODO: do we need Lean.observing? - -- This actually eliminates the error messages - Lean.observing? do - trace[Arith] "lookupPropHasImp: observing" - let ty ← Lean.Meta.inferType e - trace[Arith] "lookupPropHasImp: ty: {ty}" - let cl ← mkAppM ``PropHasImp #[ty] - let inst ← trySynthInstance cl - match inst with - | LOption.some i => - trace[Arith] "Found PropHasImp instance" - let i_prop ← mkProjection i (Name.mkSimple "prop") - some (← mkAppM' i_prop #[e]) - | _ => none - --- Collect the instances of `PropHasImp` for the subexpressions in the context -def collectPropHasImpInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupPropHasImp - -elab "display_prop_has_imp_instances" : tactic => do - trace[Arith] "Displaying the PropHasImp instances" - let hs ← collectPropHasImpInstancesFromMainCtx - hs.forM fun e => do - trace[Arith] "+ PropHasImp instance: {e}" - -example (x y : Int) (_ : x ≠ y) (_ : ¬ x = y) : True := by - display_prop_has_imp_instances - simp - -def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.TacticM Expr := - -- I don't think we need that - Lean.Elab.Tactic.withMainContext do - -- Insert the new declaration - let withDecl := if asLet then withLetDecl name type val else withLocalDeclD name type - withDecl fun nval => do - -- For debugging - let lctx ← Lean.MonadLCtx.getLCtx - let fid := nval.fvarId! - let decl := lctx.get! fid - trace[Arith] " new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" - -- - -- Tranform the main goal `?m0` to `let x = nval in ?m1` - let mvarId ← Tactic.getMainGoal - let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) - let newVal ← mkLetFVars #[nval] newMVar - -- There are two cases: - -- - asLet is true: newVal is `let $name := $val in $newMVar` - -- - asLet is false: ewVal is `λ $name => $newMVar` - -- We need to apply it to `val` - let newVal := if asLet then newVal else mkAppN newVal #[val] - -- Assign the main goal and update the current goal - mvarId.assign newVal - let goals ← Tactic.getUnsolvedGoals - Lean.Elab.Tactic.setGoals (newMVar.mvarId! :: goals) - -- Return the new value - note: we are in the *new* context, created - -- after the declaration was added, so it will persist - pure nval - -def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) : Tactic.TacticM Unit := - -- I don't think we need that - Lean.Elab.Tactic.withMainContext do - -- - let val ← elabTerm val .none - let type ← inferType val - -- In some situations, the type will be left as a metavariable (for instance, - -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will - -- not choose): we force the instantiation of the meta-variable - synthesizeSyntheticMVarsUsingDefault - -- - let _ ← addDecl name val type asLet - -elab "custom_let " n:ident " := " v:term : tactic => do - addDeclSyntax n.getId v (asLet := true) - -elab "custom_have " n:ident " := " v:term : tactic => - addDeclSyntax n.getId v (asLet := false) - -example : Nat := by - custom_let x := 4 - custom_have y := 4 - apply y - -example (x : Bool) : Nat := by - cases x <;> custom_let x := 3 <;> apply x - --- Lookup instances in a context and introduce them with additional declarations. -def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) : Tactic.TacticM (Array Expr) := do - let hs ← collectInstancesFromMainCtx lookup - hs.toArray.mapM fun e => do - let type ← inferType e - let name ← mkFreshUserName `h - -- Add a declaration - let nval ← addDecl name e type (asLet := false) - -- Simplify to unfold the declaration to unfold (i.e., the projector) - let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) - -- Add the equational theorem for the decl to unfold - let simpTheorems ← simpTheorems.addDeclToUnfold declToUnfold - let congrTheorems ← getSimpCongrTheorems - let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } - -- Where to apply the simplifier - let loc := Tactic.Location.targets #[mkIdent name] false - -- Apply the simplifier - let _ ← Tactic.simpLocation ctx (discharge? := .none) loc - -- Return the new value - pure nval - --- Lookup the instances of `HasProp for all the sub-expressions in the context, --- and introduce the corresponding assumptions -elab "intro_has_prop_instances" : tactic => do - trace[Arith] "Introducing the HasProp instances" - let _ ← introInstances ``HasProp.prop_ty lookupHasProp - -example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by - intro_has_prop_instances - simp [*] - -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - intro_has_prop_instances - simp_all [Scalar.max, Scalar.min] - --- Tactic to split on a disjunction. --- The expression `h` should be an fvar. -def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do - trace[Arith] "assumption on which to split: {h}" - -- Retrieve the main goal - Lean.Elab.Tactic.withMainContext do - let goalType ← Lean.Elab.Tactic.getMainTarget - let hDecl := (← getLCtx).get! h.fvarId! - let hName := hDecl.userName - -- Case disjunction - let hTy ← inferType h - hTy.withApp fun f xs => do - trace[Arith] "as app: {f} {xs}" - -- Sanity check - if ¬ (f.isConstOf ``Or ∧ xs.size = 2) then throwError "Invalid argument to splitDisj" - let a := xs.get! 0 - let b := xs.get! 1 - -- Introduce the new goals - -- Returns: - -- - the match branch - -- - a fresh new mvar id - let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do - -- Introduce a variable for the assumption (`a` or `b`). Note that we reuse - -- the name of the assumption we split. - withLocalDeclD hName hTy fun var => do - -- The new goal - let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) - -- Clear the assumption that we split - let mgoal ← mgoal.mvarId!.tryClearMany #[h.fvarId!] - -- The branch expression - let branch ← mkLambdaFVars #[var] (mkMVar mgoal) - pure (branch, mgoal) - let (inl, mleft) ← mkGoal a "left" - let (inr, mright) ← mkGoal b "right" - trace[Arith] "left: {inl}: {mleft}" - trace[Arith] "right: {inr}: {mright}" - -- Create the match expression - withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do - let motive ← mkLambdaFVars #[hVar] goalType - let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] - let mgoal ← Tactic.getMainGoal - trace[Arith] "goals: {← Tactic.getUnsolvedGoals}" - trace[Arith] "main goal: {mgoal}" - mgoal.assign casesExpr - let goals ← Tactic.getUnsolvedGoals - -- Focus on the left - Tactic.setGoals [mleft] - kleft - let leftGoals ← Tactic.getUnsolvedGoals - -- Focus on the right - Tactic.setGoals [mright] - kright - let rightGoals ← Tactic.getUnsolvedGoals - -- Put all the goals back - Tactic.setGoals (leftGoals ++ rightGoals ++ goals) - trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" - -elab "split_disj " n:ident : tactic => do - Lean.Elab.Tactic.withMainContext do - let decl ← Lean.Meta.getLocalDeclFromUserName n.getId - let fvar := mkFVar decl.fvarId - splitDisj fvar (fun _ => pure ()) (fun _ => pure ()) - -example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by - split_disj h0 - . left; assumption - . right; assumption - --- Lookup the instances of `PropHasImp for all the sub-expressions in the context, --- and introduce the corresponding assumptions -elab "intro_prop_has_imp_instances" : tactic => do - trace[Arith] "Introducing the PropHasImp instances" - let _ ← introInstances ``PropHasImp.concl lookupPropHasImp - -example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by - intro_prop_has_imp_instances - rename_i h - split_disj h - . linarith - . linarith - -/- Boosting a bit the linarith tac. - - We do the following: - - for all the assumptions of the shape `(x : Int) ≠ y` or `¬ (x = y), we - introduce two goals with the assumptions `x < y` and `x > y` - TODO: we could create a PR for mathlib. - -/ -def intTacPreprocess : Tactic.TacticM Unit := do - Lean.Elab.Tactic.withMainContext do - -- Lookup the instances of PropHasImp (this is how we detect assumptions - -- of the proper shape), introduce assumptions in the context and split - -- on those - -- TODO: get rid of the assumptions that we split - let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := - match asms with - | [] => pure () - | asm :: asms => - let k := splitOnAsms asms - splitDisj asm k k - -- Introduce - let asms ← introInstances ``PropHasImp.concl lookupPropHasImp - -- Split - splitOnAsms asms.toList - -elab "int_tac_preprocess" : tactic => - intTacPreprocess - -example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by - int_tac_preprocess - linarith - linarith - -syntax "int_tac" : tactic -macro_rules - | `(tactic| int_tac) => - `(tactic| - (repeat (apply And.intro)) <;> -- TODO: improve this - int_tac_preprocess <;> - linarith) - -example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by - int_tac - --- Checking that things append correctly when there are several disjunctions -example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by - int_tac - --- A tactic to solve linear arithmetic goals in the presence of scalars -syntax "scalar_tac" : tactic -macro_rules - | `(tactic| scalar_tac) => - `(tactic| - intro_has_prop_instances; - have := Scalar.cMin_bound ScalarTy.Usize; - have := Scalar.cMin_bound ScalarTy.Isize; - have := Scalar.cMax_bound ScalarTy.Usize; - have := Scalar.cMax_bound ScalarTy.Isize; - -- TODO: not too sure about that - simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; - int_tac) - -example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by - scalar_tac - -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - scalar_tac - -end Arith diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean new file mode 100644 index 00000000..0ba73d18 --- /dev/null +++ b/backends/lean/Base/Arith/Arith.lean @@ -0,0 +1,409 @@ +/- This file contains tactics to solve arithmetic goals -/ + +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith +-- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet +--import Mathlib.Tactic.Omega +import Base.Primitives +import Base.Utils +import Base.Arith.Base + +/- +Mathlib tactics: +- rcases: https://leanprover-community.github.io/mathlib_docs/tactics.html#rcases +- split_ifs: https://leanprover-community.github.io/mathlib_docs/tactics.html#split_ifs +- norm_num: https://leanprover-community.github.io/mathlib_docs/tactics.html#norm_num +- should we use linarith or omega? +- hint: https://leanprover-community.github.io/mathlib_docs/tactics.html#hint +- classical: https://leanprover-community.github.io/mathlib_docs/tactics.html#classical +-/ + +namespace List + + -- TODO: I could not find this function?? + @[simp] def flatten {a : Type u} : List (List a) → List a + | [] => [] + | x :: ls => x ++ flatten ls + +end List + +namespace Lean + +namespace LocalContext + + open Lean Lean.Elab Command Term Lean.Meta + + -- Small utility: return the list of declarations in the context, from + -- the last to the first. + def getAllDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := + lctx.foldrM (fun d ls => do let d ← instantiateLocalDeclMVars d; pure (d :: ls)) [] + + -- Return the list of declarations in the context, but filter the + -- declarations which are considered as implementation details + def getDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := do + let ls ← lctx.getAllDecls + pure (ls.filter (fun d => not d.isImplementationDetail)) + +end LocalContext + +end Lean + +namespace Arith + +open Primitives + +-- TODO: move? +theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by + cases h: x <;> simp_all + . rename_i n; + cases n <;> simp_all + . apply Int.negSucc_lt_zero + +-- TODO: move? +theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by + have hne : x - y ≠ 0 := by + simp + intro h + have: x = y := by linarith + simp_all + have h := ne_zero_is_lt_or_gt hne + match h with + | .inl _ => left; linarith + | .inr _ => right; linarith + +-- TODO: move +instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val + +-- TODO: move +/- Remark: we can't write the following instance because of restrictions about + the type class parameters (`ty` doesn't appear in the return type, which is + forbidden): + + ``` + instance Scalar.cast (ty : ScalarTy) : Coe (Scalar ty) Int where coe := λ v => v.val + ``` + -/ +def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val + +-- Remark: I tried a version of the shape `HasProp {a : Type} (x : a)` +-- but the lookup didn't work +class HasProp (a : Sort u) where + prop_ty : a → Prop + prop : ∀ x:a, prop_ty x + +instance (ty : ScalarTy) : HasProp (Scalar ty) where + -- prop_ty is inferred + prop := λ x => And.intro x.hmin x.hmax + +instance (a : Type) : HasProp (Vec a) where + prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize + prop := λ ⟨ _, l ⟩ => l + +class PropHasImp (x : Prop) where + concl : Prop + prop : x → concl + +-- This also works for `x ≠ y` because this expression reduces to `¬ x = y` +-- and `Ne` is marked as `reducible` +instance (x y : Int) : PropHasImp (¬ x = y) where + concl := x < y ∨ x > y + prop := λ (h:x ≠ y) => ne_is_lt_or_gt h + +open Lean Lean.Elab Command Term Lean.Meta + +-- Small utility: print all the declarations in the context +elab "print_all_decls" : tactic => do + let ctx ← Lean.MonadLCtx.getLCtx + for decl in ← ctx.getDecls do + let ty ← Lean.Meta.inferType decl.toExpr + logInfo m!"{decl.toExpr} : {ty}" + pure () + +-- Explore a term by decomposing the applications (we explore the applied +-- functions and their arguments, but ignore lambdas, forall, etc. - +-- should we go inside?). +partial def foldTermApps (k : α → Expr → MetaM α) (s : α) (e : Expr) : MetaM α := do + -- We do it in a very simpler manner: we deconstruct applications, + -- and recursively explore the sub-expressions. Note that we do + -- not go inside foralls and abstractions (should we?). + e.withApp fun f args => do + let s ← k s f + args.foldlM (foldTermApps k) s + +-- Provided a function `k` which lookups type class instances on an expression, +-- collect all the instances lookuped by applying `k` on the sub-expressions of `e`. +def collectInstances + (k : Expr → MetaM (Option Expr)) (s : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do + let k s e := do + match ← k e with + | none => pure s + | some i => pure (s.insert i) + foldTermApps k s e + +-- Similar to `collectInstances`, but explores all the local declarations in the +-- main context. +def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do + Lean.Elab.Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + -- Just a matter of precaution + let ctx ← instantiateLCtxMVars ctx + -- Initialize the hashset + let hs := HashSet.empty + -- Explore the declarations + let decls ← ctx.getDecls + decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs + +-- Return an instance of `HasProp` for `e` if it has some +def lookupHasProp (e : Expr) : MetaM (Option Expr) := do + trace[Arith] "lookupHasProp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] "lookupHasProp: observing" + let ty ← Lean.Meta.inferType e + let hasProp ← mkAppM ``HasProp #[ty] + let hasPropInst ← trySynthInstance hasProp + match hasPropInst with + | LOption.some i => + trace[Arith] "Found HasProp instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Collect the instances of `HasProp` for the subexpressions in the context +def collectHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupHasProp + +elab "display_has_prop_instances" : tactic => do + trace[Arith] "Displaying the HasProp instances" + let hs ← collectHasPropInstancesFromMainCtx + hs.forM fun e => do + trace[Arith] "+ HasProp instance: {e}" + +example (x : U32) : True := by + let i : HasProp U32 := inferInstance + have p := @HasProp.prop _ i x + simp only [HasProp.prop_ty] at p + display_has_prop_instances + simp + +-- Return an instance of `PropHasImp` for `e` if it has some +def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do + trace[Arith] "lookupPropHasImp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] "lookupPropHasImp: observing" + let ty ← Lean.Meta.inferType e + trace[Arith] "lookupPropHasImp: ty: {ty}" + let cl ← mkAppM ``PropHasImp #[ty] + let inst ← trySynthInstance cl + match inst with + | LOption.some i => + trace[Arith] "Found PropHasImp instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Collect the instances of `PropHasImp` for the subexpressions in the context +def collectPropHasImpInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupPropHasImp + +elab "display_prop_has_imp_instances" : tactic => do + trace[Arith] "Displaying the PropHasImp instances" + let hs ← collectPropHasImpInstancesFromMainCtx + hs.forM fun e => do + trace[Arith] "+ PropHasImp instance: {e}" + +example (x y : Int) (_ : x ≠ y) (_ : ¬ x = y) : True := by + display_prop_has_imp_instances + simp + +-- Lookup instances in a context and introduce them with additional declarations. +def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) : Tactic.TacticM (Array Expr) := do + let hs ← collectInstancesFromMainCtx lookup + hs.toArray.mapM fun e => do + let type ← inferType e + let name ← mkFreshUserName `h + -- Add a declaration + let nval ← Utils.addDecl name e type (asLet := false) + -- Simplify to unfold the declaration to unfold (i.e., the projector) + let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) + -- Add the equational theorem for the decl to unfold + let simpTheorems ← simpTheorems.addDeclToUnfold declToUnfold + let congrTheorems ← getSimpCongrTheorems + let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } + -- Where to apply the simplifier + let loc := Tactic.Location.targets #[mkIdent name] false + -- Apply the simplifier + let _ ← Tactic.simpLocation ctx (discharge? := .none) loc + -- Return the new value + pure nval + +-- Lookup the instances of `HasProp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_has_prop_instances" : tactic => do + trace[Arith] "Introducing the HasProp instances" + let _ ← introInstances ``HasProp.prop_ty lookupHasProp + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + intro_has_prop_instances + simp [*] + +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + intro_has_prop_instances + simp_all [Scalar.max, Scalar.min] + +-- Tactic to split on a disjunction. +-- The expression `h` should be an fvar. +def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do + trace[Arith] "assumption on which to split: {h}" + -- Retrieve the main goal + Lean.Elab.Tactic.withMainContext do + let goalType ← Lean.Elab.Tactic.getMainTarget + let hDecl := (← getLCtx).get! h.fvarId! + let hName := hDecl.userName + -- Case disjunction + let hTy ← inferType h + hTy.withApp fun f xs => do + trace[Arith] "as app: {f} {xs}" + -- Sanity check + if ¬ (f.isConstOf ``Or ∧ xs.size = 2) then throwError "Invalid argument to splitDisj" + let a := xs.get! 0 + let b := xs.get! 1 + -- Introduce the new goals + -- Returns: + -- - the match branch + -- - a fresh new mvar id + let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do + -- Introduce a variable for the assumption (`a` or `b`). Note that we reuse + -- the name of the assumption we split. + withLocalDeclD hName hTy fun var => do + -- The new goal + let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) + -- Clear the assumption that we split + let mgoal ← mgoal.mvarId!.tryClearMany #[h.fvarId!] + -- The branch expression + let branch ← mkLambdaFVars #[var] (mkMVar mgoal) + pure (branch, mgoal) + let (inl, mleft) ← mkGoal a "left" + let (inr, mright) ← mkGoal b "right" + trace[Arith] "left: {inl}: {mleft}" + trace[Arith] "right: {inr}: {mright}" + -- Create the match expression + withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do + let motive ← mkLambdaFVars #[hVar] goalType + let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] + let mgoal ← Tactic.getMainGoal + trace[Arith] "goals: {← Tactic.getUnsolvedGoals}" + trace[Arith] "main goal: {mgoal}" + mgoal.assign casesExpr + let goals ← Tactic.getUnsolvedGoals + -- Focus on the left + Tactic.setGoals [mleft] + kleft + let leftGoals ← Tactic.getUnsolvedGoals + -- Focus on the right + Tactic.setGoals [mright] + kright + let rightGoals ← Tactic.getUnsolvedGoals + -- Put all the goals back + Tactic.setGoals (leftGoals ++ rightGoals ++ goals) + trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" + +elab "split_disj " n:ident : tactic => do + Lean.Elab.Tactic.withMainContext do + let decl ← Lean.Meta.getLocalDeclFromUserName n.getId + let fvar := mkFVar decl.fvarId + splitDisj fvar (fun _ => pure ()) (fun _ => pure ()) + +example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by + split_disj h0 + . left; assumption + . right; assumption + +-- Lookup the instances of `PropHasImp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_prop_has_imp_instances" : tactic => do + trace[Arith] "Introducing the PropHasImp instances" + let _ ← introInstances ``PropHasImp.concl lookupPropHasImp + +example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by + intro_prop_has_imp_instances + rename_i h + split_disj h + . linarith + . linarith + +/- Boosting a bit the linarith tac. + + We do the following: + - for all the assumptions of the shape `(x : Int) ≠ y` or `¬ (x = y), we + introduce two goals with the assumptions `x < y` and `x > y` + TODO: we could create a PR for mathlib. + -/ +def intTacPreprocess : Tactic.TacticM Unit := do + Lean.Elab.Tactic.withMainContext do + -- Lookup the instances of PropHasImp (this is how we detect assumptions + -- of the proper shape), introduce assumptions in the context and split + -- on those + -- TODO: get rid of the assumptions that we split + let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := + match asms with + | [] => pure () + | asm :: asms => + let k := splitOnAsms asms + splitDisj asm k k + -- Introduce + let asms ← introInstances ``PropHasImp.concl lookupPropHasImp + -- Split + splitOnAsms asms.toList + +elab "int_tac_preprocess" : tactic => + intTacPreprocess + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac_preprocess + linarith + linarith + +syntax "int_tac" : tactic +macro_rules + | `(tactic| int_tac) => + `(tactic| + (repeat (apply And.intro)) <;> -- TODO: improve this + int_tac_preprocess <;> + linarith) + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac + +-- Checking that things append correctly when there are several disjunctions +example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by + int_tac + +-- A tactic to solve linear arithmetic goals in the presence of scalars +syntax "scalar_tac" : tactic +macro_rules + | `(tactic| scalar_tac) => + `(tactic| + intro_has_prop_instances; + have := Scalar.cMin_bound ScalarTy.Usize; + have := Scalar.cMin_bound ScalarTy.Isize; + have := Scalar.cMax_bound ScalarTy.Usize; + have := Scalar.cMax_bound ScalarTy.Isize; + -- TODO: not too sure about that + simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; + int_tac) + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + scalar_tac + +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + scalar_tac + +end Arith diff --git a/backends/lean/Base/Arith/Base.lean b/backends/lean/Base/Arith/Base.lean new file mode 100644 index 00000000..ddd2dc24 --- /dev/null +++ b/backends/lean/Base/Arith/Base.lean @@ -0,0 +1,10 @@ +import Lean + +namespace Arith + +open Lean Elab Term Meta + +-- We can't define and use trace classes in the same file +initialize registerTraceClass `Arith + +end Arith diff --git a/backends/lean/Base/ArithBase.lean b/backends/lean/Base/ArithBase.lean deleted file mode 100644 index ddd2dc24..00000000 --- a/backends/lean/Base/ArithBase.lean +++ /dev/null @@ -1,10 +0,0 @@ -import Lean - -namespace Arith - -open Lean Elab Term Meta - --- We can't define and use trace classes in the same file -initialize registerTraceClass `Arith - -end Arith diff --git a/backends/lean/Base/Diverge/Elab.lean b/backends/lean/Base/Diverge/Elab.lean index 96f7abc0..f109e847 100644 --- a/backends/lean/Base/Diverge/Elab.lean +++ b/backends/lean/Base/Diverge/Elab.lean @@ -14,8 +14,8 @@ namespace Diverge syntax (name := divergentDef) declModifiers "divergent" "def" declId ppIndent(optDeclSig) declVal : command -open Utils open Lean Elab Term Meta Primitives Lean.Meta +open Utils /- The following was copied from the `wfRecursion` function. -/ @@ -47,21 +47,6 @@ def getSigmaTypes (ty : Expr) : MetaM (Expr × Expr) := do else pure (args.get! 0, args.get! 1) -/- Like `lambdaTelescopeN` but only destructs a fixed number of lambdas -/ -def lambdaTelescopeN (e : Expr) (n : Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := - lambdaTelescope e fun xs body => do - if xs.size < n then throwError "lambdaTelescopeN: not enough lambdas"; - let xs := xs.extract 0 n - let ys := xs.extract n xs.size - let body ← mkLambdaFVars ys body - k xs body - -/- Like `lambdaTelescope`, but only destructs one lambda - TODO: is there an equivalent of this function somewhere in the - standard library? -/ -def lambdaOne (e : Expr) (k : Expr → Expr → MetaM α) : MetaM α := - lambdaTelescopeN e 1 λ xs b => k (xs.get! 0) b - /- Generate a Sigma type from a list of *variables* (all the expressions must be variables). diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 161b9ddb..2ce63620 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -116,4 +116,99 @@ partial def mapVisit (k : Nat → Expr → MetaM Expr) (e : Expr) : MetaM Expr : | .proj _ _ b => return e.updateProj! (← visit (i + 1) b) visit 0 e +section Methods + variable [MonadLiftT MetaM m] [MonadControlT MetaM m] [Monad m] [MonadError m] + variable {a : Type} + + /- Like `lambdaTelescopeN` but only destructs a fixed number of lambdas -/ + def lambdaTelescopeN (e : Expr) (n : Nat) (k : Array Expr → Expr → m a) : m a := + lambdaTelescope e fun xs body => do + if xs.size < n then throwError "lambdaTelescopeN: not enough lambdas" + let xs := xs.extract 0 n + let ys := xs.extract n xs.size + let body ← liftMetaM (mkLambdaFVars ys body) + k xs body + + /- Like `lambdaTelescope`, but only destructs one lambda + TODO: is there an equivalent of this function somewhere in the + standard library? -/ + def lambdaOne (e : Expr) (k : Expr → Expr → m a) : m a := + lambdaTelescopeN e 1 λ xs b => k (xs.get! 0) b + + def isExists (e : Expr) : Bool := e.getAppFn.isConstOf ``Exists ∧ e.getAppNumArgs = 2 + + -- Remark: Lean doesn't find the inhabited and nonempty instances if we don' + -- put them explicitely in the signature + partial def existsTelescopeProcess [Inhabited (m a)] [Nonempty (m a)] + (fvars : Array Expr) (e : Expr) (k : Array Expr → Expr → m a) : m a := do + -- Attempt to deconstruct an existential + if isExists e then do + let p := e.appArg! + lambdaOne p fun x ne => + existsTelescopeProcess (fvars.push x) ne k + else + -- No existential: call the continuation + k fvars e + + def existsTelescope [Inhabited (m a)] [Nonempty (m a)] (e : Expr) (k : Array Expr → Expr → m a) : m a := do + existsTelescopeProcess #[] e k + +end Methods + +def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.TacticM Expr := + -- I don't think we need that + Lean.Elab.Tactic.withMainContext do + -- Insert the new declaration + let withDecl := if asLet then withLetDecl name type val else withLocalDeclD name type + withDecl fun nval => do + -- For debugging + let lctx ← Lean.MonadLCtx.getLCtx + let fid := nval.fvarId! + let decl := lctx.get! fid + trace[Arith] " new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" + -- + -- Tranform the main goal `?m0` to `let x = nval in ?m1` + let mvarId ← Tactic.getMainGoal + let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) + let newVal ← mkLetFVars #[nval] newMVar + -- There are two cases: + -- - asLet is true: newVal is `let $name := $val in $newMVar` + -- - asLet is false: ewVal is `λ $name => $newMVar` + -- We need to apply it to `val` + let newVal := if asLet then newVal else mkAppN newVal #[val] + -- Assign the main goal and update the current goal + mvarId.assign newVal + let goals ← Tactic.getUnsolvedGoals + Lean.Elab.Tactic.setGoals (newMVar.mvarId! :: goals) + -- Return the new value - note: we are in the *new* context, created + -- after the declaration was added, so it will persist + pure nval + +def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) : Tactic.TacticM Unit := + -- I don't think we need that + Lean.Elab.Tactic.withMainContext do + -- + let val ← elabTerm val .none + let type ← inferType val + -- In some situations, the type will be left as a metavariable (for instance, + -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will + -- not choose): we force the instantiation of the meta-variable + synthesizeSyntheticMVarsUsingDefault + -- + let _ ← addDecl name val type asLet + +elab "custom_let " n:ident " := " v:term : tactic => do + addDeclSyntax n.getId v (asLet := true) + +elab "custom_have " n:ident " := " v:term : tactic => + addDeclSyntax n.getId v (asLet := false) + +example : Nat := by + custom_let x := 4 + custom_have y := 4 + apply y + +example (x : Bool) : Nat := by + cases x <;> custom_let x := 3 <;> apply x + end Utils -- cgit v1.2.3 From 6166c410a4b3353377e640acbae9f56e877a9118 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 11 Jul 2023 15:23:49 +0200 Subject: Work on the progress tactic --- backends/lean/Base/Arith.lean | 1 + backends/lean/Base/Arith/Arith.lean | 42 ++++--- backends/lean/Base/Progress.lean | 1 + backends/lean/Base/Progress/Base.lean | 175 ++++++++++++++++++++++++++++++ backends/lean/Base/Progress/Progress.lean | 112 +++++++++++++++++++ backends/lean/Base/Utils.lean | 28 +++++ 6 files changed, 346 insertions(+), 13 deletions(-) create mode 100644 backends/lean/Base/Arith.lean create mode 100644 backends/lean/Base/Progress.lean create mode 100644 backends/lean/Base/Progress/Base.lean create mode 100644 backends/lean/Base/Progress/Progress.lean diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean new file mode 100644 index 00000000..fd5698c5 --- /dev/null +++ b/backends/lean/Base/Arith.lean @@ -0,0 +1 @@ +import Base.Arith.Arith diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index 0ba73d18..ff628cf3 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -146,7 +146,7 @@ def collectInstances -- Similar to `collectInstances`, but explores all the local declarations in the -- main context. def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do - Lean.Elab.Tactic.withMainContext do + Tactic.withMainContext do -- Get the local context let ctx ← Lean.MonadLCtx.getLCtx -- Just a matter of precaution @@ -263,8 +263,8 @@ example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do trace[Arith] "assumption on which to split: {h}" -- Retrieve the main goal - Lean.Elab.Tactic.withMainContext do - let goalType ← Lean.Elab.Tactic.getMainTarget + Tactic.withMainContext do + let goalType ← Tactic.getMainTarget let hDecl := (← getLCtx).get! h.fvarId! let hName := hDecl.userName -- Case disjunction @@ -316,7 +316,7 @@ def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM U trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" elab "split_disj " n:ident : tactic => do - Lean.Elab.Tactic.withMainContext do + Tactic.withMainContext do let decl ← Lean.Meta.getLocalDeclFromUserName n.getId let fvar := mkFVar decl.fvarId splitDisj fvar (fun _ => pure ()) (fun _ => pure ()) @@ -347,7 +347,7 @@ example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by TODO: we could create a PR for mathlib. -/ def intTacPreprocess : Tactic.TacticM Unit := do - Lean.Elab.Tactic.withMainContext do + Tactic.withMainContext do -- Lookup the instances of PropHasImp (this is how we detect assumptions -- of the proper shape), introduce assumptions in the context and split -- on those @@ -366,19 +366,31 @@ def intTacPreprocess : Tactic.TacticM Unit := do elab "int_tac_preprocess" : tactic => intTacPreprocess +def intTac : Tactic.TacticM Unit := do + Tactic.withMainContext do + Tactic.focus do + -- Preprocess - wondering if we should do this before or after splitting + -- the goal. I think before leads to a smaller proof term? + Tactic.allGoals intTacPreprocess + -- Split the conjunctions in the goal + Utils.repeatTac Utils.splitConjTarget + -- Call linarith + let linarith := + let cfg : Linarith.LinarithConfig := { + -- We do this with our custom preprocessing + splitNe := false + } + Tactic.liftMetaFinishingTactic <| Linarith.linarith false [] cfg + Tactic.allGoals linarith + +elab "int_tac" : tactic => + intTac + example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac_preprocess linarith linarith -syntax "int_tac" : tactic -macro_rules - | `(tactic| int_tac) => - `(tactic| - (repeat (apply And.intro)) <;> -- TODO: improve this - int_tac_preprocess <;> - linarith) - example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac @@ -386,6 +398,10 @@ example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by int_tac +-- Checking that things append correctly when there are several disjunctions +example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y ∧ x + y ≥ 2 := by + int_tac + -- A tactic to solve linear arithmetic goals in the presence of scalars syntax "scalar_tac" : tactic macro_rules diff --git a/backends/lean/Base/Progress.lean b/backends/lean/Base/Progress.lean new file mode 100644 index 00000000..d812b896 --- /dev/null +++ b/backends/lean/Base/Progress.lean @@ -0,0 +1 @@ +import Base.Progress.Progress diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean new file mode 100644 index 00000000..3f44f46c --- /dev/null +++ b/backends/lean/Base/Progress/Base.lean @@ -0,0 +1,175 @@ +import Lean +import Base.Utils +import Base.Primitives + +namespace Progress + +open Lean Elab Term Meta +open Utils + +-- We can't define and use trace classes in the same file +initialize registerTraceClass `Progress + +-- Return the first conjunct if the expression is a conjunction, or the +-- expression itself otherwise. Also return the second conjunct if it is a +-- conjunction. +def getFirstConj (e : Expr) : MetaM (Expr × Option Expr) := do + e.withApp fun f args => + if f.isConstOf ``And ∧ args.size = 2 then pure (args.get! 0, some (args.get! 1)) + else pure (e, none) + +-- Destruct an equaliy and return the two sides +def destEq (e : Expr) : MetaM (Expr × Expr) := do + e.withApp fun f args => + if f.isConstOf ``Eq ∧ args.size = 3 then pure (args.get! 1, args.get! 2) + else throwError "Not an equality: {e}" + +-- Return the set of FVarIds in the expression +partial def getFVarIds (e : Expr) (hs : HashSet FVarId := HashSet.empty) : MetaM (HashSet FVarId) := do + e.withApp fun body args => do + let hs := if body.isFVar then hs.insert body.fvarId! else hs + args.foldlM (fun hs arg => getFVarIds arg hs) hs + +/- # Progress tactic -/ + +structure PSpecDesc where + -- The universally quantified variables + fvars : Array Expr + -- The existentially quantified variables + evars : Array Expr + -- The function + fName : Name + -- The function arguments + fLevels : List Level + args : Array Expr + -- The universally quantified variables which appear in the function arguments + argsFVars : Array FVarId + -- The returned value + ret : Expr + -- The postcondition (if there is) + post : Option Expr + +section Methods + variable [MonadLiftT MetaM m] [MonadControlT MetaM m] [Monad m] [MonadOptions m] + variable [MonadTrace m] [MonadLiftT IO m] [MonadRef m] [AddMessageContext m] + variable [MonadError m] + variable {a : Type} + + /- Analyze a pspec theorem to decompose its arguments. + + PSpec theorems should be of the following shape: + ``` + ∀ x1 ... xn, H1 → ... Hn → ∃ y1 ... ym. f x1 ... xn = .ret ... ∧ Post1 ∧ ... ∧ Postk + ``` + + The continuation `k` receives the following inputs: + - universally quantified variables + - assumptions + - existentially quantified variables + - function name + - function arguments + - return + - postconditions + + TODO: generalize for when we do inductive proofs + -/ + partial + def withPSpec [Inhabited (m a)] [Nonempty (m a)] (th : Expr) (k : PSpecDesc → m a) + (sanityChecks : Bool := false) : + m a := do + trace[Progress] "Theorem: {th}" + -- Dive into the quantified variables and the assumptions + forallTelescope th fun fvars th => do + trace[Progress] "All argumens: {fvars}" + /- -- Filter the argumens which are not propositions + let rec getFirstPropIdx (i : Nat) : MetaM Nat := do + if i ≥ fargs.size then pure i + else do + let x := fargs.get! i + if ← Meta.isProp (← inferType x) then pure i + else getFirstPropIdx (i + 1) + let i ← getFirstPropIdx 0 + let fvars := fargs.extract 0 i + let hyps := fargs.extract i fargs.size + trace[Progress] "Quantified variables: {fvars}" + trace[Progress] "Assumptions: {hyps}" + -- Sanity check: all hypotheses are propositions (in particular, all the + -- quantified variables are at the beginning) + let hypsAreProp ← hyps.allM fun x => do Meta.isProp (← inferType x) + if ¬ hypsAreProp then + throwError "The theorem doesn't have the proper shape: all the quantified arguments should be at the beginning" + -/ + -- Dive into the existentials + existsTelescope th fun evars th => do + trace[Progress] "Existentials: {evars}" + -- Take the first conjunct + let (th, post) ← getFirstConj th + -- Destruct the equality + let (th, ret) ← destEq th + -- Destruct the application to get the name + th.withApp fun f args => do + if ¬ f.isConst then throwError "Not a constant: {f}" + -- Compute the set of universally quantified variables which appear in the function arguments + let allArgsFVars ← args.foldlM (fun hs arg => getFVarIds arg hs) HashSet.empty + -- Sanity check + if sanityChecks then + let fvarsSet : HashSet FVarId := HashSet.ofArray (fvars.map (fun x => x.fvarId!)) + let filtArgsFVars := allArgsFVars.toArray.filter (fun fvar => ¬ fvarsSet.contains fvar) + if ¬ filtArgsFVars.isEmpty then + let filtArgsFVars := filtArgsFVars.map (fun fvarId => Expr.fvar fvarId) + throwError "Some of the function inputs are not universally quantified: {filtArgsFVars}" + let argsFVars := fvars.map (fun x => x.fvarId!) + let argsFVars := argsFVars.filter (fun fvar => allArgsFVars.contains fvar) + -- Return + trace[Progress] "Function: {f.constName!}"; + let thDesc := { + fvars := fvars + evars := evars + fName := f.constName! + fLevels := f.constLevels! + args := args + argsFVars + ret := ret + post := post + } + k thDesc +end Methods + + +def getPSpecFunName (th : Expr) : MetaM Name := + withPSpec th (fun d => do pure d.fName) true + +structure PSpecAttr where + attr : AttributeImpl + ext : MapDeclarationExtension Name + deriving Inhabited + +/- The persistent map from function to pspec theorems. -/ +initialize pspecAttr : PSpecAttr ← do + let ext ← mkMapDeclarationExtension `pspecMap + let attrImpl := { + name := `pspec + descr := "Marks theorems to use with the `progress` tactic" + add := fun thName stx attrKind => do + Attribute.Builtin.ensureNoArgs stx + -- TODO: use the attribute kind + unless attrKind == AttributeKind.global do + throwError "invalid attribute 'pspec', must be global" + -- Lookup the theorem + let env ← getEnv + let thDecl := env.constants.find! thName + let fName ← MetaM.run' (getPSpecFunName thDecl.type) + trace[Progress] "Registering spec theorem for {fName}" + let env := ext.addEntry env (fName, thName) + setEnv env + pure () + } + registerBuiltinAttribute attrImpl + pure { attr := attrImpl, ext := ext } + +def PSpecAttr.find? (s : PSpecAttr) (name : Name) : MetaM (Option Name) := do + return (s.ext.getState (← getEnv)).find? name + --return s.ext.find? (← getEnv) name + + +end Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean new file mode 100644 index 00000000..1b9ee55c --- /dev/null +++ b/backends/lean/Base/Progress/Progress.lean @@ -0,0 +1,112 @@ +import Lean +import Base.Arith +import Base.Progress.Base + +namespace Progress + +open Lean Elab Term Meta Tactic +open Utils + +namespace Test + open Primitives + + set_option trace.Progress true + + @[pspec] + theorem vec_index_test (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : + ∃ x, v.index α i = .ret x := by + apply + sorry + + #eval pspecAttr.find? ``Primitives.Vec.index +end Test + +#check isDefEq +#check allGoals + +def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do + withMainContext do + -- Retrieve the goal + let mgoal ← Tactic.getMainGoal + let goalTy ← mgoal.getType + -- Dive into the goal to lookup the theorem + let (fName, fLevels, args) ← do + withPSpec goalTy fun desc => + -- TODO: check that no universally quantified variables in the arguments + pure (desc.fName, desc.fLevels, desc.args) + -- TODO: also try the assumptions + trace[Progress] "Function: {fName}" + -- TODO: use a list of theorems, and try them one by one? + let thName ← do + match ← pspecAttr.find? fName with + | none => throwError "Could not find a pspec theorem for {fName}" + | some thName => pure thName + trace[Progress] "Lookuped up: {thName}" + /- Apply the theorem + We try to match the theorem with the goal + In order to do so, we introduce meta-variables for all the parameters + (i.e., quantified variables and assumpions), and unify those with the goal. + Remark: we do not introduce meta-variables for the quantified variables + which don't appear in the function arguments (we want to let them + quantified). + We also make sure that all the meta variables which appear in the + function arguments have been instantiated + -/ + let env ← getEnv + let thDecl := env.constants.find! thName + let thTy := thDecl.type + -- TODO: the tactic fails if we uncomment withNewMCtxDepth + -- withNewMCtxDepth do + let (mvars, binders, thExBody) ← forallMetaTelescope thTy + -- Introduce the existentially quantified variables and the post-condition + -- in the context + let thBody ← + existsTelescope thExBody fun _evars thBody => do + let (thBody, _) ← destEq thBody + -- There shouldn't be any existential variables in thBody + pure thBody + -- Match the body with the target + let target := mkAppN (.const fName fLevels) args + trace[Progress] "mvars:\n{mvars.map Expr.mvarId!}" + trace[Progress] "thBody: {thBody}" + trace[Progress] "target: {target}" + let ok ← isDefEq thBody target + if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {target}" + postprocessAppMVars `progress mgoal mvars binders true true + Term.synthesizeSyntheticMVarsNoPostponing + let thBody ← instantiateMVars thBody + trace[Progress] "thBody (after instantiation): {thBody}" + -- Add the instantiated theorem to the assumptions (we apply it on the metavariables). + let th ← mkAppOptM thName (mvars.map some) + let asmName ← mkFreshUserName `h + let thTy ← inferType th + let thAsm ← Utils.addDecl asmName th thTy (asLet := false) + -- Update the set of goals + let curGoals ← getUnsolvedGoals + let newGoals := mvars.map Expr.mvarId! + let newGoals ← newGoals.filterM fun mvar => not <$> mvar.isAssigned + trace[Progress] "new goals: {newGoals}" + setGoals newGoals.toList + allGoals asmTac + let newGoals ← getUnsolvedGoals + setGoals (newGoals ++ curGoals) + -- + pure () + +elab "progress" : tactic => do + progressLookupTheorem (firstTac [assumptionTac, Arith.intTac]) + +namespace Test + open Primitives + + set_option trace.Progress true + + @[pspec] + theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : + ∃ x, v.index α i = .ret x := by + progress + tauto + +end Test + +end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 2ce63620..1351f3d4 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -1,4 +1,5 @@ import Lean +import Mathlib.Tactic.Core namespace Utils @@ -211,4 +212,31 @@ example : Nat := by example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x +-- Repeatedly apply a tactic +partial def repeatTac (tac : Tactic.TacticM Unit) : Tactic.TacticM Unit := do + try + tac + Tactic.allGoals (Tactic.focus (repeatTac tac)) + -- TODO: does this restore the state? + catch _ => pure () + +def firstTac (tacl : List (Tactic.TacticM Unit)) : Tactic.TacticM Unit := do + match tacl with + | [] => pure () + | tac :: tacl => + try tac + catch _ => firstTac tacl + +-- Split the goal if it is a conjunction +def splitConjTarget : Tactic.TacticM Unit := do + Tactic.withMainContext do + let and_intro := Expr.const ``And.intro [] + let mvarIds' ← _root_.Lean.MVarId.apply (← Tactic.getMainGoal) and_intro + Term.synthesizeSyntheticMVarsNoPostponing + Tactic.replaceMainGoal mvarIds' + +-- Taken from Lean.Elab.Tactic.evalAssumption +def assumptionTac : Tactic.TacticM Unit := + Tactic.liftMetaTactic fun mvarId => do mvarId.assumption; pure [] + end Utils -- cgit v1.2.3 From a18d899a2c2b9bdd36f4a5a4b70472c12a835a96 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 12 Jul 2023 14:34:55 +0200 Subject: Finish a first version of the progress tactic --- backends/lean/Base/Arith/Arith.lean | 122 ++++----------- backends/lean/Base/Diverge/Base.lean | 2 +- backends/lean/Base/Primitives.lean | 89 ++++++++--- backends/lean/Base/Progress/Base.lean | 24 +-- backends/lean/Base/Progress/Progress.lean | 36 ++++- backends/lean/Base/Utils.lean | 247 +++++++++++++++++++++++++++--- 6 files changed, 349 insertions(+), 171 deletions(-) diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index ff628cf3..3557d350 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -230,25 +230,20 @@ def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) let type ← inferType e let name ← mkFreshUserName `h -- Add a declaration - let nval ← Utils.addDecl name e type (asLet := false) + let nval ← Utils.addDeclTac name e type (asLet := false) -- Simplify to unfold the declaration to unfold (i.e., the projector) - let simpTheorems ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) - -- Add the equational theorem for the decl to unfold - let simpTheorems ← simpTheorems.addDeclToUnfold declToUnfold - let congrTheorems ← getSimpCongrTheorems - let ctx : Simp.Context := { simpTheorems := #[simpTheorems], congrTheorems } - -- Where to apply the simplifier - let loc := Tactic.Location.targets #[mkIdent name] false - -- Apply the simplifier - let _ ← Tactic.simpLocation ctx (discharge? := .none) loc + Utils.simpAt [declToUnfold] [] [] (Tactic.Location.targets #[mkIdent name] false) -- Return the new value pure nval +def introHasPropInstances : Tactic.TacticM (Array Expr) := do + trace[Arith] "Introducing the HasProp instances" + introInstances ``HasProp.prop_ty lookupHasProp + -- Lookup the instances of `HasProp for all the sub-expressions in the context, -- and introduce the corresponding assumptions elab "intro_has_prop_instances" : tactic => do - trace[Arith] "Introducing the HasProp instances" - let _ ← introInstances ``HasProp.prop_ty lookupHasProp + let _ ← introHasPropInstances example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by intro_has_prop_instances @@ -258,74 +253,6 @@ example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by intro_has_prop_instances simp_all [Scalar.max, Scalar.min] --- Tactic to split on a disjunction. --- The expression `h` should be an fvar. -def splitDisj (h : Expr) (kleft kright : Tactic.TacticM Unit) : Tactic.TacticM Unit := do - trace[Arith] "assumption on which to split: {h}" - -- Retrieve the main goal - Tactic.withMainContext do - let goalType ← Tactic.getMainTarget - let hDecl := (← getLCtx).get! h.fvarId! - let hName := hDecl.userName - -- Case disjunction - let hTy ← inferType h - hTy.withApp fun f xs => do - trace[Arith] "as app: {f} {xs}" - -- Sanity check - if ¬ (f.isConstOf ``Or ∧ xs.size = 2) then throwError "Invalid argument to splitDisj" - let a := xs.get! 0 - let b := xs.get! 1 - -- Introduce the new goals - -- Returns: - -- - the match branch - -- - a fresh new mvar id - let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do - -- Introduce a variable for the assumption (`a` or `b`). Note that we reuse - -- the name of the assumption we split. - withLocalDeclD hName hTy fun var => do - -- The new goal - let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) - -- Clear the assumption that we split - let mgoal ← mgoal.mvarId!.tryClearMany #[h.fvarId!] - -- The branch expression - let branch ← mkLambdaFVars #[var] (mkMVar mgoal) - pure (branch, mgoal) - let (inl, mleft) ← mkGoal a "left" - let (inr, mright) ← mkGoal b "right" - trace[Arith] "left: {inl}: {mleft}" - trace[Arith] "right: {inr}: {mright}" - -- Create the match expression - withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do - let motive ← mkLambdaFVars #[hVar] goalType - let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] - let mgoal ← Tactic.getMainGoal - trace[Arith] "goals: {← Tactic.getUnsolvedGoals}" - trace[Arith] "main goal: {mgoal}" - mgoal.assign casesExpr - let goals ← Tactic.getUnsolvedGoals - -- Focus on the left - Tactic.setGoals [mleft] - kleft - let leftGoals ← Tactic.getUnsolvedGoals - -- Focus on the right - Tactic.setGoals [mright] - kright - let rightGoals ← Tactic.getUnsolvedGoals - -- Put all the goals back - Tactic.setGoals (leftGoals ++ rightGoals ++ goals) - trace[Arith] "new goals: {← Tactic.getUnsolvedGoals}" - -elab "split_disj " n:ident : tactic => do - Tactic.withMainContext do - let decl ← Lean.Meta.getLocalDeclFromUserName n.getId - let fvar := mkFVar decl.fvarId - splitDisj fvar (fun _ => pure ()) (fun _ => pure ()) - -example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by - split_disj h0 - . left; assumption - . right; assumption - -- Lookup the instances of `PropHasImp for all the sub-expressions in the context, -- and introduce the corresponding assumptions elab "intro_prop_has_imp_instances" : tactic => do @@ -357,7 +284,7 @@ def intTacPreprocess : Tactic.TacticM Unit := do | [] => pure () | asm :: asms => let k := splitOnAsms asms - splitDisj asm k k + Utils.splitDisjTac asm k k -- Introduce let asms ← introInstances ``PropHasImp.concl lookupPropHasImp -- Split @@ -403,18 +330,27 @@ example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : int_tac -- A tactic to solve linear arithmetic goals in the presence of scalars -syntax "scalar_tac" : tactic -macro_rules - | `(tactic| scalar_tac) => - `(tactic| - intro_has_prop_instances; - have := Scalar.cMin_bound ScalarTy.Usize; - have := Scalar.cMin_bound ScalarTy.Isize; - have := Scalar.cMax_bound ScalarTy.Usize; - have := Scalar.cMax_bound ScalarTy.Isize; - -- TODO: not too sure about that - simp only [*, Scalar.max, Scalar.min, Scalar.cMin, Scalar.cMax] at *; - int_tac) +def scalarTac : Tactic.TacticM Unit := do + Tactic.withMainContext do + -- Introduce the scalar bounds + let _ ← introHasPropInstances + Tactic.allGoals do + -- Inroduce the bounds for the isize/usize types + let add (e : Expr) : Tactic.TacticM Unit := do + let ty ← inferType e + let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) + add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Usize []]) + add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) + -- Reveal the concrete bounds - TODO: not too sure about that. + -- Maybe we should reveal the "concrete" bounds (after normalization) + Utils.simpAt [``Scalar.max, ``Scalar.min, ``Scalar.cMin, ``Scalar.cMax] [] [] .wildcard + -- Apply the integer tactic + intTac + +elab "scalar_tac" : tactic => + scalarTac example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by scalar_tac diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index e22eb914..d2c91ff8 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -14,7 +14,7 @@ TODO: Actually, the cases from mathlib seems already quite powerful (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) For instance: cases h : e - Also: cases_matching + Also: **casesm** - better split tactic - we need conversions to operate on the head of applications. Actually, something like this works: diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 14f5971e..6210688d 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -175,27 +175,28 @@ open System.Platform.getNumBits @[simp] def U128.min : Int := 0 @[simp] def U128.max : Int := HPow.hPow 2 128 - 1 -#assert (I8.min == -128) -#assert (I8.max == 127) -#assert (I16.min == -32768) -#assert (I16.max == 32767) -#assert (I32.min == -2147483648) -#assert (I32.max == 2147483647) -#assert (I64.min == -9223372036854775808) -#assert (I64.max == 9223372036854775807) -#assert (I128.min == -170141183460469231731687303715884105728) -#assert (I128.max == 170141183460469231731687303715884105727) -#assert (U8.min == 0) -#assert (U8.max == 255) -#assert (U16.min == 0) -#assert (U16.max == 65535) -#assert (U32.min == 0) -#assert (U32.max == 4294967295) -#assert (U64.min == 0) -#assert (U64.max == 18446744073709551615) -#assert (U128.min == 0) -#assert (U128.max == 340282366920938463463374607431768211455) - +-- The normalized bounds +@[simp] def I8.norm_min := -128 +@[simp] def I8.norm_max := 127 +@[simp] def I16.norm_min := -32768 +@[simp] def I16.norm_max := 32767 +@[simp] def I32.norm_min := -2147483648 +@[simp] def I32.norm_max := 2147483647 +@[simp] def I64.norm_min := -9223372036854775808 +@[simp] def I64.norm_max := 9223372036854775807 +@[simp] def I128.norm_min := -170141183460469231731687303715884105728 +@[simp] def I128.norm_max := 170141183460469231731687303715884105727 +@[simp] def U8.norm_min := 0 +@[simp] def U8.norm_max := 255 +@[simp] def U16.norm_min := 0 +@[simp] def U16.norm_max := 65535 +@[simp] def U32.norm_min := 0 +@[simp] def U32.norm_max := 4294967295 +@[simp] def U64.norm_min := 0 +@[simp] def U64.norm_max := 18446744073709551615 +@[simp] def U128.norm_min := 0 +@[simp] def U128.norm_max := 340282366920938463463374607431768211455 + inductive ScalarTy := | Isize | I8 @@ -240,6 +241,46 @@ def Scalar.max (ty : ScalarTy) : Int := | .U64 => U64.max | .U128 => U128.max +@[simp] def Scalar.norm_min (ty : ScalarTy) : Int := + match ty with + -- We can't normalize the bounds for isize/usize + | .Isize => Isize.min + | .Usize => Usize.min + -- + | .I8 => I8.norm_min + | .I16 => I16.norm_min + | .I32 => I32.norm_min + | .I64 => I64.norm_min + | .I128 => I128.norm_min + | .U8 => U8.norm_min + | .U16 => U16.norm_min + | .U32 => U32.norm_min + | .U64 => U64.norm_min + | .U128 => U128.norm_min + +@[simp] def Scalar.norm_max (ty : ScalarTy) : Int := + match ty with + -- We can't normalize the bounds for isize/usize + | .Isize => Isize.max + | .Usize => Usize.max + -- + | .I8 => I8.norm_max + | .I16 => I16.norm_max + | .I32 => I32.norm_max + | .I64 => I64.norm_max + | .I128 => I128.norm_max + | .U8 => U8.norm_max + | .U16 => U16.norm_max + | .U32 => U32.norm_max + | .U64 => U64.norm_max + | .U128 => U128.norm_max + +def Scalar.norm_min_eq (ty : ScalarTy) : Scalar.min ty = Scalar.norm_min ty := by + cases ty <;> rfl + +def Scalar.norm_max_eq (ty : ScalarTy) : Scalar.max ty = Scalar.norm_max ty := by + cases ty <;> rfl + -- "Conservative" bounds -- We use those because we can't compare to the isize bounds (which can't -- reduce at compile-time). Whenever we perform an arithmetic operation like @@ -249,13 +290,13 @@ def Scalar.max (ty : ScalarTy) : Int := -- type-checking time. def Scalar.cMin (ty : ScalarTy) : Int := match ty with - | .Isize => I32.min + | .Isize => Scalar.min .I32 | _ => Scalar.min ty def Scalar.cMax (ty : ScalarTy) : Int := match ty with - | .Isize => I32.max - | .Usize => U32.max + | .Isize => Scalar.max .I32 + | .Usize => Scalar.max .U32 | _ => Scalar.max ty theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 3f44f46c..613f38f8 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -10,26 +10,6 @@ open Utils -- We can't define and use trace classes in the same file initialize registerTraceClass `Progress --- Return the first conjunct if the expression is a conjunction, or the --- expression itself otherwise. Also return the second conjunct if it is a --- conjunction. -def getFirstConj (e : Expr) : MetaM (Expr × Option Expr) := do - e.withApp fun f args => - if f.isConstOf ``And ∧ args.size = 2 then pure (args.get! 0, some (args.get! 1)) - else pure (e, none) - --- Destruct an equaliy and return the two sides -def destEq (e : Expr) : MetaM (Expr × Expr) := do - e.withApp fun f args => - if f.isConstOf ``Eq ∧ args.size = 3 then pure (args.get! 1, args.get! 2) - else throwError "Not an equality: {e}" - --- Return the set of FVarIds in the expression -partial def getFVarIds (e : Expr) (hs : HashSet FVarId := HashSet.empty) : MetaM (HashSet FVarId) := do - e.withApp fun body args => do - let hs := if body.isFVar then hs.insert body.fvarId! else hs - args.foldlM (fun hs arg => getFVarIds arg hs) hs - /- # Progress tactic -/ structure PSpecDesc where @@ -103,7 +83,7 @@ section Methods existsTelescope th fun evars th => do trace[Progress] "Existentials: {evars}" -- Take the first conjunct - let (th, post) ← getFirstConj th + let (th, post) ← optSplitConj th -- Destruct the equality let (th, ret) ← destEq th -- Destruct the application to get the name @@ -169,7 +149,5 @@ initialize pspecAttr : PSpecAttr ← do def PSpecAttr.find? (s : PSpecAttr) (name : Name) : MetaM (Option Name) := do return (s.ext.getState (← getEnv)).find? name - --return s.ext.find? (← getEnv) name - end Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 1b9ee55c..4c68b3bd 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -21,9 +21,6 @@ namespace Test #eval pspecAttr.find? ``Primitives.Vec.index end Test -#check isDefEq -#check allGoals - def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do -- Retrieve the goal @@ -80,7 +77,28 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do let th ← mkAppOptM thName (mvars.map some) let asmName ← mkFreshUserName `h let thTy ← inferType th - let thAsm ← Utils.addDecl asmName th thTy (asLet := false) + let thAsm ← Utils.addDeclTac asmName th thTy (asLet := false) + withMainContext do -- The context changed - TODO: remove once addDeclTac is updated + let ngoal ← getMainGoal + trace[Progress] "current goal: {ngoal}" + trace[Progress] "current goal: {← ngoal.isAssigned}" + -- The assumption should be of the shape: + -- `∃ x1 ... xn, f args = ... ∧ ...` + -- We introduce the existentially quantified variables and split the top-most + -- conjunction if there is one + splitAllExistsTac thAsm fun h => do + -- Split the conjunction + let splitConj (k : Expr → TacticM Unit) : TacticM Unit := do + if ← isConj (← inferType h) then + splitConjTac h (fun h _ => k h) + else k h + -- Simplify the target by using the equality + splitConj fun h => do + simpAt [] [] [h.fvarId!] (.targets #[] true) + -- Clear the equality + let mgoal ← getMainGoal + let mgoal ← mgoal.tryClearMany #[h.fvarId!] + setGoals (mgoal :: (← getUnsolvedGoals)) -- Update the set of goals let curGoals ← getUnsolvedGoals let newGoals := mvars.map Expr.mvarId! @@ -94,7 +112,7 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do pure () elab "progress" : tactic => do - progressLookupTheorem (firstTac [assumptionTac, Arith.intTac]) + progressLookupTheorem (firstTac [assumptionTac, Arith.scalarTac]) namespace Test open Primitives @@ -103,10 +121,12 @@ namespace Test @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : - ∃ x, v.index α i = .ret x := by + ∃ (x: α), v.index α i = .ret x := by progress - tauto - + simp + + set_option trace.Progress false + end Test end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 1351f3d4..14feb567 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -1,9 +1,10 @@ import Lean import Mathlib.Tactic.Core +import Mathlib.Tactic.LeftRight namespace Utils -open Lean Elab Term Meta +open Lean Elab Term Meta Tactic -- Useful helper to explore definitions and figure out the variant -- of their sub-expressions. @@ -156,9 +157,10 @@ section Methods end Methods -def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.TacticM Expr := +-- TODO: this should take a continuation +def addDeclTac (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : TacticM Expr := -- I don't think we need that - Lean.Elab.Tactic.withMainContext do + withMainContext do -- Insert the new declaration let withDecl := if asLet then withLetDecl name type val else withLocalDeclD name type withDecl fun nval => do @@ -169,7 +171,7 @@ def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.Tac trace[Arith] " new decl: \"{decl.userName}\" ({nval}) : {decl.type} := {decl.value}" -- -- Tranform the main goal `?m0` to `let x = nval in ?m1` - let mvarId ← Tactic.getMainGoal + let mvarId ← getMainGoal let newMVar ← mkFreshExprSyntheticOpaqueMVar (← mvarId.getType) let newVal ← mkLetFVars #[nval] newMVar -- There are two cases: @@ -179,30 +181,30 @@ def addDecl (name : Name) (val : Expr) (type : Expr) (asLet : Bool) : Tactic.Tac let newVal := if asLet then newVal else mkAppN newVal #[val] -- Assign the main goal and update the current goal mvarId.assign newVal - let goals ← Tactic.getUnsolvedGoals - Lean.Elab.Tactic.setGoals (newMVar.mvarId! :: goals) + let goals ← getUnsolvedGoals + setGoals (newMVar.mvarId! :: goals) -- Return the new value - note: we are in the *new* context, created -- after the declaration was added, so it will persist pure nval -def addDeclSyntax (name : Name) (val : Syntax) (asLet : Bool) : Tactic.TacticM Unit := +def addDeclTacSyntax (name : Name) (val : Syntax) (asLet : Bool) : TacticM Unit := -- I don't think we need that - Lean.Elab.Tactic.withMainContext do + withMainContext do -- - let val ← elabTerm val .none + let val ← Term.elabTerm val .none let type ← inferType val -- In some situations, the type will be left as a metavariable (for instance, -- if the term is `3`, Lean has the choice between `Nat` and `Int` and will -- not choose): we force the instantiation of the meta-variable synthesizeSyntheticMVarsUsingDefault -- - let _ ← addDecl name val type asLet + let _ ← addDeclTac name val type asLet elab "custom_let " n:ident " := " v:term : tactic => do - addDeclSyntax n.getId v (asLet := true) + addDeclTacSyntax n.getId v (asLet := true) elab "custom_have " n:ident " := " v:term : tactic => - addDeclSyntax n.getId v (asLet := false) + addDeclTacSyntax n.getId v (asLet := false) example : Nat := by custom_let x := 4 @@ -213,14 +215,14 @@ example (x : Bool) : Nat := by cases x <;> custom_let x := 3 <;> apply x -- Repeatedly apply a tactic -partial def repeatTac (tac : Tactic.TacticM Unit) : Tactic.TacticM Unit := do +partial def repeatTac (tac : TacticM Unit) : TacticM Unit := do try tac - Tactic.allGoals (Tactic.focus (repeatTac tac)) + allGoals (focus (repeatTac tac)) -- TODO: does this restore the state? catch _ => pure () -def firstTac (tacl : List (Tactic.TacticM Unit)) : Tactic.TacticM Unit := do +def firstTac (tacl : List (TacticM Unit)) : TacticM Unit := do match tacl with | [] => pure () | tac :: tacl => @@ -228,15 +230,216 @@ def firstTac (tacl : List (Tactic.TacticM Unit)) : Tactic.TacticM Unit := do catch _ => firstTac tacl -- Split the goal if it is a conjunction -def splitConjTarget : Tactic.TacticM Unit := do - Tactic.withMainContext do +def splitConjTarget : TacticM Unit := do + withMainContext do let and_intro := Expr.const ``And.intro [] - let mvarIds' ← _root_.Lean.MVarId.apply (← Tactic.getMainGoal) and_intro + let mvarIds' ← _root_.Lean.MVarId.apply (← getMainGoal) and_intro Term.synthesizeSyntheticMVarsNoPostponing - Tactic.replaceMainGoal mvarIds' + replaceMainGoal mvarIds' --- Taken from Lean.Elab.Tactic.evalAssumption -def assumptionTac : Tactic.TacticM Unit := - Tactic.liftMetaTactic fun mvarId => do mvarId.assumption; pure [] +-- Taken from Lean.Elab.evalAssumption +def assumptionTac : TacticM Unit := + liftMetaTactic fun mvarId => do mvarId.assumption; pure [] + +def isConj (e : Expr) : MetaM Bool := + e.withApp fun f args => pure (f.isConstOf ``And ∧ args.size = 2) + +-- Return the first conjunct if the expression is a conjunction, or the +-- expression itself otherwise. Also return the second conjunct if it is a +-- conjunction. +def optSplitConj (e : Expr) : MetaM (Expr × Option Expr) := do + e.withApp fun f args => + if f.isConstOf ``And ∧ args.size = 2 then pure (args.get! 0, some (args.get! 1)) + else pure (e, none) + +-- Destruct an equaliy and return the two sides +def destEq (e : Expr) : MetaM (Expr × Expr) := do + e.withApp fun f args => + if f.isConstOf ``Eq ∧ args.size = 3 then pure (args.get! 1, args.get! 2) + else throwError "Not an equality: {e}" + +-- Return the set of FVarIds in the expression +partial def getFVarIds (e : Expr) (hs : HashSet FVarId := HashSet.empty) : MetaM (HashSet FVarId) := do + e.withApp fun body args => do + let hs := if body.isFVar then hs.insert body.fvarId! else hs + args.foldlM (fun hs arg => getFVarIds arg hs) hs + +-- Tactic to split on a disjunction. +-- The expression `h` should be an fvar. +-- TODO: there must be simpler. Use use _root_.Lean.MVarId.cases for instance +def splitDisjTac (h : Expr) (kleft kright : TacticM Unit) : TacticM Unit := do + trace[Arith] "assumption on which to split: {h}" + -- Retrieve the main goal + withMainContext do + let goalType ← getMainTarget + let hDecl := (← getLCtx).get! h.fvarId! + let hName := hDecl.userName + -- Case disjunction + let hTy ← inferType h + hTy.withApp fun f xs => do + trace[Arith] "as app: {f} {xs}" + -- Sanity check + if ¬ (f.isConstOf ``Or ∧ xs.size = 2) then throwError "Invalid argument to splitDisjTac" + let a := xs.get! 0 + let b := xs.get! 1 + -- Introduce the new goals + -- Returns: + -- - the match branch + -- - a fresh new mvar id + let mkGoal (hTy : Expr) (nGoalName : String) : MetaM (Expr × MVarId) := do + -- Introduce a variable for the assumption (`a` or `b`). Note that we reuse + -- the name of the assumption we split. + withLocalDeclD hName hTy fun var => do + -- The new goal + let mgoal ← mkFreshExprSyntheticOpaqueMVar goalType (tag := Name.mkSimple nGoalName) + -- Clear the assumption that we split + let mgoal ← mgoal.mvarId!.tryClearMany #[h.fvarId!] + -- The branch expression + let branch ← mkLambdaFVars #[var] (mkMVar mgoal) + pure (branch, mgoal) + let (inl, mleft) ← mkGoal a "left" + let (inr, mright) ← mkGoal b "right" + trace[Arith] "left: {inl}: {mleft}" + trace[Arith] "right: {inr}: {mright}" + -- Create the match expression + withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do + let motive ← mkLambdaFVars #[hVar] goalType + let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] + let mgoal ← getMainGoal + trace[Arith] "goals: {← getUnsolvedGoals}" + trace[Arith] "main goal: {mgoal}" + mgoal.assign casesExpr + let goals ← getUnsolvedGoals + -- Focus on the left + setGoals [mleft] + withMainContext kleft + let leftGoals ← getUnsolvedGoals + -- Focus on the right + setGoals [mright] + withMainContext kright + let rightGoals ← getUnsolvedGoals + -- Put all the goals back + setGoals (leftGoals ++ rightGoals ++ goals) + trace[Arith] "new goals: {← getUnsolvedGoals}" + +elab "split_disj " n:ident : tactic => do + withMainContext do + let decl ← Lean.Meta.getLocalDeclFromUserName n.getId + let fvar := mkFVar decl.fvarId + splitDisjTac fvar (fun _ => pure ()) (fun _ => pure ()) + +example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by + split_disj h0 + . left; assumption + . right; assumption + + +-- Tactic to split on an exists +def splitExistsTac (h : Expr) (k : Expr → Expr → TacticM α) : TacticM α := do + withMainContext do + let goal ← getMainGoal + let hTy ← inferType h + if isExists hTy then do + let newGoals ← goal.cases h.fvarId! #[] + -- There should be exactly one goal + match newGoals.toList with + | [ newGoal ] => + -- Set the new goal + let goals ← getUnsolvedGoals + setGoals (newGoal.mvarId :: goals) + -- There should be exactly two fields + let fields := newGoal.fields + withMainContext do + k (fields.get! 0) (fields.get! 1) + | _ => + throwError "Unreachable" + else + throwError "Not a conjunction" + +partial def splitAllExistsTac [Inhabited α] (h : Expr) (k : Expr → TacticM α) : TacticM α := do + try + splitExistsTac h (fun _ body => splitAllExistsTac body k) + catch _ => k h + +-- Tactic to split on a conjunction. +def splitConjTac (h : Expr) (k : Expr → Expr → TacticM α) : TacticM α := do + withMainContext do + let goal ← getMainGoal + let hTy ← inferType h + if ← isConj hTy then do + let newGoals ← goal.cases h.fvarId! #[] + -- There should be exactly one goal + match newGoals.toList with + | [ newGoal ] => + -- Set the new goal + let goals ← getUnsolvedGoals + setGoals (newGoal.mvarId :: goals) + -- There should be exactly two fields + let fields := newGoal.fields + withMainContext do + k (fields.get! 0) (fields.get! 1) + | _ => + throwError "Unreachable" + else + throwError "Not a conjunction" + +elab "split_conj " n:ident : tactic => do + withMainContext do + let decl ← Lean.Meta.getLocalDeclFromUserName n.getId + let fvar := mkFVar decl.fvarId + splitConjTac fvar (fun _ _ => pure ()) + +elab "split_all_exists " n:ident : tactic => do + withMainContext do + let decl ← Lean.Meta.getLocalDeclFromUserName n.getId + let fvar := mkFVar decl.fvarId + splitAllExistsTac fvar (fun _ => pure ()) + +example (h : a ∧ b) : a := by + split_all_exists h + split_conj h + assumption + +example (h : ∃ x y z, x + y + z ≥ 0) : ∃ x, x ≥ 0 := by + split_all_exists h + rename_i x y z h + exists x + y + z + +/- Call the simp tactic. + The initialization of the context is adapted from Tactic.elabSimpArgs. + Something very annoying is that there is no function which allows to + initialize a simp context without doing an elaboration - as a consequence + we write our own here. -/ +def simpAt (declsToUnfold : List Name) (thms : List Name) (hypsToUse : List FVarId) + (loc : Tactic.Location) : + Tactic.TacticM Unit := do + -- Initialize with the builtin simp theorems + let simpThms ← Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) + -- Add the equational theorem for the declarations to unfold + let simpThms ← + declsToUnfold.foldlM (fun thms decl => thms.addDeclToUnfold decl) simpThms + -- Add the hypotheses and the rewriting theorems + let simpThms ← + hypsToUse.foldlM (fun thms fvarId => + -- post: TODO: don't know what that is + -- inv: invert the equality + thms.add (.fvar fvarId) #[] (mkFVar fvarId) (post := false) (inv := false) + -- thms.eraseCore (.fvar fvar) + ) simpThms + -- Add the rewriting theorems to use + let simpThms ← + thms.foldlM (fun thms thmName => do + let info ← getConstInfo thmName + if (← isProp info.type) then + -- post: TODO: don't know what that is + -- inv: invert the equality + thms.addConst thmName (post := false) (inv := false) + else + throwError "Not a proposition: {thmName}" + ) simpThms + let congrTheorems ← getSimpCongrTheorems + let ctx : Simp.Context := { simpTheorems := #[simpThms], congrTheorems } + -- Apply the simplifier + let _ ← Tactic.simpLocation ctx (discharge? := .none) loc end Utils -- cgit v1.2.3 From 59e4a06480b5365f48dc68de80f44841f94094ed Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 12 Jul 2023 15:41:29 +0200 Subject: Improve the handling of arithmetic bounds --- backends/lean/Base/Arith/Arith.lean | 8 +- backends/lean/Base/Primitives.lean | 228 +++++++++++++++--------------- backends/lean/Base/Progress/Progress.lean | 5 +- 3 files changed, 126 insertions(+), 115 deletions(-) diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index 3557d350..20420f36 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -339,13 +339,17 @@ def scalarTac : Tactic.TacticM Unit := do let add (e : Expr) : Tactic.TacticM Unit := do let ty ← inferType e let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) - add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Usize []]) add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) -- Reveal the concrete bounds - TODO: not too sure about that. -- Maybe we should reveal the "concrete" bounds (after normalization) - Utils.simpAt [``Scalar.max, ``Scalar.min, ``Scalar.cMin, ``Scalar.cMax] [] [] .wildcard + Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, + ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, + ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, + ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, + ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max + ] [] [] .wildcard -- Apply the integer tactic intTac diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 6210688d..37abdede 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -149,54 +149,78 @@ open System.Platform.getNumBits @[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val -- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. --- We keep the F* convention for now. -@[simp] def Isize.min : Int := - (HPow.hPow 2 (size_num_bits - 1)) -@[simp] def Isize.max : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -@[simp] def I8.min : Int := - (HPow.hPow 2 7) -@[simp] def I8.max : Int := HPow.hPow 2 7 - 1 -@[simp] def I16.min : Int := - (HPow.hPow 2 15) -@[simp] def I16.max : Int := HPow.hPow 2 15 - 1 -@[simp] def I32.min : Int := -(HPow.hPow 2 31) -@[simp] def I32.max : Int := HPow.hPow 2 31 - 1 -@[simp] def I64.min : Int := -(HPow.hPow 2 63) -@[simp] def I64.max : Int := HPow.hPow 2 63 - 1 -@[simp] def I128.min : Int := -(HPow.hPow 2 127) -@[simp] def I128.max : Int := HPow.hPow 2 127 - 1 -@[simp] def Usize.min : Int := 0 -@[simp] def Usize.max : Int := HPow.hPow 2 size_num_bits - 1 -@[simp] def U8.min : Int := 0 -@[simp] def U8.max : Int := HPow.hPow 2 8 - 1 -@[simp] def U16.min : Int := 0 -@[simp] def U16.max : Int := HPow.hPow 2 16 - 1 -@[simp] def U32.min : Int := 0 -@[simp] def U32.max : Int := HPow.hPow 2 32 - 1 -@[simp] def U64.min : Int := 0 -@[simp] def U64.max : Int := HPow.hPow 2 64 - 1 -@[simp] def U128.min : Int := 0 -@[simp] def U128.max : Int := HPow.hPow 2 128 - 1 - --- The normalized bounds -@[simp] def I8.norm_min := -128 -@[simp] def I8.norm_max := 127 -@[simp] def I16.norm_min := -32768 -@[simp] def I16.norm_max := 32767 -@[simp] def I32.norm_min := -2147483648 -@[simp] def I32.norm_max := 2147483647 -@[simp] def I64.norm_min := -9223372036854775808 -@[simp] def I64.norm_max := 9223372036854775807 -@[simp] def I128.norm_min := -170141183460469231731687303715884105728 -@[simp] def I128.norm_max := 170141183460469231731687303715884105727 -@[simp] def U8.norm_min := 0 -@[simp] def U8.norm_max := 255 -@[simp] def U16.norm_min := 0 -@[simp] def U16.norm_max := 65535 -@[simp] def U32.norm_min := 0 -@[simp] def U32.norm_max := 4294967295 -@[simp] def U64.norm_min := 0 -@[simp] def U64.norm_max := 18446744073709551615 -@[simp] def U128.norm_min := 0 -@[simp] def U128.norm_max := 340282366920938463463374607431768211455 - + +-- The "structured" bounds +def Isize.smin : Int := - (HPow.hPow 2 (size_num_bits - 1)) +def Isize.smax : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 +def I8.smin : Int := - (HPow.hPow 2 7) +def I8.smax : Int := HPow.hPow 2 7 - 1 +def I16.smin : Int := - (HPow.hPow 2 15) +def I16.smax : Int := HPow.hPow 2 15 - 1 +def I32.smin : Int := -(HPow.hPow 2 31) +def I32.smax : Int := HPow.hPow 2 31 - 1 +def I64.smin : Int := -(HPow.hPow 2 63) +def I64.smax : Int := HPow.hPow 2 63 - 1 +def I128.smin : Int := -(HPow.hPow 2 127) +def I128.smax : Int := HPow.hPow 2 127 - 1 +def Usize.smin : Int := 0 +def Usize.smax : Int := HPow.hPow 2 size_num_bits - 1 +def U8.smin : Int := 0 +def U8.smax : Int := HPow.hPow 2 8 - 1 +def U16.smin : Int := 0 +def U16.smax : Int := HPow.hPow 2 16 - 1 +def U32.smin : Int := 0 +def U32.smax : Int := HPow.hPow 2 32 - 1 +def U64.smin : Int := 0 +def U64.smax : Int := HPow.hPow 2 64 - 1 +def U128.smin : Int := 0 +def U128.smax : Int := HPow.hPow 2 128 - 1 + +-- The "normalized" bounds, that we use in practice +def I8.min := -128 +def I8.max := 127 +def I16.min := -32768 +def I16.max := 32767 +def I32.min := -2147483648 +def I32.max := 2147483647 +def I64.min := -9223372036854775808 +def I64.max := 9223372036854775807 +def I128.min := -170141183460469231731687303715884105728 +def I128.max := 170141183460469231731687303715884105727 +@[simp] def U8.min := 0 +def U8.max := 255 +@[simp] def U16.min := 0 +def U16.max := 65535 +@[simp] def U32.min := 0 +def U32.max := 4294967295 +@[simp] def U64.min := 0 +def U64.max := 18446744073709551615 +@[simp] def U128.min := 0 +def U128.max := 340282366920938463463374607431768211455 +@[simp] def Usize.min := 0 + +def Isize.refined_min : { n:Int // n = I32.min ∨ n = I64.min } := + ⟨ Isize.smin, by + simp [Isize.smin] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Isize.refined_max : { n:Int // n = I32.max ∨ n = I64.max } := + ⟨ Isize.smax, by + simp [Isize.smax] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Usize.refined_max : { n:Int // n = U32.max ∨ n = U64.max } := + ⟨ Usize.smax, by + simp [Usize.smax] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Isize.min := Isize.refined_min.val +def Isize.max := Isize.refined_max.val +def Usize.max := Usize.refined_max.val + inductive ScalarTy := | Isize | I8 @@ -211,6 +235,36 @@ inductive ScalarTy := | U64 | U128 +def Scalar.smin (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.smin + | .I8 => I8.smin + | .I16 => I16.smin + | .I32 => I32.smin + | .I64 => I64.smin + | .I128 => I128.smin + | .Usize => Usize.smin + | .U8 => U8.smin + | .U16 => U16.smin + | .U32 => U32.smin + | .U64 => U64.smin + | .U128 => U128.smin + +def Scalar.smax (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.smax + | .I8 => I8.smax + | .I16 => I16.smax + | .I32 => I32.smax + | .I64 => I64.smax + | .I128 => I128.smax + | .Usize => Usize.smax + | .U8 => U8.smax + | .U16 => U16.smax + | .U32 => U32.smax + | .U64 => U64.smax + | .U128 => U128.smax + def Scalar.min (ty : ScalarTy) : Int := match ty with | .Isize => Isize.min @@ -241,44 +295,10 @@ def Scalar.max (ty : ScalarTy) : Int := | .U64 => U64.max | .U128 => U128.max -@[simp] def Scalar.norm_min (ty : ScalarTy) : Int := - match ty with - -- We can't normalize the bounds for isize/usize - | .Isize => Isize.min - | .Usize => Usize.min - -- - | .I8 => I8.norm_min - | .I16 => I16.norm_min - | .I32 => I32.norm_min - | .I64 => I64.norm_min - | .I128 => I128.norm_min - | .U8 => U8.norm_min - | .U16 => U16.norm_min - | .U32 => U32.norm_min - | .U64 => U64.norm_min - | .U128 => U128.norm_min - -@[simp] def Scalar.norm_max (ty : ScalarTy) : Int := - match ty with - -- We can't normalize the bounds for isize/usize - | .Isize => Isize.max - | .Usize => Usize.max - -- - | .I8 => I8.norm_max - | .I16 => I16.norm_max - | .I32 => I32.norm_max - | .I64 => I64.norm_max - | .I128 => I128.norm_max - | .U8 => U8.norm_max - | .U16 => U16.norm_max - | .U32 => U32.norm_max - | .U64 => U64.norm_max - | .U128 => U128.norm_max - -def Scalar.norm_min_eq (ty : ScalarTy) : Scalar.min ty = Scalar.norm_min ty := by +def Scalar.smin_eq (ty : ScalarTy) : Scalar.min ty = Scalar.smin ty := by cases ty <;> rfl -def Scalar.norm_max_eq (ty : ScalarTy) : Scalar.max ty = Scalar.norm_max ty := by +def Scalar.smax_eq (ty : ScalarTy) : Scalar.max ty = Scalar.smax ty := by cases ty <;> rfl -- "Conservative" bounds @@ -301,30 +321,22 @@ def Scalar.cMax (ty : ScalarTy) : Int := theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] + have h := Isize.refined_min.property + cases h <;> simp [*, Isize.min] theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * + . have h := Isize.refined_max.property + cases h <;> simp [*, Isize.max] + . have h := Usize.refined_max.property + cases h <;> simp [*, Usize.max] theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * - -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + have := Scalar.cMin_bound ty linarith theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * <;> - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * <;> - -- TODO: I would have expected terms like `-(1 + 1) ^ 63` to be simplified + have := Scalar.cMax_bound ty linarith structure Scalar (ty : ScalarTy) where @@ -609,7 +621,7 @@ def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usiz def Vec.len (α : Type u) (v : Vec α) : Usize := let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by simp [Scalar.min]) l + Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l -- This shouldn't be used def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () @@ -620,13 +632,9 @@ def Vec.push (α : Type u) (v : Vec α) (x : α) : Result (Vec α) let nlen := List.length v.val + 1 if h : nlen ≤ U32.max || nlen ≤ Usize.max then have h : nlen ≤ Usize.max := by - simp at * - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> - simp [*] at * <;> - try assumption - cases h <;> - linarith + simp [Usize.max] at * + have hm := Usize.refined_max.property + cases h <;> cases hm <;> simp [U32.max, U64.max] at * <;> try linarith return ⟨ List.concat v.val x, by simp at *; assumption ⟩ else fail maximumSizeExceeded @@ -647,7 +655,6 @@ def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := .ret ⟨ List.set v.val i x, by have h: List.length v.val ≤ Usize.max := v.property simp [*] at * - assumption ⟩ else .fail arrayOutOfBounds @@ -688,7 +695,6 @@ def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec .ret ⟨ List.set v.val i x, by have h: List.length v.val ≤ Usize.max := v.property simp [*] at * - assumption ⟩ else .fail arrayOutOfBounds diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 4c68b3bd..a4df5c96 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -92,9 +92,10 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do if ← isConj (← inferType h) then splitConjTac h (fun h _ => k h) else k h - -- Simplify the target by using the equality + -- Simplify the target by using the equality and some monad simplifications splitConj fun h => do - simpAt [] [] [h.fvarId!] (.targets #[] true) + simpAt [] [``Primitives.bind_tc_ret, ``Primitives.bind_tc_fail, ``Primitives.bind_tc_div] + [h.fvarId!] (.targets #[] true) -- Clear the equality let mgoal ← getMainGoal let mgoal ← mgoal.tryClearMany #[h.fvarId!] -- cgit v1.2.3 From e010c10fb9a1e2d88b52a4f6b4a0865448276013 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 12 Jul 2023 15:58:38 +0200 Subject: Make the `by inlit` implicit --- backends/lean/Base/Primitives.lean | 15 ++-- compiler/Extract.ml | 2 +- tests/lean/BetreeMain/Funs.lean | 31 ++++---- tests/lean/Constants.lean | 35 ++++----- tests/lean/External/Funs.lean | 10 +-- tests/lean/Hashmap/Funs.lean | 81 ++++++++------------ tests/lean/HashmapMain/Funs.lean | 86 +++++++++------------ tests/lean/Loops/Funs.lean | 140 ++++++++++++++++------------------ tests/lean/NoNestedBorrows.lean | 152 +++++++++++++++++-------------------- tests/lean/Paper.lean | 48 +++++------- tests/lean/lake-manifest.json | 8 +- 11 files changed, 277 insertions(+), 331 deletions(-) diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 37abdede..0506f4c0 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -356,8 +356,14 @@ def Scalar.ofIntCore {ty : ScalarTy} (x : Int) (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := { val := x, hmin := hmin, hmax := hmax } +-- Tactic to prove that integers are in bounds +-- TODO: use this: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/instance.20with.20tactic.20autoparam +syntax "intlit" : tactic +macro_rules + | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices; decide) + def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : Scalar ty := + (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by intlit) : Scalar ty := -- Remark: we initially wrote: -- let ⟨ hmin, hmax ⟩ := h -- Scalar.ofIntCore x hmin hmax @@ -573,13 +579,6 @@ instance (ty : ScalarTy) : DecidableEq (Scalar ty) := def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val --- Tactic to prove that integers are in bounds --- TODO: use this: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/instance.20with.20tactic.20autoparam -syntax "intlit" : tactic - -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices ; decide) - -- -- We now define a type class that subsumes the various machine integer types, so -- -- as to write a concise definition for scalar_cast, rather than exhaustively -- -- enumerating all of the possible pairs. We remark that Rust has sane semantics diff --git a/compiler/Extract.ml b/compiler/Extract.ml index 558a981d..b16f9639 100644 --- a/compiler/Extract.ml +++ b/compiler/Extract.ml @@ -820,7 +820,7 @@ let mk_formatter (ctx : trans_ctx) (crate_name : string) F.pp_print_string fmt ")"; F.pp_print_string fmt ")") else Z.pp_print fmt sv.value; - F.pp_print_string fmt " (by intlit))") + F.pp_print_string fmt ")") | Bool b -> let b = match !backend with diff --git a/tests/lean/BetreeMain/Funs.lean b/tests/lean/BetreeMain/Funs.lean index b0939155..142adf08 100644 --- a/tests/lean/BetreeMain/Funs.lean +++ b/tests/lean/BetreeMain/Funs.lean @@ -39,33 +39,33 @@ def betree.store_leaf_node /- [betree_main::betree::fresh_node_id]: forward function -/ def betree.fresh_node_id (counter : U64) : Result U64 := do - let _ ← counter + (U64.ofInt 1 (by intlit)) + let _ ← counter + (U64.ofInt 1) Result.ret counter /- [betree_main::betree::fresh_node_id]: backward function 0 -/ def betree.fresh_node_id_back (counter : U64) : Result U64 := - counter + (U64.ofInt 1 (by intlit)) + counter + (U64.ofInt 1) /- [betree_main::betree::NodeIdCounter::{0}::new]: forward function -/ def betree.NodeIdCounter.new : Result betree.NodeIdCounter := - Result.ret { next_node_id := (U64.ofInt 0 (by intlit)) } + Result.ret { next_node_id := (U64.ofInt 0) } /- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: forward function -/ def betree.NodeIdCounter.fresh_id (self : betree.NodeIdCounter) : Result U64 := do - let _ ← self.next_node_id + (U64.ofInt 1 (by intlit)) + let _ ← self.next_node_id + (U64.ofInt 1) Result.ret self.next_node_id /- [betree_main::betree::NodeIdCounter::{0}::fresh_id]: backward function 0 -/ def betree.NodeIdCounter.fresh_id_back (self : betree.NodeIdCounter) : Result betree.NodeIdCounter := do - let i ← self.next_node_id + (U64.ofInt 1 (by intlit)) + let i ← self.next_node_id + (U64.ofInt 1) Result.ret { next_node_id := i } /- [core::num::u64::{10}::MAX] -/ def core_num_u64_max_body : Result U64 := - Result.ret (U64.ofInt 18446744073709551615 (by intlit)) + Result.ret (U64.ofInt 18446744073709551615) def core_num_u64_max_c : U64 := eval_global core_num_u64_max_body (by simp) /- [betree_main::betree::upsert_update]: forward function -/ @@ -75,7 +75,7 @@ def betree.upsert_update | Option.none => match st with | betree.UpsertFunState.Add v => Result.ret v - | betree.UpsertFunState.Sub i => Result.ret (U64.ofInt 0 (by intlit)) + | betree.UpsertFunState.Sub i => Result.ret (U64.ofInt 0) | Option.some prev0 => match st with | betree.UpsertFunState.Add v => @@ -87,7 +87,7 @@ def betree.upsert_update | betree.UpsertFunState.Sub v => if prev0 >= v then prev0 - v - else Result.ret (U64.ofInt 0 (by intlit)) + else Result.ret (U64.ofInt 0) /- [betree_main::betree::List::{1}::len]: forward function -/ divergent def betree.List.len (T : Type) (self : betree.List T) : Result U64 := @@ -95,21 +95,21 @@ divergent def betree.List.len (T : Type) (self : betree.List T) : Result U64 := | betree.List.Cons t tl => do let i ← betree.List.len T tl - (U64.ofInt 1 (by intlit)) + i - | betree.List.Nil => Result.ret (U64.ofInt 0 (by intlit)) + (U64.ofInt 1) + i + | betree.List.Nil => Result.ret (U64.ofInt 0) /- [betree_main::betree::List::{1}::split_at]: forward function -/ divergent def betree.List.split_at (T : Type) (self : betree.List T) (n : U64) : Result ((betree.List T) × (betree.List T)) := - if n = (U64.ofInt 0 (by intlit)) + if n = (U64.ofInt 0) then Result.ret (betree.List.Nil, self) else match self with | betree.List.Cons hd tl => do - let i ← n - (U64.ofInt 1 (by intlit)) + let i ← n - (U64.ofInt 1) let p ← betree.List.split_at T tl i let (ls0, ls1) := p let l := ls0 @@ -740,7 +740,7 @@ mutual divergent def betree.Node.apply_messages let (st0, content) ← betree.load_leaf_node node.id st let content0 ← betree.Node.apply_messages_to_leaf content msgs let len ← betree.List.len (U64 × U64) content0 - let i ← (U64.ofInt 2 (by intlit)) * params.split_size + let i ← (U64.ofInt 2) * params.split_size if len >= i then do @@ -790,7 +790,7 @@ divergent def betree.Node.apply_messages_back let (st0, content) ← betree.load_leaf_node node.id st let content0 ← betree.Node.apply_messages_to_leaf content msgs let len ← betree.List.len (U64 × U64) content0 - let i ← (U64.ofInt 2 (by intlit)) * params.split_size + let i ← (U64.ofInt 2) * params.split_size if len >= i then do @@ -922,8 +922,7 @@ def betree.BeTree.new params := { min_flush_size := min_flush_size, split_size := split_size }, node_id_cnt := node_id_cnt0, - root := - (betree.Node.Leaf { id := id, size := (U64.ofInt 0 (by intlit)) }) + root := (betree.Node.Leaf { id := id, size := (U64.ofInt 0) }) }) /- [betree_main::betree::BeTree::{6}::apply]: forward function -/ diff --git a/tests/lean/Constants.lean b/tests/lean/Constants.lean index 8f22bfba..4a5a7b8f 100644 --- a/tests/lean/Constants.lean +++ b/tests/lean/Constants.lean @@ -5,12 +5,11 @@ open Primitives namespace constants /- [constants::X0] -/ -def x0_body : Result U32 := Result.ret (U32.ofInt 0 (by intlit)) +def x0_body : Result U32 := Result.ret (U32.ofInt 0) def x0_c : U32 := eval_global x0_body (by simp) /- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_body : Result U32 := Result.ret (U32.ofInt 4294967295) def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [constants::X1] -/ @@ -18,15 +17,15 @@ def x1_body : Result U32 := Result.ret core_num_u32_max_c def x1_c : U32 := eval_global x1_body (by simp) /- [constants::X2] -/ -def x2_body : Result U32 := Result.ret (U32.ofInt 3 (by intlit)) +def x2_body : Result U32 := Result.ret (U32.ofInt 3) def x2_c : U32 := eval_global x2_body (by simp) /- [constants::incr]: forward function -/ def incr (n : U32) : Result U32 := - n + (U32.ofInt 1 (by intlit)) + n + (U32.ofInt 1) /- [constants::X3] -/ -def x3_body : Result U32 := incr (U32.ofInt 32 (by intlit)) +def x3_body : Result U32 := incr (U32.ofInt 32) def x3_c : U32 := eval_global x3_body (by simp) /- [constants::mk_pair0]: forward function -/ @@ -43,23 +42,20 @@ def mk_pair1 (x : U32) (y : U32) : Result (Pair U32 U32) := Result.ret { x := x, y := y } /- [constants::P0] -/ -def p0_body : Result (U32 × U32) := - mk_pair0 (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) +def p0_body : Result (U32 × U32) := mk_pair0 (U32.ofInt 0) (U32.ofInt 1) def p0_c : (U32 × U32) := eval_global p0_body (by simp) /- [constants::P1] -/ -def p1_body : Result (Pair U32 U32) := - mk_pair1 (U32.ofInt 0 (by intlit)) (U32.ofInt 1 (by intlit)) +def p1_body : Result (Pair U32 U32) := mk_pair1 (U32.ofInt 0) (U32.ofInt 1) def p1_c : Pair U32 U32 := eval_global p1_body (by simp) /- [constants::P2] -/ -def p2_body : Result (U32 × U32) := - Result.ret ((U32.ofInt 0 (by intlit)), (U32.ofInt 1 (by intlit))) +def p2_body : Result (U32 × U32) := Result.ret ((U32.ofInt 0), (U32.ofInt 1)) def p2_c : (U32 × U32) := eval_global p2_body (by simp) /- [constants::P3] -/ def p3_body : Result (Pair U32 U32) := - Result.ret { x := (U32.ofInt 0 (by intlit)), y := (U32.ofInt 1 (by intlit)) } + Result.ret { x := (U32.ofInt 0), y := (U32.ofInt 1) } def p3_c : Pair U32 U32 := eval_global p3_body (by simp) /- [constants::Wrap] -/ @@ -71,7 +67,7 @@ def Wrap.new (T : Type) (val : T) : Result (Wrap T) := Result.ret { val := val } /- [constants::Y] -/ -def y_body : Result (Wrap I32) := Wrap.new I32 (I32.ofInt 2 (by intlit)) +def y_body : Result (Wrap I32) := Wrap.new I32 (I32.ofInt 2) def y_c : Wrap I32 := eval_global y_body (by simp) /- [constants::unwrap_y]: forward function -/ @@ -83,7 +79,7 @@ def yval_body : Result I32 := unwrap_y def yval_c : I32 := eval_global yval_body (by simp) /- [constants::get_z1::Z1] -/ -def get_z1_z1_body : Result I32 := Result.ret (I32.ofInt 3 (by intlit)) +def get_z1_z1_body : Result I32 := Result.ret (I32.ofInt 3) def get_z1_z1_c : I32 := eval_global get_z1_z1_body (by simp) /- [constants::get_z1]: forward function -/ @@ -95,7 +91,7 @@ def add (a : I32) (b : I32) : Result I32 := a + b /- [constants::Q1] -/ -def q1_body : Result I32 := Result.ret (I32.ofInt 5 (by intlit)) +def q1_body : Result I32 := Result.ret (I32.ofInt 5) def q1_c : I32 := eval_global q1_body (by simp) /- [constants::Q2] -/ @@ -103,7 +99,7 @@ def q2_body : Result I32 := Result.ret q1_c def q2_c : I32 := eval_global q2_body (by simp) /- [constants::Q3] -/ -def q3_body : Result I32 := add q2_c (I32.ofInt 3 (by intlit)) +def q3_body : Result I32 := add q2_c (I32.ofInt 3) def q3_c : I32 := eval_global q3_body (by simp) /- [constants::get_z2]: forward function -/ @@ -114,7 +110,7 @@ def get_z2 : Result I32 := add q1_c i0 /- [constants::S1] -/ -def s1_body : Result U32 := Result.ret (U32.ofInt 6 (by intlit)) +def s1_body : Result U32 := Result.ret (U32.ofInt 6) def s1_c : U32 := eval_global s1_body (by simp) /- [constants::S2] -/ @@ -126,8 +122,7 @@ def s3_body : Result (Pair U32 U32) := Result.ret p3_c def s3_c : Pair U32 U32 := eval_global s3_body (by simp) /- [constants::S4] -/ -def s4_body : Result (Pair U32 U32) := - mk_pair1 (U32.ofInt 7 (by intlit)) (U32.ofInt 8 (by intlit)) +def s4_body : Result (Pair U32 U32) := mk_pair1 (U32.ofInt 7) (U32.ofInt 8) def s4_c : Pair U32 U32 := eval_global s4_body (by simp) end constants diff --git a/tests/lean/External/Funs.lean b/tests/lean/External/Funs.lean index 122f94da..674aaebd 100644 --- a/tests/lean/External/Funs.lean +++ b/tests/lean/External/Funs.lean @@ -36,7 +36,7 @@ def test_new_non_zero_u32 def test_vec : Result Unit := do let v := Vec.new U32 - let _ ← Vec.push U32 v (U32.ofInt 0 (by intlit)) + let _ ← Vec.push U32 v (U32.ofInt 0) Result.ret () /- Unit test for [external::test_vec] -/ @@ -74,14 +74,14 @@ def test_custom_swap_back (x : U32) (y : U32) (st : State) (st0 : State) : Result (State × (U32 × U32)) := - custom_swap_back U32 x y st (U32.ofInt 1 (by intlit)) st0 + custom_swap_back U32 x y st (U32.ofInt 1) st0 /- [external::test_swap_non_zero]: forward function -/ def test_swap_non_zero (x : U32) (st : State) : Result (State × U32) := do - let (st0, _) ← swap U32 x (U32.ofInt 0 (by intlit)) st - let (st1, (x0, _)) ← swap_back U32 x (U32.ofInt 0 (by intlit)) st st0 - if x0 = (U32.ofInt 0 (by intlit)) + let (st0, _) ← swap U32 x (U32.ofInt 0) st + let (st1, (x0, _)) ← swap_back U32 x (U32.ofInt 0) st st0 + if x0 = (U32.ofInt 0) then Result.fail Error.panic else Result.ret (st1, x0) diff --git a/tests/lean/Hashmap/Funs.lean b/tests/lean/Hashmap/Funs.lean index 5e11ffdd..870693b5 100644 --- a/tests/lean/Hashmap/Funs.lean +++ b/tests/lean/Hashmap/Funs.lean @@ -12,11 +12,11 @@ def hash_key (k : Usize) : Result Usize := /- [hashmap::HashMap::{0}::allocate_slots]: loop 0: forward function -/ divergent def HashMap.allocate_slots_loop (T : Type) (slots : Vec (List T)) (n : Usize) : Result (Vec (List T)) := - if n > (Usize.ofInt 0 (by intlit)) + if n > (Usize.ofInt 0) then do let slots0 ← Vec.push (List T) slots List.Nil - let n0 ← n - (Usize.ofInt 1 (by intlit)) + let n0 ← n - (Usize.ofInt 1) HashMap.allocate_slots_loop T slots0 n0 else Result.ret slots @@ -38,7 +38,7 @@ def HashMap.new_with_capacity let i0 ← i / max_load_divisor Result.ret { - num_entries := (Usize.ofInt 0 (by intlit)), + num_entries := (Usize.ofInt 0), max_load_factor := (max_load_dividend, max_load_divisor), max_load := i0, slots := slots @@ -46,8 +46,7 @@ def HashMap.new_with_capacity /- [hashmap::HashMap::{0}::new]: forward function -/ def HashMap.new (T : Type) : Result (HashMap T) := - HashMap.new_with_capacity T (Usize.ofInt 32 (by intlit)) - (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) + HashMap.new_with_capacity T (Usize.ofInt 32) (Usize.ofInt 4) (Usize.ofInt 5) /- [hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ @@ -57,7 +56,7 @@ divergent def HashMap.clear_loop if i < i0 then do - let i1 ← i + (Usize.ofInt 1 (by intlit)) + let i1 ← i + (Usize.ofInt 1) let slots0 ← Vec.index_mut_back (List T) slots i List.Nil HashMap.clear_loop T slots0 i1 else Result.ret slots @@ -66,9 +65,8 @@ divergent def HashMap.clear_loop (there is a single backward function, and the forward function returns ()) -/ def HashMap.clear (T : Type) (self : HashMap T) : Result (HashMap T) := do - let v ← HashMap.clear_loop T self.slots (Usize.ofInt 0 (by intlit)) - Result.ret - { self with num_entries := (Usize.ofInt 0 (by intlit)), slots := v } + let v ← HashMap.clear_loop T self.slots (Usize.ofInt 0) + Result.ret { self with num_entries := (Usize.ofInt 0), slots := v } /- [hashmap::HashMap::{0}::len]: forward function -/ def HashMap.len (T : Type) (self : HashMap T) : Result Usize := @@ -123,7 +121,7 @@ def HashMap.insert_no_resize if inserted then do - let i0 ← self.num_entries + (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries + (Usize.ofInt 1) let l0 ← HashMap.insert_in_list_back T key value l let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 Result.ret { self with num_entries := i0, slots := v } @@ -134,8 +132,7 @@ def HashMap.insert_no_resize Result.ret { self with slots := v } /- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_body : Result U32 := Result.ret (U32.ofInt 4294967295) def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function @@ -168,7 +165,7 @@ divergent def HashMap.move_elements_loop let l ← Vec.index_mut (List T) slots i let ls := mem.replace (List T) l List.Nil let ntable0 ← HashMap.move_elements_from_list T ntable ls - let i1 ← i + (Usize.ofInt 1 (by intlit)) + let i1 ← i + (Usize.ofInt 1) let l0 := mem.replace_back (List T) l List.Nil let slots0 ← Vec.index_mut_back (List T) slots i l0 HashMap.move_elements_loop T ntable0 slots0 i1 @@ -188,16 +185,16 @@ def HashMap.try_resize (T : Type) (self : HashMap T) : Result (HashMap T) := do let max_usize ← Scalar.cast .Usize core_num_u32_max_c let capacity := Vec.len (List T) self.slots - let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) + let n1 ← max_usize / (Usize.ofInt 2) let (i, i0) := self.max_load_factor let i1 ← n1 / i if capacity <= i1 then do - let i2 ← capacity * (Usize.ofInt 2 (by intlit)) + let i2 ← capacity * (Usize.ofInt 2) let ntable ← HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - HashMap.move_elements T ntable self.slots (Usize.ofInt 0 (by intlit)) + HashMap.move_elements T ntable self.slots (Usize.ofInt 0) Result.ret { ntable0 @@ -377,7 +374,7 @@ def HashMap.remove | Option.none => Result.ret Option.none | Option.some x0 => do - let _ ← self.num_entries - (Usize.ofInt 1 (by intlit)) + let _ ← self.num_entries - (Usize.ofInt 1) Result.ret (Option.some x0) /- [hashmap::HashMap::{0}::remove]: backward function 0 -/ @@ -397,7 +394,7 @@ def HashMap.remove_back Result.ret { self with slots := v } | Option.some x0 => do - let i0 ← self.num_entries - (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries - (Usize.ofInt 1) let l0 ← HashMap.remove_from_list_back T key l let v ← Vec.index_mut_back (List T) self.slots hash_mod l0 Result.ret { self with num_entries := i0, slots := v } @@ -406,55 +403,43 @@ def HashMap.remove_back def test1 : Result Unit := do let hm ← HashMap.new U64 - let hm0 ← - HashMap.insert U64 hm (Usize.ofInt 0 (by intlit)) - (U64.ofInt 42 (by intlit)) - let hm1 ← - HashMap.insert U64 hm0 (Usize.ofInt 128 (by intlit)) - (U64.ofInt 18 (by intlit)) - let hm2 ← - HashMap.insert U64 hm1 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 138 (by intlit)) - let hm3 ← - HashMap.insert U64 hm2 (Usize.ofInt 1056 (by intlit)) - (U64.ofInt 256 (by intlit)) - let i ← HashMap.get U64 hm3 (Usize.ofInt 128 (by intlit)) - if not (i = (U64.ofInt 18 (by intlit))) + let hm0 ← HashMap.insert U64 hm (Usize.ofInt 0) (U64.ofInt 42) + let hm1 ← HashMap.insert U64 hm0 (Usize.ofInt 128) (U64.ofInt 18) + let hm2 ← HashMap.insert U64 hm1 (Usize.ofInt 1024) (U64.ofInt 138) + let hm3 ← HashMap.insert U64 hm2 (Usize.ofInt 1056) (U64.ofInt 256) + let i ← HashMap.get U64 hm3 (Usize.ofInt 128) + if not (i = (U64.ofInt 18)) then Result.fail Error.panic else do let hm4 ← - HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 56 (by intlit)) - let i0 ← HashMap.get U64 hm4 (Usize.ofInt 1024 (by intlit)) - if not (i0 = (U64.ofInt 56 (by intlit))) + HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024) (U64.ofInt 56) + let i0 ← HashMap.get U64 hm4 (Usize.ofInt 1024) + if not (i0 = (U64.ofInt 56)) then Result.fail Error.panic else do - let x ← HashMap.remove U64 hm4 (Usize.ofInt 1024 (by intlit)) + let x ← HashMap.remove U64 hm4 (Usize.ofInt 1024) match x with | Option.none => Result.fail Error.panic | Option.some x0 => - if not (x0 = (U64.ofInt 56 (by intlit))) + if not (x0 = (U64.ofInt 56)) then Result.fail Error.panic else do - let hm5 ← - HashMap.remove_back U64 hm4 (Usize.ofInt 1024 (by intlit)) - let i1 ← HashMap.get U64 hm5 (Usize.ofInt 0 (by intlit)) - if not (i1 = (U64.ofInt 42 (by intlit))) + let hm5 ← HashMap.remove_back U64 hm4 (Usize.ofInt 1024) + let i1 ← HashMap.get U64 hm5 (Usize.ofInt 0) + if not (i1 = (U64.ofInt 42)) then Result.fail Error.panic else do - let i2 ← - HashMap.get U64 hm5 (Usize.ofInt 128 (by intlit)) - if not (i2 = (U64.ofInt 18 (by intlit))) + let i2 ← HashMap.get U64 hm5 (Usize.ofInt 128) + if not (i2 = (U64.ofInt 18)) then Result.fail Error.panic else do - let i3 ← - HashMap.get U64 hm5 (Usize.ofInt 1056 (by intlit)) - if not (i3 = (U64.ofInt 256 (by intlit))) + let i3 ← HashMap.get U64 hm5 (Usize.ofInt 1056) + if not (i3 = (U64.ofInt 256)) then Result.fail Error.panic else Result.ret () diff --git a/tests/lean/HashmapMain/Funs.lean b/tests/lean/HashmapMain/Funs.lean index e82cc9b2..610bae46 100644 --- a/tests/lean/HashmapMain/Funs.lean +++ b/tests/lean/HashmapMain/Funs.lean @@ -15,11 +15,11 @@ divergent def hashmap.HashMap.allocate_slots_loop (T : Type) (slots : Vec (hashmap.List T)) (n : Usize) : Result (Vec (hashmap.List T)) := - if n > (Usize.ofInt 0 (by intlit)) + if n > (Usize.ofInt 0) then do let slots0 ← Vec.push (hashmap.List T) slots hashmap.List.Nil - let n0 ← n - (Usize.ofInt 1 (by intlit)) + let n0 ← n - (Usize.ofInt 1) hashmap.HashMap.allocate_slots_loop T slots0 n0 else Result.ret slots @@ -43,7 +43,7 @@ def hashmap.HashMap.new_with_capacity let i0 ← i / max_load_divisor Result.ret { - num_entries := (Usize.ofInt 0 (by intlit)), + num_entries := (Usize.ofInt 0), max_load_factor := (max_load_dividend, max_load_divisor), max_load := i0, slots := slots @@ -51,8 +51,8 @@ def hashmap.HashMap.new_with_capacity /- [hashmap_main::hashmap::HashMap::{0}::new]: forward function -/ def hashmap.HashMap.new (T : Type) : Result (hashmap.HashMap T) := - hashmap.HashMap.new_with_capacity T (Usize.ofInt 32 (by intlit)) - (Usize.ofInt 4 (by intlit)) (Usize.ofInt 5 (by intlit)) + hashmap.HashMap.new_with_capacity T (Usize.ofInt 32) (Usize.ofInt 4) + (Usize.ofInt 5) /- [hashmap_main::hashmap::HashMap::{0}::clear]: loop 0: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ @@ -64,7 +64,7 @@ divergent def hashmap.HashMap.clear_loop if i < i0 then do - let i1 ← i + (Usize.ofInt 1 (by intlit)) + let i1 ← i + (Usize.ofInt 1) let slots0 ← Vec.index_mut_back (hashmap.List T) slots i hashmap.List.Nil hashmap.HashMap.clear_loop T slots0 i1 @@ -75,10 +75,8 @@ divergent def hashmap.HashMap.clear_loop def hashmap.HashMap.clear (T : Type) (self : hashmap.HashMap T) : Result (hashmap.HashMap T) := do - let v ← - hashmap.HashMap.clear_loop T self.slots (Usize.ofInt 0 (by intlit)) - Result.ret - { self with num_entries := (Usize.ofInt 0 (by intlit)), slots := v } + let v ← hashmap.HashMap.clear_loop T self.slots (Usize.ofInt 0) + Result.ret { self with num_entries := (Usize.ofInt 0), slots := v } /- [hashmap_main::hashmap::HashMap::{0}::len]: forward function -/ def hashmap.HashMap.len (T : Type) (self : hashmap.HashMap T) : Result Usize := @@ -138,7 +136,7 @@ def hashmap.HashMap.insert_no_resize if inserted then do - let i0 ← self.num_entries + (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries + (Usize.ofInt 1) let l0 ← hashmap.HashMap.insert_in_list_back T key value l let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 Result.ret { self with num_entries := i0, slots := v } @@ -149,8 +147,7 @@ def hashmap.HashMap.insert_no_resize Result.ret { self with slots := v } /- [core::num::u32::{9}::MAX] -/ -def core_num_u32_max_body : Result U32 := - Result.ret (U32.ofInt 4294967295 (by intlit)) +def core_num_u32_max_body : Result U32 := Result.ret (U32.ofInt 4294967295) def core_num_u32_max_c : U32 := eval_global core_num_u32_max_body (by simp) /- [hashmap_main::hashmap::HashMap::{0}::move_elements_from_list]: loop 0: merged forward/backward function @@ -188,7 +185,7 @@ divergent def hashmap.HashMap.move_elements_loop let l ← Vec.index_mut (hashmap.List T) slots i let ls := mem.replace (hashmap.List T) l hashmap.List.Nil let ntable0 ← hashmap.HashMap.move_elements_from_list T ntable ls - let i1 ← i + (Usize.ofInt 1 (by intlit)) + let i1 ← i + (Usize.ofInt 1) let l0 := mem.replace_back (hashmap.List T) l hashmap.List.Nil let slots0 ← Vec.index_mut_back (hashmap.List T) slots i l0 hashmap.HashMap.move_elements_loop T ntable0 slots0 i1 @@ -210,17 +207,16 @@ def hashmap.HashMap.try_resize do let max_usize ← Scalar.cast .Usize core_num_u32_max_c let capacity := Vec.len (hashmap.List T) self.slots - let n1 ← max_usize / (Usize.ofInt 2 (by intlit)) + let n1 ← max_usize / (Usize.ofInt 2) let (i, i0) := self.max_load_factor let i1 ← n1 / i if capacity <= i1 then do - let i2 ← capacity * (Usize.ofInt 2 (by intlit)) + let i2 ← capacity * (Usize.ofInt 2) let ntable ← hashmap.HashMap.new_with_capacity T i2 i i0 let (ntable0, _) ← - hashmap.HashMap.move_elements T ntable self.slots - (Usize.ofInt 0 (by intlit)) + hashmap.HashMap.move_elements T ntable self.slots (Usize.ofInt 0) Result.ret { ntable0 @@ -411,7 +407,7 @@ def hashmap.HashMap.remove | Option.none => Result.ret Option.none | Option.some x0 => do - let _ ← self.num_entries - (Usize.ofInt 1 (by intlit)) + let _ ← self.num_entries - (Usize.ofInt 1) Result.ret (Option.some x0) /- [hashmap_main::hashmap::HashMap::{0}::remove]: backward function 0 -/ @@ -433,7 +429,7 @@ def hashmap.HashMap.remove_back Result.ret { self with slots := v } | Option.some x0 => do - let i0 ← self.num_entries - (Usize.ofInt 1 (by intlit)) + let i0 ← self.num_entries - (Usize.ofInt 1) let l0 ← hashmap.HashMap.remove_from_list_back T key l let v ← Vec.index_mut_back (hashmap.List T) self.slots hash_mod l0 Result.ret { self with num_entries := i0, slots := v } @@ -442,60 +438,48 @@ def hashmap.HashMap.remove_back def hashmap.test1 : Result Unit := do let hm ← hashmap.HashMap.new U64 - let hm0 ← - hashmap.HashMap.insert U64 hm (Usize.ofInt 0 (by intlit)) - (U64.ofInt 42 (by intlit)) - let hm1 ← - hashmap.HashMap.insert U64 hm0 (Usize.ofInt 128 (by intlit)) - (U64.ofInt 18 (by intlit)) + let hm0 ← hashmap.HashMap.insert U64 hm (Usize.ofInt 0) (U64.ofInt 42) + let hm1 ← hashmap.HashMap.insert U64 hm0 (Usize.ofInt 128) (U64.ofInt 18) let hm2 ← - hashmap.HashMap.insert U64 hm1 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 138 (by intlit)) + hashmap.HashMap.insert U64 hm1 (Usize.ofInt 1024) (U64.ofInt 138) let hm3 ← - hashmap.HashMap.insert U64 hm2 (Usize.ofInt 1056 (by intlit)) - (U64.ofInt 256 (by intlit)) - let i ← hashmap.HashMap.get U64 hm3 (Usize.ofInt 128 (by intlit)) - if not (i = (U64.ofInt 18 (by intlit))) + hashmap.HashMap.insert U64 hm2 (Usize.ofInt 1056) (U64.ofInt 256) + let i ← hashmap.HashMap.get U64 hm3 (Usize.ofInt 128) + if not (i = (U64.ofInt 18)) then Result.fail Error.panic else do let hm4 ← - hashmap.HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024 (by intlit)) - (U64.ofInt 56 (by intlit)) - let i0 ← hashmap.HashMap.get U64 hm4 (Usize.ofInt 1024 (by intlit)) - if not (i0 = (U64.ofInt 56 (by intlit))) + hashmap.HashMap.get_mut_back U64 hm3 (Usize.ofInt 1024) + (U64.ofInt 56) + let i0 ← hashmap.HashMap.get U64 hm4 (Usize.ofInt 1024) + if not (i0 = (U64.ofInt 56)) then Result.fail Error.panic else do - let x ← - hashmap.HashMap.remove U64 hm4 (Usize.ofInt 1024 (by intlit)) + let x ← hashmap.HashMap.remove U64 hm4 (Usize.ofInt 1024) match x with | Option.none => Result.fail Error.panic | Option.some x0 => - if not (x0 = (U64.ofInt 56 (by intlit))) + if not (x0 = (U64.ofInt 56)) then Result.fail Error.panic else do let hm5 ← - hashmap.HashMap.remove_back U64 hm4 - (Usize.ofInt 1024 (by intlit)) - let i1 ← - hashmap.HashMap.get U64 hm5 (Usize.ofInt 0 (by intlit)) - if not (i1 = (U64.ofInt 42 (by intlit))) + hashmap.HashMap.remove_back U64 hm4 (Usize.ofInt 1024) + let i1 ← hashmap.HashMap.get U64 hm5 (Usize.ofInt 0) + if not (i1 = (U64.ofInt 42)) then Result.fail Error.panic else do - let i2 ← - hashmap.HashMap.get U64 hm5 - (Usize.ofInt 128 (by intlit)) - if not (i2 = (U64.ofInt 18 (by intlit))) + let i2 ← hashmap.HashMap.get U64 hm5 (Usize.ofInt 128) + if not (i2 = (U64.ofInt 18)) then Result.fail Error.panic else do let i3 ← - hashmap.HashMap.get U64 hm5 - (Usize.ofInt 1056 (by intlit)) - if not (i3 = (U64.ofInt 256 (by intlit))) + hashmap.HashMap.get U64 hm5 (Usize.ofInt 1056) + if not (i3 = (U64.ofInt 256)) then Result.fail Error.panic else Result.ret () diff --git a/tests/lean/Loops/Funs.lean b/tests/lean/Loops/Funs.lean index 8cac7ac0..f7e6603d 100644 --- a/tests/lean/Loops/Funs.lean +++ b/tests/lean/Loops/Funs.lean @@ -8,16 +8,15 @@ namespace loops /- [loops::sum]: loop 0: forward function -/ divergent def sum_loop (max : U32) (i : U32) (s : U32) : Result U32 := if i < max - then - do - let s0 ← s + i - let i0 ← i + (U32.ofInt 1 (by intlit)) - sum_loop max i0 s0 - else s * (U32.ofInt 2 (by intlit)) + then do + let s0 ← s + i + let i0 ← i + (U32.ofInt 1) + sum_loop max i0 s0 + else s * (U32.ofInt 2) /- [loops::sum]: forward function -/ def sum (max : U32) : Result U32 := - sum_loop max (U32.ofInt 0 (by intlit)) (U32.ofInt 0 (by intlit)) + sum_loop max (U32.ofInt 0) (U32.ofInt 0) /- [loops::sum_with_mut_borrows]: loop 0: forward function -/ divergent def sum_with_mut_borrows_loop @@ -26,14 +25,13 @@ divergent def sum_with_mut_borrows_loop then do let ms0 ← ms + mi - let mi0 ← mi + (U32.ofInt 1 (by intlit)) + let mi0 ← mi + (U32.ofInt 1) sum_with_mut_borrows_loop max mi0 ms0 - else ms * (U32.ofInt 2 (by intlit)) + else ms * (U32.ofInt 2) /- [loops::sum_with_mut_borrows]: forward function -/ def sum_with_mut_borrows (max : U32) : Result U32 := - sum_with_mut_borrows_loop max (U32.ofInt 0 (by intlit)) - (U32.ofInt 0 (by intlit)) + sum_with_mut_borrows_loop max (U32.ofInt 0) (U32.ofInt 0) /- [loops::sum_with_shared_borrows]: loop 0: forward function -/ divergent def sum_with_shared_borrows_loop @@ -41,15 +39,14 @@ divergent def sum_with_shared_borrows_loop if i < max then do - let i0 ← i + (U32.ofInt 1 (by intlit)) + let i0 ← i + (U32.ofInt 1) let s0 ← s + i0 sum_with_shared_borrows_loop max i0 s0 - else s * (U32.ofInt 2 (by intlit)) + else s * (U32.ofInt 2) /- [loops::sum_with_shared_borrows]: forward function -/ def sum_with_shared_borrows (max : U32) : Result U32 := - sum_with_shared_borrows_loop max (U32.ofInt 0 (by intlit)) - (U32.ofInt 0 (by intlit)) + sum_with_shared_borrows_loop max (U32.ofInt 0) (U32.ofInt 0) /- [loops::clear]: loop 0: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ @@ -58,15 +55,15 @@ divergent def clear_loop (v : Vec U32) (i : Usize) : Result (Vec U32) := if i < i0 then do - let i1 ← i + (Usize.ofInt 1 (by intlit)) - let v0 ← Vec.index_mut_back U32 v i (U32.ofInt 0 (by intlit)) + let i1 ← i + (Usize.ofInt 1) + let v0 ← Vec.index_mut_back U32 v i (U32.ofInt 0) clear_loop v0 i1 else Result.ret v /- [loops::clear]: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ def clear (v : Vec U32) : Result (Vec U32) := - clear_loop v (Usize.ofInt 0 (by intlit)) + clear_loop v (Usize.ofInt 0) /- [loops::list_mem]: loop 0: forward function -/ divergent def list_mem_loop (x : U32) (ls : List U32) : Result Bool := @@ -85,12 +82,11 @@ divergent def list_nth_mut_loop_loop (T : Type) (ls : List T) (i : U32) : Result T := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_loop T tl i0 + else do + let i0 ← i - (U32.ofInt 1) + list_nth_mut_loop_loop T tl i0 | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop]: forward function -/ @@ -102,11 +98,11 @@ divergent def list_nth_mut_loop_loop_back (T : Type) (ls : List T) (i : U32) (ret0 : T) : Result (List T) := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl0 ← list_nth_mut_loop_loop_back T tl i0 ret0 Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic @@ -121,12 +117,11 @@ divergent def list_nth_shared_loop_loop (T : Type) (ls : List T) (i : U32) : Result T := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_shared_loop_loop T tl i0 + else do + let i0 ← i - (U32.ofInt 1) + list_nth_shared_loop_loop T tl i0 | List.Nil => Result.fail Error.panic /- [loops::list_nth_shared_loop]: forward function -/ @@ -144,7 +139,7 @@ divergent def get_elem_mut_loop (x : Usize) (ls : List Usize) : Result Usize := /- [loops::get_elem_mut]: forward function -/ def get_elem_mut (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0) get_elem_mut_loop x l /- [loops::get_elem_mut]: loop 0: backward function 0 -/ @@ -166,9 +161,9 @@ def get_elem_mut_back Result (Vec (List Usize)) := do - let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index_mut (List Usize) slots (Usize.ofInt 0) let l0 ← get_elem_mut_loop_back x l ret0 - Vec.index_mut_back (List Usize) slots (Usize.ofInt 0 (by intlit)) l0 + Vec.index_mut_back (List Usize) slots (Usize.ofInt 0) l0 /- [loops::get_elem_shared]: loop 0: forward function -/ divergent def get_elem_shared_loop @@ -182,7 +177,7 @@ divergent def get_elem_shared_loop /- [loops::get_elem_shared]: forward function -/ def get_elem_shared (slots : Vec (List Usize)) (x : Usize) : Result Usize := do - let l ← Vec.index (List Usize) slots (Usize.ofInt 0 (by intlit)) + let l ← Vec.index (List Usize) slots (Usize.ofInt 0) get_elem_shared_loop x l /- [loops::id_mut]: forward function -/ @@ -202,12 +197,11 @@ divergent def list_nth_mut_loop_with_id_loop (T : Type) (i : U32) (ls : List T) : Result T := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x - else - do - let i0 ← i - (U32.ofInt 1 (by intlit)) - list_nth_mut_loop_with_id_loop T i0 tl + else do + let i0 ← i - (U32.ofInt 1) + list_nth_mut_loop_with_id_loop T i0 tl | List.Nil => Result.fail Error.panic /- [loops::list_nth_mut_loop_with_id]: forward function -/ @@ -221,11 +215,11 @@ divergent def list_nth_mut_loop_with_id_loop_back (T : Type) (i : U32) (ls : List T) (ret0 : T) : Result (List T) := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl0 ← list_nth_mut_loop_with_id_loop_back T i0 tl ret0 Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic @@ -243,11 +237,11 @@ divergent def list_nth_shared_loop_with_id_loop (T : Type) (i : U32) (ls : List T) : Result T := match ls with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared_loop_with_id_loop T i0 tl | List.Nil => Result.fail Error.panic @@ -265,11 +259,11 @@ divergent def list_nth_mut_loop_pair_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -288,11 +282,11 @@ divergent def list_nth_mut_loop_pair_loop_back'a | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl0) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl00 ← list_nth_mut_loop_pair_loop_back'a T tl0 tl1 i0 ret0 Result.ret (List.Cons x0 tl00) | List.Nil => Result.fail Error.panic @@ -314,11 +308,11 @@ divergent def list_nth_mut_loop_pair_loop_back'b | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl10 ← list_nth_mut_loop_pair_loop_back'b T tl0 tl1 i0 ret0 Result.ret (List.Cons x1 tl10) | List.Nil => Result.fail Error.panic @@ -338,11 +332,11 @@ divergent def list_nth_shared_loop_pair_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -359,11 +353,11 @@ divergent def list_nth_mut_loop_pair_merge_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -382,12 +376,12 @@ divergent def list_nth_mut_loop_pair_merge_loop_back | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then let (t, t0) := ret0 Result.ret (List.Cons t tl0, List.Cons t0 tl1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let (tl00, tl10) ← list_nth_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 Result.ret (List.Cons x0 tl00, List.Cons x1 tl10) @@ -408,11 +402,11 @@ divergent def list_nth_shared_loop_pair_merge_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -429,11 +423,11 @@ divergent def list_nth_mut_shared_loop_pair_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut_shared_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -452,11 +446,11 @@ divergent def list_nth_mut_shared_loop_pair_loop_back | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl0) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl00 ← list_nth_mut_shared_loop_pair_loop_back T tl0 tl1 i0 ret0 Result.ret (List.Cons x0 tl00) @@ -477,11 +471,11 @@ divergent def list_nth_mut_shared_loop_pair_merge_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut_shared_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -500,11 +494,11 @@ divergent def list_nth_mut_shared_loop_pair_merge_loop_back | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl0) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl00 ← list_nth_mut_shared_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 Result.ret (List.Cons x0 tl00) @@ -525,11 +519,11 @@ divergent def list_nth_shared_mut_loop_pair_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared_mut_loop_pair_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -548,11 +542,11 @@ divergent def list_nth_shared_mut_loop_pair_loop_back | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl10 ← list_nth_shared_mut_loop_pair_loop_back T tl0 tl1 i0 ret0 Result.ret (List.Cons x1 tl10) @@ -573,11 +567,11 @@ divergent def list_nth_shared_mut_loop_pair_merge_loop | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (x0, x1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared_mut_loop_pair_merge_loop T tl0 tl1 i0 | List.Nil => Result.fail Error.panic | List.Nil => Result.fail Error.panic @@ -596,11 +590,11 @@ divergent def list_nth_shared_mut_loop_pair_merge_loop_back | List.Cons x0 tl0 => match ls1 with | List.Cons x1 tl1 => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl1) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl10 ← list_nth_shared_mut_loop_pair_merge_loop_back T tl0 tl1 i0 ret0 Result.ret (List.Cons x1 tl10) diff --git a/tests/lean/NoNestedBorrows.lean b/tests/lean/NoNestedBorrows.lean index 1c6421bb..bc707fd9 100644 --- a/tests/lean/NoNestedBorrows.lean +++ b/tests/lean/NoNestedBorrows.lean @@ -53,7 +53,7 @@ def div_test (x : U32) (y : U32) : Result U32 := /- [no_nested_borrows::div_test1]: forward function -/ def div_test1 (x : U32) : Result U32 := - x / (U32.ofInt 2 (by intlit)) + x / (U32.ofInt 2) /- [no_nested_borrows::rem_test]: forward function -/ def rem_test (x : U32) (y : U32) : Result U32 := @@ -66,7 +66,7 @@ def cast_test (x : U32) : Result I32 := /- [no_nested_borrows::test2]: forward function -/ def test2 : Result Unit := do - let _ ← (U32.ofInt 23 (by intlit)) + (U32.ofInt 44 (by intlit)) + let _ ← (U32.ofInt 23) + (U32.ofInt 44) Result.ret () /- Unit test for [no_nested_borrows::test2] -/ @@ -81,10 +81,10 @@ def get_max (x : U32) (y : U32) : Result U32 := /- [no_nested_borrows::test3]: forward function -/ def test3 : Result Unit := do - let x ← get_max (U32.ofInt 4 (by intlit)) (U32.ofInt 3 (by intlit)) - let y ← get_max (U32.ofInt 10 (by intlit)) (U32.ofInt 11 (by intlit)) + let x ← get_max (U32.ofInt 4) (U32.ofInt 3) + let y ← get_max (U32.ofInt 10) (U32.ofInt 11) let z ← x + y - if not (z = (U32.ofInt 15 (by intlit))) + if not (z = (U32.ofInt 15)) then Result.fail Error.panic else Result.ret () @@ -94,8 +94,8 @@ def test3 : Result Unit := /- [no_nested_borrows::test_neg1]: forward function -/ def test_neg1 : Result Unit := do - let y ← - (I32.ofInt 3 (by intlit)) - if not (y = (I32.ofInt (-(3:Int)) (by intlit))) + let y ← - (I32.ofInt 3) + if not (y = (I32.ofInt (-(3:Int)))) then Result.fail Error.panic else Result.ret () @@ -104,7 +104,7 @@ def test_neg1 : Result Unit := /- [no_nested_borrows::refs_test1]: forward function -/ def refs_test1 : Result Unit := - if not ((I32.ofInt 1 (by intlit)) = (I32.ofInt 1 (by intlit))) + if not ((I32.ofInt 1) = (I32.ofInt 1)) then Result.fail Error.panic else Result.ret () @@ -113,16 +113,16 @@ def refs_test1 : Result Unit := /- [no_nested_borrows::refs_test2]: forward function -/ def refs_test2 : Result Unit := - if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + if not ((I32.ofInt 2) = (I32.ofInt 2)) then Result.fail Error.panic else - if not ((I32.ofInt 0 (by intlit)) = (I32.ofInt 0 (by intlit))) + if not ((I32.ofInt 0) = (I32.ofInt 0)) then Result.fail Error.panic else - if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + if not ((I32.ofInt 2) = (I32.ofInt 2)) then Result.fail Error.panic else - if not ((I32.ofInt 2 (by intlit)) = (I32.ofInt 2 (by intlit))) + if not ((I32.ofInt 2) = (I32.ofInt 2)) then Result.fail Error.panic else Result.ret () @@ -138,9 +138,9 @@ def test_list1 : Result Unit := /- [no_nested_borrows::test_box1]: forward function -/ def test_box1 : Result Unit := - let b := (I32.ofInt 1 (by intlit)) + let b := (I32.ofInt 1) let x := b - if not (x = (I32.ofInt 1 (by intlit))) + if not (x = (I32.ofInt 1)) then Result.fail Error.panic else Result.ret () @@ -166,8 +166,8 @@ def test_panic (b : Bool) : Result Unit := /- [no_nested_borrows::test_copy_int]: forward function -/ def test_copy_int : Result Unit := do - let y ← copy_int (I32.ofInt 0 (by intlit)) - if not ((I32.ofInt 0 (by intlit)) = y) + let y ← copy_int (I32.ofInt 0) + if not ((I32.ofInt 0) = y) then Result.fail Error.panic else Result.ret () @@ -184,7 +184,7 @@ def is_cons (T : Type) (l : List T) : Result Bool := def test_is_cons : Result Unit := do let l := List.Nil - let b ← is_cons I32 (List.Cons (I32.ofInt 0 (by intlit)) l) + let b ← is_cons I32 (List.Cons (I32.ofInt 0) l) if not b then Result.fail Error.panic else Result.ret () @@ -202,9 +202,9 @@ def split_list (T : Type) (l : List T) : Result (T × (List T)) := def test_split_list : Result Unit := do let l := List.Nil - let p ← split_list I32 (List.Cons (I32.ofInt 0 (by intlit)) l) + let p ← split_list I32 (List.Cons (I32.ofInt 0) l) let (hd, _) := p - if not (hd = (I32.ofInt 0 (by intlit))) + if not (hd = (I32.ofInt 0)) then Result.fail Error.panic else Result.ret () @@ -227,20 +227,17 @@ def choose_back /- [no_nested_borrows::choose_test]: forward function -/ def choose_test : Result Unit := do - let z ← - choose I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) - let z0 ← z + (I32.ofInt 1 (by intlit)) - if not (z0 = (I32.ofInt 1 (by intlit))) + let z ← choose I32 true (I32.ofInt 0) (I32.ofInt 0) + let z0 ← z + (I32.ofInt 1) + if not (z0 = (I32.ofInt 1)) then Result.fail Error.panic else do - let (x, y) ← - choose_back I32 true (I32.ofInt 0 (by intlit)) - (I32.ofInt 0 (by intlit)) z0 - if not (x = (I32.ofInt 1 (by intlit))) + let (x, y) ← choose_back I32 true (I32.ofInt 0) (I32.ofInt 0) z0 + if not (x = (I32.ofInt 1)) then Result.fail Error.panic else - if not (y = (I32.ofInt 0 (by intlit))) + if not (y = (I32.ofInt 0)) then Result.fail Error.panic else Result.ret () @@ -268,20 +265,19 @@ end /- [no_nested_borrows::list_length]: forward function -/ divergent def list_length (T : Type) (l : List T) : Result U32 := match l with - | List.Cons t l1 => - do - let i ← list_length T l1 - (U32.ofInt 1 (by intlit)) + i - | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) + | List.Cons t l1 => do + let i ← list_length T l1 + (U32.ofInt 1) + i + | List.Nil => Result.ret (U32.ofInt 0) /- [no_nested_borrows::list_nth_shared]: forward function -/ divergent def list_nth_shared (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_shared T tl i0 | List.Nil => Result.fail Error.panic @@ -289,10 +285,10 @@ divergent def list_nth_shared (T : Type) (l : List T) (i : U32) : Result T := divergent def list_nth_mut (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut T tl i0 | List.Nil => Result.fail Error.panic @@ -301,11 +297,11 @@ divergent def list_nth_mut_back (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl0 ← list_nth_mut_back T tl i0 ret0 Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic @@ -327,52 +323,47 @@ def list_rev (T : Type) (l : List T) : Result (List T) := def test_list_functions : Result Unit := do let l := List.Nil - let l0 := List.Cons (I32.ofInt 2 (by intlit)) l - let l1 := List.Cons (I32.ofInt 1 (by intlit)) l0 - let i ← list_length I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) - if not (i = (U32.ofInt 3 (by intlit))) + let l0 := List.Cons (I32.ofInt 2) l + let l1 := List.Cons (I32.ofInt 1) l0 + let i ← list_length I32 (List.Cons (I32.ofInt 0) l1) + if not (i = (U32.ofInt 3)) then Result.fail Error.panic else do let i0 ← - list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) - (U32.ofInt 0 (by intlit)) - if not (i0 = (I32.ofInt 0 (by intlit))) + list_nth_shared I32 (List.Cons (I32.ofInt 0) l1) (U32.ofInt 0) + if not (i0 = (I32.ofInt 0)) then Result.fail Error.panic else do let i1 ← - list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) - (U32.ofInt 1 (by intlit)) - if not (i1 = (I32.ofInt 1 (by intlit))) + list_nth_shared I32 (List.Cons (I32.ofInt 0) l1) (U32.ofInt 1) + if not (i1 = (I32.ofInt 1)) then Result.fail Error.panic else do let i2 ← - list_nth_shared I32 (List.Cons (I32.ofInt 0 (by intlit)) l1) - (U32.ofInt 2 (by intlit)) - if not (i2 = (I32.ofInt 2 (by intlit))) + list_nth_shared I32 (List.Cons (I32.ofInt 0) l1) + (U32.ofInt 2) + if not (i2 = (I32.ofInt 2)) then Result.fail Error.panic else do let ls ← - list_nth_mut_back I32 (List.Cons - (I32.ofInt 0 (by intlit)) l1) (U32.ofInt 1 (by intlit)) - (I32.ofInt 3 (by intlit)) - let i3 ← list_nth_shared I32 ls (U32.ofInt 0 (by intlit)) - if not (i3 = (I32.ofInt 0 (by intlit))) + list_nth_mut_back I32 (List.Cons (I32.ofInt 0) l1) + (U32.ofInt 1) (I32.ofInt 3) + let i3 ← list_nth_shared I32 ls (U32.ofInt 0) + if not (i3 = (I32.ofInt 0)) then Result.fail Error.panic else do - let i4 ← - list_nth_shared I32 ls (U32.ofInt 1 (by intlit)) - if not (i4 = (I32.ofInt 3 (by intlit))) + let i4 ← list_nth_shared I32 ls (U32.ofInt 1) + if not (i4 = (I32.ofInt 3)) then Result.fail Error.panic else do - let i5 ← - list_nth_shared I32 ls (U32.ofInt 2 (by intlit)) - if not (i5 = (I32.ofInt 2 (by intlit))) + let i5 ← list_nth_shared I32 ls (U32.ofInt 2) + if not (i5 = (I32.ofInt 2)) then Result.fail Error.panic else Result.ret () @@ -435,15 +426,15 @@ structure StructWithTuple (T1 T2 : Type) where /- [no_nested_borrows::new_tuple1]: forward function -/ def new_tuple1 : Result (StructWithTuple U32 U32) := - Result.ret { p := ((U32.ofInt 1 (by intlit)), (U32.ofInt 2 (by intlit))) } + Result.ret { p := ((U32.ofInt 1), (U32.ofInt 2)) } /- [no_nested_borrows::new_tuple2]: forward function -/ def new_tuple2 : Result (StructWithTuple I16 I16) := - Result.ret { p := ((I16.ofInt 1 (by intlit)), (I16.ofInt 2 (by intlit))) } + Result.ret { p := ((I16.ofInt 1), (I16.ofInt 2)) } /- [no_nested_borrows::new_tuple3]: forward function -/ def new_tuple3 : Result (StructWithTuple U64 I64) := - Result.ret { p := ((U64.ofInt 1 (by intlit)), (I64.ofInt 2 (by intlit))) } + Result.ret { p := ((U64.ofInt 1), (I64.ofInt 2)) } /- [no_nested_borrows::StructWithPair] -/ structure StructWithPair (T1 T2 : Type) where @@ -451,32 +442,31 @@ structure StructWithPair (T1 T2 : Type) where /- [no_nested_borrows::new_pair1]: forward function -/ def new_pair1 : Result (StructWithPair U32 U32) := - Result.ret - { p := { x := (U32.ofInt 1 (by intlit)), y := (U32.ofInt 2 (by intlit)) } } + Result.ret { p := { x := (U32.ofInt 1), y := (U32.ofInt 2) } } /- [no_nested_borrows::test_constants]: forward function -/ def test_constants : Result Unit := do let swt ← new_tuple1 let (i, _) := swt.p - if not (i = (U32.ofInt 1 (by intlit))) + if not (i = (U32.ofInt 1)) then Result.fail Error.panic else do let swt0 ← new_tuple2 let (i0, _) := swt0.p - if not (i0 = (I16.ofInt 1 (by intlit))) + if not (i0 = (I16.ofInt 1)) then Result.fail Error.panic else do let swt1 ← new_tuple3 let (i1, _) := swt1.p - if not (i1 = (U64.ofInt 1 (by intlit))) + if not (i1 = (U64.ofInt 1)) then Result.fail Error.panic else do let swp ← new_pair1 - if not (swp.p.x = (U32.ofInt 1 (by intlit))) + if not (swp.p.x = (U32.ofInt 1)) then Result.fail Error.panic else Result.ret () @@ -493,29 +483,29 @@ def test_weird_borrows1 : Result Unit := /- [no_nested_borrows::test_mem_replace]: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ def test_mem_replace (px : U32) : Result U32 := - let y := mem.replace U32 px (U32.ofInt 1 (by intlit)) - if not (y = (U32.ofInt 0 (by intlit))) + let y := mem.replace U32 px (U32.ofInt 1) + if not (y = (U32.ofInt 0)) then Result.fail Error.panic - else Result.ret (U32.ofInt 2 (by intlit)) + else Result.ret (U32.ofInt 2) /- [no_nested_borrows::test_shared_borrow_bool1]: forward function -/ def test_shared_borrow_bool1 (b : Bool) : Result U32 := if b - then Result.ret (U32.ofInt 0 (by intlit)) - else Result.ret (U32.ofInt 1 (by intlit)) + then Result.ret (U32.ofInt 0) + else Result.ret (U32.ofInt 1) /- [no_nested_borrows::test_shared_borrow_bool2]: forward function -/ def test_shared_borrow_bool2 : Result U32 := - Result.ret (U32.ofInt 0 (by intlit)) + Result.ret (U32.ofInt 0) /- [no_nested_borrows::test_shared_borrow_enum1]: forward function -/ def test_shared_borrow_enum1 (l : List U32) : Result U32 := match l with - | List.Cons i l0 => Result.ret (U32.ofInt 1 (by intlit)) - | List.Nil => Result.ret (U32.ofInt 0 (by intlit)) + | List.Cons i l0 => Result.ret (U32.ofInt 1) + | List.Nil => Result.ret (U32.ofInt 0) /- [no_nested_borrows::test_shared_borrow_enum2]: forward function -/ def test_shared_borrow_enum2 : Result U32 := - Result.ret (U32.ofInt 0 (by intlit)) + Result.ret (U32.ofInt 0) end no_nested_borrows diff --git a/tests/lean/Paper.lean b/tests/lean/Paper.lean index ade65656..cee7128a 100644 --- a/tests/lean/Paper.lean +++ b/tests/lean/Paper.lean @@ -7,13 +7,13 @@ namespace paper /- [paper::ref_incr]: merged forward/backward function (there is a single backward function, and the forward function returns ()) -/ def ref_incr (x : I32) : Result I32 := - x + (I32.ofInt 1 (by intlit)) + x + (I32.ofInt 1) /- [paper::test_incr]: forward function -/ def test_incr : Result Unit := do - let x ← ref_incr (I32.ofInt 0 (by intlit)) - if not (x = (I32.ofInt 1 (by intlit))) + let x ← ref_incr (I32.ofInt 0) + if not (x = (I32.ofInt 1)) then Result.fail Error.panic else Result.ret () @@ -36,20 +36,17 @@ def choose_back /- [paper::test_choose]: forward function -/ def test_choose : Result Unit := do - let z ← - choose I32 true (I32.ofInt 0 (by intlit)) (I32.ofInt 0 (by intlit)) - let z0 ← z + (I32.ofInt 1 (by intlit)) - if not (z0 = (I32.ofInt 1 (by intlit))) + let z ← choose I32 true (I32.ofInt 0) (I32.ofInt 0) + let z0 ← z + (I32.ofInt 1) + if not (z0 = (I32.ofInt 1)) then Result.fail Error.panic else do - let (x, y) ← - choose_back I32 true (I32.ofInt 0 (by intlit)) - (I32.ofInt 0 (by intlit)) z0 - if not (x = (I32.ofInt 1 (by intlit))) + let (x, y) ← choose_back I32 true (I32.ofInt 0) (I32.ofInt 0) z0 + if not (x = (I32.ofInt 1)) then Result.fail Error.panic else - if not (y = (I32.ofInt 0 (by intlit))) + if not (y = (I32.ofInt 0)) then Result.fail Error.panic else Result.ret () @@ -65,10 +62,10 @@ inductive List (T : Type) := divergent def list_nth_mut (T : Type) (l : List T) (i : U32) : Result T := match l with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret x else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) list_nth_mut T tl i0 | List.Nil => Result.fail Error.panic @@ -77,11 +74,11 @@ divergent def list_nth_mut_back (T : Type) (l : List T) (i : U32) (ret0 : T) : Result (List T) := match l with | List.Cons x tl => - if i = (U32.ofInt 0 (by intlit)) + if i = (U32.ofInt 0) then Result.ret (List.Cons ret0 tl) else do - let i0 ← i - (U32.ofInt 1 (by intlit)) + let i0 ← i - (U32.ofInt 1) let tl0 ← list_nth_mut_back T tl i0 ret0 Result.ret (List.Cons x tl0) | List.Nil => Result.fail Error.panic @@ -92,23 +89,20 @@ divergent def sum (l : List I32) : Result I32 := | List.Cons x tl => do let i ← sum tl x + i - | List.Nil => Result.ret (I32.ofInt 0 (by intlit)) + | List.Nil => Result.ret (I32.ofInt 0) /- [paper::test_nth]: forward function -/ def test_nth : Result Unit := do let l := List.Nil - let l0 := List.Cons (I32.ofInt 3 (by intlit)) l - let l1 := List.Cons (I32.ofInt 2 (by intlit)) l0 - let x ← - list_nth_mut I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) - (U32.ofInt 2 (by intlit)) - let x0 ← x + (I32.ofInt 1 (by intlit)) + let l0 := List.Cons (I32.ofInt 3) l + let l1 := List.Cons (I32.ofInt 2) l0 + let x ← list_nth_mut I32 (List.Cons (I32.ofInt 1) l1) (U32.ofInt 2) + let x0 ← x + (I32.ofInt 1) let l2 ← - list_nth_mut_back I32 (List.Cons (I32.ofInt 1 (by intlit)) l1) - (U32.ofInt 2 (by intlit)) x0 + list_nth_mut_back I32 (List.Cons (I32.ofInt 1) l1) (U32.ofInt 2) x0 let i ← sum l2 - if not (i = (I32.ofInt 7 (by intlit))) + if not (i = (I32.ofInt 7)) then Result.fail Error.panic else Result.ret () @@ -120,7 +114,7 @@ def call_choose (p : (U32 × U32)) : Result U32 := do let (px, py) := p let pz ← choose U32 true px py - let pz0 ← pz + (U32.ofInt 1 (by intlit)) + let pz0 ← pz + (U32.ofInt 1) let (px0, _) ← choose_back U32 true px py pz0 Result.ret px0 diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json index 75f7010a..8bbfb7cd 100644 --- a/tests/lean/lake-manifest.json +++ b/tests/lean/lake-manifest.json @@ -8,10 +8,16 @@ "name": "proofwidgets", "inputRev?": "v0.0.11"}}, {"path": {"name": "Base", "dir": "./../../backends/lean"}}, + {"git": + {"url": "https://github.com/mhuisi/lean4-cli.git", + "subDir?": null, + "rev": "5a858c32963b6b19be0d477a30a1f4b6c120be7e", + "name": "Cli", + "inputRev?": "nightly"}}, {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "bb4fb766e41dd3a64197263ec132c7f9c4b50065", + "rev": "82fe7e902b01fe686b91c19550f1e228ad2dec1c", "name": "mathlib", "inputRev?": null}}, {"git": -- cgit v1.2.3 From eb97bdb6761437e492bcf1a95b4fa43d2b69601b Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 12 Jul 2023 18:04:19 +0200 Subject: Improve progress to use assumptions and start working on a nice syntax --- backends/lean/Base/Arith/Arith.lean | 42 +----------- backends/lean/Base/Diverge/Base.lean | 22 ------ backends/lean/Base/Progress/Base.lean | 2 +- backends/lean/Base/Progress/Progress.lean | 107 +++++++++++++++++++++--------- backends/lean/Base/Utils.lean | 62 +++++++++++++++++ 5 files changed, 140 insertions(+), 95 deletions(-) diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index 20420f36..ab4fd182 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -11,49 +11,9 @@ import Base.Primitives import Base.Utils import Base.Arith.Base -/- -Mathlib tactics: -- rcases: https://leanprover-community.github.io/mathlib_docs/tactics.html#rcases -- split_ifs: https://leanprover-community.github.io/mathlib_docs/tactics.html#split_ifs -- norm_num: https://leanprover-community.github.io/mathlib_docs/tactics.html#norm_num -- should we use linarith or omega? -- hint: https://leanprover-community.github.io/mathlib_docs/tactics.html#hint -- classical: https://leanprover-community.github.io/mathlib_docs/tactics.html#classical --/ - -namespace List - - -- TODO: I could not find this function?? - @[simp] def flatten {a : Type u} : List (List a) → List a - | [] => [] - | x :: ls => x ++ flatten ls - -end List - -namespace Lean - -namespace LocalContext - - open Lean Lean.Elab Command Term Lean.Meta - - -- Small utility: return the list of declarations in the context, from - -- the last to the first. - def getAllDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := - lctx.foldrM (fun d ls => do let d ← instantiateLocalDeclMVars d; pure (d :: ls)) [] - - -- Return the list of declarations in the context, but filter the - -- declarations which are considered as implementation details - def getDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := do - let ls ← lctx.getAllDecls - pure (ls.filter (fun d => not d.isImplementationDetail)) - -end LocalContext - -end Lean - namespace Arith -open Primitives +open Primitives Utils -- TODO: move? theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index d2c91ff8..0a9ea4c4 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -6,28 +6,6 @@ import Mathlib.Tactic.Linarith import Base.Primitives -/- -TODO: -- we want an easier to use cases: - - keeps in the goal an equation of the shape: `t = case` - - if called on Prop terms, uses Classical.em - Actually, the cases from mathlib seems already quite powerful - (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) - For instance: cases h : e - Also: **casesm** -- better split tactic -- we need conversions to operate on the head of applications. - Actually, something like this works: - ``` - conv at Hl => - apply congr_fun - simp [fix_fuel_P] - ``` - Maybe we need a rpt ... ; focus? -- simplifier/rewriter have a strange behavior sometimes --/ - - /- TODO: this is very useful, but is there more? -/ set_option profiler true set_option profiler.threshold 100 diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 613f38f8..a288d889 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -60,7 +60,7 @@ section Methods trace[Progress] "Theorem: {th}" -- Dive into the quantified variables and the assumptions forallTelescope th fun fvars th => do - trace[Progress] "All argumens: {fvars}" + trace[Progress] "All arguments: {fvars}" /- -- Filter the argumens which are not propositions let rec getFirstPropIdx (i : Nat) : MetaM Nat := do if i ≥ fargs.size then pure i diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index a4df5c96..b0db465d 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -21,24 +21,11 @@ namespace Test #eval pspecAttr.find? ``Primitives.Vec.index end Test -def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do - withMainContext do - -- Retrieve the goal - let mgoal ← Tactic.getMainGoal - let goalTy ← mgoal.getType - -- Dive into the goal to lookup the theorem - let (fName, fLevels, args) ← do - withPSpec goalTy fun desc => - -- TODO: check that no universally quantified variables in the arguments - pure (desc.fName, desc.fLevels, desc.args) - -- TODO: also try the assumptions - trace[Progress] "Function: {fName}" - -- TODO: use a list of theorems, and try them one by one? - let thName ← do - match ← pspecAttr.find? fName with - | none => throwError "Could not find a pspec theorem for {fName}" - | some thName => pure thName - trace[Progress] "Lookuped up: {thName}" +inductive TheoremOrLocal where +| Theorem (thName : Name) +| Local (asm : LocalDecl) + +def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do /- Apply the theorem We try to match the theorem with the goal In order to do so, we introduce meta-variables for all the parameters @@ -48,10 +35,14 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do quantified). We also make sure that all the meta variables which appear in the function arguments have been instantiated - -/ + -/ let env ← getEnv - let thDecl := env.constants.find! thName - let thTy := thDecl.type + let thTy ← do + match th with + | .Theorem thName => + let thDecl := env.constants.find! thName + pure thDecl.type + | .Local asmDecl => pure asmDecl.type -- TODO: the tactic fails if we uncomment withNewMCtxDepth -- withNewMCtxDepth do let (mvars, binders, thExBody) ← forallMetaTelescope thTy @@ -63,18 +54,19 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do -- There shouldn't be any existential variables in thBody pure thBody -- Match the body with the target - let target := mkAppN (.const fName fLevels) args - trace[Progress] "mvars:\n{mvars.map Expr.mvarId!}" - trace[Progress] "thBody: {thBody}" - trace[Progress] "target: {target}" - let ok ← isDefEq thBody target - if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {target}" + trace[Progress] "Maching `{thBody}` with `{fnExpr}`" + let ok ← isDefEq thBody fnExpr + if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {fnExpr}" + let mgoal ← Tactic.getMainGoal postprocessAppMVars `progress mgoal mvars binders true true Term.synthesizeSyntheticMVarsNoPostponing let thBody ← instantiateMVars thBody trace[Progress] "thBody (after instantiation): {thBody}" -- Add the instantiated theorem to the assumptions (we apply it on the metavariables). - let th ← mkAppOptM thName (mvars.map some) + let th ← do + match th with + | .Theorem thName => mkAppOptM thName (mvars.map some) + | .Local decl => mkAppOptM' (mkFVar decl.fvarId) (mvars.map some) let asmName ← mkFreshUserName `h let thTy ← inferType th let thAsm ← Utils.addDeclTac asmName th thTy (asLet := false) @@ -112,18 +104,71 @@ def progressLookupTheorem (asmTac : TacticM Unit) : TacticM Unit := do -- pure () -elab "progress" : tactic => do - progressLookupTheorem (firstTac [assumptionTac, Arith.scalarTac]) +-- The array of ids are identifiers to use when introducing fresh variables +def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do + withMainContext do + -- Retrieve the goal + let mgoal ← Tactic.getMainGoal + let goalTy ← mgoal.getType + -- Dive into the goal to lookup the theorem + let (fName, fLevels, args) ← do + withPSpec goalTy fun desc => + -- TODO: check that no universally quantified variables in the arguments + pure (desc.fName, desc.fLevels, desc.args) + -- TODO: this should be in the pspec desc + let fnExpr := mkAppN (.const fName fLevels) args + trace[Progress] "Function: {fName}" + -- Try all the assumptions one by one and if it fails try to lookup a theorem + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getDecls + for decl in decls.reverse do + trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" + try + progressWith fnExpr (.Local decl) ids asmTac + return () + catch _ => continue + -- It failed: try to lookup a theorem + -- TODO: use a list of theorems, and try them one by one? + trace[Progress] "No assumption succeeded: trying to lookup a theorem" + let thName ← do + match ← pspecAttr.find? fName with + | none => throwError "Could not find a pspec theorem for {fName}" + | some thName => pure thName + trace[Progress] "Lookuped up: {thName}" + -- Apply the theorem + progressWith fnExpr (.Theorem thName) ids asmTac + +#check Syntax +syntax progressArgs := ("as" " ⟨ " (ident)+ " ⟩")? + +def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do + let args := args.raw + -- Process the arguments to retrieve the identifiers to use + trace[Progress] "Progressing arguments: {args}" + let args := args.getArgs + let ids := + if args.size > 0 then + let args := (args.get! 0).getArgs + let args := (args.get! 2).getArgs + args.map Syntax.getId + else #[] + trace[Progress] "Ids: {ids}" + --if args[0] ≠ some "as" then throwError "Invalid syntax: should be: `progress as ⟨ ... ⟩`" + progressAsmsOrLookupTheorem ids (firstTac [assumptionTac, Arith.scalarTac]) + +elab "progress" args:progressArgs : tactic => + evalProgress args namespace Test open Primitives set_option trace.Progress true + set_option pp.rawOnError true @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : ∃ (x: α), v.index α i = .ret x := by - progress + progress as ⟨ x y z ⟩ simp set_option trace.Progress false diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 14feb567..505412b9 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -2,6 +2,68 @@ import Lean import Mathlib.Tactic.Core import Mathlib.Tactic.LeftRight +/- +Mathlib tactics: +- rcases: https://leanprover-community.github.io/mathlib_docs/tactics.html#rcases +- split_ifs: https://leanprover-community.github.io/mathlib_docs/tactics.html#split_ifs +- norm_num: https://leanprover-community.github.io/mathlib_docs/tactics.html#norm_num +- should we use linarith or omega? +- hint: https://leanprover-community.github.io/mathlib_docs/tactics.html#hint +- classical: https://leanprover-community.github.io/mathlib_docs/tactics.html#classical +-/ + +/- +TODO: +- we want an easier to use cases: + - keeps in the goal an equation of the shape: `t = case` + - if called on Prop terms, uses Classical.em + Actually, the cases from mathlib seems already quite powerful + (https://leanprover-community.github.io/mathlib_docs/tactics.html#cases) + For instance: cases h : e + Also: **casesm** +- better split tactic +- we need conversions to operate on the head of applications. + Actually, something like this works: + ``` + conv at Hl => + apply congr_fun + simp [fix_fuel_P] + ``` + Maybe we need a rpt ... ; focus? +- simplifier/rewriter have a strange behavior sometimes +-/ + + +namespace List + + -- TODO: I could not find this function?? + @[simp] def flatten {a : Type u} : List (List a) → List a + | [] => [] + | x :: ls => x ++ flatten ls + +end List + +namespace Lean + +namespace LocalContext + + open Lean Lean.Elab Command Term Lean.Meta + + -- Small utility: return the list of declarations in the context, from + -- the last to the first. + def getAllDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := + lctx.foldrM (fun d ls => do let d ← instantiateLocalDeclMVars d; pure (d :: ls)) [] + + -- Return the list of declarations in the context, but filter the + -- declarations which are considered as implementation details + def getDecls (lctx : Lean.LocalContext) : MetaM (List Lean.LocalDecl) := do + let ls ← lctx.getAllDecls + pure (ls.filter (fun d => not d.isImplementationDetail)) + +end LocalContext + +end Lean + namespace Utils open Lean Elab Term Meta Tactic -- cgit v1.2.3 From 6cc0279045d40231f1cce83f0edb7aada1e59d92 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 13 Jul 2023 10:37:16 +0200 Subject: Finish implementing the syntax for `progress` --- backends/lean/Base/Progress/Progress.lean | 98 ++++++++++++++++++++++--------- backends/lean/Base/Utils.lean | 47 +++++++++++---- 2 files changed, 107 insertions(+), 38 deletions(-) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index b0db465d..835dc468 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -25,7 +25,17 @@ inductive TheoremOrLocal where | Theorem (thName : Name) | Local (asm : LocalDecl) -def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do +/- Type to propagate the errors of `progressWith`. + We need this because we use the exceptions to backtrack, when trying to + use the assumptions for instance. When there is actually an error we want + to propagate to the user, we return it. -/ +inductive ProgressError +| Ok +| Error (msg : MessageData) +deriving Inhabited + +def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) + (asmTac : TacticM Unit) : TacticM ProgressError := do /- Apply the theorem We try to match the theorem with the goal In order to do so, we introduce meta-variables for all the parameters @@ -77,32 +87,62 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) (asmTa -- The assumption should be of the shape: -- `∃ x1 ... xn, f args = ... ∧ ...` -- We introduce the existentially quantified variables and split the top-most - -- conjunction if there is one - splitAllExistsTac thAsm fun h => do - -- Split the conjunction - let splitConj (k : Expr → TacticM Unit) : TacticM Unit := do - if ← isConj (← inferType h) then - splitConjTac h (fun h _ => k h) - else k h - -- Simplify the target by using the equality and some monad simplifications - splitConj fun h => do + -- conjunction if there is one. We use the provided `ids` list to name the + -- introduced variables. + let res ← splitAllExistsTac thAsm ids.toList fun h ids => do + -- Split the conjunctions. + -- For the conjunctions, we split according once to separate the equality `f ... = .ret ...` + -- from the postcondition, if there is, then continue to split the postcondition if there + -- are remaining ids. + let splitEqAndPost (k : Expr → Option Expr → List Name → TacticM ProgressError) : TacticM ProgressError := do + if ← isConj (← inferType h) then do + let hName := (← h.fvarId!.getDecl).userName + let (optId, ids) := listTryPopHead ids + let optIds := match optId with | none => none | some id => some (hName, id) + splitConjTac h optIds (fun hEq hPost => k hEq (some hPost) ids) + else k h none ids + -- Simplify the target by using the equality and some monad simplifications, + -- then continue splitting the post-condition + splitEqAndPost fun hEq hPost ids => do + trace[Progress] "eq and post:\n{hEq} : {← inferType hEq}\n{hPost}" simpAt [] [``Primitives.bind_tc_ret, ``Primitives.bind_tc_fail, ``Primitives.bind_tc_div] - [h.fvarId!] (.targets #[] true) + [hEq.fvarId!] (.targets #[] true) -- Clear the equality let mgoal ← getMainGoal - let mgoal ← mgoal.tryClearMany #[h.fvarId!] + let mgoal ← mgoal.tryClearMany #[hEq.fvarId!] setGoals (mgoal :: (← getUnsolvedGoals)) - -- Update the set of goals - let curGoals ← getUnsolvedGoals - let newGoals := mvars.map Expr.mvarId! - let newGoals ← newGoals.filterM fun mvar => not <$> mvar.isAssigned - trace[Progress] "new goals: {newGoals}" - setGoals newGoals.toList - allGoals asmTac - let newGoals ← getUnsolvedGoals - setGoals (newGoals ++ curGoals) - -- - pure () + trace[Progress] "Goal after splitting eq and post and simplifying the target: {mgoal}" + -- Continue splitting following the ids provided by the user + if ¬ ids.isEmpty then + let hPost ← + match hPost with + | none => do return (.Error m!"Too many ids provided ({ids}): there is no postcondition to split") + | some hPost => pure hPost + let curPostId := (← hPost.fvarId!.getDecl).userName + let rec splitPost (hPost : Expr) (ids : List Name) : TacticM ProgressError := do + match ids with + | [] => pure .Ok -- Stop + | nid :: ids => do + -- Split + if ← isConj hPost then + splitConjTac hPost (some (nid, curPostId)) (λ _ nhPost => splitPost nhPost ids) + else return (.Error m!"Too many ids provided ({nid :: ids}) not enough conjuncts to split in the postcondition") + splitPost hPost ids + else return .Ok + match res with + | .Error _ => return res -- Can we get there? We're using "return" + | .Ok => + -- Update the set of goals + let curGoals ← getUnsolvedGoals + let newGoals := mvars.map Expr.mvarId! + let newGoals ← newGoals.filterM fun mvar => not <$> mvar.isAssigned + trace[Progress] "new goals: {newGoals}" + setGoals newGoals.toList + allGoals asmTac + let newGoals ← getUnsolvedGoals + setGoals (newGoals ++ curGoals) + -- + pure .Ok -- The array of ids are identifiers to use when introducing fresh variables def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do @@ -124,8 +164,9 @@ def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : Tac for decl in decls.reverse do trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" try - progressWith fnExpr (.Local decl) ids asmTac - return () + match ← progressWith fnExpr (.Local decl) ids asmTac with + | .Ok => return () + | .Error msg => throwError msg catch _ => continue -- It failed: try to lookup a theorem -- TODO: use a list of theorems, and try them one by one? @@ -136,9 +177,10 @@ def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : Tac | some thName => pure thName trace[Progress] "Lookuped up: {thName}" -- Apply the theorem - progressWith fnExpr (.Theorem thName) ids asmTac + match ← progressWith fnExpr (.Theorem thName) ids asmTac with + | .Ok => return () + | .Error msg => throwError msg -#check Syntax syntax progressArgs := ("as" " ⟨ " (ident)+ " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do @@ -168,7 +210,7 @@ namespace Test @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : ∃ (x: α), v.index α i = .ret x := by - progress as ⟨ x y z ⟩ + progress as ⟨ x ⟩ simp set_option trace.Progress false diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 505412b9..599c3a9f 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -396,13 +396,21 @@ example (x y : Int) (h0 : x ≤ y ∨ x ≥ y) : x ≤ y ∨ x ≥ y := by . right; assumption --- Tactic to split on an exists -def splitExistsTac (h : Expr) (k : Expr → Expr → TacticM α) : TacticM α := do +-- Tactic to split on an exists. +-- `h` must be an FVar +def splitExistsTac (h : Expr) (optId : Option Name) (k : Expr → Expr → TacticM α) : TacticM α := do withMainContext do let goal ← getMainGoal let hTy ← inferType h if isExists hTy then do - let newGoals ← goal.cases h.fvarId! #[] + -- Try to use the user-provided names + let altVarNames ← + match optId with + | none => pure #[] + | some id => do + let hDecl ← h.fvarId!.getDecl + pure #[{ varNames := [id, hDecl.userName] }] + let newGoals ← goal.cases h.fvarId! altVarNames -- There should be exactly one goal match newGoals.toList with | [ newGoal ] => @@ -418,18 +426,37 @@ def splitExistsTac (h : Expr) (k : Expr → Expr → TacticM α) : TacticM α := else throwError "Not a conjunction" -partial def splitAllExistsTac [Inhabited α] (h : Expr) (k : Expr → TacticM α) : TacticM α := do +-- TODO: move +def listTryPopHead (ls : List α) : Option α × List α := + match ls with + | [] => (none, ls) + | hd :: tl => (some hd, tl) + +/- Destruct all the existentials appearing in `h`, and introduce them as variables + in the context. + + If `ids` is not empty, we use it to name the introduced variables. We + transmit the stripped expression and the remaining ids to the continuation. + -/ +partial def splitAllExistsTac [Inhabited α] (h : Expr) (ids : List Name) (k : Expr → List Name → TacticM α) : TacticM α := do try - splitExistsTac h (fun _ body => splitAllExistsTac body k) - catch _ => k h + let (optId, ids) := listTryPopHead ids + splitExistsTac h optId (fun _ body => splitAllExistsTac body ids k) + catch _ => k h ids -- Tactic to split on a conjunction. -def splitConjTac (h : Expr) (k : Expr → Expr → TacticM α) : TacticM α := do +def splitConjTac (h : Expr) (optIds : Option (Name × Name)) (k : Expr → Expr → TacticM α) : TacticM α := do withMainContext do let goal ← getMainGoal let hTy ← inferType h if ← isConj hTy then do - let newGoals ← goal.cases h.fvarId! #[] + -- Try to use the user-provided names + let altVarNames ← + match optIds with + | none => pure #[] + | some (id0, id1) => do + pure #[{ varNames := [id0, id1] }] + let newGoals ← goal.cases h.fvarId! altVarNames -- There should be exactly one goal match newGoals.toList with | [ newGoal ] => @@ -449,13 +476,13 @@ elab "split_conj " n:ident : tactic => do withMainContext do let decl ← Lean.Meta.getLocalDeclFromUserName n.getId let fvar := mkFVar decl.fvarId - splitConjTac fvar (fun _ _ => pure ()) + splitConjTac fvar none (fun _ _ => pure ()) elab "split_all_exists " n:ident : tactic => do withMainContext do let decl ← Lean.Meta.getLocalDeclFromUserName n.getId let fvar := mkFVar decl.fvarId - splitAllExistsTac fvar (fun _ => pure ()) + splitAllExistsTac fvar [] (fun _ _ => pure ()) example (h : a ∧ b) : a := by split_all_exists h -- cgit v1.2.3 From 2dbd529b499c2bb9dae754df0e449cad577ac7a0 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 13 Jul 2023 14:00:11 +0200 Subject: Add IList.lean --- backends/hol4/ilistScript.sml | 3 + backends/lean/Base/Arith/Arith.lean | 136 +++++++++++++++++++----------------- backends/lean/Base/Arith/Base.lean | 40 +++++++++++ backends/lean/Base/IList.lean | 127 +++++++++++++++++++++++++++++++++ 4 files changed, 242 insertions(+), 64 deletions(-) create mode 100644 backends/lean/Base/IList.lean diff --git a/backends/hol4/ilistScript.sml b/backends/hol4/ilistScript.sml index fb0c7688..2b465af3 100644 --- a/backends/hol4/ilistScript.sml +++ b/backends/hol4/ilistScript.sml @@ -23,6 +23,8 @@ val _ = BasicProvers.export_rewrites ["len_def"] Remark: we initially added the following case, so that we wouldn't need the premise [i < len ls] is [index_eq_EL]: “index (i : int) [] = EL (Num i) []” + + TODO: this can be simplified. See the Lean backend. *) val index_def = Define ‘ index (i : int) (x :: ls) = if i = 0 then x else (if 0 < i then index (i - 1) ls else ARB) @@ -44,6 +46,7 @@ Proof exfalso >> cooper_tac QED +(* TODO: this can be simplified. See the Lean backend. *) val update_def = Define ‘ update ([] : 'a list) (i : int) (y : 'a) : 'a list = [] ∧ diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index ab4fd182..2ff030fe 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -15,25 +15,6 @@ namespace Arith open Primitives Utils --- TODO: move? -theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by - cases h: x <;> simp_all - . rename_i n; - cases n <;> simp_all - . apply Int.negSucc_lt_zero - --- TODO: move? -theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by - have hne : x - y ≠ 0 := by - simp - intro h - have: x = y := by linarith - simp_all - have h := ne_zero_is_lt_or_gt hne - match h with - | .inl _ => left; linarith - | .inr _ => right; linarith - -- TODO: move instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val @@ -48,17 +29,21 @@ instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val -/ def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val --- Remark: I tried a version of the shape `HasProp {a : Type} (x : a)` +-- Remark: I tried a version of the shape `HasScalarProp {a : Type} (x : a)` -- but the lookup didn't work -class HasProp (a : Sort u) where +class HasScalarProp (a : Sort u) where + prop_ty : a → Prop + prop : ∀ x:a, prop_ty x + +class HasIntProp (a : Sort u) where prop_ty : a → Prop prop : ∀ x:a, prop_ty x -instance (ty : ScalarTy) : HasProp (Scalar ty) where +instance (ty : ScalarTy) : HasScalarProp (Scalar ty) where -- prop_ty is inferred prop := λ x => And.intro x.hmin x.hmax -instance (a : Type) : HasProp (Vec a) where +instance (a : Type) : HasScalarProp (Vec a) where prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize prop := λ ⟨ _, l ⟩ => l @@ -117,37 +102,49 @@ def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.Tact let decls ← ctx.getDecls decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs --- Return an instance of `HasProp` for `e` if it has some -def lookupHasProp (e : Expr) : MetaM (Option Expr) := do - trace[Arith] "lookupHasProp" +-- Helper +def lookupProp (fName : String) (className : Name) (e : Expr) : MetaM (Option Expr) := do + trace[Arith] fName -- TODO: do we need Lean.observing? -- This actually eliminates the error messages Lean.observing? do - trace[Arith] "lookupHasProp: observing" + trace[Arith] m!"{fName}: observing" let ty ← Lean.Meta.inferType e - let hasProp ← mkAppM ``HasProp #[ty] + let hasProp ← mkAppM className #[ty] let hasPropInst ← trySynthInstance hasProp match hasPropInst with | LOption.some i => - trace[Arith] "Found HasProp instance" + trace[Arith] "Found HasScalarProp instance" let i_prop ← mkProjection i (Name.mkSimple "prop") some (← mkAppM' i_prop #[e]) | _ => none --- Collect the instances of `HasProp` for the subexpressions in the context -def collectHasPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupHasProp +-- Return an instance of `HasIntProp` for `e` if it has some +def lookupHasIntProp (e : Expr) : MetaM (Option Expr) := + lookupProp "lookupHasScalarProp" ``HasIntProp e + +-- Return an instance of `HasScalarProp` for `e` if it has some +def lookupHasScalarProp (e : Expr) : MetaM (Option Expr) := + lookupProp "lookupHasScalarProp" ``HasScalarProp e + +-- Collect the instances of `HasIntProp` for the subexpressions in the context +def collectHasIntPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupHasIntProp + +-- Collect the instances of `HasScalarProp` for the subexpressions in the context +def collectHasScalarPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupHasScalarProp elab "display_has_prop_instances" : tactic => do - trace[Arith] "Displaying the HasProp instances" - let hs ← collectHasPropInstancesFromMainCtx + trace[Arith] "Displaying the HasScalarProp instances" + let hs ← collectHasScalarPropInstancesFromMainCtx hs.forM fun e => do - trace[Arith] "+ HasProp instance: {e}" + trace[Arith] "+ HasScalarProp instance: {e}" example (x : U32) : True := by - let i : HasProp U32 := inferInstance - have p := @HasProp.prop _ i x - simp only [HasProp.prop_ty] at p + let i : HasScalarProp U32 := inferInstance + have p := @HasScalarProp.prop _ i x + simp only [HasScalarProp.prop_ty] at p display_has_prop_instances simp @@ -196,14 +193,18 @@ def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) -- Return the new value pure nval -def introHasPropInstances : Tactic.TacticM (Array Expr) := do - trace[Arith] "Introducing the HasProp instances" - introInstances ``HasProp.prop_ty lookupHasProp +def introHasIntPropInstances : Tactic.TacticM (Array Expr) := do + trace[Arith] "Introducing the HasIntProp instances" + introInstances ``HasIntProp.prop_ty lookupHasIntProp + +def introHasScalarPropInstances : Tactic.TacticM (Array Expr) := do + trace[Arith] "Introducing the HasScalarProp instances" + introInstances ``HasScalarProp.prop_ty lookupHasScalarProp --- Lookup the instances of `HasProp for all the sub-expressions in the context, +-- Lookup the instances of `HasScalarProp for all the sub-expressions in the context, -- and introduce the corresponding assumptions elab "intro_has_prop_instances" : tactic => do - let _ ← introHasPropInstances + let _ ← introHasScalarPropInstances example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by intro_has_prop_instances @@ -246,6 +247,7 @@ def intTacPreprocess : Tactic.TacticM Unit := do let k := splitOnAsms asms Utils.splitDisjTac asm k k -- Introduce + let _ ← introHasIntPropInstances let asms ← introInstances ``PropHasImp.concl lookupPropHasImp -- Split splitOnAsms asms.toList @@ -289,29 +291,35 @@ example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y ∧ x + y ≥ 2 := by int_tac +def scalarTacPreprocess (tac : Tactic.TacticM Unit) : Tactic.TacticM Unit := do + Tactic.withMainContext do + -- Introduce the scalar bounds + let _ ← introHasScalarPropInstances + Tactic.allGoals do + -- Inroduce the bounds for the isize/usize types + let add (e : Expr) : Tactic.TacticM Unit := do + let ty ← inferType e + let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) + add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) + -- Reveal the concrete bounds - TODO: not too sure about that. + -- Maybe we should reveal the "concrete" bounds (after normalization) + Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, + ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, + ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, + ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, + ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max + ] [] [] .wildcard + -- Finish the proof + tac + +elab "scalar_tac_preprocess" : tactic => + scalarTacPreprocess intTacPreprocess + -- A tactic to solve linear arithmetic goals in the presence of scalars def scalarTac : Tactic.TacticM Unit := do - Tactic.withMainContext do - -- Introduce the scalar bounds - let _ ← introHasPropInstances - Tactic.allGoals do - -- Inroduce the bounds for the isize/usize types - let add (e : Expr) : Tactic.TacticM Unit := do - let ty ← inferType e - let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) - add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) - add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) - add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) - -- Reveal the concrete bounds - TODO: not too sure about that. - -- Maybe we should reveal the "concrete" bounds (after normalization) - Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, - ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, - ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, - ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, - ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max - ] [] [] .wildcard - -- Apply the integer tactic - intTac + scalarTacPreprocess intTac elab "scalar_tac" : tactic => scalarTac diff --git a/backends/lean/Base/Arith/Base.lean b/backends/lean/Base/Arith/Base.lean index ddd2dc24..a6e59b74 100644 --- a/backends/lean/Base/Arith/Base.lean +++ b/backends/lean/Base/Arith/Base.lean @@ -1,4 +1,6 @@ import Lean +import Std.Data.Int.Lemmas +import Mathlib.Tactic.Linarith namespace Arith @@ -7,4 +9,42 @@ open Lean Elab Term Meta -- We can't define and use trace classes in the same file initialize registerTraceClass `Arith +-- TODO: move? +theorem ne_zero_is_lt_or_gt {x : Int} (hne : x ≠ 0) : x < 0 ∨ x > 0 := by + cases h: x <;> simp_all + . rename_i n; + cases n <;> simp_all + . apply Int.negSucc_lt_zero + +-- TODO: move? +theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by + have hne : x - y ≠ 0 := by + simp + intro h + have: x = y := by linarith + simp_all + have h := ne_zero_is_lt_or_gt hne + match h with + | .inl _ => left; linarith + | .inr _ => right; linarith + + +/- Induction over positive integers -/ +-- TODO: move +theorem int_pos_ind (p : Int → Prop) : + (zero:p 0) → (pos:∀ i, 0 ≤ i → p i → p (i + 1)) → ∀ i, 0 ≤ i → p i := by + intro h0 hr i hpos +-- have heq : Int.toNat i = i := by +-- cases i <;> simp_all + have ⟨ n, heq ⟩ : {n:Nat // n = i } := ⟨ Int.toNat i, by cases i <;> simp_all ⟩ + revert i + induction n + . intro i hpos heq + cases i <;> simp_all + . rename_i n hi + intro i hpos heq + cases i <;> simp_all + rename_i m + cases m <;> simp_all + end Arith diff --git a/backends/lean/Base/IList.lean b/backends/lean/Base/IList.lean new file mode 100644 index 00000000..7e764d63 --- /dev/null +++ b/backends/lean/Base/IList.lean @@ -0,0 +1,127 @@ +/- Complementary list functions and lemmas which operate on integers rather + than natural numbers. -/ + +import Std.Data.Int.Lemmas +import Mathlib.Tactic.Linarith +import Base.Arith + +namespace List + +#check List.get +def len (ls : List α) : Int := + match ls with + | [] => 0 + | _ :: tl => 1 + len tl + +-- Remark: if i < 0, then the result is none +def optIndex (i : Int) (ls : List α) : Option α := + match ls with + | [] => none + | hd :: tl => if i = 0 then some hd else optIndex (i - 1) tl + +-- Remark: if i < 0, then the result is the defaul element +def index [Inhabited α] (i : Int) (ls : List α) : α := + match ls with + | [] => Inhabited.default + | x :: tl => + if i = 0 then x else index (i - 1) tl + +-- Remark: the list is unchanged if the index is not in bounds (in particular +-- if it is < 0) +def update (ls : List α) (i : Int) (y : α) : List α := + match ls with + | [] => [] + | x :: tl => if i = 0 then y :: tl else x :: update tl (i - 1) y + +-- Remark: the whole list is dropped if the index is not in bounds (in particular +-- if it is < 0) +def idrop (i : Int) (ls : List α) : List α := + match ls with + | [] => [] + | x :: tl => if i = 0 then x :: tl else idrop (i - 1) tl + +@[simp] theorem len_nil : len ([] : List α) = 0 := by simp [len] +@[simp] theorem len_cons : len ((x :: tl) : List α) = 1 + len tl := by simp [len] + +@[simp] theorem index_zero_cons [Inhabited α] : index 0 ((x :: tl) : List α) = x := by simp [index] +@[simp] theorem index_nzero_cons [Inhabited α] (hne : i ≠ 0) : index i ((x :: tl) : List α) = index (i - 1) tl := by simp [*, index] + +@[simp] theorem update_nil : update ([] : List α) i y = [] := by simp [update] +@[simp] theorem update_zero_cons : update ((x :: tl) : List α) 0 y = y :: tl := by simp [update] +@[simp] theorem update_nzero_cons (hne : i ≠ 0) : update ((x :: tl) : List α) i y = x :: update tl (i - 1) y := by simp [*, update] + +@[simp] theorem idrop_nil : idrop i ([] : List α) = [] := by simp [idrop] +@[simp] theorem idrop_zero : idrop 0 (ls : List α) = ls := by cases ls <;> simp [idrop] +@[simp] theorem idrop_nzero_cons (hne : i ≠ 0) : idrop i ((x :: tl) : List α) = idrop (i - 1) tl := by simp [*, idrop] + +theorem len_eq_length (ls : List α) : ls.len = ls.length := by + induction ls + . rfl + . simp [*, Int.ofNat_succ, Int.add_comm] + +theorem len_pos : 0 ≤ (ls : List α).len := by + induction ls <;> simp [*] + linarith + +instance (a : Type u) : Arith.HasIntProp (List a) where + prop_ty := λ ls => 0 ≤ ls.len + prop := λ ls => ls.len_pos + +@[simp] theorem len_append (l1 l2 : List α) : (l1 ++ l2).len = l1.len + l2.len := by + -- Remark: simp loops here because of the following rewritings: + -- @Nat.cast_add: ↑(List.length l1 + List.length l2) ==> ↑(List.length l1) + ↑(List.length l2) + -- Int.ofNat_add_ofNat: ↑(List.length l1) + ↑(List.length l2) ==> ↑(List.length l1 + List.length l2) + -- TODO: post an issue? + simp only [len_eq_length] + simp only [length_append] + simp only [Int.ofNat_add] + +theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + revert l1' + induction l1 + . intro l1'; cases l1' <;> simp [*] + . intro l1'; cases l1' <;> simp_all; tauto + +theorem right_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.length = l2'.length) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + have := left_length_eq_append_eq l1 l2 l1' l2' + constructor <;> intro heq2 <;> + have : l1.length + l2.length = l1'.length + l2'.length := by + have : (l1 ++ l2).length = (l1' ++ l2').length := by simp [*] + simp only [length_append] at this + apply this + . simp [heq] at this + tauto + . tauto + +theorem left_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.len = l1'.len) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + simp [len_eq_length] at heq + apply left_length_eq_append_eq + assumption + +theorem right_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.len = l2'.len) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + simp [len_eq_length] at heq + apply right_length_eq_append_eq + assumption + +open Arith in +theorem idrop_eq_nil_of_le (hineq : ls.len ≤ i) : idrop i ls = [] := by + revert i + induction ls <;> simp [*] + rename_i hd tl hi + intro i hineq + if heq: i = 0 then + simp [*] at * + have := tl.len_pos + linarith + else + simp at hineq + have : 0 < i := by int_tac + simp [*] + apply hi + linarith + +end List -- cgit v1.2.3 From a9a3376443e4c6d9a5257bdd310966a59aa9e716 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 13 Jul 2023 14:00:48 +0200 Subject: Update a comment --- backends/lean/Base/Arith/Arith.lean | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index 2ff030fe..8bfad6ae 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -303,8 +303,7 @@ def scalarTacPreprocess (tac : Tactic.TacticM Unit) : Tactic.TacticM Unit := do add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) - -- Reveal the concrete bounds - TODO: not too sure about that. - -- Maybe we should reveal the "concrete" bounds (after normalization) + -- Reveal the concrete bounds Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, -- cgit v1.2.3 From 4f7ebc2358d78d31d63a609a32e5a732b82d468e Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 17 Jul 2023 12:12:34 +0200 Subject: Update the lean dependencies and update IList --- backends/lean/Base.lean | 1 + backends/lean/Base/IList.lean | 1 - backends/lean/Base/Progress/Progress.lean | 3 --- backends/lean/lake-manifest.json | 14 ++++++++++---- backends/lean/lean-toolchain | 2 +- tests/lean/lake-manifest.json | 8 ++++---- tests/lean/lean-toolchain | 2 +- 7 files changed, 17 insertions(+), 14 deletions(-) diff --git a/backends/lean/Base.lean b/backends/lean/Base.lean index 51211704..2077d410 100644 --- a/backends/lean/Base.lean +++ b/backends/lean/Base.lean @@ -3,3 +3,4 @@ import Base.Primitives import Base.Diverge import Base.Arith import Base.Progress +import Base.IList diff --git a/backends/lean/Base/IList.lean b/backends/lean/Base/IList.lean index 7e764d63..3db00cbb 100644 --- a/backends/lean/Base/IList.lean +++ b/backends/lean/Base/IList.lean @@ -7,7 +7,6 @@ import Base.Arith namespace List -#check List.get def len (ls : List α) : Int := match ls with | [] => 0 diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 835dc468..35a3c25a 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -15,7 +15,6 @@ namespace Test @[pspec] theorem vec_index_test (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : ∃ x, v.index α i = .ret x := by - apply sorry #eval pspecAttr.find? ``Primitives.Vec.index @@ -195,7 +194,6 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do args.map Syntax.getId else #[] trace[Progress] "Ids: {ids}" - --if args[0] ≠ some "as" then throwError "Invalid syntax: should be: `progress as ⟨ ... ⟩`" progressAsmsOrLookupTheorem ids (firstTac [assumptionTac, Arith.scalarTac]) elab "progress" args:progressArgs : tactic => @@ -205,7 +203,6 @@ namespace Test open Primitives set_option trace.Progress true - set_option pp.rawOnError true @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : diff --git a/backends/lean/lake-manifest.json b/backends/lean/lake-manifest.json index f4759ad3..5a089838 100644 --- a/backends/lean/lake-manifest.json +++ b/backends/lean/lake-manifest.json @@ -7,27 +7,33 @@ "rev": "c43db94a8f495dad37829e9d7ad65483d68c86b8", "name": "proofwidgets", "inputRev?": "v0.0.11"}}, + {"git": + {"url": "https://github.com/mhuisi/lean4-cli.git", + "subDir?": null, + "rev": "5a858c32963b6b19be0d477a30a1f4b6c120be7e", + "name": "Cli", + "inputRev?": "nightly"}}, {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "cc5d11f24e1b92db65ec3389bb5142f4b2d7670e", + "rev": "fa05951a270fef2873666c46f138e90338cd48d6", "name": "mathlib", "inputRev?": null}}, {"git": {"url": "https://github.com/gebner/quote4", "subDir?": null, - "rev": "c71f94e34c1cda52eef5c93dc9da409ab2727420", + "rev": "c0d9516f44d07feee01c1103c8f2f7c24a822b55", "name": "Qq", "inputRev?": "master"}}, {"git": {"url": "https://github.com/JLimperg/aesop", "subDir?": null, - "rev": "ca73109cc40837bc61df8024c9016da4b4f99d4c", + "rev": "f04538ab6ad07642368cf11d2702acc0a9b4bcee", "name": "aesop", "inputRev?": "master"}}, {"git": {"url": "https://github.com/leanprover/std4", "subDir?": null, - "rev": "e68aa8f5fe47aad78987df45f99094afbcb5e936", + "rev": "dff883c55395438ae2a5c65ad5ddba084b600feb", "name": "std", "inputRev?": "main"}}]} diff --git a/backends/lean/lean-toolchain b/backends/lean/lean-toolchain index 42e7d786..334c5053 100644 --- a/backends/lean/lean-toolchain +++ b/backends/lean/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:nightly-2023-06-20 \ No newline at end of file +leanprover/lean4:nightly-2023-07-12 \ No newline at end of file diff --git a/tests/lean/lake-manifest.json b/tests/lean/lake-manifest.json index 8bbfb7cd..94030cb6 100644 --- a/tests/lean/lake-manifest.json +++ b/tests/lean/lake-manifest.json @@ -17,24 +17,24 @@ {"git": {"url": "https://github.com/leanprover-community/mathlib4.git", "subDir?": null, - "rev": "82fe7e902b01fe686b91c19550f1e228ad2dec1c", + "rev": "fa05951a270fef2873666c46f138e90338cd48d6", "name": "mathlib", "inputRev?": null}}, {"git": {"url": "https://github.com/gebner/quote4", "subDir?": null, - "rev": "c71f94e34c1cda52eef5c93dc9da409ab2727420", + "rev": "c0d9516f44d07feee01c1103c8f2f7c24a822b55", "name": "Qq", "inputRev?": "master"}}, {"git": {"url": "https://github.com/JLimperg/aesop", "subDir?": null, - "rev": "ca73109cc40837bc61df8024c9016da4b4f99d4c", + "rev": "f04538ab6ad07642368cf11d2702acc0a9b4bcee", "name": "aesop", "inputRev?": "master"}}, {"git": {"url": "https://github.com/leanprover/std4", "subDir?": null, - "rev": "e68aa8f5fe47aad78987df45f99094afbcb5e936", + "rev": "dff883c55395438ae2a5c65ad5ddba084b600feb", "name": "std", "inputRev?": "main"}}]} diff --git a/tests/lean/lean-toolchain b/tests/lean/lean-toolchain index 42e7d786..334c5053 100644 --- a/tests/lean/lean-toolchain +++ b/tests/lean/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:nightly-2023-06-20 \ No newline at end of file +leanprover/lean4:nightly-2023-07-12 \ No newline at end of file -- cgit v1.2.3 From d45c6ed9e8049b81170c3e6950043d08006ba9f2 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 17 Jul 2023 12:14:03 +0200 Subject: Move a definition --- backends/lean/Base/Arith/Arith.lean | 3 --- backends/lean/Base/Primitives.lean | 3 +++ 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index 8bfad6ae..da263e86 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -15,9 +15,6 @@ namespace Arith open Primitives Utils --- TODO: move -instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val - -- TODO: move /- Remark: we can't write the following instance because of restrictions about the type class parameters (`ty` doesn't appear in the return type, which is diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 0506f4c0..1a0c665d 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -616,6 +616,9 @@ def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } +-- TODO: do we really need it? It should be with Subtype by default +instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val + def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ def Vec.len (α : Type u) (v : Vec α) : Usize := -- cgit v1.2.3 From 510e409b551f876a28f93f869e108f3f9e761212 Mon Sep 17 00:00:00 2001 From: Aymeric Fromherz Date: Mon, 17 Jul 2023 16:09:33 +0200 Subject: With @sonmarcho, some Lean proofs for hashmaps + comments about possible improvements --- tests/lean/Hashmap.lean | 1 + tests/lean/Hashmap/Properties.lean | 195 +++++++++++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 tests/lean/Hashmap/Properties.lean diff --git a/tests/lean/Hashmap.lean b/tests/lean/Hashmap.lean index 41630205..35034754 100644 --- a/tests/lean/Hashmap.lean +++ b/tests/lean/Hashmap.lean @@ -1 +1,2 @@ import Hashmap.Funs +import Hashmap.Properties diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean new file mode 100644 index 00000000..ca1f29c4 --- /dev/null +++ b/tests/lean/Hashmap/Properties.lean @@ -0,0 +1,195 @@ +import Hashmap.Funs + +open Primitives +open Result + + +namespace List + +theorem index_ne + {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (j: ℤ) (x: α) : + 0 ≤ i → i < l.len → 0 ≤ j → j < l.len → j ≠ i → + (l.update i x).index j = l.index j + := + λ _ _ _ _ _ => match l with + | [] => by simp at * + | hd :: tl => + if h: i = 0 then + have : j ≠ 0 := by scalar_tac + by simp [*] + else if h : j = 0 then + have : i ≠ 0 := by scalar_tac + by simp [*] + else + by + simp [*] + simp at * + apply index_ne <;> scalar_tac + +theorem index_eq + {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (x: α) : + 0 ≤ i → i < l.len → + (l.update i x).index i = x + := + fun _ _ => match l with + | [] => by simp at *; exfalso; scalar_tac -- TODO: exfalso needed. Son FIXME + | hd :: tl => + if h: i = 0 then + by + simp [*] + else + by + simp [*] + simp at * + apply index_eq <;> scalar_tac + +end List + + +namespace Primitives + +@[pspec] +theorem Vec.index_mut_spec + {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) (h: i.val < v.val.len) : + ∃ x, + v.index_mut α i = ret x ∧ x = v.val.index i.val + := by sorry + +@[pspec] +theorem Vec.index_mut_back_spec + {α : Type u} (v: Vec α) (i: Usize) (x:α) : + i.val < v.val.len → ∃ nv, + v.index_mut_back α i x = ret nv ∧ nv.val = v.val.update i.val x + := by sorry + +end Primitives + +namespace List + +def allP {α : Type u} (l : List α) (p: α → Prop) : Prop := + foldr (fun a r => p a ∧ r) True l + +@[simp] +theorem allP_nil {α : Type u} (p: α → Prop) : allP [] p := + by simp [allP, foldr] + +@[simp] +theorem allP_cons {α : Type u} (hd: α) (tl : List α) (p: α → Prop) : + allP (hd :: tl) p ↔ p hd ∧ allP tl p + := by simp [allP, foldr] + + +def pairwise_rel + {α : Type u} (rel : α → α → Prop) (l: List α) : Prop + := match l with + | [] => True + | hd :: tl => allP tl (rel hd) ∧ pairwise_rel rel tl + +@[simp] +theorem pairwise_rel_nil {α : Type u} (rel : α → α → Prop) : + pairwise_rel rel [] + := by simp [pairwise_rel] + +@[simp] +theorem pairwise_rel_cons {α : Type u} (rel : α → α → Prop) (hd: α) (tl: List α) : + pairwise_rel rel (hd :: tl) ↔ allP tl (rel hd) ∧ pairwise_rel rel tl + := by simp [pairwise_rel] + +end List + +namespace hashmap + +namespace List + +def v {α : Type} (ls: List α) : _root_.List (Usize × α) := + match ls with + | Nil => [] + | Cons k x tl => (k, x) :: v tl + +def lookup {α : Type} (ls: _root_.List (Usize × α)) (key: Usize) : Option α := + match ls with + | [] => none + | (k, x) :: tl => if k = key then some x else lookup tl key + +end List + +namespace HashMap + +@[pspec] +theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : + ∃ b, + insert_in_list α key value ls = ret b ∧ + (b ↔ List.lookup ls.v key = none) + := match ls with + | .Nil => by simp [insert_in_list, insert_in_list_loop, List.lookup] + | .Cons k v tl => + if h: k = key then -- TODO: The order of k/key matters + by + simp [insert_in_list, List.lookup] + rw [insert_in_list_loop] + simp [h] + else + by + have ⟨ b, hi ⟩ := insert_in_list_spec key value tl + exists b + simp [insert_in_list, List.lookup] + rw [insert_in_list_loop] -- TODO: Using it in simp leads to infinite recursion + simp [h] + simp [insert_in_list] at hi + exact hi + +/-- +@[pspec] +theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : + ∃ b, + insert_in_list α key value ls = ret b ∧ + (b = (List.lookup ls.v key = none)) + := by + induction ls + case Nil => simp [insert_in_list, insert_in_list_loop, List.lookup] + case Cons k v tl ih => + simp only [insert_in_list, List.lookup] + rw [insert_in_list_loop] + simp only + if h: k = key then + simp [h] + else + conv => + rhs; ext; arg 1; simp [h] -- TODO: Simplify + simp [insert_in_list] at ih; + progress -- TODO: Does not work +--/ + +@[pspec] +theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List α) : + ∃ l1, + insert_in_list_back α key value l0 = ret l1 ∧ + List.lookup l1.v key = value ∧ + (∀ k, k ≠ key → List.lookup l1.v k = List.lookup l0.v k) + := match l0 with + | .Nil => by simp [insert_in_list_back, insert_in_list_loop_back, List.lookup]; tauto + | .Cons k v tl => + if h: k = key then + by + simp [insert_in_list_back, List.lookup] + rw [insert_in_list_loop_back] + simp [h, List.lookup] + intro k1 h1 + have h2 : ¬(key = k1) := by tauto -- TODO: Why is the order of args in eq swapped + simp [h2] + else + by + simp [insert_in_list_back, List.lookup] + rw [insert_in_list_loop_back] + simp [h, List.lookup] + have ⟨tl0 , _, _ ⟩ := insert_in_list_back_spec key value tl -- TODO: Use progress + simp [insert_in_list_back] at * + simp [*] + have : ¬ (key = k) := by tauto + simp [List.lookup, *] + simp (config := {contextual := true}) [*] + +end HashMap +-- def distinct_keys {α : Type u} + +end hashmap -- cgit v1.2.3 From 3e8060b5501ec83940a4309389a68898df26ebd0 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 17 Jul 2023 23:37:31 +0200 Subject: Reorganize the Lean backend --- backends/lean/Base/Arith.lean | 3 +- backends/lean/Base/Arith/Arith.lean | 329 -------------- backends/lean/Base/Arith/Int.lean | 236 ++++++++++ backends/lean/Base/Arith/Scalar.lean | 48 ++ backends/lean/Base/IList.lean | 127 +----- backends/lean/Base/IList/IList.lean | 142 ++++++ backends/lean/Base/Primitives.lean | 718 +----------------------------- backends/lean/Base/Primitives/Base.lean | 130 ++++++ backends/lean/Base/Primitives/Scalar.lean | 507 +++++++++++++++++++++ backends/lean/Base/Primitives/Vec.lean | 113 +++++ backends/lean/Base/Progress/Progress.lean | 2 + 11 files changed, 1184 insertions(+), 1171 deletions(-) create mode 100644 backends/lean/Base/Arith/Int.lean create mode 100644 backends/lean/Base/Arith/Scalar.lean create mode 100644 backends/lean/Base/IList/IList.lean create mode 100644 backends/lean/Base/Primitives/Base.lean create mode 100644 backends/lean/Base/Primitives/Scalar.lean create mode 100644 backends/lean/Base/Primitives/Vec.lean diff --git a/backends/lean/Base/Arith.lean b/backends/lean/Base/Arith.lean index fd5698c5..c0d09fd2 100644 --- a/backends/lean/Base/Arith.lean +++ b/backends/lean/Base/Arith.lean @@ -1 +1,2 @@ -import Base.Arith.Arith +import Base.Arith.Int +import Base.Arith.Scalar diff --git a/backends/lean/Base/Arith/Arith.lean b/backends/lean/Base/Arith/Arith.lean index da263e86..e69de29b 100644 --- a/backends/lean/Base/Arith/Arith.lean +++ b/backends/lean/Base/Arith/Arith.lean @@ -1,329 +0,0 @@ -/- This file contains tactics to solve arithmetic goals -/ - -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd -import Mathlib.Tactic.Linarith --- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet ---import Mathlib.Tactic.Omega -import Base.Primitives -import Base.Utils -import Base.Arith.Base - -namespace Arith - -open Primitives Utils - --- TODO: move -/- Remark: we can't write the following instance because of restrictions about - the type class parameters (`ty` doesn't appear in the return type, which is - forbidden): - - ``` - instance Scalar.cast (ty : ScalarTy) : Coe (Scalar ty) Int where coe := λ v => v.val - ``` - -/ -def Scalar.toInt {ty : ScalarTy} (x : Scalar ty) : Int := x.val - --- Remark: I tried a version of the shape `HasScalarProp {a : Type} (x : a)` --- but the lookup didn't work -class HasScalarProp (a : Sort u) where - prop_ty : a → Prop - prop : ∀ x:a, prop_ty x - -class HasIntProp (a : Sort u) where - prop_ty : a → Prop - prop : ∀ x:a, prop_ty x - -instance (ty : ScalarTy) : HasScalarProp (Scalar ty) where - -- prop_ty is inferred - prop := λ x => And.intro x.hmin x.hmax - -instance (a : Type) : HasScalarProp (Vec a) where - prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize - prop := λ ⟨ _, l ⟩ => l - -class PropHasImp (x : Prop) where - concl : Prop - prop : x → concl - --- This also works for `x ≠ y` because this expression reduces to `¬ x = y` --- and `Ne` is marked as `reducible` -instance (x y : Int) : PropHasImp (¬ x = y) where - concl := x < y ∨ x > y - prop := λ (h:x ≠ y) => ne_is_lt_or_gt h - -open Lean Lean.Elab Command Term Lean.Meta - --- Small utility: print all the declarations in the context -elab "print_all_decls" : tactic => do - let ctx ← Lean.MonadLCtx.getLCtx - for decl in ← ctx.getDecls do - let ty ← Lean.Meta.inferType decl.toExpr - logInfo m!"{decl.toExpr} : {ty}" - pure () - --- Explore a term by decomposing the applications (we explore the applied --- functions and their arguments, but ignore lambdas, forall, etc. - --- should we go inside?). -partial def foldTermApps (k : α → Expr → MetaM α) (s : α) (e : Expr) : MetaM α := do - -- We do it in a very simpler manner: we deconstruct applications, - -- and recursively explore the sub-expressions. Note that we do - -- not go inside foralls and abstractions (should we?). - e.withApp fun f args => do - let s ← k s f - args.foldlM (foldTermApps k) s - --- Provided a function `k` which lookups type class instances on an expression, --- collect all the instances lookuped by applying `k` on the sub-expressions of `e`. -def collectInstances - (k : Expr → MetaM (Option Expr)) (s : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do - let k s e := do - match ← k e with - | none => pure s - | some i => pure (s.insert i) - foldTermApps k s e - --- Similar to `collectInstances`, but explores all the local declarations in the --- main context. -def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do - Tactic.withMainContext do - -- Get the local context - let ctx ← Lean.MonadLCtx.getLCtx - -- Just a matter of precaution - let ctx ← instantiateLCtxMVars ctx - -- Initialize the hashset - let hs := HashSet.empty - -- Explore the declarations - let decls ← ctx.getDecls - decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs - --- Helper -def lookupProp (fName : String) (className : Name) (e : Expr) : MetaM (Option Expr) := do - trace[Arith] fName - -- TODO: do we need Lean.observing? - -- This actually eliminates the error messages - Lean.observing? do - trace[Arith] m!"{fName}: observing" - let ty ← Lean.Meta.inferType e - let hasProp ← mkAppM className #[ty] - let hasPropInst ← trySynthInstance hasProp - match hasPropInst with - | LOption.some i => - trace[Arith] "Found HasScalarProp instance" - let i_prop ← mkProjection i (Name.mkSimple "prop") - some (← mkAppM' i_prop #[e]) - | _ => none - --- Return an instance of `HasIntProp` for `e` if it has some -def lookupHasIntProp (e : Expr) : MetaM (Option Expr) := - lookupProp "lookupHasScalarProp" ``HasIntProp e - --- Return an instance of `HasScalarProp` for `e` if it has some -def lookupHasScalarProp (e : Expr) : MetaM (Option Expr) := - lookupProp "lookupHasScalarProp" ``HasScalarProp e - --- Collect the instances of `HasIntProp` for the subexpressions in the context -def collectHasIntPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupHasIntProp - --- Collect the instances of `HasScalarProp` for the subexpressions in the context -def collectHasScalarPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupHasScalarProp - -elab "display_has_prop_instances" : tactic => do - trace[Arith] "Displaying the HasScalarProp instances" - let hs ← collectHasScalarPropInstancesFromMainCtx - hs.forM fun e => do - trace[Arith] "+ HasScalarProp instance: {e}" - -example (x : U32) : True := by - let i : HasScalarProp U32 := inferInstance - have p := @HasScalarProp.prop _ i x - simp only [HasScalarProp.prop_ty] at p - display_has_prop_instances - simp - --- Return an instance of `PropHasImp` for `e` if it has some -def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do - trace[Arith] "lookupPropHasImp" - -- TODO: do we need Lean.observing? - -- This actually eliminates the error messages - Lean.observing? do - trace[Arith] "lookupPropHasImp: observing" - let ty ← Lean.Meta.inferType e - trace[Arith] "lookupPropHasImp: ty: {ty}" - let cl ← mkAppM ``PropHasImp #[ty] - let inst ← trySynthInstance cl - match inst with - | LOption.some i => - trace[Arith] "Found PropHasImp instance" - let i_prop ← mkProjection i (Name.mkSimple "prop") - some (← mkAppM' i_prop #[e]) - | _ => none - --- Collect the instances of `PropHasImp` for the subexpressions in the context -def collectPropHasImpInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do - collectInstancesFromMainCtx lookupPropHasImp - -elab "display_prop_has_imp_instances" : tactic => do - trace[Arith] "Displaying the PropHasImp instances" - let hs ← collectPropHasImpInstancesFromMainCtx - hs.forM fun e => do - trace[Arith] "+ PropHasImp instance: {e}" - -example (x y : Int) (_ : x ≠ y) (_ : ¬ x = y) : True := by - display_prop_has_imp_instances - simp - --- Lookup instances in a context and introduce them with additional declarations. -def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) : Tactic.TacticM (Array Expr) := do - let hs ← collectInstancesFromMainCtx lookup - hs.toArray.mapM fun e => do - let type ← inferType e - let name ← mkFreshUserName `h - -- Add a declaration - let nval ← Utils.addDeclTac name e type (asLet := false) - -- Simplify to unfold the declaration to unfold (i.e., the projector) - Utils.simpAt [declToUnfold] [] [] (Tactic.Location.targets #[mkIdent name] false) - -- Return the new value - pure nval - -def introHasIntPropInstances : Tactic.TacticM (Array Expr) := do - trace[Arith] "Introducing the HasIntProp instances" - introInstances ``HasIntProp.prop_ty lookupHasIntProp - -def introHasScalarPropInstances : Tactic.TacticM (Array Expr) := do - trace[Arith] "Introducing the HasScalarProp instances" - introInstances ``HasScalarProp.prop_ty lookupHasScalarProp - --- Lookup the instances of `HasScalarProp for all the sub-expressions in the context, --- and introduce the corresponding assumptions -elab "intro_has_prop_instances" : tactic => do - let _ ← introHasScalarPropInstances - -example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by - intro_has_prop_instances - simp [*] - -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - intro_has_prop_instances - simp_all [Scalar.max, Scalar.min] - --- Lookup the instances of `PropHasImp for all the sub-expressions in the context, --- and introduce the corresponding assumptions -elab "intro_prop_has_imp_instances" : tactic => do - trace[Arith] "Introducing the PropHasImp instances" - let _ ← introInstances ``PropHasImp.concl lookupPropHasImp - -example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by - intro_prop_has_imp_instances - rename_i h - split_disj h - . linarith - . linarith - -/- Boosting a bit the linarith tac. - - We do the following: - - for all the assumptions of the shape `(x : Int) ≠ y` or `¬ (x = y), we - introduce two goals with the assumptions `x < y` and `x > y` - TODO: we could create a PR for mathlib. - -/ -def intTacPreprocess : Tactic.TacticM Unit := do - Tactic.withMainContext do - -- Lookup the instances of PropHasImp (this is how we detect assumptions - -- of the proper shape), introduce assumptions in the context and split - -- on those - -- TODO: get rid of the assumptions that we split - let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := - match asms with - | [] => pure () - | asm :: asms => - let k := splitOnAsms asms - Utils.splitDisjTac asm k k - -- Introduce - let _ ← introHasIntPropInstances - let asms ← introInstances ``PropHasImp.concl lookupPropHasImp - -- Split - splitOnAsms asms.toList - -elab "int_tac_preprocess" : tactic => - intTacPreprocess - -def intTac : Tactic.TacticM Unit := do - Tactic.withMainContext do - Tactic.focus do - -- Preprocess - wondering if we should do this before or after splitting - -- the goal. I think before leads to a smaller proof term? - Tactic.allGoals intTacPreprocess - -- Split the conjunctions in the goal - Utils.repeatTac Utils.splitConjTarget - -- Call linarith - let linarith := - let cfg : Linarith.LinarithConfig := { - -- We do this with our custom preprocessing - splitNe := false - } - Tactic.liftMetaFinishingTactic <| Linarith.linarith false [] cfg - Tactic.allGoals linarith - -elab "int_tac" : tactic => - intTac - -example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by - int_tac_preprocess - linarith - linarith - -example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by - int_tac - --- Checking that things append correctly when there are several disjunctions -example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by - int_tac - --- Checking that things append correctly when there are several disjunctions -example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y ∧ x + y ≥ 2 := by - int_tac - -def scalarTacPreprocess (tac : Tactic.TacticM Unit) : Tactic.TacticM Unit := do - Tactic.withMainContext do - -- Introduce the scalar bounds - let _ ← introHasScalarPropInstances - Tactic.allGoals do - -- Inroduce the bounds for the isize/usize types - let add (e : Expr) : Tactic.TacticM Unit := do - let ty ← inferType e - let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) - add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) - add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) - add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) - -- Reveal the concrete bounds - Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, - ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, - ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, - ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, - ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max - ] [] [] .wildcard - -- Finish the proof - tac - -elab "scalar_tac_preprocess" : tactic => - scalarTacPreprocess intTacPreprocess - --- A tactic to solve linear arithmetic goals in the presence of scalars -def scalarTac : Tactic.TacticM Unit := do - scalarTacPreprocess intTac - -elab "scalar_tac" : tactic => - scalarTac - -example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by - scalar_tac - -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - scalar_tac - -end Arith diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean new file mode 100644 index 00000000..5f00ab52 --- /dev/null +++ b/backends/lean/Base/Arith/Int.lean @@ -0,0 +1,236 @@ +/- This file contains tactics to solve arithmetic goals -/ + +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith +-- TODO: there is no Omega tactic for now - it seems it hasn't been ported yet +--import Mathlib.Tactic.Omega +import Base.Utils +import Base.Arith.Base + +namespace Arith + +open Utils + +-- Remark: I tried a version of the shape `HasScalarProp {a : Type} (x : a)` +-- but the lookup didn't work +class HasIntProp (a : Sort u) where + prop_ty : a → Prop + prop : ∀ x:a, prop_ty x + +class PropHasImp (x : Prop) where + concl : Prop + prop : x → concl + +-- This also works for `x ≠ y` because this expression reduces to `¬ x = y` +-- and `Ne` is marked as `reducible` +instance (x y : Int) : PropHasImp (¬ x = y) where + concl := x < y ∨ x > y + prop := λ (h:x ≠ y) => ne_is_lt_or_gt h + +open Lean Lean.Elab Lean.Meta + +-- Small utility: print all the declarations in the context +elab "print_all_decls" : tactic => do + let ctx ← Lean.MonadLCtx.getLCtx + for decl in ← ctx.getDecls do + let ty ← Lean.Meta.inferType decl.toExpr + logInfo m!"{decl.toExpr} : {ty}" + pure () + +-- Explore a term by decomposing the applications (we explore the applied +-- functions and their arguments, but ignore lambdas, forall, etc. - +-- should we go inside?). +partial def foldTermApps (k : α → Expr → MetaM α) (s : α) (e : Expr) : MetaM α := do + -- We do it in a very simpler manner: we deconstruct applications, + -- and recursively explore the sub-expressions. Note that we do + -- not go inside foralls and abstractions (should we?). + e.withApp fun f args => do + let s ← k s f + args.foldlM (foldTermApps k) s + +-- Provided a function `k` which lookups type class instances on an expression, +-- collect all the instances lookuped by applying `k` on the sub-expressions of `e`. +def collectInstances + (k : Expr → MetaM (Option Expr)) (s : HashSet Expr) (e : Expr) : MetaM (HashSet Expr) := do + let k s e := do + match ← k e with + | none => pure s + | some i => pure (s.insert i) + foldTermApps k s e + +-- Similar to `collectInstances`, but explores all the local declarations in the +-- main context. +def collectInstancesFromMainCtx (k : Expr → MetaM (Option Expr)) : Tactic.TacticM (HashSet Expr) := do + Tactic.withMainContext do + -- Get the local context + let ctx ← Lean.MonadLCtx.getLCtx + -- Just a matter of precaution + let ctx ← instantiateLCtxMVars ctx + -- Initialize the hashset + let hs := HashSet.empty + -- Explore the declarations + let decls ← ctx.getDecls + decls.foldlM (fun hs d => collectInstances k hs d.toExpr) hs + +-- Helper +def lookupProp (fName : String) (className : Name) (e : Expr) : MetaM (Option Expr) := do + trace[Arith] fName + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] m!"{fName}: observing" + let ty ← Lean.Meta.inferType e + let hasProp ← mkAppM className #[ty] + let hasPropInst ← trySynthInstance hasProp + match hasPropInst with + | LOption.some i => + trace[Arith] "Found {fName} instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Return an instance of `HasIntProp` for `e` if it has some +def lookupHasIntProp (e : Expr) : MetaM (Option Expr) := + lookupProp "lookupHasIntProp" ``HasIntProp e + +-- Collect the instances of `HasIntProp` for the subexpressions in the context +def collectHasIntPropInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupHasIntProp + +-- Return an instance of `PropHasImp` for `e` if it has some +def lookupPropHasImp (e : Expr) : MetaM (Option Expr) := do + trace[Arith] "lookupPropHasImp" + -- TODO: do we need Lean.observing? + -- This actually eliminates the error messages + Lean.observing? do + trace[Arith] "lookupPropHasImp: observing" + let ty ← Lean.Meta.inferType e + trace[Arith] "lookupPropHasImp: ty: {ty}" + let cl ← mkAppM ``PropHasImp #[ty] + let inst ← trySynthInstance cl + match inst with + | LOption.some i => + trace[Arith] "Found PropHasImp instance" + let i_prop ← mkProjection i (Name.mkSimple "prop") + some (← mkAppM' i_prop #[e]) + | _ => none + +-- Collect the instances of `PropHasImp` for the subexpressions in the context +def collectPropHasImpInstancesFromMainCtx : Tactic.TacticM (HashSet Expr) := do + collectInstancesFromMainCtx lookupPropHasImp + +elab "display_prop_has_imp_instances" : tactic => do + trace[Arith] "Displaying the PropHasImp instances" + let hs ← collectPropHasImpInstancesFromMainCtx + hs.forM fun e => do + trace[Arith] "+ PropHasImp instance: {e}" + +example (x y : Int) (_ : x ≠ y) (_ : ¬ x = y) : True := by + display_prop_has_imp_instances + simp + +-- Lookup instances in a context and introduce them with additional declarations. +def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) : Tactic.TacticM (Array Expr) := do + let hs ← collectInstancesFromMainCtx lookup + hs.toArray.mapM fun e => do + let type ← inferType e + let name ← mkFreshUserName `h + -- Add a declaration + let nval ← Utils.addDeclTac name e type (asLet := false) + -- Simplify to unfold the declaration to unfold (i.e., the projector) + Utils.simpAt [declToUnfold] [] [] (Tactic.Location.targets #[mkIdent name] false) + -- Return the new value + pure nval + +def introHasIntPropInstances : Tactic.TacticM (Array Expr) := do + trace[Arith] "Introducing the HasIntProp instances" + introInstances ``HasIntProp.prop_ty lookupHasIntProp + +-- Lookup the instances of `HasIntProp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_has_int_prop_instances" : tactic => do + let _ ← introHasIntPropInstances + +-- Lookup the instances of `PropHasImp for all the sub-expressions in the context, +-- and introduce the corresponding assumptions +elab "intro_prop_has_imp_instances" : tactic => do + trace[Arith] "Introducing the PropHasImp instances" + let _ ← introInstances ``PropHasImp.concl lookupPropHasImp + +example (x y : Int) (h0 : x ≤ y) (h1 : x ≠ y) : x < y := by + intro_prop_has_imp_instances + rename_i h + split_disj h + . linarith + . linarith + +/- Boosting a bit the linarith tac. + + We do the following: + - for all the assumptions of the shape `(x : Int) ≠ y` or `¬ (x = y), we + introduce two goals with the assumptions `x < y` and `x > y` + TODO: we could create a PR for mathlib. + -/ +def intTacPreprocess (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do + Tactic.withMainContext do + -- Lookup the instances of PropHasImp (this is how we detect assumptions + -- of the proper shape), introduce assumptions in the context and split + -- on those + -- TODO: get rid of the assumptions that we split + let rec splitOnAsms (asms : List Expr) : Tactic.TacticM Unit := + match asms with + | [] => pure () + | asm :: asms => + let k := splitOnAsms asms + Utils.splitDisjTac asm k k + -- Introduce the scalar bounds + let _ ← introHasIntPropInstances + -- Extra preprocessing, before we split on the disjunctions + extraPreprocess + -- Split + let asms ← introInstances ``PropHasImp.concl lookupPropHasImp + splitOnAsms asms.toList + +elab "int_tac_preprocess" : tactic => + intTacPreprocess (do pure ()) + +def intTac (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do + Tactic.withMainContext do + Tactic.focus do + -- Preprocess - wondering if we should do this before or after splitting + -- the goal. I think before leads to a smaller proof term? + Tactic.allGoals (intTacPreprocess extraPreprocess) + -- Split the conjunctions in the goal + Tactic.allGoals (Utils.repeatTac Utils.splitConjTarget) + -- Call linarith + let linarith := + let cfg : Linarith.LinarithConfig := { + -- We do this with our custom preprocessing + splitNe := false + } + Tactic.liftMetaFinishingTactic <| Linarith.linarith false [] cfg + Tactic.allGoals linarith + +elab "int_tac" : tactic => + intTac (do pure ()) + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac_preprocess + linarith + linarith + +example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by + int_tac + +-- Checking that things append correctly when there are several disjunctions +example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by + int_tac + +-- Checking that things append correctly when there are several disjunctions +example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y ∧ x + y ≥ 2 := by + int_tac + +end Arith diff --git a/backends/lean/Base/Arith/Scalar.lean b/backends/lean/Base/Arith/Scalar.lean new file mode 100644 index 00000000..f8903ecf --- /dev/null +++ b/backends/lean/Base/Arith/Scalar.lean @@ -0,0 +1,48 @@ +import Base.Arith.Int +import Base.Primitives.Scalar + +/- Automation for scalars - TODO: not sure it is worth having two files (Int.lean and Scalar.lean) -/ +namespace Arith + +open Lean Lean.Elab Lean.Meta +open Primitives + +def scalarTacExtraPreprocess : Tactic.TacticM Unit := do + Tactic.withMainContext do + -- Inroduce the bounds for the isize/usize types + let add (e : Expr) : Tactic.TacticM Unit := do + let ty ← inferType e + let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) + add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) + add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) + -- Reveal the concrete bounds + Utils.simpAt [``Scalar.min, ``Scalar.max, ``Scalar.cMin, ``Scalar.cMax, + ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, + ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, + ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, + ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max + ] [] [] .wildcard + +elab "scalar_tac_preprocess" : tactic => + intTacPreprocess scalarTacExtraPreprocess + +-- A tactic to solve linear arithmetic goals in the presence of scalars +def scalarTac : Tactic.TacticM Unit := do + intTac scalarTacExtraPreprocess + +elab "scalar_tac" : tactic => + scalarTac + +instance (ty : ScalarTy) : HasIntProp (Scalar ty) where + -- prop_ty is inferred + prop := λ x => And.intro x.hmin x.hmax + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + intro_has_int_prop_instances + simp [*] + +example (x y : U32) : x.val ≤ Scalar.max ScalarTy.U32 := by + scalar_tac + +end Arith diff --git a/backends/lean/Base/IList.lean b/backends/lean/Base/IList.lean index 3db00cbb..31b66ffa 100644 --- a/backends/lean/Base/IList.lean +++ b/backends/lean/Base/IList.lean @@ -1,126 +1 @@ -/- Complementary list functions and lemmas which operate on integers rather - than natural numbers. -/ - -import Std.Data.Int.Lemmas -import Mathlib.Tactic.Linarith -import Base.Arith - -namespace List - -def len (ls : List α) : Int := - match ls with - | [] => 0 - | _ :: tl => 1 + len tl - --- Remark: if i < 0, then the result is none -def optIndex (i : Int) (ls : List α) : Option α := - match ls with - | [] => none - | hd :: tl => if i = 0 then some hd else optIndex (i - 1) tl - --- Remark: if i < 0, then the result is the defaul element -def index [Inhabited α] (i : Int) (ls : List α) : α := - match ls with - | [] => Inhabited.default - | x :: tl => - if i = 0 then x else index (i - 1) tl - --- Remark: the list is unchanged if the index is not in bounds (in particular --- if it is < 0) -def update (ls : List α) (i : Int) (y : α) : List α := - match ls with - | [] => [] - | x :: tl => if i = 0 then y :: tl else x :: update tl (i - 1) y - --- Remark: the whole list is dropped if the index is not in bounds (in particular --- if it is < 0) -def idrop (i : Int) (ls : List α) : List α := - match ls with - | [] => [] - | x :: tl => if i = 0 then x :: tl else idrop (i - 1) tl - -@[simp] theorem len_nil : len ([] : List α) = 0 := by simp [len] -@[simp] theorem len_cons : len ((x :: tl) : List α) = 1 + len tl := by simp [len] - -@[simp] theorem index_zero_cons [Inhabited α] : index 0 ((x :: tl) : List α) = x := by simp [index] -@[simp] theorem index_nzero_cons [Inhabited α] (hne : i ≠ 0) : index i ((x :: tl) : List α) = index (i - 1) tl := by simp [*, index] - -@[simp] theorem update_nil : update ([] : List α) i y = [] := by simp [update] -@[simp] theorem update_zero_cons : update ((x :: tl) : List α) 0 y = y :: tl := by simp [update] -@[simp] theorem update_nzero_cons (hne : i ≠ 0) : update ((x :: tl) : List α) i y = x :: update tl (i - 1) y := by simp [*, update] - -@[simp] theorem idrop_nil : idrop i ([] : List α) = [] := by simp [idrop] -@[simp] theorem idrop_zero : idrop 0 (ls : List α) = ls := by cases ls <;> simp [idrop] -@[simp] theorem idrop_nzero_cons (hne : i ≠ 0) : idrop i ((x :: tl) : List α) = idrop (i - 1) tl := by simp [*, idrop] - -theorem len_eq_length (ls : List α) : ls.len = ls.length := by - induction ls - . rfl - . simp [*, Int.ofNat_succ, Int.add_comm] - -theorem len_pos : 0 ≤ (ls : List α).len := by - induction ls <;> simp [*] - linarith - -instance (a : Type u) : Arith.HasIntProp (List a) where - prop_ty := λ ls => 0 ≤ ls.len - prop := λ ls => ls.len_pos - -@[simp] theorem len_append (l1 l2 : List α) : (l1 ++ l2).len = l1.len + l2.len := by - -- Remark: simp loops here because of the following rewritings: - -- @Nat.cast_add: ↑(List.length l1 + List.length l2) ==> ↑(List.length l1) + ↑(List.length l2) - -- Int.ofNat_add_ofNat: ↑(List.length l1) + ↑(List.length l2) ==> ↑(List.length l1 + List.length l2) - -- TODO: post an issue? - simp only [len_eq_length] - simp only [length_append] - simp only [Int.ofNat_add] - -theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : - l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by - revert l1' - induction l1 - . intro l1'; cases l1' <;> simp [*] - . intro l1'; cases l1' <;> simp_all; tauto - -theorem right_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.length = l2'.length) : - l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by - have := left_length_eq_append_eq l1 l2 l1' l2' - constructor <;> intro heq2 <;> - have : l1.length + l2.length = l1'.length + l2'.length := by - have : (l1 ++ l2).length = (l1' ++ l2').length := by simp [*] - simp only [length_append] at this - apply this - . simp [heq] at this - tauto - . tauto - -theorem left_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.len = l1'.len) : - l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by - simp [len_eq_length] at heq - apply left_length_eq_append_eq - assumption - -theorem right_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.len = l2'.len) : - l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by - simp [len_eq_length] at heq - apply right_length_eq_append_eq - assumption - -open Arith in -theorem idrop_eq_nil_of_le (hineq : ls.len ≤ i) : idrop i ls = [] := by - revert i - induction ls <;> simp [*] - rename_i hd tl hi - intro i hineq - if heq: i = 0 then - simp [*] at * - have := tl.len_pos - linarith - else - simp at hineq - have : 0 < i := by int_tac - simp [*] - apply hi - linarith - -end List +import Base.IList.IList diff --git a/backends/lean/Base/IList/IList.lean b/backends/lean/Base/IList/IList.lean new file mode 100644 index 00000000..2a335cac --- /dev/null +++ b/backends/lean/Base/IList/IList.lean @@ -0,0 +1,142 @@ +/- Complementary list functions and lemmas which operate on integers rather + than natural numbers. -/ + +import Std.Data.Int.Lemmas +import Base.Arith + +namespace List + +def len (ls : List α) : Int := + match ls with + | [] => 0 + | _ :: tl => 1 + len tl + +-- Remark: if i < 0, then the result is none +def indexOpt (ls : List α) (i : Int) : Option α := + match ls with + | [] => none + | hd :: tl => if i = 0 then some hd else indexOpt tl (i - 1) + +-- Remark: if i < 0, then the result is the defaul element +def index [Inhabited α] (ls : List α) (i : Int) : α := + match ls with + | [] => Inhabited.default + | x :: tl => + if i = 0 then x else index tl (i - 1) + +-- Remark: the list is unchanged if the index is not in bounds (in particular +-- if it is < 0) +def update (ls : List α) (i : Int) (y : α) : List α := + match ls with + | [] => [] + | x :: tl => if i = 0 then y :: tl else x :: update tl (i - 1) y + +-- Remark: the whole list is dropped if the index is not in bounds (in particular +-- if it is < 0) +def idrop (i : Int) (ls : List α) : List α := + match ls with + | [] => [] + | x :: tl => if i = 0 then x :: tl else idrop (i - 1) tl + +section Lemmas + +variable {α : Type u} + +@[simp] theorem len_nil : len ([] : List α) = 0 := by simp [len] +@[simp] theorem len_cons : len ((x :: tl) : List α) = 1 + len tl := by simp [len] + +@[simp] theorem index_zero_cons [Inhabited α] : index ((x :: tl) : List α) 0 = x := by simp [index] +@[simp] theorem index_nzero_cons [Inhabited α] (hne : i ≠ 0) : index ((x :: tl) : List α) i = index tl (i - 1) := by simp [*, index] + +@[simp] theorem update_nil : update ([] : List α) i y = [] := by simp [update] +@[simp] theorem update_zero_cons : update ((x :: tl) : List α) 0 y = y :: tl := by simp [update] +@[simp] theorem update_nzero_cons (hne : i ≠ 0) : update ((x :: tl) : List α) i y = x :: update tl (i - 1) y := by simp [*, update] + +@[simp] theorem idrop_nil : idrop i ([] : List α) = [] := by simp [idrop] +@[simp] theorem idrop_zero : idrop 0 (ls : List α) = ls := by cases ls <;> simp [idrop] +@[simp] theorem idrop_nzero_cons (hne : i ≠ 0) : idrop i ((x :: tl) : List α) = idrop (i - 1) tl := by simp [*, idrop] + +theorem len_eq_length (ls : List α) : ls.len = ls.length := by + induction ls + . rfl + . simp [*, Int.ofNat_succ, Int.add_comm] + +@[simp] theorem len_append (l1 l2 : List α) : (l1 ++ l2).len = l1.len + l2.len := by + -- Remark: simp loops here because of the following rewritings: + -- @Nat.cast_add: ↑(List.length l1 + List.length l2) ==> ↑(List.length l1) + ↑(List.length l2) + -- Int.ofNat_add_ofNat: ↑(List.length l1) + ↑(List.length l2) ==> ↑(List.length l1 + List.length l2) + -- TODO: post an issue? + simp only [len_eq_length] + simp only [length_append] + simp only [Int.ofNat_add] + +@[simp] +theorem length_update (ls : List α) (i : Int) (x : α) : (ls.update i x).length = ls.length := by + revert i + induction ls <;> simp_all [length, update] + intro; split <;> simp [*] + +@[simp] +theorem len_update (ls : List α) (i : Int) (x : α) : (ls.update i x).len = ls.len := by + simp [len_eq_length] + + +theorem len_pos : 0 ≤ (ls : List α).len := by + induction ls <;> simp [*] + linarith + +instance (a : Type u) : Arith.HasIntProp (List a) where + prop_ty := λ ls => 0 ≤ ls.len + prop := λ ls => ls.len_pos + +theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + revert l1' + induction l1 + . intro l1'; cases l1' <;> simp [*] + . intro l1'; cases l1' <;> simp_all; tauto + +theorem right_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.length = l2'.length) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + have := left_length_eq_append_eq l1 l2 l1' l2' + constructor <;> intro heq2 <;> + have : l1.length + l2.length = l1'.length + l2'.length := by + have : (l1 ++ l2).length = (l1' ++ l2').length := by simp [*] + simp only [length_append] at this + apply this + . simp [heq] at this + tauto + . tauto + +theorem left_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.len = l1'.len) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + simp [len_eq_length] at heq + apply left_length_eq_append_eq + assumption + +theorem right_len_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l2.len = l2'.len) : + l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by + simp [len_eq_length] at heq + apply right_length_eq_append_eq + assumption + +open Arith in +theorem idrop_eq_nil_of_le (hineq : ls.len ≤ i) : idrop i ls = [] := by + revert i + induction ls <;> simp [*] + rename_i hd tl hi + intro i hineq + if heq: i = 0 then + simp [*] at * + have := tl.len_pos + linarith + else + simp at hineq + have : 0 < i := by int_tac + simp [*] + apply hi + linarith + +end Lemmas + +end List diff --git a/backends/lean/Base/Primitives.lean b/backends/lean/Base/Primitives.lean index 1a0c665d..91823cb6 100644 --- a/backends/lean/Base/Primitives.lean +++ b/backends/lean/Base/Primitives.lean @@ -1,715 +1,3 @@ -import Lean -import Lean.Meta.Tactic.Simp -import Init.Data.List.Basic -import Mathlib.Tactic.RunCmd -import Mathlib.Tactic.Linarith - -namespace Primitives - --------------------- --- ASSERT COMMAND --Std. --------------------- - -open Lean Elab Command Term Meta - -syntax (name := assert) "#assert" term: command - -@[command_elab assert] -unsafe -def assertImpl : CommandElab := fun (_stx: Syntax) => do - runTermElabM (fun _ => do - let r ← evalTerm Bool (mkConst ``Bool) _stx[1] - if not r then - logInfo ("Assertion failed for:\n" ++ _stx[1]) - throwError ("Expression reduced to false:\n" ++ _stx[1]) - pure ()) - -#eval 2 == 2 -#assert (2 == 2) - -------------- --- PRELUDE -- -------------- - --- Results & monadic combinators - -inductive Error where - | assertionFailure: Error - | integerOverflow: Error - | divisionByZero: Error - | arrayOutOfBounds: Error - | maximumSizeExceeded: Error - | panic: Error -deriving Repr, BEq - -open Error - -inductive Result (α : Type u) where - | ret (v: α): Result α - | fail (e: Error): Result α - | div -deriving Repr, BEq - -open Result - -instance Result_Inhabited (α : Type u) : Inhabited (Result α) := - Inhabited.mk (fail panic) - -instance Result_Nonempty (α : Type u) : Nonempty (Result α) := - Nonempty.intro div - -/- HELPERS -/ - -def ret? {α: Type u} (r: Result α): Bool := - match r with - | ret _ => true - | fail _ | div => false - -def div? {α: Type u} (r: Result α): Bool := - match r with - | div => true - | ret _ | fail _ => false - -def massert (b:Bool) : Result Unit := - if b then ret () else fail assertionFailure - -def eval_global {α: Type u} (x: Result α) (_: ret? x): α := - match x with - | fail _ | div => by contradiction - | ret x => x - -/- DO-DSL SUPPORT -/ - -def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := - match x with - | ret v => f v - | fail v => fail v - | div => div - --- Allows using Result in do-blocks -instance : Bind Result where - bind := bind - --- Allows using return x in do-blocks -instance : Pure Result where - pure := fun x => ret x - -@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] -@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] -@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] - -/- CUSTOM-DSL SUPPORT -/ - --- Let-binding the Result of a monadic operation is oftentimes not sufficient, --- because we may need a hypothesis for equational reasoning in the scope. We --- rely on subtype, and a custom let-binding operator, in effect recreating our --- own variant of the do-dsl - -def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := - match o with - | ret x => ret ⟨x, rfl⟩ - | fail e => fail e - | div => div - -@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : - (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : - (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] - -@[simp] theorem bind_tc_div (f : α → Result β) : - (do let y ← div; f y) = div := by simp [Bind.bind, bind] - ----------------------- --- MACHINE INTEGERS -- ----------------------- - --- We redefine our machine integers types. - --- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` --- using the simplifier, meaning that proofs do not depend on the compile-time value of --- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at --- least officially, 16-bit microcontrollers, so this seems like a fine design decision --- for now.) - --- Note from Chris Bailey: "If there's more than one salient property of your --- definition then the subtyping strategy might get messy, and the property part --- of a subtype is less discoverable by the simplifier or tactics like --- library_search." So, we will not add refinements on the return values of the --- operations defined on Primitives, but will rather rely on custom lemmas to --- invert on possible return values of the primitive operations. - --- Machine integer constants, done via `ofNatCore`, which requires a proof that --- the `Nat` fits within the desired integer type. We provide a custom tactic. - -open System.Platform.getNumBits - --- TODO: is there a way of only importing System.Platform.getNumBits? --- -@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val - --- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. - --- The "structured" bounds -def Isize.smin : Int := - (HPow.hPow 2 (size_num_bits - 1)) -def Isize.smax : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 -def I8.smin : Int := - (HPow.hPow 2 7) -def I8.smax : Int := HPow.hPow 2 7 - 1 -def I16.smin : Int := - (HPow.hPow 2 15) -def I16.smax : Int := HPow.hPow 2 15 - 1 -def I32.smin : Int := -(HPow.hPow 2 31) -def I32.smax : Int := HPow.hPow 2 31 - 1 -def I64.smin : Int := -(HPow.hPow 2 63) -def I64.smax : Int := HPow.hPow 2 63 - 1 -def I128.smin : Int := -(HPow.hPow 2 127) -def I128.smax : Int := HPow.hPow 2 127 - 1 -def Usize.smin : Int := 0 -def Usize.smax : Int := HPow.hPow 2 size_num_bits - 1 -def U8.smin : Int := 0 -def U8.smax : Int := HPow.hPow 2 8 - 1 -def U16.smin : Int := 0 -def U16.smax : Int := HPow.hPow 2 16 - 1 -def U32.smin : Int := 0 -def U32.smax : Int := HPow.hPow 2 32 - 1 -def U64.smin : Int := 0 -def U64.smax : Int := HPow.hPow 2 64 - 1 -def U128.smin : Int := 0 -def U128.smax : Int := HPow.hPow 2 128 - 1 - --- The "normalized" bounds, that we use in practice -def I8.min := -128 -def I8.max := 127 -def I16.min := -32768 -def I16.max := 32767 -def I32.min := -2147483648 -def I32.max := 2147483647 -def I64.min := -9223372036854775808 -def I64.max := 9223372036854775807 -def I128.min := -170141183460469231731687303715884105728 -def I128.max := 170141183460469231731687303715884105727 -@[simp] def U8.min := 0 -def U8.max := 255 -@[simp] def U16.min := 0 -def U16.max := 65535 -@[simp] def U32.min := 0 -def U32.max := 4294967295 -@[simp] def U64.min := 0 -def U64.max := 18446744073709551615 -@[simp] def U128.min := 0 -def U128.max := 340282366920938463463374607431768211455 -@[simp] def Usize.min := 0 - -def Isize.refined_min : { n:Int // n = I32.min ∨ n = I64.min } := - ⟨ Isize.smin, by - simp [Isize.smin] - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> simp [*] ⟩ - -def Isize.refined_max : { n:Int // n = I32.max ∨ n = I64.max } := - ⟨ Isize.smax, by - simp [Isize.smax] - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> simp [*] ⟩ - -def Usize.refined_max : { n:Int // n = U32.max ∨ n = U64.max } := - ⟨ Usize.smax, by - simp [Usize.smax] - cases System.Platform.numBits_eq <;> - unfold System.Platform.numBits at * <;> simp [*] ⟩ - -def Isize.min := Isize.refined_min.val -def Isize.max := Isize.refined_max.val -def Usize.max := Usize.refined_max.val - -inductive ScalarTy := -| Isize -| I8 -| I16 -| I32 -| I64 -| I128 -| Usize -| U8 -| U16 -| U32 -| U64 -| U128 - -def Scalar.smin (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.smin - | .I8 => I8.smin - | .I16 => I16.smin - | .I32 => I32.smin - | .I64 => I64.smin - | .I128 => I128.smin - | .Usize => Usize.smin - | .U8 => U8.smin - | .U16 => U16.smin - | .U32 => U32.smin - | .U64 => U64.smin - | .U128 => U128.smin - -def Scalar.smax (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.smax - | .I8 => I8.smax - | .I16 => I16.smax - | .I32 => I32.smax - | .I64 => I64.smax - | .I128 => I128.smax - | .Usize => Usize.smax - | .U8 => U8.smax - | .U16 => U16.smax - | .U32 => U32.smax - | .U64 => U64.smax - | .U128 => U128.smax - -def Scalar.min (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.min - | .I8 => I8.min - | .I16 => I16.min - | .I32 => I32.min - | .I64 => I64.min - | .I128 => I128.min - | .Usize => Usize.min - | .U8 => U8.min - | .U16 => U16.min - | .U32 => U32.min - | .U64 => U64.min - | .U128 => U128.min - -def Scalar.max (ty : ScalarTy) : Int := - match ty with - | .Isize => Isize.max - | .I8 => I8.max - | .I16 => I16.max - | .I32 => I32.max - | .I64 => I64.max - | .I128 => I128.max - | .Usize => Usize.max - | .U8 => U8.max - | .U16 => U16.max - | .U32 => U32.max - | .U64 => U64.max - | .U128 => U128.max - -def Scalar.smin_eq (ty : ScalarTy) : Scalar.min ty = Scalar.smin ty := by - cases ty <;> rfl - -def Scalar.smax_eq (ty : ScalarTy) : Scalar.max ty = Scalar.smax ty := by - cases ty <;> rfl - --- "Conservative" bounds --- We use those because we can't compare to the isize bounds (which can't --- reduce at compile-time). Whenever we perform an arithmetic operation like --- addition we need to check that the result is in bounds: we first compare --- to the conservative bounds, which reduce, then compare to the real bounds. --- This is useful for the various #asserts that we want to reduce at --- type-checking time. -def Scalar.cMin (ty : ScalarTy) : Int := - match ty with - | .Isize => Scalar.min .I32 - | _ => Scalar.min ty - -def Scalar.cMax (ty : ScalarTy) : Int := - match ty with - | .Isize => Scalar.max .I32 - | .Usize => Scalar.max .U32 - | _ => Scalar.max ty - -theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * - have h := Isize.refined_min.property - cases h <;> simp [*, Isize.min] - -theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by - cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * - . have h := Isize.refined_max.property - cases h <;> simp [*, Isize.max] - . have h := Usize.refined_max.property - cases h <;> simp [*, Usize.max] - -theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by - have := Scalar.cMin_bound ty - linarith - -theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by - have := Scalar.cMax_bound ty - linarith - -structure Scalar (ty : ScalarTy) where - val : Int - hmin : Scalar.min ty ≤ val - hmax : val ≤ Scalar.max ty -deriving Repr - -theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : - Scalar.cMin ty ≤ x ∧ x ≤ Scalar.cMax ty -> - Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty - := - λ h => by - apply And.intro <;> have hmin := Scalar.cMin_bound ty <;> have hmax := Scalar.cMax_bound ty <;> linarith - -def Scalar.ofIntCore {ty : ScalarTy} (x : Int) - (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := - { val := x, hmin := hmin, hmax := hmax } - --- Tactic to prove that integers are in bounds --- TODO: use this: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/instance.20with.20tactic.20autoparam -syntax "intlit" : tactic -macro_rules - | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices; decide) - -def Scalar.ofInt {ty : ScalarTy} (x : Int) - (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by intlit) : Scalar ty := - -- Remark: we initially wrote: - -- let ⟨ hmin, hmax ⟩ := h - -- Scalar.ofIntCore x hmin hmax - -- We updated to the line below because a similar pattern in `Scalar.tryMk` - -- made reduction block. Both versions seem to work for `Scalar.ofInt`, though. - -- TODO: investigate - Scalar.ofIntCore x h.left h.right - -@[simp] def Scalar.check_bounds (ty : ScalarTy) (x : Int) : Bool := - (Scalar.cMin ty ≤ x || Scalar.min ty ≤ x) ∧ (x ≤ Scalar.cMax ty || x ≤ Scalar.max ty) - -theorem Scalar.check_bounds_prop {ty : ScalarTy} {x : Int} (h: Scalar.check_bounds ty x) : - Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by - simp at * - have ⟨ hmin, hmax ⟩ := h - have hbmin := Scalar.cMin_bound ty - have hbmax := Scalar.cMax_bound ty - cases hmin <;> cases hmax <;> apply And.intro <;> linarith - --- Further thoughts: look at what has been done here: --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean --- and --- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean --- which both contain a fair amount of reasoning already! -def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := - if h:Scalar.check_bounds ty x then - -- If we do: - -- ``` - -- let ⟨ hmin, hmax ⟩ := (Scalar.check_bounds_prop h) - -- Scalar.ofIntCore x hmin hmax - -- ``` - -- then normalization blocks (for instance, some proofs which use reflexivity fail). - -- However, the version below doesn't block reduction (TODO: investigate): - return Scalar.ofInt x (Scalar.check_bounds_prop h) - else fail integerOverflow - -def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) - -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - --- Our custom remainder operation, which satisfies the semantics of Rust --- TODO: is there a better way? -def scalar_rem (x y : Int) : Int := - if 0 ≤ x then |x| % |y| - else - (|x| % |y|) - --- Our custom division operation, which satisfies the semantics of Rust --- TODO: is there a better way? -def scalar_div (x y : Int) : Int := - if 0 ≤ x && 0 ≤ y then |x| / |y| - else if 0 ≤ x && y < 0 then - (|x| / |y|) - else if x < 0 && 0 ≤ y then - (|x| / |y|) - else |x| / |y| - --- Checking that the remainder operation is correct -#assert scalar_rem 1 2 = 1 -#assert scalar_rem (-1) 2 = -1 -#assert scalar_rem 1 (-2) = 1 -#assert scalar_rem (-1) (-2) = -1 -#assert scalar_rem 7 3 = (1:Int) -#assert scalar_rem (-7) 3 = -1 -#assert scalar_rem 7 (-3) = 1 -#assert scalar_rem (-7) (-3) = -1 - --- Checking that the division operation is correct -#assert scalar_div 3 2 = 1 -#assert scalar_div (-3) 2 = -1 -#assert scalar_div 3 (-2) = -1 -#assert scalar_div (-3) (-2) = 1 -#assert scalar_div 7 3 = 2 -#assert scalar_div (-7) 3 = -2 -#assert scalar_div 7 (-3) = -2 -#assert scalar_div (-7) (-3) = 2 - -def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero - -def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val + y.val) - -def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val - y.val) - -def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - Scalar.tryMk ty (x.val * y.val) - --- TODO: instances of +, -, * etc. for scalars - --- Cast an integer from a [src_ty] to a [tgt_ty] --- TODO: check the semantics of casts in Rust -def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := - Scalar.tryMk tgt_ty x.val - --- The scalar types --- We declare the definitions as reducible so that Lean can unfold them (useful --- for type class resolution for instance). -@[reducible] def Isize := Scalar .Isize -@[reducible] def I8 := Scalar .I8 -@[reducible] def I16 := Scalar .I16 -@[reducible] def I32 := Scalar .I32 -@[reducible] def I64 := Scalar .I64 -@[reducible] def I128 := Scalar .I128 -@[reducible] def Usize := Scalar .Usize -@[reducible] def U8 := Scalar .U8 -@[reducible] def U16 := Scalar .U16 -@[reducible] def U32 := Scalar .U32 -@[reducible] def U64 := Scalar .U64 -@[reducible] def U128 := Scalar .U128 - --- TODO: below: not sure this is the best way. --- Should we rather overload operations like +, -, etc.? --- Also, it is possible to automate the generation of those definitions --- with macros (but would it be a good idea? It would be less easy to --- read the file, which is not supposed to change a lot) - --- Negation - -/-- -Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce -one here. - -The notation typeclass for heterogeneous addition. -This enables the notation `- a : β` where `a : α`. --/ -class HNeg (α : Type u) (β : outParam (Type v)) where - /-- `- a` computes the negation of `a`. - The meaning of this notation is type-dependent. -/ - hNeg : α → β - -prefix:75 "-" => HNeg.hNeg - -instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x -instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x -instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x -instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x -instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x -instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x - --- Addition -instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hAdd x y := Scalar.add x y - --- Substraction -instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hSub x y := Scalar.sub x y - --- Multiplication -instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMul x y := Scalar.mul x y - --- Division -instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hDiv x y := Scalar.div x y - --- Remainder -instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where - hMod x y := Scalar.rem x y - --- ofIntCore --- TODO: typeclass? -def Isize.ofIntCore := @Scalar.ofIntCore .Isize -def I8.ofIntCore := @Scalar.ofIntCore .I8 -def I16.ofIntCore := @Scalar.ofIntCore .I16 -def I32.ofIntCore := @Scalar.ofIntCore .I32 -def I64.ofIntCore := @Scalar.ofIntCore .I64 -def I128.ofIntCore := @Scalar.ofIntCore .I128 -def Usize.ofIntCore := @Scalar.ofIntCore .Usize -def U8.ofIntCore := @Scalar.ofIntCore .U8 -def U16.ofIntCore := @Scalar.ofIntCore .U16 -def U32.ofIntCore := @Scalar.ofIntCore .U32 -def U64.ofIntCore := @Scalar.ofIntCore .U64 -def U128.ofIntCore := @Scalar.ofIntCore .U128 - --- ofInt --- TODO: typeclass? -def Isize.ofInt := @Scalar.ofInt .Isize -def I8.ofInt := @Scalar.ofInt .I8 -def I16.ofInt := @Scalar.ofInt .I16 -def I32.ofInt := @Scalar.ofInt .I32 -def I64.ofInt := @Scalar.ofInt .I64 -def I128.ofInt := @Scalar.ofInt .I128 -def Usize.ofInt := @Scalar.ofInt .Usize -def U8.ofInt := @Scalar.ofInt .U8 -def U16.ofInt := @Scalar.ofInt .U16 -def U32.ofInt := @Scalar.ofInt .U32 -def U64.ofInt := @Scalar.ofInt .U64 -def U128.ofInt := @Scalar.ofInt .U128 - --- Comparisons -instance {ty} : LT (Scalar ty) where - lt a b := LT.lt a.val b.val - -instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val - -instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. -instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. - -theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j - | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl - -theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := - h ▸ rfl - -theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := - fun h' => absurd (val_eq_of_eq h') h - -instance (ty : ScalarTy) : DecidableEq (Scalar ty) := - fun i j => - match decEq i.val j.val with - | isTrue h => isTrue (Scalar.eq_of_val_eq h) - | isFalse h => isFalse (Scalar.ne_of_val_ne h) - -def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val - --- -- We now define a type class that subsumes the various machine integer types, so --- -- as to write a concise definition for scalar_cast, rather than exhaustively --- -- enumerating all of the possible pairs. We remark that Rust has sane semantics --- -- and fails if a cast operation would involve a truncation or modulo. - --- class MachineInteger (t: Type) where --- size: Nat --- val: t -> Fin size --- ofNatCore: (n:Nat) -> LT.lt n size -> t - --- set_option hygiene false in --- run_cmd --- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do --- Lean.Elab.Command.elabCommand (← `( --- namespace $typeName --- instance: MachineInteger $typeName where --- size := size --- val := val --- ofNatCore := ofNatCore --- end $typeName --- )) - --- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on --- -- Lean to infer `src`. - --- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := --- if h: MachineInteger.val x < MachineInteger.size dst then --- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) --- else --- .fail integerOverflow - -------------- --- VECTORS -- -------------- - -def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } - --- TODO: do we really need it? It should be with Subtype by default -instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val - -def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ - -def Vec.len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l - --- This shouldn't be used -def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () - --- This is actually the backward function -def Vec.push (α : Type u) (v : Vec α) (x : α) : Result (Vec α) - := - let nlen := List.length v.val + 1 - if h : nlen ≤ U32.max || nlen ≤ Usize.max then - have h : nlen ≤ Usize.max := by - simp [Usize.max] at * - have hm := Usize.refined_max.property - cases h <;> cases hm <;> simp [U32.max, U64.max] at * <;> try linarith - return ⟨ List.concat v.val x, by simp at *; assumption ⟩ - else - fail maximumSizeExceeded - --- This shouldn't be used -def Vec.insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - --- This is actually the backward function -def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) - let i := i.val.toNat - .ret ⟨ List.set v.val i x, by - have h: List.length v.val ≤ Usize.max := v.property - simp [*] at * - ⟩ - else - .fail arrayOutOfBounds - -def Vec.index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : - Fin (List.length v.val) := - let j := i.val.toNat - let h: j < List.length v.val := by - have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin - apply heq.mpr - assumption - ⟨j, h⟩ - -def Vec.index (α : Type u) (v: Vec α) (i: Usize): Result α := - if h: i.val < List.length v.val then - let i := Vec.index_to_fin h - .ret (List.get v.val i) - else - .fail arrayOutOfBounds - --- This shouldn't be used -def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then - .ret () - else - .fail arrayOutOfBounds - -def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize): Result α := - if h: i.val < List.length v.val then - let i := Vec.index_to_fin h - .ret (List.get v.val i) - else - .fail arrayOutOfBounds - -def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if h: i.val < List.length v.val then - let i := Vec.index_to_fin h - .ret ⟨ List.set v.val i x, by - have h: List.length v.val ≤ Usize.max := v.property - simp [*] at * - ⟩ - else - .fail arrayOutOfBounds - ----------- --- MISC -- ----------- - -@[simp] def mem.replace (a : Type) (x : a) (_ : a) : a := x -@[simp] def mem.replace_back (a : Type) (_ : a) (y : a) : a := y - -/-- Aeneas-translated function -- useful to reduce non-recursive definitions. - Use with `simp [ aeneas ]` -/ -register_simp_attr aeneas - -end Primitives +import Base.Primitives.Base +import Base.Primitives.Scalar +import Base.Primitives.Vec diff --git a/backends/lean/Base/Primitives/Base.lean b/backends/lean/Base/Primitives/Base.lean new file mode 100644 index 00000000..db462c38 --- /dev/null +++ b/backends/lean/Base/Primitives/Base.lean @@ -0,0 +1,130 @@ +import Lean + +namespace Primitives + +-------------------- +-- ASSERT COMMAND --Std. +-------------------- + +open Lean Elab Command Term Meta + +syntax (name := assert) "#assert" term: command + +@[command_elab assert] +unsafe +def assertImpl : CommandElab := fun (_stx: Syntax) => do + runTermElabM (fun _ => do + let r ← evalTerm Bool (mkConst ``Bool) _stx[1] + if not r then + logInfo ("Assertion failed for:\n" ++ _stx[1]) + throwError ("Expression reduced to false:\n" ++ _stx[1]) + pure ()) + +#eval 2 == 2 +#assert (2 == 2) + +------------- +-- PRELUDE -- +------------- + +-- Results & monadic combinators + +inductive Error where + | assertionFailure: Error + | integerOverflow: Error + | divisionByZero: Error + | arrayOutOfBounds: Error + | maximumSizeExceeded: Error + | panic: Error +deriving Repr, BEq + +open Error + +inductive Result (α : Type u) where + | ret (v: α): Result α + | fail (e: Error): Result α + | div +deriving Repr, BEq + +open Result + +instance Result_Inhabited (α : Type u) : Inhabited (Result α) := + Inhabited.mk (fail panic) + +instance Result_Nonempty (α : Type u) : Nonempty (Result α) := + Nonempty.intro div + +/- HELPERS -/ + +def ret? {α: Type u} (r: Result α): Bool := + match r with + | ret _ => true + | fail _ | div => false + +def div? {α: Type u} (r: Result α): Bool := + match r with + | div => true + | ret _ | fail _ => false + +def massert (b:Bool) : Result Unit := + if b then ret () else fail assertionFailure + +def eval_global {α: Type u} (x: Result α) (_: ret? x): α := + match x with + | fail _ | div => by contradiction + | ret x => x + +/- DO-DSL SUPPORT -/ + +def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := + match x with + | ret v => f v + | fail v => fail v + | div => div + +-- Allows using Result in do-blocks +instance : Bind Result where + bind := bind + +-- Allows using return x in do-blocks +instance : Pure Result where + pure := fun x => ret x + +@[simp] theorem bind_ret (x : α) (f : α → Result β) : bind (.ret x) f = f x := by simp [bind] +@[simp] theorem bind_fail (x : Error) (f : α → Result β) : bind (.fail x) f = .fail x := by simp [bind] +@[simp] theorem bind_div (f : α → Result β) : bind .div f = .div := by simp [bind] + +/- CUSTOM-DSL SUPPORT -/ + +-- Let-binding the Result of a monadic operation is oftentimes not sufficient, +-- because we may need a hypothesis for equational reasoning in the scope. We +-- rely on subtype, and a custom let-binding operator, in effect recreating our +-- own variant of the do-dsl + +def Result.attach {α: Type} (o : Result α): Result { x : α // o = ret x } := + match o with + | ret x => ret ⟨x, rfl⟩ + | fail e => fail e + | div => div + +@[simp] theorem bind_tc_ret (x : α) (f : α → Result β) : + (do let y ← .ret x; f y) = f x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_fail (x : Error) (f : α → Result β) : + (do let y ← fail x; f y) = fail x := by simp [Bind.bind, bind] + +@[simp] theorem bind_tc_div (f : α → Result β) : + (do let y ← div; f y) = div := by simp [Bind.bind, bind] + +---------- +-- MISC -- +---------- + +@[simp] def mem.replace (a : Type) (x : a) (_ : a) : a := x +@[simp] def mem.replace_back (a : Type) (_ : a) (y : a) : a := y + +/-- Aeneas-translated function -- useful to reduce non-recursive definitions. + Use with `simp [ aeneas ]` -/ +register_simp_attr aeneas + +end Primitives diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean new file mode 100644 index 00000000..241dfa07 --- /dev/null +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -0,0 +1,507 @@ +import Lean +import Lean.Meta.Tactic.Simp +import Mathlib.Tactic.Linarith +import Base.Primitives.Base + +namespace Primitives + +---------------------- +-- MACHINE INTEGERS -- +---------------------- + +-- We redefine our machine integers types. + +-- For Isize/Usize, we reuse `getNumBits` from `USize`. You cannot reduce `getNumBits` +-- using the simplifier, meaning that proofs do not depend on the compile-time value of +-- USize.size. (Lean assumes 32 or 64-bit platforms, and Rust doesn't really support, at +-- least officially, 16-bit microcontrollers, so this seems like a fine design decision +-- for now.) + +-- Note from Chris Bailey: "If there's more than one salient property of your +-- definition then the subtyping strategy might get messy, and the property part +-- of a subtype is less discoverable by the simplifier or tactics like +-- library_search." So, we will not add refinements on the return values of the +-- operations defined on Primitives, but will rather rely on custom lemmas to +-- invert on possible return values of the primitive operations. + +-- Machine integer constants, done via `ofNatCore`, which requires a proof that +-- the `Nat` fits within the desired integer type. We provide a custom tactic. + +open Result Error +open System.Platform.getNumBits + +-- TODO: is there a way of only importing System.Platform.getNumBits? +-- +@[simp] def size_num_bits : Nat := (System.Platform.getNumBits ()).val + +-- Remark: Lean seems to use < for the comparisons with the upper bounds by convention. + +-- The "structured" bounds +def Isize.smin : Int := - (HPow.hPow 2 (size_num_bits - 1)) +def Isize.smax : Int := (HPow.hPow 2 (size_num_bits - 1)) - 1 +def I8.smin : Int := - (HPow.hPow 2 7) +def I8.smax : Int := HPow.hPow 2 7 - 1 +def I16.smin : Int := - (HPow.hPow 2 15) +def I16.smax : Int := HPow.hPow 2 15 - 1 +def I32.smin : Int := -(HPow.hPow 2 31) +def I32.smax : Int := HPow.hPow 2 31 - 1 +def I64.smin : Int := -(HPow.hPow 2 63) +def I64.smax : Int := HPow.hPow 2 63 - 1 +def I128.smin : Int := -(HPow.hPow 2 127) +def I128.smax : Int := HPow.hPow 2 127 - 1 +def Usize.smin : Int := 0 +def Usize.smax : Int := HPow.hPow 2 size_num_bits - 1 +def U8.smin : Int := 0 +def U8.smax : Int := HPow.hPow 2 8 - 1 +def U16.smin : Int := 0 +def U16.smax : Int := HPow.hPow 2 16 - 1 +def U32.smin : Int := 0 +def U32.smax : Int := HPow.hPow 2 32 - 1 +def U64.smin : Int := 0 +def U64.smax : Int := HPow.hPow 2 64 - 1 +def U128.smin : Int := 0 +def U128.smax : Int := HPow.hPow 2 128 - 1 + +-- The "normalized" bounds, that we use in practice +def I8.min := -128 +def I8.max := 127 +def I16.min := -32768 +def I16.max := 32767 +def I32.min := -2147483648 +def I32.max := 2147483647 +def I64.min := -9223372036854775808 +def I64.max := 9223372036854775807 +def I128.min := -170141183460469231731687303715884105728 +def I128.max := 170141183460469231731687303715884105727 +@[simp] def U8.min := 0 +def U8.max := 255 +@[simp] def U16.min := 0 +def U16.max := 65535 +@[simp] def U32.min := 0 +def U32.max := 4294967295 +@[simp] def U64.min := 0 +def U64.max := 18446744073709551615 +@[simp] def U128.min := 0 +def U128.max := 340282366920938463463374607431768211455 +@[simp] def Usize.min := 0 + +def Isize.refined_min : { n:Int // n = I32.min ∨ n = I64.min } := + ⟨ Isize.smin, by + simp [Isize.smin] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Isize.refined_max : { n:Int // n = I32.max ∨ n = I64.max } := + ⟨ Isize.smax, by + simp [Isize.smax] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Usize.refined_max : { n:Int // n = U32.max ∨ n = U64.max } := + ⟨ Usize.smax, by + simp [Usize.smax] + cases System.Platform.numBits_eq <;> + unfold System.Platform.numBits at * <;> simp [*] ⟩ + +def Isize.min := Isize.refined_min.val +def Isize.max := Isize.refined_max.val +def Usize.max := Usize.refined_max.val + +inductive ScalarTy := +| Isize +| I8 +| I16 +| I32 +| I64 +| I128 +| Usize +| U8 +| U16 +| U32 +| U64 +| U128 + +def Scalar.smin (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.smin + | .I8 => I8.smin + | .I16 => I16.smin + | .I32 => I32.smin + | .I64 => I64.smin + | .I128 => I128.smin + | .Usize => Usize.smin + | .U8 => U8.smin + | .U16 => U16.smin + | .U32 => U32.smin + | .U64 => U64.smin + | .U128 => U128.smin + +def Scalar.smax (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.smax + | .I8 => I8.smax + | .I16 => I16.smax + | .I32 => I32.smax + | .I64 => I64.smax + | .I128 => I128.smax + | .Usize => Usize.smax + | .U8 => U8.smax + | .U16 => U16.smax + | .U32 => U32.smax + | .U64 => U64.smax + | .U128 => U128.smax + +def Scalar.min (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.min + | .I8 => I8.min + | .I16 => I16.min + | .I32 => I32.min + | .I64 => I64.min + | .I128 => I128.min + | .Usize => Usize.min + | .U8 => U8.min + | .U16 => U16.min + | .U32 => U32.min + | .U64 => U64.min + | .U128 => U128.min + +def Scalar.max (ty : ScalarTy) : Int := + match ty with + | .Isize => Isize.max + | .I8 => I8.max + | .I16 => I16.max + | .I32 => I32.max + | .I64 => I64.max + | .I128 => I128.max + | .Usize => Usize.max + | .U8 => U8.max + | .U16 => U16.max + | .U32 => U32.max + | .U64 => U64.max + | .U128 => U128.max + +def Scalar.smin_eq (ty : ScalarTy) : Scalar.min ty = Scalar.smin ty := by + cases ty <;> rfl + +def Scalar.smax_eq (ty : ScalarTy) : Scalar.max ty = Scalar.smax ty := by + cases ty <;> rfl + +-- "Conservative" bounds +-- We use those because we can't compare to the isize bounds (which can't +-- reduce at compile-time). Whenever we perform an arithmetic operation like +-- addition we need to check that the result is in bounds: we first compare +-- to the conservative bounds, which reduce, then compare to the real bounds. +-- This is useful for the various #asserts that we want to reduce at +-- type-checking time. +def Scalar.cMin (ty : ScalarTy) : Int := + match ty with + | .Isize => Scalar.min .I32 + | _ => Scalar.min ty + +def Scalar.cMax (ty : ScalarTy) : Int := + match ty with + | .Isize => Scalar.max .I32 + | .Usize => Scalar.max .U32 + | _ => Scalar.max ty + +theorem Scalar.cMin_bound ty : Scalar.min ty ≤ Scalar.cMin ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * + have h := Isize.refined_min.property + cases h <;> simp [*, Isize.min] + +theorem Scalar.cMax_bound ty : Scalar.cMax ty ≤ Scalar.max ty := by + cases ty <;> simp [Scalar.min, Scalar.max, Scalar.cMin, Scalar.cMax] at * + . have h := Isize.refined_max.property + cases h <;> simp [*, Isize.max] + . have h := Usize.refined_max.property + cases h <;> simp [*, Usize.max] + +theorem Scalar.cMin_suffices ty (h : Scalar.cMin ty ≤ x) : Scalar.min ty ≤ x := by + have := Scalar.cMin_bound ty + linarith + +theorem Scalar.cMax_suffices ty (h : x ≤ Scalar.cMax ty) : x ≤ Scalar.max ty := by + have := Scalar.cMax_bound ty + linarith + +structure Scalar (ty : ScalarTy) where + val : Int + hmin : Scalar.min ty ≤ val + hmax : val ≤ Scalar.max ty +deriving Repr + +theorem Scalar.bound_suffices (ty : ScalarTy) (x : Int) : + Scalar.cMin ty ≤ x ∧ x ≤ Scalar.cMax ty -> + Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty + := + λ h => by + apply And.intro <;> have hmin := Scalar.cMin_bound ty <;> have hmax := Scalar.cMax_bound ty <;> linarith + +def Scalar.ofIntCore {ty : ScalarTy} (x : Int) + (hmin : Scalar.min ty ≤ x) (hmax : x ≤ Scalar.max ty) : Scalar ty := + { val := x, hmin := hmin, hmax := hmax } + +-- Tactic to prove that integers are in bounds +-- TODO: use this: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/instance.20with.20tactic.20autoparam +syntax "intlit" : tactic +macro_rules + | `(tactic| intlit) => `(tactic| apply Scalar.bound_suffices; decide) + +def Scalar.ofInt {ty : ScalarTy} (x : Int) + (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by intlit) : Scalar ty := + -- Remark: we initially wrote: + -- let ⟨ hmin, hmax ⟩ := h + -- Scalar.ofIntCore x hmin hmax + -- We updated to the line below because a similar pattern in `Scalar.tryMk` + -- made reduction block. Both versions seem to work for `Scalar.ofInt`, though. + -- TODO: investigate + Scalar.ofIntCore x h.left h.right + +@[simp] def Scalar.check_bounds (ty : ScalarTy) (x : Int) : Bool := + (Scalar.cMin ty ≤ x || Scalar.min ty ≤ x) ∧ (x ≤ Scalar.cMax ty || x ≤ Scalar.max ty) + +theorem Scalar.check_bounds_prop {ty : ScalarTy} {x : Int} (h: Scalar.check_bounds ty x) : + Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty := by + simp at * + have ⟨ hmin, hmax ⟩ := h + have hbmin := Scalar.cMin_bound ty + have hbmax := Scalar.cMax_bound ty + cases hmin <;> cases hmax <;> apply And.intro <;> linarith + +-- Further thoughts: look at what has been done here: +-- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/Fin/Basic.lean +-- and +-- https://github.com/leanprover-community/mathlib4/blob/master/Mathlib/Data/UInt.lean +-- which both contain a fair amount of reasoning already! +def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := + if h:Scalar.check_bounds ty x then + -- If we do: + -- ``` + -- let ⟨ hmin, hmax ⟩ := (Scalar.check_bounds_prop h) + -- Scalar.ofIntCore x hmin hmax + -- ``` + -- then normalization blocks (for instance, some proofs which use reflexivity fail). + -- However, the version below doesn't block reduction (TODO: investigate): + return Scalar.ofInt x (Scalar.check_bounds_prop h) + else fail integerOverflow + +def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) + +def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero + +-- Our custom remainder operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_rem (x y : Int) : Int := + if 0 ≤ x then |x| % |y| + else - (|x| % |y|) + +-- Our custom division operation, which satisfies the semantics of Rust +-- TODO: is there a better way? +def scalar_div (x y : Int) : Int := + if 0 ≤ x && 0 ≤ y then |x| / |y| + else if 0 ≤ x && y < 0 then - (|x| / |y|) + else if x < 0 && 0 ≤ y then - (|x| / |y|) + else |x| / |y| + +-- Checking that the remainder operation is correct +#assert scalar_rem 1 2 = 1 +#assert scalar_rem (-1) 2 = -1 +#assert scalar_rem 1 (-2) = 1 +#assert scalar_rem (-1) (-2) = -1 +#assert scalar_rem 7 3 = (1:Int) +#assert scalar_rem (-7) 3 = -1 +#assert scalar_rem 7 (-3) = 1 +#assert scalar_rem (-7) (-3) = -1 + +-- Checking that the division operation is correct +#assert scalar_div 3 2 = 1 +#assert scalar_div (-3) 2 = -1 +#assert scalar_div 3 (-2) = -1 +#assert scalar_div (-3) (-2) = 1 +#assert scalar_div 7 3 = 2 +#assert scalar_div (-7) 3 = -2 +#assert scalar_div 7 (-3) = -2 +#assert scalar_div (-7) (-3) = 2 + +def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero + +def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val + y.val) + +def Scalar.sub {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val - y.val) + +def Scalar.mul {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + Scalar.tryMk ty (x.val * y.val) + +-- TODO: instances of +, -, * etc. for scalars + +-- Cast an integer from a [src_ty] to a [tgt_ty] +-- TODO: check the semantics of casts in Rust +def Scalar.cast {src_ty : ScalarTy} (tgt_ty : ScalarTy) (x : Scalar src_ty) : Result (Scalar tgt_ty) := + Scalar.tryMk tgt_ty x.val + +-- The scalar types +-- We declare the definitions as reducible so that Lean can unfold them (useful +-- for type class resolution for instance). +@[reducible] def Isize := Scalar .Isize +@[reducible] def I8 := Scalar .I8 +@[reducible] def I16 := Scalar .I16 +@[reducible] def I32 := Scalar .I32 +@[reducible] def I64 := Scalar .I64 +@[reducible] def I128 := Scalar .I128 +@[reducible] def Usize := Scalar .Usize +@[reducible] def U8 := Scalar .U8 +@[reducible] def U16 := Scalar .U16 +@[reducible] def U32 := Scalar .U32 +@[reducible] def U64 := Scalar .U64 +@[reducible] def U128 := Scalar .U128 + +-- TODO: below: not sure this is the best way. +-- Should we rather overload operations like +, -, etc.? +-- Also, it is possible to automate the generation of those definitions +-- with macros (but would it be a good idea? It would be less easy to +-- read the file, which is not supposed to change a lot) + +-- Negation + +/-- +Remark: there is no heterogeneous negation in the Lean prelude: we thus introduce +one here. + +The notation typeclass for heterogeneous addition. +This enables the notation `- a : β` where `a : α`. +-/ +class HNeg (α : Type u) (β : outParam (Type v)) where + /-- `- a` computes the negation of `a`. + The meaning of this notation is type-dependent. -/ + hNeg : α → β + +prefix:75 "-" => HNeg.hNeg + +instance : HNeg Isize (Result Isize) where hNeg x := Scalar.neg x +instance : HNeg I8 (Result I8) where hNeg x := Scalar.neg x +instance : HNeg I16 (Result I16) where hNeg x := Scalar.neg x +instance : HNeg I32 (Result I32) where hNeg x := Scalar.neg x +instance : HNeg I64 (Result I64) where hNeg x := Scalar.neg x +instance : HNeg I128 (Result I128) where hNeg x := Scalar.neg x + +-- Addition +instance {ty} : HAdd (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hAdd x y := Scalar.add x y + +-- Substraction +instance {ty} : HSub (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hSub x y := Scalar.sub x y + +-- Multiplication +instance {ty} : HMul (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hMul x y := Scalar.mul x y + +-- Division +instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hDiv x y := Scalar.div x y + +-- Remainder +instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where + hMod x y := Scalar.rem x y + +-- ofIntCore +-- TODO: typeclass? +def Isize.ofIntCore := @Scalar.ofIntCore .Isize +def I8.ofIntCore := @Scalar.ofIntCore .I8 +def I16.ofIntCore := @Scalar.ofIntCore .I16 +def I32.ofIntCore := @Scalar.ofIntCore .I32 +def I64.ofIntCore := @Scalar.ofIntCore .I64 +def I128.ofIntCore := @Scalar.ofIntCore .I128 +def Usize.ofIntCore := @Scalar.ofIntCore .Usize +def U8.ofIntCore := @Scalar.ofIntCore .U8 +def U16.ofIntCore := @Scalar.ofIntCore .U16 +def U32.ofIntCore := @Scalar.ofIntCore .U32 +def U64.ofIntCore := @Scalar.ofIntCore .U64 +def U128.ofIntCore := @Scalar.ofIntCore .U128 + +-- ofInt +-- TODO: typeclass? +def Isize.ofInt := @Scalar.ofInt .Isize +def I8.ofInt := @Scalar.ofInt .I8 +def I16.ofInt := @Scalar.ofInt .I16 +def I32.ofInt := @Scalar.ofInt .I32 +def I64.ofInt := @Scalar.ofInt .I64 +def I128.ofInt := @Scalar.ofInt .I128 +def Usize.ofInt := @Scalar.ofInt .Usize +def U8.ofInt := @Scalar.ofInt .U8 +def U16.ofInt := @Scalar.ofInt .U16 +def U32.ofInt := @Scalar.ofInt .U32 +def U64.ofInt := @Scalar.ofInt .U64 +def U128.ofInt := @Scalar.ofInt .U128 + +-- Comparisons +instance {ty} : LT (Scalar ty) where + lt a b := LT.lt a.val b.val + +instance {ty} : LE (Scalar ty) where le a b := LE.le a.val b.val + +instance Scalar.decLt {ty} (a b : Scalar ty) : Decidable (LT.lt a b) := Int.decLt .. +instance Scalar.decLe {ty} (a b : Scalar ty) : Decidable (LE.le a b) := Int.decLe .. + +theorem Scalar.eq_of_val_eq {ty} : ∀ {i j : Scalar ty}, Eq i.val j.val → Eq i j + | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl + +theorem Scalar.val_eq_of_eq {ty} {i j : Scalar ty} (h : Eq i j) : Eq i.val j.val := + h ▸ rfl + +theorem Scalar.ne_of_val_ne {ty} {i j : Scalar ty} (h : Not (Eq i.val j.val)) : Not (Eq i j) := + fun h' => absurd (val_eq_of_eq h') h + +instance (ty : ScalarTy) : DecidableEq (Scalar ty) := + fun i j => + match decEq i.val j.val with + | isTrue h => isTrue (Scalar.eq_of_val_eq h) + | isFalse h => isFalse (Scalar.ne_of_val_ne h) + +/- Remark: we can't write the following instance because of restrictions about + the type class parameters (`ty` doesn't appear in the return type, which is + forbidden): + + ``` + instance Scalar.cast (ty : ScalarTy) : Coe (Scalar ty) Int where coe := λ v => v.val + ``` + -/ +def Scalar.toInt {ty} (n : Scalar ty) : Int := n.val + +-- -- We now define a type class that subsumes the various machine integer types, so +-- -- as to write a concise definition for scalar_cast, rather than exhaustively +-- -- enumerating all of the possible pairs. We remark that Rust has sane semantics +-- -- and fails if a cast operation would involve a truncation or modulo. + +-- class MachineInteger (t: Type) where +-- size: Nat +-- val: t -> Fin size +-- ofNatCore: (n:Nat) -> LT.lt n size -> t + +-- set_option hygiene false in +-- run_cmd +-- for typeName in [`UInt8, `UInt16, `UInt32, `UInt64, `USize].map Lean.mkIdent do +-- Lean.Elab.Command.elabCommand (← `( +-- namespace $typeName +-- instance: MachineInteger $typeName where +-- size := size +-- val := val +-- ofNatCore := ofNatCore +-- end $typeName +-- )) + +-- -- Aeneas only instantiates the destination type (`src` is implicit). We rely on +-- -- Lean to infer `src`. + +-- def scalar_cast { src: Type } (dst: Type) [ MachineInteger src ] [ MachineInteger dst ] (x: src): Result dst := +-- if h: MachineInteger.val x < MachineInteger.size dst then +-- .ret (MachineInteger.ofNatCore (MachineInteger.val x).val h) +-- else +-- .fail integerOverflow + +end Primitives diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean new file mode 100644 index 00000000..7851a232 --- /dev/null +++ b/backends/lean/Base/Primitives/Vec.lean @@ -0,0 +1,113 @@ +import Lean +import Lean.Meta.Tactic.Simp +import Init.Data.List.Basic +import Mathlib.Tactic.RunCmd +import Mathlib.Tactic.Linarith +import Base.IList +import Base.Primitives.Scalar +import Base.Arith + +namespace Primitives + +open Result Error + +------------- +-- VECTORS -- +------------- + +def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } + +-- TODO: do we really need it? It should be with Subtype by default +instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val + +instance (a : Type) : Arith.HasIntProp (Vec a) where + prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize + prop := λ ⟨ _, l ⟩ => l + +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + intro_has_int_prop_instances + simp_all [Scalar.max, Scalar.min] + +example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by + scalar_tac + +def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ + +def Vec.len (α : Type u) (v : Vec α) : Usize := + let ⟨ v, l ⟩ := v + Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l + +def Vec.length {α : Type u} (v : Vec α) : Int := v.val.len + +-- This shouldn't be used +def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () + +-- This is actually the backward function +def Vec.push (α : Type u) (v : Vec α) (x : α) : Result (Vec α) + := + let nlen := List.length v.val + 1 + if h : nlen ≤ U32.max || nlen ≤ Usize.max then + have h : nlen ≤ Usize.max := by + simp [Usize.max] at * + have hm := Usize.refined_max.property + cases h <;> cases hm <;> simp [U32.max, U64.max] at * <;> try linarith + return ⟨ List.concat v.val x, by simp at *; assumption ⟩ + else + fail maximumSizeExceeded + +-- This shouldn't be used +def Vec.insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := + if i.val < List.length v.val then + .ret () + else + .fail arrayOutOfBounds + +-- This is actually the backward function +def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := + if i.val < List.length v.val then + -- TODO: maybe we should redefine a list library which uses integers + -- (instead of natural numbers) + .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ + else + .fail arrayOutOfBounds + +-- TODO: remove +def Vec.index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : + Fin (List.length v.val) := + let j := i.val.toNat + let h: j < List.length v.val := by + have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin + apply heq.mpr + assumption + ⟨j, h⟩ + +def Vec.index (α : Type u) (v: Vec α) (i: Usize): Result α := + match v.val.indexOpt i.val with + | none => fail .arrayOutOfBounds + | some x => ret x + +-- This shouldn't be used +def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := + if i.val < List.length v.val then + .ret () + else + .fail arrayOutOfBounds + +def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize): Result α := + if h: i.val < List.length v.val then + let i := Vec.index_to_fin h + .ret (List.get v.val i) + else + .fail arrayOutOfBounds + +def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := + if h: i.val < List.length v.val then + let i := Vec.index_to_fin h + .ret ⟨ List.set v.val i x, by + have h: List.length v.val ≤ Usize.max := v.property + simp [*] at * + ⟩ + else + .fail arrayOutOfBounds + +end Primitives diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 35a3c25a..af7b426a 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -7,6 +7,7 @@ namespace Progress open Lean Elab Term Meta Tactic open Utils +-- TODO: remove namespace Test open Primitives @@ -199,6 +200,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do elab "progress" args:progressArgs : tactic => evalProgress args +-- TODO: remove namespace Test open Primitives -- cgit v1.2.3 From 2fa3cb8ee04dd7ff4184e3e1000fdc025abc50a4 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 17 Jul 2023 23:37:48 +0200 Subject: Start proving theorems for primitive definitions --- backends/lean/Base/Diverge/Base.lean | 3 +- backends/lean/Base/IList/IList.lean | 66 ++++++++++++++++++----- backends/lean/Base/Primitives/Scalar.lean | 1 + backends/lean/Base/Primitives/Vec.lean | 89 +++++++++++++++++++------------ backends/lean/Base/Progress/Base.lean | 3 +- backends/lean/Base/Progress/Progress.lean | 4 ++ 6 files changed, 116 insertions(+), 50 deletions(-) diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 0a9ea4c4..4ff1d923 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -3,8 +3,7 @@ import Lean.Meta.Tactic.Simp import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith - -import Base.Primitives +import Base.Primitives.Base /- TODO: this is very useful, but is there more? -/ set_option profiler true diff --git a/backends/lean/Base/IList/IList.lean b/backends/lean/Base/IList/IList.lean index 2a335cac..ddb10236 100644 --- a/backends/lean/Base/IList/IList.lean +++ b/backends/lean/Base/IList/IList.lean @@ -11,12 +11,27 @@ def len (ls : List α) : Int := | [] => 0 | _ :: tl => 1 + len tl +@[simp] theorem len_nil : len ([] : List α) = 0 := by simp [len] +@[simp] theorem len_cons : len ((x :: tl) : List α) = 1 + len tl := by simp [len] + +theorem len_pos : 0 ≤ (ls : List α).len := by + induction ls <;> simp [*] + linarith + +instance (a : Type u) : Arith.HasIntProp (List a) where + prop_ty := λ ls => 0 ≤ ls.len + prop := λ ls => ls.len_pos + -- Remark: if i < 0, then the result is none def indexOpt (ls : List α) (i : Int) : Option α := match ls with | [] => none | hd :: tl => if i = 0 then some hd else indexOpt tl (i - 1) +@[simp] theorem indexOpt_nil : indexOpt ([] : List α) i = none := by simp [indexOpt] +@[simp] theorem indexOpt_zero_cons : indexOpt ((x :: tl) : List α) 0 = some x := by simp [indexOpt] +@[simp] theorem indexOpt_nzero_cons (hne : i ≠ 0) : indexOpt ((x :: tl) : List α) i = indexOpt tl (i - 1) := by simp [*, indexOpt] + -- Remark: if i < 0, then the result is the defaul element def index [Inhabited α] (ls : List α) (i : Int) : α := match ls with @@ -24,6 +39,43 @@ def index [Inhabited α] (ls : List α) (i : Int) : α := | x :: tl => if i = 0 then x else index tl (i - 1) +@[simp] theorem index_zero_cons [Inhabited α] : index ((x :: tl) : List α) 0 = x := by simp [index] +@[simp] theorem index_nzero_cons [Inhabited α] (hne : i ≠ 0) : index ((x :: tl) : List α) i = index tl (i - 1) := by simp [*, index] + +theorem indexOpt_bounds (ls : List α) (i : Int) : + ls.indexOpt i = none ↔ i < 0 ∨ ls.len ≤ i := + match ls with + | [] => + have : ¬ (i < 0) → 0 ≤ i := by intro; linarith -- TODO: simplify (we could boost int_tac) + by simp; tauto + | _ :: tl => + have := indexOpt_bounds tl (i - 1) + if h: i = 0 then + by + simp [*]; + -- TODO: int_tac/scalar_tac should also explore the goal! + have := tl.len_pos + linarith + else by + simp [*] + constructor <;> intros <;> + -- TODO: tactic to split all disjunctions + rename_i hor <;> cases hor <;> + first | left; int_tac | right; int_tac + +theorem indexOpt_eq_index [Inhabited α] (ls : List α) (i : Int) : + 0 ≤ i → + i < ls.len → + ls.indexOpt i = some (ls.index i) := + match ls with + | [] => by simp; intros; linarith + | hd :: tl => + if h: i = 0 then + by simp [*] + else + have hi := indexOpt_eq_index tl (i - 1) + by simp [*]; intros; apply hi <;> int_tac + -- Remark: the list is unchanged if the index is not in bounds (in particular -- if it is < 0) def update (ls : List α) (i : Int) (y : α) : List α := @@ -42,12 +94,6 @@ section Lemmas variable {α : Type u} -@[simp] theorem len_nil : len ([] : List α) = 0 := by simp [len] -@[simp] theorem len_cons : len ((x :: tl) : List α) = 1 + len tl := by simp [len] - -@[simp] theorem index_zero_cons [Inhabited α] : index ((x :: tl) : List α) 0 = x := by simp [index] -@[simp] theorem index_nzero_cons [Inhabited α] (hne : i ≠ 0) : index ((x :: tl) : List α) i = index tl (i - 1) := by simp [*, index] - @[simp] theorem update_nil : update ([] : List α) i y = [] := by simp [update] @[simp] theorem update_zero_cons : update ((x :: tl) : List α) 0 y = y :: tl := by simp [update] @[simp] theorem update_nzero_cons (hne : i ≠ 0) : update ((x :: tl) : List α) i y = x :: update tl (i - 1) y := by simp [*, update] @@ -81,14 +127,6 @@ theorem len_update (ls : List α) (i : Int) (x : α) : (ls.update i x).len = ls. simp [len_eq_length] -theorem len_pos : 0 ≤ (ls : List α).len := by - induction ls <;> simp [*] - linarith - -instance (a : Type u) : Arith.HasIntProp (List a) where - prop_ty := λ ls => 0 ≤ ls.len - prop := λ ls => ls.len_pos - theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by revert l1' diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean index 241dfa07..3f88caa2 100644 --- a/backends/lean/Base/Primitives/Scalar.lean +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -2,6 +2,7 @@ import Lean import Lean.Meta.Tactic.Simp import Mathlib.Tactic.Linarith import Base.Primitives.Base +import Base.Diverge.Base namespace Primitives diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index 7851a232..4ecfa28f 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -6,6 +6,7 @@ import Mathlib.Tactic.Linarith import Base.IList import Base.Primitives.Scalar import Base.Arith +import Base.Progress.Base namespace Primitives @@ -56,58 +57,80 @@ def Vec.push (α : Type u) (v : Vec α) (x : α) : Result (Vec α) fail maximumSizeExceeded -- This shouldn't be used -def Vec.insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := - if i.val < List.length v.val then +def Vec.insert_fwd (α : Type u) (v: Vec α) (i: Usize) (_: α) : Result Unit := + if i.val < v.length then .ret () else .fail arrayOutOfBounds -- This is actually the backward function -def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if i.val < List.length v.val then - -- TODO: maybe we should redefine a list library which uses integers - -- (instead of natural numbers) +def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Vec α) := + if i.val < v.length then .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ else .fail arrayOutOfBounds --- TODO: remove -def Vec.index_to_fin {α : Type u} {v: Vec α} {i: Usize} (h : i.val < List.length v.val) : - Fin (List.length v.val) := - let j := i.val.toNat - let h: j < List.length v.val := by - have heq := @Int.toNat_lt (List.length v.val) i.val i.hmin - apply heq.mpr - assumption - ⟨j, h⟩ - -def Vec.index (α : Type u) (v: Vec α) (i: Usize): Result α := +@[pspec] +theorem Vec.insert_spec {α : Type u} (v: Vec α) (i: Usize) (x: α) : + i.val < v.length → + ∃ nv, v.insert α i x = ret nv ∧ nv.val = v.val.update i.val x := by + intro h + simp [insert, *] + +def Vec.index (α : Type u) (v: Vec α) (i: Usize) : Result α := match v.val.indexOpt i.val with | none => fail .arrayOutOfBounds | some x => ret x +@[pspec] +theorem Vec.index_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : + i.val < v.length → + v.index α i = ret (v.val.index i.val) := by + intro + simp only [index] + -- TODO: dependent rewrite + have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp[length] at *; simp [*]) + simp only [*] + -- This shouldn't be used -def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α): Result Unit := +def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α) : Result Unit := if i.val < List.length v.val then .ret () else .fail arrayOutOfBounds -def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize): Result α := - if h: i.val < List.length v.val then - let i := Vec.index_to_fin h - .ret (List.get v.val i) - else - .fail arrayOutOfBounds +def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize) : Result α := + match v.val.indexOpt i.val with + | none => fail .arrayOutOfBounds + | some x => ret x -def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α): Result (Vec α) := - if h: i.val < List.length v.val then - let i := Vec.index_to_fin h - .ret ⟨ List.set v.val i x, by - have h: List.length v.val ≤ Usize.max := v.property - simp [*] at * - ⟩ - else - .fail arrayOutOfBounds +@[pspec] +theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : + i.val < v.length → + v.index_mut α i = ret (v.val.index i.val) := by + intro + simp only [index_mut] + -- TODO: dependent rewrite + have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp[length] at *; simp [*]) + simp only [*] + +def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Vec α) := + match v.val.indexOpt i.val with + | none => fail .arrayOutOfBounds + | some _ => + .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ + +@[pspec] +theorem Vec.index_mut_back_spec {α : Type u} (v: Vec α) (i: Usize) (x : α) : + i.val < v.length → + ∃ nv, v.index_mut_back α i x = ret nv ∧ + nv.val = v.val.update i.val x + := by + intro + simp only [index_mut_back] + have h := List.indexOpt_bounds v.val i.val + split + . simp_all [length]; cases h <;> scalar_tac + . simp_all end Primitives diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index a288d889..00b0a478 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -1,6 +1,7 @@ import Lean +import Std.Lean.HashSet import Base.Utils -import Base.Primitives +import Base.Primitives.Base namespace Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index af7b426a..001967e5 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -7,6 +7,7 @@ namespace Progress open Lean Elab Term Meta Tactic open Utils +/- -- TODO: remove namespace Test open Primitives @@ -20,6 +21,7 @@ namespace Test #eval pspecAttr.find? ``Primitives.Vec.index end Test +-/ inductive TheoremOrLocal where | Theorem (thName : Name) @@ -200,6 +202,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do elab "progress" args:progressArgs : tactic => evalProgress args +/- -- TODO: remove namespace Test open Primitives @@ -215,5 +218,6 @@ namespace Test set_option trace.Progress false end Test +-/ end Progress -- cgit v1.2.3 From aaa2fdfd104f7010ebaf2977a22280716ac15d13 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 17 Jul 2023 23:42:25 +0200 Subject: Make minor modifications --- tests/lean/Hashmap/Properties.lean | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index ca1f29c4..1db39422 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -3,7 +3,6 @@ import Hashmap.Funs open Primitives open Result - namespace List theorem index_ne @@ -43,29 +42,6 @@ theorem index_eq simp at * apply index_eq <;> scalar_tac -end List - - -namespace Primitives - -@[pspec] -theorem Vec.index_mut_spec - {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) (h: i.val < v.val.len) : - ∃ x, - v.index_mut α i = ret x ∧ x = v.val.index i.val - := by sorry - -@[pspec] -theorem Vec.index_mut_back_spec - {α : Type u} (v: Vec α) (i: Usize) (x:α) : - i.val < v.val.len → ∃ nv, - v.index_mut_back α i x = ret nv ∧ nv.val = v.val.update i.val x - := by sorry - -end Primitives - -namespace List - def allP {α : Type u} (l : List α) (p: α → Prop) : Prop := foldr (fun a r => p a ∧ r) True l @@ -78,7 +54,6 @@ theorem allP_cons {α : Type u} (hd: α) (tl : List α) (p: α → Prop) : allP (hd :: tl) p ↔ p hd ∧ allP tl p := by simp [allP, foldr] - def pairwise_rel {α : Type u} (rel : α → α → Prop) (l: List α) : Prop := match l with -- cgit v1.2.3 From e07177ee2de3fd1346ab6b1fc09aefbcb0e24459 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 18 Jul 2023 12:22:59 +0200 Subject: Improve progress --- backends/lean/Base/Progress/Base.lean | 11 ++++++++--- backends/lean/Base/Progress/Progress.lean | 11 +++++++++-- backends/lean/Base/Utils.lean | 4 ++++ tests/lean/Hashmap/Properties.lean | 24 +++++++++++------------- 4 files changed, 32 insertions(+), 18 deletions(-) diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 00b0a478..7eace667 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -58,10 +58,10 @@ section Methods def withPSpec [Inhabited (m a)] [Nonempty (m a)] (th : Expr) (k : PSpecDesc → m a) (sanityChecks : Bool := false) : m a := do - trace[Progress] "Theorem: {th}" + trace[Progress] "Proposition: {th}" -- Dive into the quantified variables and the assumptions forallTelescope th fun fvars th => do - trace[Progress] "All arguments: {fvars}" + trace[Progress] "Universally quantified arguments and assumptions: {fvars}" /- -- Filter the argumens which are not propositions let rec getFirstPropIdx (i : Nat) : MetaM Nat := do if i ≥ fargs.size then pure i @@ -83,12 +83,16 @@ section Methods -- Dive into the existentials existsTelescope th fun evars th => do trace[Progress] "Existentials: {evars}" + trace[Progress] "Proposition after stripping the quantifiers: {th}" -- Take the first conjunct let (th, post) ← optSplitConj th + trace[Progress] "After splitting the conjunction:\n- eq: {th}\n- post: {post}" -- Destruct the equality let (th, ret) ← destEq th + trace[Progress] "After splitting the equality:\n- lhs: {th}\n- rhs: {ret}" -- Destruct the application to get the name - th.withApp fun f args => do + th.consumeMData.withApp fun f args => do + trace[Progress] "After stripping the arguments:\n- f: {f}\n- args: {args}" if ¬ f.isConst then throwError "Not a constant: {f}" -- Compute the set of universally quantified variables which appear in the function arguments let allArgsFVars ← args.foldlM (fun hs arg => getFVarIds arg hs) HashSet.empty @@ -114,6 +118,7 @@ section Methods post := post } k thDesc + end Methods diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 001967e5..ace92f4f 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -55,14 +55,20 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) let thDecl := env.constants.find! thName pure thDecl.type | .Local asmDecl => pure asmDecl.type + trace[Progress] "theorem/assumption type: {thTy}" -- TODO: the tactic fails if we uncomment withNewMCtxDepth -- withNewMCtxDepth do let (mvars, binders, thExBody) ← forallMetaTelescope thTy + trace[Progress] "After stripping foralls: {thExBody}" -- Introduce the existentially quantified variables and the post-condition -- in the context let thBody ← existsTelescope thExBody fun _evars thBody => do + trace[Progress] "After stripping existentials: {thBody}" + let (thBody, _) ← optSplitConj thBody + trace[Progress] "After splitting the conjunction: {thBody}" let (thBody, _) ← destEq thBody + trace[Progress] "After splitting equality: {thBody}" -- There shouldn't be any existential variables in thBody pure thBody -- Match the body with the target @@ -152,6 +158,7 @@ def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : Tac -- Retrieve the goal let mgoal ← Tactic.getMainGoal let goalTy ← mgoal.getType + trace[Progress] "goal: {goalTy}" -- Dive into the goal to lookup the theorem let (fName, fLevels, args) ← do withPSpec goalTy fun desc => @@ -188,7 +195,7 @@ syntax progressArgs := ("as" " ⟨ " (ident)+ " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw -- Process the arguments to retrieve the identifiers to use - trace[Progress] "Progressing arguments: {args}" + trace[Progress] "Progress arguments: {args}" let args := args.getArgs let ids := if args.size > 0 then @@ -196,7 +203,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := (args.get! 2).getArgs args.map Syntax.getId else #[] - trace[Progress] "Ids: {ids}" + trace[Progress] "User-provided ids: {ids}" progressAsmsOrLookupTheorem ids (firstTac [assumptionTac, Arith.scalarTac]) elab "progress" args:progressArgs : tactic => diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 599c3a9f..9cd0db23 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -43,6 +43,10 @@ namespace List end List +-- TODO: move? +@[simp] +theorem neq_imp {α : Type u} {x y : α} (h : ¬ x = y) : ¬ y = x := by intro; simp_all + namespace Lean namespace LocalContext diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 1db39422..ee22bebd 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -105,6 +105,8 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : simp [h] else by + -- TODO: use progress: detect that this is a recursive call, or give + -- the possibility of specifying an identifier have ⟨ b, hi ⟩ := insert_in_list_spec key value tl exists b simp [insert_in_list, List.lookup] @@ -112,13 +114,12 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : simp [h] simp [insert_in_list] at hi exact hi - -/-- + @[pspec] theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ - (b = (List.lookup ls.v key = none)) + (b ↔ (List.lookup ls.v key = none)) := by induction ls case Nil => simp [insert_in_list, insert_in_list_loop, List.lookup] @@ -130,11 +131,12 @@ theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) simp [h] else conv => - rhs; ext; arg 1; simp [h] -- TODO: Simplify - simp [insert_in_list] at ih; - progress -- TODO: Does not work ---/ - + rhs; ext; left; simp [h] -- TODO: Simplify + simp only [insert_in_list] at ih; + -- TODO: give the possibility of using underscores + progress as ⟨ b h ⟩ + simp [*] + @[pspec] theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List α) : ∃ l1, @@ -150,8 +152,7 @@ theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List rw [insert_in_list_loop_back] simp [h, List.lookup] intro k1 h1 - have h2 : ¬(key = k1) := by tauto -- TODO: Why is the order of args in eq swapped - simp [h2] + simp [*] else by simp [insert_in_list_back, List.lookup] @@ -159,12 +160,9 @@ theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List simp [h, List.lookup] have ⟨tl0 , _, _ ⟩ := insert_in_list_back_spec key value tl -- TODO: Use progress simp [insert_in_list_back] at * - simp [*] - have : ¬ (key = k) := by tauto simp [List.lookup, *] simp (config := {contextual := true}) [*] end HashMap --- def distinct_keys {α : Type u} end hashmap -- cgit v1.2.3 From 0f430c055c3a531ceab83635adc5df92f0015c6e Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 18 Jul 2023 16:55:27 +0200 Subject: Make modifications to Vec.lean --- backends/lean/Base/Primitives/Vec.lean | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index 4ecfa28f..be3a0e5b 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -38,7 +38,8 @@ def Vec.len (α : Type u) (v : Vec α) : Usize := let ⟨ v, l ⟩ := v Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l -def Vec.length {α : Type u} (v : Vec α) : Int := v.val.len +@[simp] +abbrev Vec.length {α : Type u} (v : Vec α) : Int := v.val.len -- This shouldn't be used def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () @@ -89,7 +90,7 @@ theorem Vec.index_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : intro simp only [index] -- TODO: dependent rewrite - have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp[length] at *; simp [*]) + have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) simp only [*] -- This shouldn't be used @@ -111,13 +112,14 @@ theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : intro simp only [index_mut] -- TODO: dependent rewrite - have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp[length] at *; simp [*]) + have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) simp only [*] def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Vec α) := match v.val.indexOpt i.val with | none => fail .arrayOutOfBounds | some _ => + -- TODO: int_tac: introduce the refinements in the context? .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ @[pspec] -- cgit v1.2.3 From 0a8211041814b5eafac0b9e2dbcd956957a322b5 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 18 Jul 2023 18:02:03 +0200 Subject: Move an arithmetic lemma --- backends/lean/Base/Arith/Base.lean | 6 ++++++ backends/lean/Base/Diverge/Base.lean | 14 ++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/backends/lean/Base/Arith/Base.lean b/backends/lean/Base/Arith/Base.lean index a6e59b74..e008f7b9 100644 --- a/backends/lean/Base/Arith/Base.lean +++ b/backends/lean/Base/Arith/Base.lean @@ -28,6 +28,12 @@ theorem ne_is_lt_or_gt {x y : Int} (hne : x ≠ y) : x < y ∨ x > y := by | .inl _ => left; linarith | .inr _ => right; linarith +-- TODO: move? +theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by + -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... + simp [Nat.add_one_le_iff] + simp [Nat.lt_iff_le_and_ne] + simp_all /- Induction over positive integers -/ -- TODO: move diff --git a/backends/lean/Base/Diverge/Base.lean b/backends/lean/Base/Diverge/Base.lean index 4ff1d923..1d548389 100644 --- a/backends/lean/Base/Diverge/Base.lean +++ b/backends/lean/Base/Diverge/Base.lean @@ -4,6 +4,7 @@ import Init.Data.List.Basic import Mathlib.Tactic.RunCmd import Mathlib.Tactic.Linarith import Base.Primitives.Base +import Base.Arith.Base /- TODO: this is very useful, but is there more? -/ set_option profiler true @@ -537,23 +538,16 @@ namespace FixI let j: Fin tys1.length := ⟨ j, jLt ⟩ Eq.mp (by simp) (get_fun tl j) - -- TODO: move - theorem add_one_le_iff_le_ne (n m : Nat) (h1 : m ≤ n) (h2 : m ≠ n) : m + 1 ≤ n := by - -- Damn, those proofs on natural numbers are hard - I wish Omega was in mathlib4... - simp [Nat.add_one_le_iff] - simp [Nat.lt_iff_le_and_ne] - simp_all - def for_all_fin_aux {n : Nat} (f : Fin n → Prop) (m : Nat) (h : m ≤ n) : Prop := if heq: m = n then True else f ⟨ m, by simp_all [Nat.lt_iff_le_and_ne] ⟩ ∧ - for_all_fin_aux f (m + 1) (by simp_all [add_one_le_iff_le_ne]) + for_all_fin_aux f (m + 1) (by simp_all [Arith.add_one_le_iff_le_ne]) termination_by for_all_fin_aux n _ m h => n - m decreasing_by simp_wf apply Nat.sub_add_lt_sub <;> simp - simp_all [add_one_le_iff_le_ne] + simp_all [Arith.add_one_le_iff_le_ne] def for_all_fin {n : Nat} (f : Fin n → Prop) := for_all_fin_aux f 0 (by simp) @@ -603,7 +597,7 @@ namespace FixI apply hi <;> simp_all . unfold for_all_fin_aux at hf simp_all - . simp_all [add_one_le_iff_le_ne] + . simp_all [Arith.add_one_le_iff_le_ne] -- TODO: this is not necessary anymore theorem for_all_fin_imp_forall (n : Nat) (f : Fin n → Prop) : -- cgit v1.2.3 From 204742bf2449c88abaea8ebd284c55d98b43488a Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 14:48:08 +0200 Subject: Improve progress --- backends/lean/Base/Arith/Int.lean | 8 --- backends/lean/Base/Progress/Progress.lean | 115 +++++++++++++++++++++--------- backends/lean/Base/Utils.lean | 19 +++++ tests/lean/Hashmap/Properties.lean | 34 ++++++++- 4 files changed, 131 insertions(+), 45 deletions(-) diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index 5f00ab52..ac011998 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -32,14 +32,6 @@ instance (x y : Int) : PropHasImp (¬ x = y) where open Lean Lean.Elab Lean.Meta --- Small utility: print all the declarations in the context -elab "print_all_decls" : tactic => do - let ctx ← Lean.MonadLCtx.getLCtx - for decl in ← ctx.getDecls do - let ty ← Lean.Meta.inferType decl.toExpr - logInfo m!"{decl.toExpr} : {ty}" - pure () - -- Explore a term by decomposing the applications (we explore the applied -- functions and their arguments, but ignore lambdas, forall, etc. - -- should we go inside?). diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index ace92f4f..3b0248fe 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -55,7 +55,7 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) let thDecl := env.constants.find! thName pure thDecl.type | .Local asmDecl => pure asmDecl.type - trace[Progress] "theorem/assumption type: {thTy}" + trace[Progress] "Looked up theorem/assumption type: {thTy}" -- TODO: the tactic fails if we uncomment withNewMCtxDepth -- withNewMCtxDepth do let (mvars, binders, thExBody) ← forallMetaTelescope thTy @@ -84,7 +84,7 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) let th ← do match th with | .Theorem thName => mkAppOptM thName (mvars.map some) - | .Local decl => mkAppOptM' (mkFVar decl.fvarId) (mvars.map some) + | .Local decl => mkAppOptM' (mkFVar decl.fvarId) (mvars.map some) let asmName ← mkFreshUserName `h let thTy ← inferType th let thAsm ← Utils.addDeclTac asmName th thTy (asLet := false) @@ -153,7 +153,7 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) pure .Ok -- The array of ids are identifiers to use when introducing fresh variables -def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do +def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do -- Retrieve the goal let mgoal ← Tactic.getMainGoal @@ -167,44 +167,89 @@ def progressAsmsOrLookupTheorem (ids : Array Name) (asmTac : TacticM Unit) : Tac -- TODO: this should be in the pspec desc let fnExpr := mkAppN (.const fName fLevels) args trace[Progress] "Function: {fName}" - -- Try all the assumptions one by one and if it fails try to lookup a theorem - let ctx ← Lean.MonadLCtx.getLCtx - let decls ← ctx.getDecls - for decl in decls.reverse do - trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" - try - match ← progressWith fnExpr (.Local decl) ids asmTac with + -- If the user provided a theorem/assumption: use it. + -- Otherwise, lookup one. + match withTh with + | some th => do + match ← progressWith fnExpr th ids asmTac with + | .Ok => return () + | .Error msg => throwError msg + | none => + -- Try all the assumptions one by one and if it fails try to lookup a theorem. + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getDecls + for decl in decls.reverse do + trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" + let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + match res with | .Ok => return () | .Error msg => throwError msg - catch _ => continue - -- It failed: try to lookup a theorem - -- TODO: use a list of theorems, and try them one by one? - trace[Progress] "No assumption succeeded: trying to lookup a theorem" - let thName ← do - match ← pspecAttr.find? fName with - | none => throwError "Could not find a pspec theorem for {fName}" - | some thName => pure thName - trace[Progress] "Lookuped up: {thName}" - -- Apply the theorem - match ← progressWith fnExpr (.Theorem thName) ids asmTac with - | .Ok => return () - | .Error msg => throwError msg - -syntax progressArgs := ("as" " ⟨ " (ident)+ " ⟩")? + -- It failed: try to lookup a theorem + -- TODO: use a list of theorems, and try them one by one? + trace[Progress] "No assumption succeeded: trying to lookup a theorem" + let thName ← do + match ← pspecAttr.find? fName with + | none => throwError "Could not find a pspec theorem for {fName}" + | some thName => pure thName + trace[Progress] "Lookuped up theorem: {thName}" + -- Apply the theorem + let res ← do + try + let res ← progressWith fnExpr (.Theorem thName) ids asmTac + pure (some res) + catch _ => none + match res with + | some .Ok => return () + | some (.Error msg) => throwError msg + | none => + -- Try a recursive call - we try the assumptions of kind "auxDecl" + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getAllDecls + let decls := decls.filter (λ decl => match decl.kind with + | .default | .implDetail => false | .auxDecl => true) + for decl in decls.reverse do + trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" + let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + match res with + | .Ok => return () + | .Error msg => throwError msg + -- Nothing worked: failed + throwError "Progress failed" + +syntax progressArgs := ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? +#check Environment +#check ConstMap def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw -- Process the arguments to retrieve the identifiers to use trace[Progress] "Progress arguments: {args}" let args := args.getArgs - let ids := - if args.size > 0 then - let args := (args.get! 0).getArgs - let args := (args.get! 2).getArgs - args.map Syntax.getId - else #[] + let withArg := (args.get! 0).getArgs + let withArg ← do + if withArg.size > 0 then + let id := withArg.get! 1 + trace[Progress] "With arg: {id}" + -- Attempt to lookup a local declaration + match (← getLCtx).findFromUserName? id.getId with + | some decl => do + trace[Progress] "With arg: local decl" + pure (some (.Local decl)) + | none => do + -- Not a local declaration: should be a theorem + trace[Progress] "With arg: theorem" + addCompletionInfo <| CompletionInfo.id id id.getId (danglingDot := false) {} none + let cs ← resolveGlobalConstWithInfos id + match cs with + | [] => throwError "Could not find theorem {id}" + | id :: _ => + pure (some (.Theorem id)) + else pure none + let args := (args.get! 1).getArgs + let args := (args.get! 2).getArgs + let ids := args.map Syntax.getId trace[Progress] "User-provided ids: {ids}" - progressAsmsOrLookupTheorem ids (firstTac [assumptionTac, Arith.scalarTac]) + progressAsmsOrLookupTheorem withArg ids (firstTac [assumptionTac, Arith.scalarTac]) elab "progress" args:progressArgs : tactic => evalProgress args @@ -215,16 +260,16 @@ namespace Test open Primitives set_option trace.Progress true + set_option pp.rawOnError true @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : ∃ (x: α), v.index α i = .ret x := by - progress as ⟨ x ⟩ + progress with vec_index_test as ⟨ x ⟩ simp set_option trace.Progress false -end Test --/ +end Test -/ end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 9cd0db23..acaeb26a 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -142,6 +142,25 @@ private def test2 (x : Nat) : Nat := x print_decl test1 print_decl test2 +#check LocalDecl + +def printDecls (decls : List LocalDecl) : MetaM Unit := do + let decls ← decls.foldrM (λ decl msg => do + pure (m!"\n{decl.toExpr} : {← inferType decl.toExpr}" ++ msg)) m!"" + logInfo m!"# Ctx decls:{decls}" + +-- Small utility: print all the declarations in the context (including the "implementation details") +elab "print_all_ctx_decls" : tactic => do + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getAllDecls + printDecls decls + +-- Small utility: print all declarations in the context +elab "print_ctx_decls" : tactic => do + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getDecls + printDecls decls + -- A map visitor function for expressions (adapted from `AbstractNestedProofs.visit`) -- The continuation takes as parameters: -- - the current depth of the expression (useful for printing/debugging) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index ee22bebd..3b9b960f 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -115,6 +115,37 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : simp [insert_in_list] at hi exact hi +set_option trace.Progress true +@[pspec] +theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) : + ∃ b, + insert_in_list α key value ls = ret b ∧ + (b ↔ List.lookup ls.v key = none) + := match ls with + | .Nil => by simp [insert_in_list, insert_in_list_loop, List.lookup] + | .Cons k v tl => + if h: k = key then -- TODO: The order of k/key matters + by + simp [insert_in_list, List.lookup] + rw [insert_in_list_loop] + simp [h] + else + by + simp only [insert_in_list] + rw [insert_in_list_loop] + conv => rhs; ext; simp [*] + progress as ⟨ b hi ⟩ + + -- TODO: use progress: detect that this is a recursive call, or give + -- the possibility of specifying an identifier + have ⟨ b, hi ⟩ := insert_in_list_spec key value tl + exists b + simp [insert_in_list, List.lookup] + rw [insert_in_list_loop] -- TODO: Using it in simp leads to infinite recursion + simp [h] + simp [insert_in_list] at hi + exact hi + @[pspec] theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, @@ -130,8 +161,7 @@ theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) if h: k = key then simp [h] else - conv => - rhs; ext; left; simp [h] -- TODO: Simplify + conv => rhs; ext; left; simp [h] -- TODO: Simplify simp only [insert_in_list] at ih; -- TODO: give the possibility of using underscores progress as ⟨ b h ⟩ -- cgit v1.2.3 From 753907aafc2502ced0cd8c3f9bc43fb1c4b30e93 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 14:48:36 +0200 Subject: Cleanup a bit --- backends/lean/Base/Progress/Progress.lean | 2 -- 1 file changed, 2 deletions(-) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 3b0248fe..9e2461a2 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -218,8 +218,6 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na syntax progressArgs := ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? -#check Environment -#check ConstMap def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw -- Process the arguments to retrieve the identifiers to use -- cgit v1.2.3 From 985fc7b1c08eaf027ec3a7c1e7ea635f53c00d72 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 14:49:03 +0200 Subject: Cleanup more --- backends/lean/Base/Utils.lean | 3 --- 1 file changed, 3 deletions(-) diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index acaeb26a..8aa76d8e 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -138,12 +138,9 @@ open Lean.Elab.Command private def test1 : Nat := 0 private def test2 (x : Nat) : Nat := x - print_decl test1 print_decl test2 -#check LocalDecl - def printDecls (decls : List LocalDecl) : MetaM Unit := do let decls ← decls.foldrM (λ decl msg => do pure (m!"\n{decl.toExpr} : {← inferType decl.toExpr}" ++ msg)) m!"" -- cgit v1.2.3 From 36258c9ba583f19b5ddcb3b90e6521f9845b8944 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 16:41:22 +0200 Subject: Start implementing support for some type classes for progress --- backends/lean/Base/Progress/Base.lean | 64 ++++++++++++++++++++++++- backends/lean/Base/Progress/Progress.lean | 78 ++++++++++++++++++++++--------- 2 files changed, 117 insertions(+), 25 deletions(-) diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 7eace667..0032c33d 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -121,19 +121,42 @@ section Methods end Methods - def getPSpecFunName (th : Expr) : MetaM Name := withPSpec th (fun d => do pure d.fName) true +def getPSpecClassFunNames (th : Expr) : MetaM (Name × Name) := + withPSpec th (fun d => do + let arg0 := d.args.get! 0 + arg0.withApp fun f _ => do + if ¬ f.isConst then throwError "Not a constant: {f}" + pure (d.fName, f.constName) + ) true + +-- "Regular" pspec attribute structure PSpecAttr where attr : AttributeImpl ext : MapDeclarationExtension Name deriving Inhabited +/- pspec attribute for type classes: we use the name of the type class to + lookup another map. We use the *first* argument of the type class to lookup + into this second map. + + Example: + ======== + We use type classes for addition. For instance, the addition between two + U32 is written (without syntactic sugar) as `HAdd.add (Scalar ) x y`. As a consequence, + we store the theorem through the bindings: HAdd.add → Scalar → ... +-/ +structure PSpecClassAttr where + attr : AttributeImpl + ext : MapDeclarationExtension (NameMap Name) + deriving Inhabited + /- The persistent map from function to pspec theorems. -/ initialize pspecAttr : PSpecAttr ← do let ext ← mkMapDeclarationExtension `pspecMap - let attrImpl := { + let attrImpl : AttributeImpl := { name := `pspec descr := "Marks theorems to use with the `progress` tactic" add := fun thName stx attrKind => do @@ -153,7 +176,44 @@ initialize pspecAttr : PSpecAttr ← do registerBuiltinAttribute attrImpl pure { attr := attrImpl, ext := ext } +/- The persistent map from type classes to pspec theorems -/ +initialize pspecClassAttr : PSpecClassAttr ← do + let ext : MapDeclarationExtension (NameMap Name) ← mkMapDeclarationExtension `pspecClassMap + let attrImpl : AttributeImpl := { + name := `cpspec + descr := "Marks theorems to use for type classes with the `progress` tactic" + add := fun thName stx attrKind => do + Attribute.Builtin.ensureNoArgs stx + -- TODO: use the attribute kind + unless attrKind == AttributeKind.global do + throwError "invalid attribute 'cpspec', must be global" + -- Lookup the theorem + let env ← getEnv + let thDecl := env.constants.find! thName + let (fName, argName) ← MetaM.run' (getPSpecClassFunNames thDecl.type) + trace[Progress] "Registering class spec theorem for ({fName}, {argName})" + -- Update the entry if there is one, add an entry if there is none + let env := + match (ext.getState (← getEnv)).find? fName with + | none => + let m := RBMap.ofList [(argName, thName)] + ext.addEntry env (fName, m) + | some m => + let m := m.insert argName thName + ext.addEntry env (fName, m) + setEnv env + pure () + } + registerBuiltinAttribute attrImpl + pure { attr := attrImpl, ext := ext } + + def PSpecAttr.find? (s : PSpecAttr) (name : Name) : MetaM (Option Name) := do return (s.ext.getState (← getEnv)).find? name +def PSpecClassAttr.find? (s : PSpecClassAttr) (className argName : Name) : MetaM (Option Name) := do + match (s.ext.getState (← getEnv)).find? className with + | none => return none + | some map => return map.find? argName + end Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 9e2461a2..64d1c14a 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -152,6 +152,15 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) -- pure .Ok +-- Small utility: if `args` is not empty, return the name of the app in the first +-- arg, if it is a const. +def getFirstArgAppName (args : Array Expr) : MetaM (Option Name) := do + if args.size = 0 then pure none + else + (args.get! 0).withApp fun f _ => do + if f.isConst then pure (some f.constName) + else pure none + -- The array of ids are identifiers to use when introducing fresh variables def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do @@ -187,34 +196,57 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na -- It failed: try to lookup a theorem -- TODO: use a list of theorems, and try them one by one? trace[Progress] "No assumption succeeded: trying to lookup a theorem" - let thName ← do - match ← pspecAttr.find? fName with - | none => throwError "Could not find a pspec theorem for {fName}" - | some thName => pure thName - trace[Progress] "Lookuped up theorem: {thName}" - -- Apply the theorem - let res ← do - try - let res ← progressWith fnExpr (.Theorem thName) ids asmTac - pure (some res) - catch _ => none + let res ← + match ← pspecAttr.find? fName with + | some thName => + trace[Progress] "Lookuped up theorem: {thName}" + -- Apply the theorem + let res ← do + try + let res ← progressWith fnExpr (.Theorem thName) ids asmTac + pure (some res) + catch _ => none + | none => + trace[Progress] "Could not find a pspec theorem for {fName}" + throwError "TODO" match res with | some .Ok => return () | some (.Error msg) => throwError msg | none => - -- Try a recursive call - we try the assumptions of kind "auxDecl" - let ctx ← Lean.MonadLCtx.getLCtx - let decls ← ctx.getAllDecls - let decls := decls.filter (λ decl => match decl.kind with - | .default | .implDetail => false | .auxDecl => true) - for decl in decls.reverse do - trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + -- It failed: try to lookup a *class* spec theorem + let res ← do + match ← getFirstArgAppName args with + | none => none + | some argName => do + match ← pspecClassAttr.find? fName argName with + | some thName => + trace[Progress] "Lookuped up class theorem: {thName}" + -- Apply the theorem + let res ← do + try + let res ← progressWith fnExpr (.Theorem thName) ids asmTac + pure (some res) + catch _ => none + | none => + trace[Progress] "Could not find a pspec theorem for {fName}" + pure none match res with - | .Ok => return () - | .Error msg => throwError msg - -- Nothing worked: failed - throwError "Progress failed" + | some .Ok => return () + | some (.Error msg) => throwError msg + | none => + -- Try a recursive call - we try the assumptions of kind "auxDecl" + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getAllDecls + let decls := decls.filter (λ decl => match decl.kind with + | .default | .implDetail => false | .auxDecl => true) + for decl in decls.reverse do + trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" + let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + match res with + | .Ok => return () + | .Error msg => throwError msg + -- Nothing worked: failed + throwError "Progress failed" syntax progressArgs := ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? -- cgit v1.2.3 From 3df0b36891975935c3d8035f56389ee6bbcbf251 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 18:13:31 +0200 Subject: Add arithmetic spec lemmas --- backends/lean/Base/Primitives/Scalar.lean | 167 ++++++++++++++++++++++++++++-- 1 file changed, 161 insertions(+), 6 deletions(-) diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean index 3f88caa2..aaa4027f 100644 --- a/backends/lean/Base/Primitives/Scalar.lean +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -3,6 +3,8 @@ import Lean.Meta.Tactic.Simp import Mathlib.Tactic.Linarith import Base.Primitives.Base import Base.Diverge.Base +import Base.Progress.Base +import Base.Arith.Int namespace Primitives @@ -122,6 +124,22 @@ inductive ScalarTy := | U64 | U128 +def ScalarTy.isSigned (ty : ScalarTy) : Bool := + match ty with + | Isize + | I8 + | I16 + | I32 + | I64 + | I128 => true + | Usize + | U8 + | U16 + | U32 + | U64 + | U128 => false + + def Scalar.smin (ty : ScalarTy) : Int := match ty with | .Isize => Isize.smin @@ -289,23 +307,30 @@ def Scalar.tryMk (ty : ScalarTy) (x : Int) : Result (Scalar ty) := def Scalar.neg {ty : ScalarTy} (x : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (- x.val) -def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val / y.val) else fail divisionByZero - -- Our custom remainder operation, which satisfies the semantics of Rust -- TODO: is there a better way? def scalar_rem (x y : Int) : Int := - if 0 ≤ x then |x| % |y| + if 0 ≤ x then x % y else - (|x| % |y|) +@[simp] +def scalar_rem_nonneg {x y : Int} (hx : 0 ≤ x) : scalar_rem x y = x % y := by + intros + simp [*, scalar_rem] + -- Our custom division operation, which satisfies the semantics of Rust -- TODO: is there a better way? def scalar_div (x y : Int) : Int := - if 0 ≤ x && 0 ≤ y then |x| / |y| + if 0 ≤ x && 0 ≤ y then x / y else if 0 ≤ x && y < 0 then - (|x| / |y|) else if x < 0 && 0 ≤ y then - (|x| / |y|) else |x| / |y| +@[simp] +def scalar_div_nonneg {x y : Int} (hx : 0 ≤ x) (hy : 0 ≤ y) : scalar_div x y = x / y := by + intros + simp [*, scalar_div] + -- Checking that the remainder operation is correct #assert scalar_rem 1 2 = 1 #assert scalar_rem (-1) 2 = -1 @@ -326,8 +351,11 @@ def scalar_div (x y : Int) : Int := #assert scalar_div 7 (-3) = -2 #assert scalar_div (-7) (-3) = 2 +def Scalar.div {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := + if y.val != 0 then Scalar.tryMk ty (scalar_div x.val y.val) else fail divisionByZero + def Scalar.rem {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := - if y.val != 0 then Scalar.tryMk ty (x.val % y.val) else fail divisionByZero + if y.val != 0 then Scalar.tryMk ty (scalar_rem x.val y.val) else fail divisionByZero def Scalar.add {ty : ScalarTy} (x : Scalar ty) (y : Scalar ty) : Result (Scalar ty) := Scalar.tryMk ty (x.val + y.val) @@ -410,6 +438,133 @@ instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where hMod x y := Scalar.rem x y +-- TODO: make progress work at a more fine grained level (see `Scalar.add_unsigned_spec`) +@[cpspec] +theorem Scalar.add_spec {ty} {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val + y.val) + (hmax : x.val + y.val ≤ Scalar.max ty) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + simp [HAdd.hAdd, add, Add.add] + simp [tryMk] + split + . simp [pure] + rfl + . tauto + +theorem Scalar.add_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} + (hmax : x.val + y.val ≤ Scalar.max ty) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + have hmin : Scalar.min ty ≤ x.val + y.val := by + have hx := x.hmin + have hy := y.hmin + cases ty <;> simp [min] at * <;> linarith + apply add_spec <;> assumption + +-- TODO: make it finer grained +@[cpspec] +theorem Scalar.sub_spec {ty} {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val - y.val) + (hmax : x.val - y.val ≤ Scalar.max ty) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + simp [HSub.hSub, sub, Sub.sub] + simp [tryMk] + split + . simp [pure] + rfl + . tauto + +theorem Scalar.sub_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + have : x.val - y.val ≤ Scalar.max ty := by + have hx := x.hmin + have hxm := x.hmax + have hy := y.hmin + cases ty <;> simp [min, max] at * <;> linarith + intros + apply sub_spec <;> assumption + +-- TODO: make it finer grained +@[cpspec] +theorem Scalar.mul_spec {ty} {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val * y.val) + (hmax : x.val * y.val ≤ Scalar.max ty) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + simp [HMul.hMul, mul, Mul.mul] + simp [tryMk] + split + . simp [pure] + rfl + . tauto + +theorem Scalar.mul_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} + (hmax : x.val * y.val ≤ Scalar.max ty) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + have : Scalar.min ty ≤ x.val * y.val := by + have hx := x.hmin + have hy := y.hmin + cases ty <;> simp at * <;> apply mul_nonneg hx hy + apply mul_spec <;> assumption + +-- TODO: make it finer grained +@[cpspec] +theorem Scalar.div_spec {ty} {x y : Scalar ty} + (hnz : y.val ≠ 0) + (hmin : Scalar.min ty ≤ scalar_div x.val y.val) + (hmax : scalar_div x.val y.val ≤ Scalar.max ty) : + ∃ z, x / y = ret z ∧ z.val = scalar_div x.val y.val := by + simp [HDiv.hDiv, div, Div.div] + simp [tryMk, *] + simp [pure] + rfl + +theorem Scalar.div_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : Scalar ty} + (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + have h : Scalar.min ty = 0 := by cases ty <;> simp at * + have hx := x.hmin + have hy := y.hmin + simp [h] at hx hy + have hmin : 0 ≤ x.val / y.val := Int.ediv_nonneg hx hy + have hmax : x.val / y.val ≤ Scalar.max ty := by + have := Int.ediv_le_self y.val hx + have := x.hmax + linarith + have hs := @div_spec ty x y hnz + simp [*] at hs + apply hs + +-- TODO: make it finer grained +@[cpspec] +theorem Scalar.rem_spec {ty} {x y : Scalar ty} + (hnz : y.val ≠ 0) + (hmin : Scalar.min ty ≤ scalar_rem x.val y.val) + (hmax : scalar_rem x.val y.val ≤ Scalar.max ty) : + ∃ z, x % y = ret z ∧ z.val = scalar_rem x.val y.val := by + simp [HMod.hMod, rem] + simp [tryMk, *] + simp [pure] + rfl + +theorem Scalar.rem_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : Scalar ty} + (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = scalar_rem x.val y.val := by + have h : Scalar.min ty = 0 := by cases ty <;> simp at * + have hx := x.hmin + have hy := y.hmin + simp [h] at hx hy + have hmin : 0 ≤ x.val % y.val := Int.emod_nonneg x.val hnz + have hmax : x.val % y.val ≤ Scalar.max ty := by + have h := @Int.ediv_emod_unique x.val y.val (x.val % y.val) (x.val / y.val) + simp at h + have : 0 < y.val := by int_tac + simp [*] at h + have := y.hmax + linarith + have hs := @rem_spec ty x y hnz + simp [*] at hs + simp [*] + -- ofIntCore -- TODO: typeclass? def Isize.ofIntCore := @Scalar.ofIntCore .Isize -- cgit v1.2.3 From abee28555eb9f95b1c548cc17b9fe746bc982b56 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 18:50:19 +0200 Subject: Add some utilities for progress --- backends/lean/Base/Progress/Base.lean | 19 +++++++++++++++++++ backends/lean/Base/Progress/Progress.lean | 21 ++++++++++++++++----- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 0032c33d..785b9362 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -211,9 +211,28 @@ initialize pspecClassAttr : PSpecClassAttr ← do def PSpecAttr.find? (s : PSpecAttr) (name : Name) : MetaM (Option Name) := do return (s.ext.getState (← getEnv)).find? name +def PSpecAttr.getState (s : PSpecAttr) : MetaM (NameMap Name) := do + pure (s.ext.getState (← getEnv)) + def PSpecClassAttr.find? (s : PSpecClassAttr) (className argName : Name) : MetaM (Option Name) := do match (s.ext.getState (← getEnv)).find? className with | none => return none | some map => return map.find? argName +def PSpecClassAttr.getState (s : PSpecClassAttr) : MetaM (NameMap (NameMap Name)) := do + pure (s.ext.getState (← getEnv)) + +def showStoredPSpec : MetaM Unit := do + let st ← pspecAttr.getState + let s := st.toList.foldl (fun s (f, th) => f!"{s}\n{f} → {th}") f!"" + IO.println s + +def showStoredPSpecClass : MetaM Unit := do + let st ← pspecClassAttr.getState + let s := st.toList.foldl (fun s (f, m) => + let ms := m.toList.foldl (fun s (f, th) => + f!"{s}\n {f} → {th}") f!"" + f!"{s}\n{f} → [{ms}]") f!"" + IO.println s + end Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 64d1c14a..9c75ee3c 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -208,7 +208,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na catch _ => none | none => trace[Progress] "Could not find a pspec theorem for {fName}" - throwError "TODO" + pure none match res with | some .Ok => return () | some (.Error msg) => throwError msg @@ -228,7 +228,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na pure (some res) catch _ => none | none => - trace[Progress] "Could not find a pspec theorem for {fName}" + trace[Progress] "Could not find a class pspec theorem for ({fName}, {argName})" pure none match res with | some .Ok => return () @@ -287,11 +287,22 @@ elab "progress" args:progressArgs : tactic => /- -- TODO: remove namespace Test - open Primitives + open Primitives Result set_option trace.Progress true - set_option pp.rawOnError true + -- #eval do pspecClassAttr.getState + -- #eval showStoredPSpec + -- #eval showStoredPSpecClass + +/- theorem Scalar.add_spec {ty} {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val + y.val) + (hmax : x.val + y.val ≤ Scalar.max ty) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + progress + simp [*] -/ + +/- @[pspec] theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : ∃ (x: α), v.index α i = .ret x := by @@ -299,7 +310,7 @@ namespace Test simp set_option trace.Progress false - +-/ end Test -/ end Progress -- cgit v1.2.3 From 821b09b14794ebc2fe7b7047fc60fd56fb2cd107 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 19 Jul 2023 19:03:17 +0200 Subject: Fix a small issue with the persistent state of progress --- backends/lean/Base/Progress/Base.lean | 9 +++++++++ backends/lean/Base/Progress/Progress.lean | 9 ++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 785b9362..72438d40 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -153,6 +153,15 @@ structure PSpecClassAttr where ext : MapDeclarationExtension (NameMap Name) deriving Inhabited +-- TODO: the original function doesn't define correctly the `addImportedFn`. Do a PR? +def mkMapDeclarationExtension [Inhabited α] (name : Name := by exact decl_name%) : IO (MapDeclarationExtension α) := + registerSimplePersistentEnvExtension { + name := name, + addImportedFn := fun a => a.foldl (fun s a => a.foldl (fun s (k, v) => s.insert k v) s) RBMap.empty, + addEntryFn := fun s n => s.insert n.1 n.2 , + toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) + } + /- The persistent map from function to pspec theorems. -/ initialize pspecAttr : PSpecAttr ← do let ext ← mkMapDeclarationExtension `pspecMap diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 9c75ee3c..84053150 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -291,16 +291,15 @@ namespace Test set_option trace.Progress true - -- #eval do pspecClassAttr.getState - -- #eval showStoredPSpec - -- #eval showStoredPSpecClass + #eval showStoredPSpec + #eval showStoredPSpecClass -/- theorem Scalar.add_spec {ty} {x y : Scalar ty} + theorem Scalar.add_spec {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by progress - simp [*] -/ + simp [*] /- @[pspec] -- cgit v1.2.3 From 975b7c555cbffef2648a6469b777d1f1760d926d Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 11:22:18 +0200 Subject: Improve progress further --- backends/lean/Base/Progress/Base.lean | 102 +++++++++++++++++++++------ backends/lean/Base/Progress/Progress.lean | 112 +++++++++++++++++------------- 2 files changed, 142 insertions(+), 72 deletions(-) diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 72438d40..3599d866 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -62,24 +62,6 @@ section Methods -- Dive into the quantified variables and the assumptions forallTelescope th fun fvars th => do trace[Progress] "Universally quantified arguments and assumptions: {fvars}" - /- -- Filter the argumens which are not propositions - let rec getFirstPropIdx (i : Nat) : MetaM Nat := do - if i ≥ fargs.size then pure i - else do - let x := fargs.get! i - if ← Meta.isProp (← inferType x) then pure i - else getFirstPropIdx (i + 1) - let i ← getFirstPropIdx 0 - let fvars := fargs.extract 0 i - let hyps := fargs.extract i fargs.size - trace[Progress] "Quantified variables: {fvars}" - trace[Progress] "Assumptions: {hyps}" - -- Sanity check: all hypotheses are propositions (in particular, all the - -- quantified variables are at the beginning) - let hypsAreProp ← hyps.allM fun x => do Meta.isProp (← inferType x) - if ¬ hypsAreProp then - throwError "The theorem doesn't have the proper shape: all the quantified arguments should be at the beginning" - -/ -- Dive into the existentials existsTelescope th fun evars th => do trace[Progress] "Existentials: {evars}" @@ -98,6 +80,8 @@ section Methods let allArgsFVars ← args.foldlM (fun hs arg => getFVarIds arg hs) HashSet.empty -- Sanity check if sanityChecks then + -- All the variables which appear in the inputs given to the function are + -- universally quantified (in particular, they are not *existentially* quantified) let fvarsSet : HashSet FVarId := HashSet.ofArray (fvars.map (fun x => x.fvarId!)) let filtArgsFVars := allArgsFVars.toArray.filter (fun fvar => ¬ fvarsSet.contains fvar) if ¬ filtArgsFVars.isEmpty then @@ -132,6 +116,12 @@ def getPSpecClassFunNames (th : Expr) : MetaM (Name × Name) := pure (d.fName, f.constName) ) true +def getPSpecClassFunNameArg (th : Expr) : MetaM (Name × Expr) := + withPSpec th (fun d => do + let arg0 := d.args.get! 0 + pure (d.fName, arg0) + ) true + -- "Regular" pspec attribute structure PSpecAttr where attr : AttributeImpl @@ -145,14 +135,26 @@ structure PSpecAttr where Example: ======== We use type classes for addition. For instance, the addition between two - U32 is written (without syntactic sugar) as `HAdd.add (Scalar ) x y`. As a consequence, + U32 is written (without syntactic sugar) as `HAdd.add (Scalar ty) x y`. As a consequence, we store the theorem through the bindings: HAdd.add → Scalar → ... + + SH: TODO: this (and `PSpecClassExprAttr`) is a bit ad-hoc. For now it works for the + specs of the scalar operations, which is what I really need, but I'm not sure it + applies well to other situations. A better way would probably to use type classes, but + I couldn't get them to work on those cases. It is worth retrying. -/ structure PSpecClassAttr where attr : AttributeImpl ext : MapDeclarationExtension (NameMap Name) deriving Inhabited +/- Same as `PSpecClassAttr` but we use the full first argument (it works when it + is a constant). -/ +structure PSpecClassExprAttr where + attr : AttributeImpl + ext : MapDeclarationExtension (HashMap Expr Name) + deriving Inhabited + -- TODO: the original function doesn't define correctly the `addImportedFn`. Do a PR? def mkMapDeclarationExtension [Inhabited α] (name : Name := by exact decl_name%) : IO (MapDeclarationExtension α) := registerSimplePersistentEnvExtension { @@ -216,21 +218,69 @@ initialize pspecClassAttr : PSpecClassAttr ← do registerBuiltinAttribute attrImpl pure { attr := attrImpl, ext := ext } +/- The 2nd persistent map from type classes to pspec theorems -/ +initialize pspecClassExprAttr : PSpecClassExprAttr ← do + let ext : MapDeclarationExtension (HashMap Expr Name) ← mkMapDeclarationExtension `pspecClassExprMap + let attrImpl : AttributeImpl := { + name := `cepspec + descr := "Marks theorems to use for type classes with the `progress` tactic" + add := fun thName stx attrKind => do + Attribute.Builtin.ensureNoArgs stx + -- TODO: use the attribute kind + unless attrKind == AttributeKind.global do + throwError "invalid attribute 'cpspec', must be global" + -- Lookup the theorem + let env ← getEnv + let thDecl := env.constants.find! thName + let (fName, arg) ← MetaM.run' (getPSpecClassFunNameArg thDecl.type) + -- Sanity check: no variables appear in the argument + MetaM.run' do + let fvars ← getFVarIds arg + if ¬ fvars.isEmpty then throwError "The first argument ({arg}) contains variables" + -- We store two bindings: + -- - arg to theorem name + -- - reduced arg to theorem name + let rarg ← MetaM.run' (reduce arg) + trace[Progress] "Registering class spec theorem for ({fName}, {arg}) and ({fName}, {rarg})" + -- Update the entry if there is one, add an entry if there is none + let env := + match (ext.getState (← getEnv)).find? fName with + | none => + let m := HashMap.ofList [(arg, thName), (rarg, thName)] + ext.addEntry env (fName, m) + | some m => + let m := m.insert arg thName + let m := m.insert rarg thName + ext.addEntry env (fName, m) + setEnv env + pure () + } + registerBuiltinAttribute attrImpl + pure { attr := attrImpl, ext := ext } + def PSpecAttr.find? (s : PSpecAttr) (name : Name) : MetaM (Option Name) := do return (s.ext.getState (← getEnv)).find? name -def PSpecAttr.getState (s : PSpecAttr) : MetaM (NameMap Name) := do - pure (s.ext.getState (← getEnv)) - def PSpecClassAttr.find? (s : PSpecClassAttr) (className argName : Name) : MetaM (Option Name) := do match (s.ext.getState (← getEnv)).find? className with | none => return none | some map => return map.find? argName +def PSpecClassExprAttr.find? (s : PSpecClassExprAttr) (className : Name) (arg : Expr) : MetaM (Option Name) := do + match (s.ext.getState (← getEnv)).find? className with + | none => return none + | some map => return map.find? arg + +def PSpecAttr.getState (s : PSpecAttr) : MetaM (NameMap Name) := do + pure (s.ext.getState (← getEnv)) + def PSpecClassAttr.getState (s : PSpecClassAttr) : MetaM (NameMap (NameMap Name)) := do pure (s.ext.getState (← getEnv)) +def PSpecClassExprAttr.getState (s : PSpecClassExprAttr) : MetaM (NameMap (HashMap Expr Name)) := do + pure (s.ext.getState (← getEnv)) + def showStoredPSpec : MetaM Unit := do let st ← pspecAttr.getState let s := st.toList.foldl (fun s (f, th) => f!"{s}\n{f} → {th}") f!"" @@ -244,4 +294,12 @@ def showStoredPSpecClass : MetaM Unit := do f!"{s}\n{f} → [{ms}]") f!"" IO.println s +def showStoredPSpecExprClass : MetaM Unit := do + let st ← pspecClassExprAttr.getState + let s := st.toList.foldl (fun s (f, m) => + let ms := m.toList.foldl (fun s (f, th) => + f!"{s}\n {f} → {th}") f!"" + f!"{s}\n{f} → [{ms}]") f!"" + IO.println s + end Progress diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 84053150..974a6364 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -27,6 +27,9 @@ inductive TheoremOrLocal where | Theorem (thName : Name) | Local (asm : LocalDecl) +instance : ToMessageData TheoremOrLocal where + toMessageData := λ x => match x with | .Theorem thName => m!"{thName}" | .Local asm => m!"{asm.userName}" + /- Type to propagate the errors of `progressWith`. We need this because we use the exceptions to backtrack, when trying to use the assumptions for instance. When there is actually an error we want @@ -161,6 +164,32 @@ def getFirstArgAppName (args : Array Expr) : MetaM (Option Name) := do if f.isConst then pure (some f.constName) else pure none +def getFirstArg (args : Array Expr) : Option Expr := do + if args.size = 0 then none + else some (args.get! 0) + +/- Helper: try to lookup a theorem and apply it, or continue with another tactic + if it fails -/ +def tryLookupApply (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) + (kind : String) (th : Option TheoremOrLocal) (x : TacticM Unit) : TacticM Unit := do + let res ← do + match th with + | none => + trace[Progress] "Could not find a {kind}" + pure none + | some th => do + trace[Progress] "Lookuped up {kind}: {th}" + -- Apply the theorem + let res ← do + try + let res ← progressWith fnExpr th ids asmTac + pure (some res) + catch _ => none + match res with + | some .Ok => return () + | some (.Error msg) => throwError msg + | none => x + -- The array of ids are identifiers to use when introducing fresh variables def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do @@ -196,57 +225,40 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na -- It failed: try to lookup a theorem -- TODO: use a list of theorems, and try them one by one? trace[Progress] "No assumption succeeded: trying to lookup a theorem" - let res ← - match ← pspecAttr.find? fName with - | some thName => - trace[Progress] "Lookuped up theorem: {thName}" - -- Apply the theorem - let res ← do - try - let res ← progressWith fnExpr (.Theorem thName) ids asmTac - pure (some res) - catch _ => none - | none => - trace[Progress] "Could not find a pspec theorem for {fName}" - pure none - match res with - | some .Ok => return () - | some (.Error msg) => throwError msg - | none => - -- It failed: try to lookup a *class* spec theorem - let res ← do - match ← getFirstArgAppName args with - | none => none - | some argName => do - match ← pspecClassAttr.find? fName argName with - | some thName => - trace[Progress] "Lookuped up class theorem: {thName}" - -- Apply the theorem - let res ← do - try - let res ← progressWith fnExpr (.Theorem thName) ids asmTac - pure (some res) - catch _ => none - | none => - trace[Progress] "Could not find a class pspec theorem for ({fName}, {argName})" - pure none + let pspec ← do + let thName ← pspecAttr.find? fName + pure (thName.map fun th => .Theorem th) + tryLookupApply ids asmTac fnExpr "pspec theorem" pspec do + -- It failed: try to lookup a *class* expr spec theorem (those are more + -- specific than class spec theorems) + let pspecClassExpr ← do + match getFirstArg args with + | none => pure none + | some arg => do + let thName ← pspecClassExprAttr.find? fName arg + pure (thName.map fun th => .Theorem th) + tryLookupApply ids asmTac fnExpr "pspec class expr theorem" pspecClassExpr do + -- It failed: try to lookup a *class* spec theorem + let pspecClass ← do + match ← getFirstArgAppName args with + | none => pure none + | some argName => do + let thName ← pspecClassAttr.find? fName argName + pure (thName.map fun th => .Theorem th) + tryLookupApply ids asmTac fnExpr "pspec class theorem" pspecClass do + -- Try a recursive call - we try the assumptions of kind "auxDecl" + let ctx ← Lean.MonadLCtx.getLCtx + let decls ← ctx.getAllDecls + let decls := decls.filter (λ decl => match decl.kind with + | .default | .implDetail => false | .auxDecl => true) + for decl in decls.reverse do + trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" + let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue match res with - | some .Ok => return () - | some (.Error msg) => throwError msg - | none => - -- Try a recursive call - we try the assumptions of kind "auxDecl" - let ctx ← Lean.MonadLCtx.getLCtx - let decls ← ctx.getAllDecls - let decls := decls.filter (λ decl => match decl.kind with - | .default | .implDetail => false | .auxDecl => true) - for decl in decls.reverse do - trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue - match res with - | .Ok => return () - | .Error msg => throwError msg - -- Nothing worked: failed - throwError "Progress failed" + | .Ok => return () + | .Error msg => throwError msg + -- Nothing worked: failed + throwError "Progress failed" syntax progressArgs := ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? -- cgit v1.2.3 From d87e35e1a53b2252cc2c8c554216115773fd9678 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 11:38:55 +0200 Subject: Add fine-grained lemmas for the arithmetic operations --- backends/lean/Base/Primitives/Scalar.lean | 137 ++++++++++++++++++++++++++++-- backends/lean/Base/Progress/Base.lean | 2 +- 2 files changed, 131 insertions(+), 8 deletions(-) diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean index aaa4027f..1e9b51c2 100644 --- a/backends/lean/Base/Primitives/Scalar.lean +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -438,7 +438,7 @@ instance {ty} : HDiv (Scalar ty) (Scalar ty) (Result (Scalar ty)) where instance {ty} : HMod (Scalar ty) (Scalar ty) (Result (Scalar ty)) where hMod x y := Scalar.rem x y --- TODO: make progress work at a more fine grained level (see `Scalar.add_unsigned_spec`) +-- Generic theorem - shouldn't be used much @[cpspec] theorem Scalar.add_spec {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val + y.val) @@ -460,7 +460,32 @@ theorem Scalar.add_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} cases ty <;> simp [min] at * <;> linarith apply add_spec <;> assumption --- TODO: make it finer grained +/- Fine-grained theorems -/ +@[cepspec] theorem Usize.add_spec {x y : Usize} (hmax : x.val + y.val ≤ Usize.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U8.add_spec {x y : U8} (hmax : x.val + y.val ≤ U8.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U16.add_spec {x y : U16} (hmax : x.val + y.val ≤ U16.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U32.add_spec {x y : U32} (hmax : x.val + y.val ≤ U32.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U64.add_spec {x y : U64} (hmax : x.val + y.val ≤ U64.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U128.add_spec {x y : U128} (hmax : x.val + y.val ≤ U128.max) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + apply Scalar.add_unsigned_spec <;> simp only [Scalar.max, *] + +-- Generic theorem - shouldn't be used much @[cpspec] theorem Scalar.sub_spec {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val - y.val) @@ -484,8 +509,32 @@ theorem Scalar.sub_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} intros apply sub_spec <;> assumption --- TODO: make it finer grained -@[cpspec] +/- Fine-grained theorems -/ +@[cepspec] theorem Usize.sub_spec {x y : Usize} (hmin : Usize.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +@[cepspec] theorem U8.sub_spec {x y : U8} (hmin : U8.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +@[cepspec] theorem U16.sub_spec {x y : U16} (hmin : U16.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +@[cepspec] theorem U32.sub_spec {x y : U32} (hmin : U32.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +@[cepspec] theorem U64.sub_spec {x y : U64} (hmin : U64.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +@[cepspec] theorem U128.sub_spec {x y : U128} (hmin : U128.min ≤ x.val - y.val) : + ∃ z, x - y = ret z ∧ z.val = x.val - y.val := by + apply Scalar.sub_unsigned_spec <;> simp only [Scalar.min, *] + +-- Generic theorem - shouldn't be used much theorem Scalar.mul_spec {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val * y.val) (hmax : x.val * y.val ≤ Scalar.max ty) : @@ -506,7 +555,32 @@ theorem Scalar.mul_unsigned_spec {ty} (s: ¬ ty.isSigned) {x y : Scalar ty} cases ty <;> simp at * <;> apply mul_nonneg hx hy apply mul_spec <;> assumption --- TODO: make it finer grained +/- Fine-grained theorems -/ +@[cepspec] theorem Usize.mul_spec {x y : Usize} (hmax : x.val * y.val ≤ Usize.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U8.mul_spec {x y : U8} (hmax : x.val * y.val ≤ U8.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U16.mul_spec {x y : U16} (hmax : x.val * y.val ≤ U16.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U32.mul_spec {x y : U32} (hmax : x.val * y.val ≤ U32.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U64.mul_spec {x y : U64} (hmax : x.val * y.val ≤ U64.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +@[cepspec] theorem U128.mul_spec {x y : U128} (hmax : x.val * y.val ≤ U128.max) : + ∃ z, x * y = ret z ∧ z.val = x.val * y.val := by + apply Scalar.mul_unsigned_spec <;> simp only [Scalar.max, *] + +-- Generic theorem - shouldn't be used much @[cpspec] theorem Scalar.div_spec {ty} {x y : Scalar ty} (hnz : y.val ≠ 0) @@ -534,7 +608,32 @@ theorem Scalar.div_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : S simp [*] at hs apply hs --- TODO: make it finer grained +/- Fine-grained theorems -/ +@[cepspec] theorem Usize.div_spec (x : Usize) {y : Usize} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [*] + +@[cepspec] theorem U8.div_spec (x : U8) {y : U8} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U16.div_spec (x : U16) {y : U16} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U32.div_spec (x : U32) {y : U32} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U64.div_spec (x : U64) {y : U64} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U128.div_spec (x : U128) {y : U128} (hnz : y.val ≠ 0) : + ∃ z, x / y = ret z ∧ z.val = x.val / y.val := by + apply Scalar.div_unsigned_spec <;> simp [Scalar.max, *] + +-- Generic theorem - shouldn't be used much @[cpspec] theorem Scalar.rem_spec {ty} {x y : Scalar ty} (hnz : y.val ≠ 0) @@ -548,7 +647,7 @@ theorem Scalar.rem_spec {ty} {x y : Scalar ty} theorem Scalar.rem_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : Scalar ty} (hnz : y.val ≠ 0) : - ∃ z, x % y = ret z ∧ z.val = scalar_rem x.val y.val := by + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by have h : Scalar.min ty = 0 := by cases ty <;> simp at * have hx := x.hmin have hy := y.hmin @@ -565,6 +664,30 @@ theorem Scalar.rem_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : S simp [*] at hs simp [*] +@[cepspec] theorem Usize.rem_spec (x : Usize) {y : Usize} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [*] + +@[cepspec] theorem U8.rem_spec (x : U8) {y : U8} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U16.rem_spec (x : U16) {y : U16} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U32.rem_spec (x : U32) {y : U32} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U64.rem_spec (x : U64) {y : U64} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [Scalar.max, *] + +@[cepspec] theorem U128.rem_spec (x : U128) {y : U128} (hnz : y.val ≠ 0) : + ∃ z, x % y = ret z ∧ z.val = x.val % y.val := by + apply Scalar.rem_unsigned_spec <;> simp [Scalar.max, *] + -- ofIntCore -- TODO: typeclass? def Isize.ofIntCore := @Scalar.ofIntCore .Isize diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 3599d866..2fbd24dd 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -240,7 +240,7 @@ initialize pspecClassExprAttr : PSpecClassExprAttr ← do -- We store two bindings: -- - arg to theorem name -- - reduced arg to theorem name - let rarg ← MetaM.run' (reduce arg) + let rarg ← MetaM.run' (reduceAll arg) trace[Progress] "Registering class spec theorem for ({fName}, {arg}) and ({fName}, {rarg})" -- Update the entry if there is one, add an entry if there is none let env := -- cgit v1.2.3 From 6ef1d360b89fd9f9383e63609888bf925a6a16ab Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 12:08:09 +0200 Subject: Improve progress further and move some lemmas --- backends/lean/Base/IList/IList.lean | 67 ++++++++++++++++++++++ backends/lean/Base/Progress/Progress.lean | 55 +++++++++++------- tests/lean/Hashmap/Properties.lean | 92 +++---------------------------- 3 files changed, 109 insertions(+), 105 deletions(-) diff --git a/backends/lean/Base/IList/IList.lean b/backends/lean/Base/IList/IList.lean index ddb10236..1773e593 100644 --- a/backends/lean/Base/IList/IList.lean +++ b/backends/lean/Base/IList/IList.lean @@ -175,6 +175,73 @@ theorem idrop_eq_nil_of_le (hineq : ls.len ≤ i) : idrop i ls = [] := by apply hi linarith +@[simp] +theorem index_ne + {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (j: ℤ) (x: α) : + 0 ≤ i → i < l.len → 0 ≤ j → j < l.len → j ≠ i → + (l.update i x).index j = l.index j + := + λ _ _ _ _ _ => match l with + | [] => by simp at * + | hd :: tl => + if h: i = 0 then + have : j ≠ 0 := by scalar_tac + by simp [*] + else if h : j = 0 then + have : i ≠ 0 := by scalar_tac + by simp [*] + else + by + simp [*] + simp at * + apply index_ne <;> scalar_tac + +@[simp] +theorem index_eq + {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (x: α) : + 0 ≤ i → i < l.len → + (l.update i x).index i = x + := + fun _ _ => match l with + | [] => by simp at *; exfalso; scalar_tac -- TODO: exfalso needed. Son FIXME + | hd :: tl => + if h: i = 0 then + by + simp [*] + else + by + simp [*] + simp at * + apply index_eq <;> scalar_tac + +def allP {α : Type u} (l : List α) (p: α → Prop) : Prop := + foldr (fun a r => p a ∧ r) True l + +@[simp] +theorem allP_nil {α : Type u} (p: α → Prop) : allP [] p := + by simp [allP, foldr] + +@[simp] +theorem allP_cons {α : Type u} (hd: α) (tl : List α) (p: α → Prop) : + allP (hd :: tl) p ↔ p hd ∧ allP tl p + := by simp [allP, foldr] + +def pairwise_rel + {α : Type u} (rel : α → α → Prop) (l: List α) : Prop + := match l with + | [] => True + | hd :: tl => allP tl (rel hd) ∧ pairwise_rel rel tl + +@[simp] +theorem pairwise_rel_nil {α : Type u} (rel : α → α → Prop) : + pairwise_rel rel [] + := by simp [pairwise_rel] + +@[simp] +theorem pairwise_rel_cons {α : Type u} (rel : α → α → Prop) (hd: α) (tl: List α) : + pairwise_rel rel (hd :: tl) ↔ allP tl (rel hd) ∧ pairwise_rel rel tl + := by simp [pairwise_rel] + end Lemmas end List diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 974a6364..1f734415 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -39,7 +39,7 @@ inductive ProgressError | Error (msg : MessageData) deriving Inhabited -def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) +def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) : TacticM ProgressError := do /- Apply the theorem We try to match the theorem with the goal @@ -88,7 +88,7 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) match th with | .Theorem thName => mkAppOptM thName (mvars.map some) | .Local decl => mkAppOptM' (mkFVar decl.fvarId) (mvars.map some) - let asmName ← mkFreshUserName `h + let asmName ← do match keep with | none => mkFreshUserName `h | some n => do pure n let thTy ← inferType th let thAsm ← Utils.addDeclTac asmName th thTy (asLet := false) withMainContext do -- The context changed - TODO: remove once addDeclTac is updated @@ -109,7 +109,9 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) if ← isConj (← inferType h) then do let hName := (← h.fvarId!.getDecl).userName let (optId, ids) := listTryPopHead ids - let optIds := match optId with | none => none | some id => some (hName, id) + let optIds ← match optId with + | none => do pure (some (hName, ← mkFreshUserName `h)) + | some id => do pure (some (hName, id)) splitConjTac h optIds (fun hEq hPost => k hEq (some hPost) ids) else k h none ids -- Simplify the target by using the equality and some monad simplifications, @@ -118,9 +120,12 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (ids : Array Name) trace[Progress] "eq and post:\n{hEq} : {← inferType hEq}\n{hPost}" simpAt [] [``Primitives.bind_tc_ret, ``Primitives.bind_tc_fail, ``Primitives.bind_tc_div] [hEq.fvarId!] (.targets #[] true) - -- Clear the equality - let mgoal ← getMainGoal - let mgoal ← mgoal.tryClearMany #[hEq.fvarId!] + -- Clear the equality, unless the user requests not to do so + let mgoal ← do + if keep.isSome then getMainGoal + else do + let mgoal ← getMainGoal + mgoal.tryClearMany #[hEq.fvarId!] setGoals (mgoal :: (← getUnsolvedGoals)) trace[Progress] "Goal after splitting eq and post and simplifying the target: {mgoal}" -- Continue splitting following the ids provided by the user @@ -170,7 +175,7 @@ def getFirstArg (args : Array Expr) : Option Expr := do /- Helper: try to lookup a theorem and apply it, or continue with another tactic if it fails -/ -def tryLookupApply (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) +def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) (kind : String) (th : Option TheoremOrLocal) (x : TacticM Unit) : TacticM Unit := do let res ← do match th with @@ -182,7 +187,7 @@ def tryLookupApply (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) -- Apply the theorem let res ← do try - let res ← progressWith fnExpr th ids asmTac + let res ← progressWith fnExpr th keep ids asmTac pure (some res) catch _ => none match res with @@ -191,7 +196,7 @@ def tryLookupApply (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) | none => x -- The array of ids are identifiers to use when introducing fresh variables -def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do +def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do -- Retrieve the goal let mgoal ← Tactic.getMainGoal @@ -209,7 +214,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na -- Otherwise, lookup one. match withTh with | some th => do - match ← progressWith fnExpr th ids asmTac with + match ← progressWith fnExpr th keep ids asmTac with | .Ok => return () | .Error msg => throwError msg | none => @@ -218,7 +223,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na let decls ← ctx.getDecls for decl in decls.reverse do trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + let res ← do try progressWith fnExpr (.Local decl) keep ids asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg @@ -228,7 +233,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na let pspec ← do let thName ← pspecAttr.find? fName pure (thName.map fun th => .Theorem th) - tryLookupApply ids asmTac fnExpr "pspec theorem" pspec do + tryLookupApply keep ids asmTac fnExpr "pspec theorem" pspec do -- It failed: try to lookup a *class* expr spec theorem (those are more -- specific than class spec theorems) let pspecClassExpr ← do @@ -237,7 +242,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na | some arg => do let thName ← pspecClassExprAttr.find? fName arg pure (thName.map fun th => .Theorem th) - tryLookupApply ids asmTac fnExpr "pspec class expr theorem" pspecClassExpr do + tryLookupApply keep ids asmTac fnExpr "pspec class expr theorem" pspecClassExpr do -- It failed: try to lookup a *class* spec theorem let pspecClass ← do match ← getFirstArgAppName args with @@ -245,7 +250,7 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na | some argName => do let thName ← pspecClassAttr.find? fName argName pure (thName.map fun th => .Theorem th) - tryLookupApply ids asmTac fnExpr "pspec class theorem" pspecClass do + tryLookupApply keep ids asmTac fnExpr "pspec class theorem" pspecClass do -- Try a recursive call - we try the assumptions of kind "auxDecl" let ctx ← Lean.MonadLCtx.getLCtx let decls ← ctx.getAllDecls @@ -253,21 +258,29 @@ def progressAsmsOrLookupTheorem (withTh : Option TheoremOrLocal) (ids : Array Na | .default | .implDetail => false | .auxDecl => true) for decl in decls.reverse do trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) ids asmTac catch _ => continue + let res ← do try progressWith fnExpr (.Local decl) keep ids asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg -- Nothing worked: failed throwError "Progress failed" -syntax progressArgs := ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? +syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw -- Process the arguments to retrieve the identifiers to use trace[Progress] "Progress arguments: {args}" let args := args.getArgs - let withArg := (args.get! 0).getArgs + let keep : Option Name ← do + let args := (args.get! 0).getArgs + if args.size > 0 then do + let args := (args.get! 1).getArgs + if args.size > 0 then pure (some (args.get! 1).getId) + else do pure (some (← mkFreshUserName `h)) + else pure none + trace[Progress] "Keep: {keep}" + let withArg := (args.get! 1).getArgs let withArg ← do if withArg.size > 0 then let id := withArg.get! 1 @@ -287,11 +300,11 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do | id :: _ => pure (some (.Theorem id)) else pure none - let args := (args.get! 1).getArgs + let args := (args.get! 2).getArgs let args := (args.get! 2).getArgs let ids := args.map Syntax.getId trace[Progress] "User-provided ids: {ids}" - progressAsmsOrLookupTheorem withArg ids (firstTac [assumptionTac, Arith.scalarTac]) + progressAsmsOrLookupTheorem keep withArg ids (firstTac [assumptionTac, Arith.scalarTac]) elab "progress" args:progressArgs : tactic => evalProgress args @@ -306,11 +319,11 @@ namespace Test #eval showStoredPSpec #eval showStoredPSpecClass - theorem Scalar.add_spec {ty} {x y : Scalar ty} + theorem Scalar.add_spec1 {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by - progress + progress keep as h with Scalar.add_spec as ⟨ z ⟩ simp [*] /- diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 3b9b960f..baa8f5c8 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -3,75 +3,6 @@ import Hashmap.Funs open Primitives open Result -namespace List - -theorem index_ne - {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (j: ℤ) (x: α) : - 0 ≤ i → i < l.len → 0 ≤ j → j < l.len → j ≠ i → - (l.update i x).index j = l.index j - := - λ _ _ _ _ _ => match l with - | [] => by simp at * - | hd :: tl => - if h: i = 0 then - have : j ≠ 0 := by scalar_tac - by simp [*] - else if h : j = 0 then - have : i ≠ 0 := by scalar_tac - by simp [*] - else - by - simp [*] - simp at * - apply index_ne <;> scalar_tac - -theorem index_eq - {α : Type u} [Inhabited α] (l: List α) (i: ℤ) (x: α) : - 0 ≤ i → i < l.len → - (l.update i x).index i = x - := - fun _ _ => match l with - | [] => by simp at *; exfalso; scalar_tac -- TODO: exfalso needed. Son FIXME - | hd :: tl => - if h: i = 0 then - by - simp [*] - else - by - simp [*] - simp at * - apply index_eq <;> scalar_tac - -def allP {α : Type u} (l : List α) (p: α → Prop) : Prop := - foldr (fun a r => p a ∧ r) True l - -@[simp] -theorem allP_nil {α : Type u} (p: α → Prop) : allP [] p := - by simp [allP, foldr] - -@[simp] -theorem allP_cons {α : Type u} (hd: α) (tl : List α) (p: α → Prop) : - allP (hd :: tl) p ↔ p hd ∧ allP tl p - := by simp [allP, foldr] - -def pairwise_rel - {α : Type u} (rel : α → α → Prop) (l: List α) : Prop - := match l with - | [] => True - | hd :: tl => allP tl (rel hd) ∧ pairwise_rel rel tl - -@[simp] -theorem pairwise_rel_nil {α : Type u} (rel : α → α → Prop) : - pairwise_rel rel [] - := by simp [pairwise_rel] - -@[simp] -theorem pairwise_rel_cons {α : Type u} (rel : α → α → Prop) (hd: α) (tl: List α) : - pairwise_rel rel (hd :: tl) ↔ allP tl (rel hd) ∧ pairwise_rel rel tl - := by simp [pairwise_rel] - -end List - namespace hashmap namespace List @@ -104,18 +35,16 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : rw [insert_in_list_loop] simp [h] else + have ⟨ b, hi ⟩ := insert_in_list_spec key value tl by - -- TODO: use progress: detect that this is a recursive call, or give - -- the possibility of specifying an identifier - have ⟨ b, hi ⟩ := insert_in_list_spec key value tl exists b simp [insert_in_list, List.lookup] - rw [insert_in_list_loop] -- TODO: Using it in simp leads to infinite recursion + rw [insert_in_list_loop] -- TODO: Using simp leads to infinite recursion simp [h] simp [insert_in_list] at hi exact hi -set_option trace.Progress true +-- Variation: use progress @[pspec] theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, @@ -134,18 +63,13 @@ theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) simp only [insert_in_list] rw [insert_in_list_loop] conv => rhs; ext; simp [*] - progress as ⟨ b hi ⟩ - - -- TODO: use progress: detect that this is a recursive call, or give - -- the possibility of specifying an identifier - have ⟨ b, hi ⟩ := insert_in_list_spec key value tl + progress keep as heq as ⟨ b hi ⟩ + simp only [insert_in_list] at heq exists b - simp [insert_in_list, List.lookup] - rw [insert_in_list_loop] -- TODO: Using it in simp leads to infinite recursion - simp [h] - simp [insert_in_list] at hi - exact hi + simp only [heq, hi] + simp [*, List.lookup] +-- Variation: use tactics from the beginning @[pspec] theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, -- cgit v1.2.3 From 03492250b45855fe9db5e0a28a96166607cd84a1 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 14:14:34 +0200 Subject: Make some proofs in Hashmap/Properties.lean and improve progress --- backends/lean/Base/Arith/Int.lean | 2 +- backends/lean/Base/Progress/Base.lean | 25 +++++++--- backends/lean/Base/Progress/Progress.lean | 68 +++++++++------------------ backends/lean/Base/Utils.lean | 32 +++++++++---- tests/lean/Hashmap/Properties.lean | 76 ++++++++++++++++++++++++++----- 5 files changed, 129 insertions(+), 74 deletions(-) diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index ac011998..fa957293 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -198,7 +198,7 @@ def intTac (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do -- Split the conjunctions in the goal Tactic.allGoals (Utils.repeatTac Utils.splitConjTarget) -- Call linarith - let linarith := + let linarith := do let cfg : Linarith.LinarithConfig := { -- We do this with our custom preprocessing splitNe := false diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index 2fbd24dd..b54bdf7a 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -19,6 +19,7 @@ structure PSpecDesc where -- The existentially quantified variables evars : Array Expr -- The function + fExpr : Expr fName : Name -- The function arguments fLevels : List Level @@ -60,21 +61,30 @@ section Methods m a := do trace[Progress] "Proposition: {th}" -- Dive into the quantified variables and the assumptions - forallTelescope th fun fvars th => do + forallTelescope th.consumeMData fun fvars th => do trace[Progress] "Universally quantified arguments and assumptions: {fvars}" -- Dive into the existentials - existsTelescope th fun evars th => do + existsTelescope th.consumeMData fun evars th => do trace[Progress] "Existentials: {evars}" trace[Progress] "Proposition after stripping the quantifiers: {th}" -- Take the first conjunct - let (th, post) ← optSplitConj th + let (th, post) ← optSplitConj th.consumeMData trace[Progress] "After splitting the conjunction:\n- eq: {th}\n- post: {post}" -- Destruct the equality - let (th, ret) ← destEq th + let (mExpr, ret) ← destEq th.consumeMData trace[Progress] "After splitting the equality:\n- lhs: {th}\n- rhs: {ret}" - -- Destruct the application to get the name - th.consumeMData.withApp fun f args => do - trace[Progress] "After stripping the arguments:\n- f: {f}\n- args: {args}" + -- Destruct the monadic application to dive into the bind, if necessary (this + -- is for when we use `withPSpec` inside of the `progress` tactic), and + -- destruct the application to get the function name + mExpr.consumeMData.withApp fun mf margs => do + trace[Progress] "After stripping the arguments of the monad expression:\n- mf: {mf}\n- margs: {margs}" + let (fExpr, f, args) ← do + if mf.isConst ∧ mf.constName = ``Bind.bind then do + -- Dive into the bind + let fExpr := margs.get! 4 + fExpr.consumeMData.withApp fun f args => pure (fExpr, f, args) + else pure (mExpr, mf, margs) + trace[Progress] "After stripping the arguments of the function call:\n- f: {f}\n- args: {args}" if ¬ f.isConst then throwError "Not a constant: {f}" -- Compute the set of universally quantified variables which appear in the function arguments let allArgsFVars ← args.foldlM (fun hs arg => getFVarIds arg hs) HashSet.empty @@ -94,6 +104,7 @@ section Methods let thDesc := { fvars := fvars evars := evars + fExpr fName := f.constName! fLevels := f.constLevels! args := args diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 1f734415..dabd25b8 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -7,22 +7,6 @@ namespace Progress open Lean Elab Term Meta Tactic open Utils -/- --- TODO: remove -namespace Test - open Primitives - - set_option trace.Progress true - - @[pspec] - theorem vec_index_test (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : - ∃ x, v.index α i = .ret x := by - sorry - - #eval pspecAttr.find? ``Primitives.Vec.index -end Test --/ - inductive TheoremOrLocal where | Theorem (thName : Name) | Local (asm : LocalDecl) @@ -39,7 +23,7 @@ inductive ProgressError | Error (msg : MessageData) deriving Inhabited -def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids : Array Name) +def progressWith (fExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) : TacticM ProgressError := do /- Apply the theorem We try to match the theorem with the goal @@ -66,7 +50,7 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids -- Introduce the existentially quantified variables and the post-condition -- in the context let thBody ← - existsTelescope thExBody fun _evars thBody => do + existsTelescope thExBody.consumeMData fun _evars thBody => do trace[Progress] "After stripping existentials: {thBody}" let (thBody, _) ← optSplitConj thBody trace[Progress] "After splitting the conjunction: {thBody}" @@ -75,9 +59,9 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids -- There shouldn't be any existential variables in thBody pure thBody -- Match the body with the target - trace[Progress] "Maching `{thBody}` with `{fnExpr}`" - let ok ← isDefEq thBody fnExpr - if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {fnExpr}" + trace[Progress] "Matching `{thBody}` with `{fExpr}`" + let ok ← isDefEq thBody fExpr + if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {fExpr}" let mgoal ← Tactic.getMainGoal postprocessAppMVars `progress mgoal mvars binders true true Term.synthesizeSyntheticMVarsNoPostponing @@ -139,8 +123,9 @@ def progressWith (fnExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids match ids with | [] => pure .Ok -- Stop | nid :: ids => do + trace[Progress] "Splitting post: {hPost}" -- Split - if ← isConj hPost then + if ← isConj (← inferType hPost) then splitConjTac hPost (some (nid, curPostId)) (λ _ nhPost => splitPost nhPost ids) else return (.Error m!"Too many ids provided ({nid :: ids}) not enough conjuncts to split in the postcondition") splitPost hPost ids @@ -175,7 +160,7 @@ def getFirstArg (args : Array Expr) : Option Expr := do /- Helper: try to lookup a theorem and apply it, or continue with another tactic if it fails -/ -def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) (fnExpr : Expr) +def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) (fExpr : Expr) (kind : String) (th : Option TheoremOrLocal) (x : TacticM Unit) : TacticM Unit := do let res ← do match th with @@ -187,7 +172,7 @@ def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Uni -- Apply the theorem let res ← do try - let res ← progressWith fnExpr th keep ids asmTac + let res ← progressWith fExpr th keep ids asmTac pure (some res) catch _ => none match res with @@ -203,18 +188,16 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL let goalTy ← mgoal.getType trace[Progress] "goal: {goalTy}" -- Dive into the goal to lookup the theorem - let (fName, fLevels, args) ← do + let (fExpr, fName, args) ← do withPSpec goalTy fun desc => - -- TODO: check that no universally quantified variables in the arguments - pure (desc.fName, desc.fLevels, desc.args) - -- TODO: this should be in the pspec desc - let fnExpr := mkAppN (.const fName fLevels) args + -- TODO: check that no quantified variables in the arguments + pure (desc.fExpr, desc.fName, desc.args) trace[Progress] "Function: {fName}" -- If the user provided a theorem/assumption: use it. -- Otherwise, lookup one. match withTh with | some th => do - match ← progressWith fnExpr th keep ids asmTac with + match ← progressWith fExpr th keep ids asmTac with | .Ok => return () | .Error msg => throwError msg | none => @@ -223,7 +206,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL let decls ← ctx.getDecls for decl in decls.reverse do trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) keep ids asmTac catch _ => continue + let res ← do try progressWith fExpr (.Local decl) keep ids asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg @@ -233,7 +216,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL let pspec ← do let thName ← pspecAttr.find? fName pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fnExpr "pspec theorem" pspec do + tryLookupApply keep ids asmTac fExpr "pspec theorem" pspec do -- It failed: try to lookup a *class* expr spec theorem (those are more -- specific than class spec theorems) let pspecClassExpr ← do @@ -242,7 +225,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | some arg => do let thName ← pspecClassExprAttr.find? fName arg pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fnExpr "pspec class expr theorem" pspecClassExpr do + tryLookupApply keep ids asmTac fExpr "pspec class expr theorem" pspecClassExpr do -- It failed: try to lookup a *class* spec theorem let pspecClass ← do match ← getFirstArgAppName args with @@ -250,7 +233,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | some argName => do let thName ← pspecClassAttr.find? fName argName pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fnExpr "pspec class theorem" pspecClass do + tryLookupApply keep ids asmTac fExpr "pspec class theorem" pspecClass do -- Try a recursive call - we try the assumptions of kind "auxDecl" let ctx ← Lean.MonadLCtx.getLCtx let decls ← ctx.getAllDecls @@ -258,7 +241,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | .default | .implDetail => false | .auxDecl => true) for decl in decls.reverse do trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fnExpr (.Local decl) keep ids asmTac catch _ => continue + let res ← do try progressWith fExpr (.Local decl) keep ids asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg @@ -310,7 +293,6 @@ elab "progress" args:progressArgs : tactic => evalProgress args /- --- TODO: remove namespace Test open Primitives Result @@ -319,22 +301,14 @@ namespace Test #eval showStoredPSpec #eval showStoredPSpecClass - theorem Scalar.add_spec1 {ty} {x y : Scalar ty} + example {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by - progress keep as h with Scalar.add_spec as ⟨ z ⟩ +-- progress keep as h with Scalar.add_spec as ⟨ z ⟩ + progress keep as h simp [*] -/- - @[pspec] - theorem vec_index_test2 (α : Type u) (v: Vec α) (i: Usize) (h: i.val < v.val.length) : - ∃ (x: α), v.index α i = .ret x := by - progress with vec_index_test as ⟨ x ⟩ - simp - - set_option trace.Progress false --/ end Test -/ end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 8aa76d8e..44590176 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -308,8 +308,23 @@ def firstTac (tacl : List (TacticM Unit)) : TacticM Unit := do match tacl with | [] => pure () | tac :: tacl => - try tac + -- Should use try ... catch or Lean.observing? + -- Generally speaking we should use Lean.observing? to restore the state, + -- but with tactics the try ... catch variant seems to work + try do + tac + -- Check that there are no remaining goals + let gl ← Tactic.getUnsolvedGoals + if ¬ gl.isEmpty then throwError "tactic failed" catch _ => firstTac tacl +/- let res ← Lean.observing? do + tac + -- Check that there are no remaining goals + let gl ← Tactic.getUnsolvedGoals + if ¬ gl.isEmpty then throwError "tactic failed" + match res with + | some _ => pure () + | none => firstTac tacl -/ -- Split the goal if it is a conjunction def splitConjTarget : TacticM Unit := do @@ -424,12 +439,13 @@ def splitExistsTac (h : Expr) (optId : Option Name) (k : Expr → Expr → Tacti let hTy ← inferType h if isExists hTy then do -- Try to use the user-provided names - let altVarNames ← - match optId with - | none => pure #[] - | some id => do - let hDecl ← h.fvarId!.getDecl - pure #[{ varNames := [id, hDecl.userName] }] + let altVarNames ← do + let hDecl ← h.fvarId!.getDecl + let id ← do + match optId with + | none => mkFreshUserName `x + | some id => pure id + pure #[{ varNames := [id, hDecl.userName] }] let newGoals ← goal.cases h.fvarId! altVarNames -- There should be exactly one goal match newGoals.toList with @@ -511,7 +527,7 @@ example (h : a ∧ b) : a := by example (h : ∃ x y z, x + y + z ≥ 0) : ∃ x, x ≥ 0 := by split_all_exists h - rename_i x y z h + rename_i x y z exists x + y + z /- Call the simp tactic. diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index baa8f5c8..e065bb36 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -21,8 +21,9 @@ end List namespace HashMap -@[pspec] -theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : +abbrev Core.List := _root_.List + +theorem insert_in_list_spec0 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ (b ↔ List.lookup ls.v key = none) @@ -35,7 +36,7 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : rw [insert_in_list_loop] simp [h] else - have ⟨ b, hi ⟩ := insert_in_list_spec key value tl + have ⟨ b, hi ⟩ := insert_in_list_spec0 key value tl by exists b simp [insert_in_list, List.lookup] @@ -45,7 +46,6 @@ theorem insert_in_list_spec {α : Type} (key: Usize) (value: α) (ls: List α) : exact hi -- Variation: use progress -@[pspec] theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ @@ -70,7 +70,6 @@ theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) simp [*, List.lookup] -- Variation: use tactics from the beginning -@[pspec] theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ @@ -91,10 +90,10 @@ theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) progress as ⟨ b h ⟩ simp [*] -@[pspec] theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List α) : ∃ l1, insert_in_list_back α key value l0 = ret l1 ∧ + -- We update the binding List.lookup l1.v key = value ∧ (∀ k, k ≠ key → List.lookup l1.v k = List.lookup l0.v k) := match l0 with @@ -112,11 +111,66 @@ theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List simp [insert_in_list_back, List.lookup] rw [insert_in_list_loop_back] simp [h, List.lookup] - have ⟨tl0 , _, _ ⟩ := insert_in_list_back_spec key value tl -- TODO: Use progress - simp [insert_in_list_back] at * - simp [List.lookup, *] - simp (config := {contextual := true}) [*] - + progress keep as heq as ⟨ tl hp1 hp2 ⟩ + simp [insert_in_list_back] at heq + simp (config := {contextual := true}) [*, List.lookup] + +def distinct_keys (ls : Core.List (Usize × α)) := ls.pairwise_rel (λ x y => x.fst ≠ y.fst) + +def hash_mod_key (k : Usize) (l : Int) : Int := + match hash_key k with + | .ret k => k.val % l + | _ => 0 + +def slot_s_inv_hash (l i : Int) (ls : Core.List (Usize × α)) : Prop := + ls.allP (λ (k, _) => hash_mod_key k l = i) + +@[simp] +def slot_s_inv (l i : Int) (ls : Core.List (Usize × α)) : Prop := + distinct_keys ls ∧ + slot_s_inv_hash l i ls + +def slot_t_inv (l i : Int) (s : List α) : Prop := slot_s_inv l i s.v + +@[pspec] +theorem insert_in_list_back_spec1 {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) + (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) : + ∃ l1, + insert_in_list_back α key value l0 = ret l1 ∧ + -- We update the binding + List.lookup l1.v key = value ∧ + (∀ k, k ≠ key → List.lookup l1.v k = List.lookup l0.v k) ∧ + -- We preserve part of the key invariant + slot_s_inv_hash l (hash_mod_key key l) l1.v + := match l0 with + | .Nil => by + simp [insert_in_list_back, insert_in_list_loop_back, List.lookup, List.v, slot_s_inv_hash] + tauto + | .Cons k v tl0 => + if h: k = key then + by + simp [insert_in_list_back, List.lookup] + rw [insert_in_list_loop_back] + simp [h, List.lookup] + constructor + . intros; simp [*] + . simp [List.v, slot_s_inv_hash] at * + simp [*] + else + by + simp [insert_in_list_back, List.lookup] + rw [insert_in_list_loop_back] + simp [h, List.lookup] + have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by + simp_all [List.v, slot_s_inv_hash] + progress keep as heq as ⟨ tl1 hp1 hp2 hp3 ⟩ + simp only [insert_in_list_back] at heq + have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by + simp [List.v, slot_s_inv_hash] at * + simp [*] + simp (config := {contextual := true}) [*, List.lookup] + + end HashMap end hashmap -- cgit v1.2.3 From e58872aa4dc31f0819fe17b13e6b7e4b0d9635c8 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 15:46:11 +0200 Subject: Make progress on some of the hashmap proofs --- backends/lean/Base/Utils.lean | 30 +++++-- tests/lean/Hashmap/Properties.lean | 167 ++++++++++++++++++++++++++++--------- 2 files changed, 149 insertions(+), 48 deletions(-) diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 44590176..f014e112 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -326,14 +326,6 @@ def firstTac (tacl : List (TacticM Unit)) : TacticM Unit := do | some _ => pure () | none => firstTac tacl -/ --- Split the goal if it is a conjunction -def splitConjTarget : TacticM Unit := do - withMainContext do - let and_intro := Expr.const ``And.intro [] - let mvarIds' ← _root_.Lean.MVarId.apply (← getMainGoal) and_intro - Term.synthesizeSyntheticMVarsNoPostponing - replaceMainGoal mvarIds' - -- Taken from Lean.Elab.evalAssumption def assumptionTac : TacticM Unit := liftMetaTactic fun mvarId => do mvarId.assumption; pure [] @@ -349,6 +341,24 @@ def optSplitConj (e : Expr) : MetaM (Expr × Option Expr) := do if f.isConstOf ``And ∧ args.size = 2 then pure (args.get! 0, some (args.get! 1)) else pure (e, none) +-- Split the goal if it is a conjunction +def splitConjTarget : TacticM Unit := do + withMainContext do + let g ← getMainTarget + -- The tactic was initially implemened with `_root_.Lean.MVarId.apply` + -- but it tended to mess the goal by unfolding terms, even when it failed + let (l, r) ← optSplitConj g + match r with + | none => do throwError "The goal is not a conjunction" + | some r => do + let lmvar ← mkFreshExprSyntheticOpaqueMVar l + let rmvar ← mkFreshExprSyntheticOpaqueMVar r + let and_intro ← mkAppM ``And.intro #[lmvar, rmvar] + let g ← getMainGoal + g.assign and_intro + let goals ← getUnsolvedGoals + setGoals (lmvar.mvarId! :: rmvar.mvarId! :: goals) + -- Destruct an equaliy and return the two sides def destEq (e : Expr) : MetaM (Expr × Expr) := do e.withApp fun f args => @@ -520,6 +530,10 @@ elab "split_all_exists " n:ident : tactic => do let fvar := mkFVar decl.fvarId splitAllExistsTac fvar [] (fun _ _ => pure ()) +elab "split_target_conjs" : tactic => + withMainContext do + repeatTac splitConjTarget + example (h : a ∧ b) : a := by split_all_exists h split_conj h diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index e065bb36..66c386f2 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -3,6 +3,18 @@ import Hashmap.Funs open Primitives open Result +namespace List + +-- TODO: we don't want to use the original List.lookup because it uses BEq +-- TODO: rewrite rule: match x == y with ... -> if x = y then ... else ... ? +@[simp] +def lookup' {α : Type} (ls: _root_.List (Usize × α)) (key: Usize) : Option α := + match ls with + | [] => none + | (k, x) :: tl => if k = key then some x else lookup' tl key + +end List + namespace hashmap namespace List @@ -12,10 +24,15 @@ def v {α : Type} (ls: List α) : _root_.List (Usize × α) := | Nil => [] | Cons k x tl => (k, x) :: v tl -def lookup {α : Type} (ls: _root_.List (Usize × α)) (key: Usize) : Option α := - match ls with - | [] => none - | (k, x) :: tl => if k = key then some x else lookup tl key +@[simp] theorem v_nil (α : Type) : (Nil : List α).v = [] := by rfl +@[simp] theorem v_cons {α : Type} k x (tl: List α) : (Cons k x tl).v = (k, x) :: v tl := by rfl + +@[simp] +abbrev lookup {α : Type} (ls: List α) (key: Usize) : Option α := + ls.v.lookup' key + +@[simp] +abbrev len {α : Type} (ls : List α) : Int := ls.v.len end List @@ -23,39 +40,51 @@ namespace HashMap abbrev Core.List := _root_.List +namespace List + +end List + +-- TODO: move +@[simp] theorem neq_imp_nbeq [BEq α] [LawfulBEq α] (x y : α) (heq : ¬ x = y) : ¬ x == y := by simp [*] +@[simp] theorem neq_imp_nbeq_rev [BEq α] [LawfulBEq α] (x y : α) (heq : ¬ x = y) : ¬ y == x := by simp [*] + +-- TODO: move +theorem match_lawful_beq [BEq α] [LawfulBEq α] [DecidableEq α] (x y : α) : + (x == y) = (if x = y then true else false) := by + split <;> simp_all + theorem insert_in_list_spec0 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ - (b ↔ List.lookup ls.v key = none) + (b ↔ ls.lookup key = none) := match ls with - | .Nil => by simp [insert_in_list, insert_in_list_loop, List.lookup] + | .Nil => by simp [insert_in_list, insert_in_list_loop] | .Cons k v tl => if h: k = key then -- TODO: The order of k/key matters by - simp [insert_in_list, List.lookup] + simp [insert_in_list] rw [insert_in_list_loop] simp [h] else have ⟨ b, hi ⟩ := insert_in_list_spec0 key value tl by exists b - simp [insert_in_list, List.lookup] + simp [insert_in_list] rw [insert_in_list_loop] -- TODO: Using simp leads to infinite recursion - simp [h] - simp [insert_in_list] at hi - exact hi + simp only [insert_in_list] at hi + simp [*] -- Variation: use progress theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ - (b ↔ List.lookup ls.v key = none) + (b ↔ ls.lookup key = none) := match ls with - | .Nil => by simp [insert_in_list, insert_in_list_loop, List.lookup] + | .Nil => by simp [insert_in_list, insert_in_list_loop] | .Cons k v tl => if h: k = key then -- TODO: The order of k/key matters by - simp [insert_in_list, List.lookup] + simp [insert_in_list] rw [insert_in_list_loop] simp [h] else @@ -66,19 +95,17 @@ theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) progress keep as heq as ⟨ b hi ⟩ simp only [insert_in_list] at heq exists b - simp only [heq, hi] - simp [*, List.lookup] -- Variation: use tactics from the beginning theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ - (b ↔ (List.lookup ls.v key = none)) + (b ↔ (ls.lookup key = none)) := by induction ls - case Nil => simp [insert_in_list, insert_in_list_loop, List.lookup] + case Nil => simp [insert_in_list, insert_in_list_loop] case Cons k v tl ih => - simp only [insert_in_list, List.lookup] + simp only [insert_in_list] rw [insert_in_list_loop] simp only if h: k = key then @@ -94,26 +121,27 @@ theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List ∃ l1, insert_in_list_back α key value l0 = ret l1 ∧ -- We update the binding - List.lookup l1.v key = value ∧ - (∀ k, k ≠ key → List.lookup l1.v k = List.lookup l0.v k) + l1.lookup key = value ∧ + (∀ k, k ≠ key → l1.lookup k = l0.lookup k) := match l0 with - | .Nil => by simp [insert_in_list_back, insert_in_list_loop_back, List.lookup]; tauto + | .Nil => by + simp (config := {contextual := true}) [insert_in_list_back, insert_in_list_loop_back] | .Cons k v tl => if h: k = key then by - simp [insert_in_list_back, List.lookup] + simp [insert_in_list_back] rw [insert_in_list_loop_back] - simp [h, List.lookup] + simp [h] intro k1 h1 simp [*] else by - simp [insert_in_list_back, List.lookup] + simp [insert_in_list_back] rw [insert_in_list_loop_back] - simp [h, List.lookup] + simp [h] progress keep as heq as ⟨ tl hp1 hp2 ⟩ simp [insert_in_list_back] at heq - simp (config := {contextual := true}) [*, List.lookup] + simp (config := {contextual := true}) [*] def distinct_keys (ls : Core.List (Usize × α)) := ls.pairwise_rel (λ x y => x.fst ≠ y.fst) @@ -132,44 +160,103 @@ def slot_s_inv (l i : Int) (ls : Core.List (Usize × α)) : Prop := def slot_t_inv (l i : Int) (s : List α) : Prop := slot_s_inv l i s.v -@[pspec] -theorem insert_in_list_back_spec1 {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) +theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) : ∃ l1, insert_in_list_back α key value l0 = ret l1 ∧ -- We update the binding - List.lookup l1.v key = value ∧ - (∀ k, k ≠ key → List.lookup l1.v k = List.lookup l0.v k) ∧ + l1.lookup key = value ∧ + (∀ k, k ≠ key → l1.lookup k = l0.lookup k) ∧ -- We preserve part of the key invariant - slot_s_inv_hash l (hash_mod_key key l) l1.v + slot_s_inv_hash l (hash_mod_key key l) l1.v ∧ + -- Reasoning about the length + match l0.lookup key with + | none => l1.len = l0.len + 1 + | some _ => l1.len = l0.len := match l0 with | .Nil => by - simp [insert_in_list_back, insert_in_list_loop_back, List.lookup, List.v, slot_s_inv_hash] - tauto + simp (config := {contextual := true}) [insert_in_list_back, insert_in_list_loop_back, List.v, slot_s_inv_hash] | .Cons k v tl0 => if h: k = key then by - simp [insert_in_list_back, List.lookup] + simp [insert_in_list_back] rw [insert_in_list_loop_back] - simp [h, List.lookup] + simp [h] constructor . intros; simp [*] . simp [List.v, slot_s_inv_hash] at * simp [*] else by - simp [insert_in_list_back, List.lookup] + simp [insert_in_list_back] rw [insert_in_list_loop_back] - simp [h, List.lookup] + simp [h] have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by simp_all [List.v, slot_s_inv_hash] - progress keep as heq as ⟨ tl1 hp1 hp2 hp3 ⟩ + progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 ⟩ simp only [insert_in_list_back] at heq have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by simp [List.v, slot_s_inv_hash] at * simp [*] - simp (config := {contextual := true}) [*, List.lookup] + -- TODO: canonize addition by default? + simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] +theorem insert_in_list_back_spec_aux1 {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) + (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) + (hdk : distinct_keys l0.v) : + ∃ l1, + insert_in_list_back α key value l0 = ret l1 ∧ + -- We update the binding + l1.lookup key = value ∧ + (∀ k, k ≠ key → l1.lookup k = l0.lookup k) ∧ + -- We preserve part of the key invariant + slot_s_inv_hash l (hash_mod_key key l) l1.v ∧ + -- Reasoning about the length + (match l0.lookup key with + | none => l1.len = l0.len + 1 + | some _ => l1.len = l0.len) ∧ + -- The keys are distinct + distinct_keys l1.v ∧ + -- We need this auxiliary property to prove that the keys distinct properties is preserved + (∀ k, k ≠ key → l0.v.allP (λ (k1, _) => k ≠ k1) → l1.v.allP (λ (k1, _) => k ≠ k1)) + := match l0 with + | .Nil => by + simp (config := {contextual := true}) + [insert_in_list_back, insert_in_list_loop_back, + List.v, slot_s_inv_hash, distinct_keys, List.pairwise_rel] + | .Cons k v tl0 => + if h: k = key then + by + simp [insert_in_list_back] + rw [insert_in_list_loop_back] + simp [h] + split_target_conjs + . intros; simp [*] + . simp [List.v, slot_s_inv_hash] at * + simp [*] + . simp [*, distinct_keys] at * + apply hdk + . tauto + else + by + simp [insert_in_list_back] + rw [insert_in_list_loop_back] + simp [h] + have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by + simp_all [List.v, slot_s_inv_hash] + have : distinct_keys (List.v tl0) := by + simp [distinct_keys] at hdk + simp [hdk, distinct_keys] + progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 hp5 hp6 ⟩ -- TODO: naming is weird + simp only [insert_in_list_back] at heq + have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by + simp [List.v, slot_s_inv_hash] at * + simp [*] + have : distinct_keys ((k, v) :: List.v tl1) := by + simp [distinct_keys] at * + simp [*] + -- TODO: canonize addition by default? + simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] end HashMap -- cgit v1.2.3 From 9b1498aa7fe014ac430467919504d35b0a688934 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 16:13:35 +0200 Subject: Fix a naming issue with progress --- backends/lean/Base/Progress/Progress.lean | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index dabd25b8..1c509775 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -118,17 +118,17 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids match hPost with | none => do return (.Error m!"Too many ids provided ({ids}): there is no postcondition to split") | some hPost => pure hPost - let curPostId := (← hPost.fvarId!.getDecl).userName - let rec splitPost (hPost : Expr) (ids : List Name) : TacticM ProgressError := do + let rec splitPost (prevId : Name) (hPost : Expr) (ids : List Name) : TacticM ProgressError := do match ids with | [] => pure .Ok -- Stop | nid :: ids => do trace[Progress] "Splitting post: {hPost}" -- Split if ← isConj (← inferType hPost) then - splitConjTac hPost (some (nid, curPostId)) (λ _ nhPost => splitPost nhPost ids) + splitConjTac hPost (some (prevId, nid)) (λ _ nhPost => splitPost nid nhPost ids) else return (.Error m!"Too many ids provided ({nid :: ids}) not enough conjuncts to split in the postcondition") - splitPost hPost ids + let curPostId := (← hPost.fvarId!.getDecl).userName + splitPost curPostId hPost ids else return .Ok match res with | .Error _ => return res -- Can we get there? We're using "return" -- cgit v1.2.3 From c5536f372194240d164583cecee5265213b3e671 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Thu, 20 Jul 2023 16:13:47 +0200 Subject: Improve the interactivity of some hashmap proofs --- tests/lean/Hashmap/Properties.lean | 109 ++++++++++++------------------------- 1 file changed, 34 insertions(+), 75 deletions(-) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 66c386f2..dce33fa4 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -6,7 +6,8 @@ open Result namespace List -- TODO: we don't want to use the original List.lookup because it uses BEq --- TODO: rewrite rule: match x == y with ... -> if x = y then ... else ... ? +-- TODO: rewrite rule: match x == y with ... -> if x = y then ... else ... ? (actually doesn't work because of sugar) +-- TODO: move? @[simp] def lookup' {α : Type} (ls: _root_.List (Usize × α)) (key: Usize) : Option α := match ls with @@ -49,6 +50,7 @@ end List @[simp] theorem neq_imp_nbeq_rev [BEq α] [LawfulBEq α] (x y : α) (heq : ¬ x = y) : ¬ y == x := by simp [*] -- TODO: move +-- TODO: this doesn't work because of sugar theorem match_lawful_beq [BEq α] [LawfulBEq α] [DecidableEq α] (x y : α) : (x == y) = (if x = y then true else false) := by split <;> simp_all @@ -161,47 +163,6 @@ def slot_s_inv (l i : Int) (ls : Core.List (Usize × α)) : Prop := def slot_t_inv (l i : Int) (s : List α) : Prop := slot_s_inv l i s.v theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) - (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) : - ∃ l1, - insert_in_list_back α key value l0 = ret l1 ∧ - -- We update the binding - l1.lookup key = value ∧ - (∀ k, k ≠ key → l1.lookup k = l0.lookup k) ∧ - -- We preserve part of the key invariant - slot_s_inv_hash l (hash_mod_key key l) l1.v ∧ - -- Reasoning about the length - match l0.lookup key with - | none => l1.len = l0.len + 1 - | some _ => l1.len = l0.len - := match l0 with - | .Nil => by - simp (config := {contextual := true}) [insert_in_list_back, insert_in_list_loop_back, List.v, slot_s_inv_hash] - | .Cons k v tl0 => - if h: k = key then - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - constructor - . intros; simp [*] - . simp [List.v, slot_s_inv_hash] at * - simp [*] - else - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by - simp_all [List.v, slot_s_inv_hash] - progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 ⟩ - simp only [insert_in_list_back] at heq - have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by - simp [List.v, slot_s_inv_hash] at * - simp [*] - -- TODO: canonize addition by default? - simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] - -theorem insert_in_list_back_spec_aux1 {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) (hdk : distinct_keys l0.v) : ∃ l1, @@ -220,43 +181,41 @@ theorem insert_in_list_back_spec_aux1 {α : Type} (l : Int) (key: Usize) (value: -- We need this auxiliary property to prove that the keys distinct properties is preserved (∀ k, k ≠ key → l0.v.allP (λ (k1, _) => k ≠ k1) → l1.v.allP (λ (k1, _) => k ≠ k1)) := match l0 with - | .Nil => by + | .Nil => by checkpoint simp (config := {contextual := true}) [insert_in_list_back, insert_in_list_loop_back, List.v, slot_s_inv_hash, distinct_keys, List.pairwise_rel] | .Cons k v tl0 => - if h: k = key then - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - split_target_conjs - . intros; simp [*] - . simp [List.v, slot_s_inv_hash] at * - simp [*] - . simp [*, distinct_keys] at * - apply hdk - . tauto - else - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by - simp_all [List.v, slot_s_inv_hash] - have : distinct_keys (List.v tl0) := by - simp [distinct_keys] at hdk - simp [hdk, distinct_keys] - progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 hp5 hp6 ⟩ -- TODO: naming is weird - simp only [insert_in_list_back] at heq - have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by - simp [List.v, slot_s_inv_hash] at * - simp [*] - have : distinct_keys ((k, v) :: List.v tl1) := by - simp [distinct_keys] at * - simp [*] - -- TODO: canonize addition by default? - simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] + if h: k = key then by checkpoint + simp [insert_in_list_back] + rw [insert_in_list_loop_back] + simp [h] + split_target_conjs + . intros; simp [*] + . simp [List.v, slot_s_inv_hash] at * + simp [*] + . simp [*, distinct_keys] at * + apply hdk + . tauto + else by checkpoint + simp [insert_in_list_back] + rw [insert_in_list_loop_back] + simp [h] + have : slot_s_inv_hash l (hash_mod_key key l) (List.v tl0) := by checkpoint + simp_all [List.v, slot_s_inv_hash] + have : distinct_keys (List.v tl0) := by checkpoint + simp [distinct_keys] at hdk + simp [hdk, distinct_keys] + progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 hp5 hp6 ⟩ + simp only [insert_in_list_back] at heq + have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by checkpoint + simp [List.v, slot_s_inv_hash] at * + simp [*] + have : distinct_keys ((k, v) :: List.v tl1) := by checkpoint + simp [distinct_keys] at * + simp [*] + -- TODO: canonize addition by default? + simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] end HashMap -- cgit v1.2.3 From 2dd56a51df01421fe7766858c9d37998db4123b5 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 11:53:49 +0200 Subject: Improve the syntax of progress: `as ⟨ x, y .. ⟩` --- backends/lean/Base/Progress/Progress.lean | 77 ++++++++++++++++++------------- backends/lean/Base/Utils.lean | 61 ++++++++++++++++++------ tests/lean/Hashmap/Properties.lean | 34 ++------------ 3 files changed, 98 insertions(+), 74 deletions(-) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 1c509775..c8f94e9e 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -23,7 +23,8 @@ inductive ProgressError | Error (msg : MessageData) deriving Inhabited -def progressWith (fExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids : Array Name) +def progressWith (fExpr : Expr) (th : TheoremOrLocal) + (keep : Option Name) (ids : Array Name) (splitPost : Bool) (asmTac : TacticM Unit) : TacticM ProgressError := do /- Apply the theorem We try to match the theorem with the goal @@ -112,24 +113,31 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) (keep : Option Name) (ids mgoal.tryClearMany #[hEq.fvarId!] setGoals (mgoal :: (← getUnsolvedGoals)) trace[Progress] "Goal after splitting eq and post and simplifying the target: {mgoal}" - -- Continue splitting following the ids provided by the user - if ¬ ids.isEmpty then - let hPost ← - match hPost with - | none => do return (.Error m!"Too many ids provided ({ids}): there is no postcondition to split") - | some hPost => pure hPost - let rec splitPost (prevId : Name) (hPost : Expr) (ids : List Name) : TacticM ProgressError := do + -- Continue splitting following the post following the user's instructions + match hPost with + | none => + -- Sanity check + if ¬ ids.isEmpty then + return (.Error m!"Too many ids provided ({ids}): there is no postcondition to split") + else return .Ok + | some hPost => do + let rec splitPostWithIds (prevId : Name) (hPost : Expr) (ids : List Name) : TacticM ProgressError := do match ids with - | [] => pure .Ok -- Stop + | [] => + /- We used all the user provided ids. + Split the remaining conjunctions by using fresh ids if the user + instructed to fully split the post-condition, otherwise stop -/ + if splitPost then + splitFullConjTac hPost (λ _ => pure .Ok) + else pure .Ok | nid :: ids => do trace[Progress] "Splitting post: {hPost}" -- Split if ← isConj (← inferType hPost) then - splitConjTac hPost (some (prevId, nid)) (λ _ nhPost => splitPost nid nhPost ids) + splitConjTac hPost (some (prevId, nid)) (λ _ nhPost => splitPostWithIds nid nhPost ids) else return (.Error m!"Too many ids provided ({nid :: ids}) not enough conjuncts to split in the postcondition") let curPostId := (← hPost.fvarId!.getDecl).userName - splitPost curPostId hPost ids - else return .Ok + splitPostWithIds curPostId hPost ids match res with | .Error _ => return res -- Can we get there? We're using "return" | .Ok => @@ -160,7 +168,8 @@ def getFirstArg (args : Array Expr) : Option Expr := do /- Helper: try to lookup a theorem and apply it, or continue with another tactic if it fails -/ -def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Unit) (fExpr : Expr) +def tryLookupApply (keep : Option Name) (ids : Array Name) (splitPost : Bool) + (asmTac : TacticM Unit) (fExpr : Expr) (kind : String) (th : Option TheoremOrLocal) (x : TacticM Unit) : TacticM Unit := do let res ← do match th with @@ -172,7 +181,7 @@ def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Uni -- Apply the theorem let res ← do try - let res ← progressWith fExpr th keep ids asmTac + let res ← progressWith fExpr th keep ids splitPost asmTac pure (some res) catch _ => none match res with @@ -181,7 +190,8 @@ def tryLookupApply (keep : Option Name) (ids : Array Name) (asmTac : TacticM Uni | none => x -- The array of ids are identifiers to use when introducing fresh variables -def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrLocal) (ids : Array Name) (asmTac : TacticM Unit) : TacticM Unit := do +def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrLocal) + (ids : Array Name) (splitPost : Bool) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do -- Retrieve the goal let mgoal ← Tactic.getMainGoal @@ -197,7 +207,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL -- Otherwise, lookup one. match withTh with | some th => do - match ← progressWith fExpr th keep ids asmTac with + match ← progressWith fExpr th keep ids splitPost asmTac with | .Ok => return () | .Error msg => throwError msg | none => @@ -206,7 +216,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL let decls ← ctx.getDecls for decl in decls.reverse do trace[Progress] "Trying assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fExpr (.Local decl) keep ids asmTac catch _ => continue + let res ← do try progressWith fExpr (.Local decl) keep ids splitPost asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg @@ -216,7 +226,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL let pspec ← do let thName ← pspecAttr.find? fName pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fExpr "pspec theorem" pspec do + tryLookupApply keep ids splitPost asmTac fExpr "pspec theorem" pspec do -- It failed: try to lookup a *class* expr spec theorem (those are more -- specific than class spec theorems) let pspecClassExpr ← do @@ -225,7 +235,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | some arg => do let thName ← pspecClassExprAttr.find? fName arg pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fExpr "pspec class expr theorem" pspecClassExpr do + tryLookupApply keep ids splitPost asmTac fExpr "pspec class expr theorem" pspecClassExpr do -- It failed: try to lookup a *class* spec theorem let pspecClass ← do match ← getFirstArgAppName args with @@ -233,7 +243,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | some argName => do let thName ← pspecClassAttr.find? fName argName pure (thName.map fun th => .Theorem th) - tryLookupApply keep ids asmTac fExpr "pspec class theorem" pspecClass do + tryLookupApply keep ids splitPost asmTac fExpr "pspec class theorem" pspecClass do -- Try a recursive call - we try the assumptions of kind "auxDecl" let ctx ← Lean.MonadLCtx.getLCtx let decls ← ctx.getAllDecls @@ -241,14 +251,14 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL | .default | .implDetail => false | .auxDecl => true) for decl in decls.reverse do trace[Progress] "Trying recursive assumption: {decl.userName} : {decl.type}" - let res ← do try progressWith fExpr (.Local decl) keep ids asmTac catch _ => continue + let res ← do try progressWith fExpr (.Local decl) keep ids splitPost asmTac catch _ => continue match res with | .Ok => return () | .Error msg => throwError msg -- Nothing worked: failed throwError "Progress failed" -syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " (ident)+ " ⟩")? +syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " ident,* " .."? " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw @@ -263,8 +273,8 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do else do pure (some (← mkFreshUserName `h)) else pure none trace[Progress] "Keep: {keep}" - let withArg := (args.get! 1).getArgs let withArg ← do + let withArg := (args.get! 1).getArgs if withArg.size > 0 then let id := withArg.get! 1 trace[Progress] "With arg: {id}" @@ -283,20 +293,25 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do | id :: _ => pure (some (.Theorem id)) else pure none - let args := (args.get! 2).getArgs - let args := (args.get! 2).getArgs - let ids := args.map Syntax.getId + let ids := + let args := (args.get! 2).getArgs + let args := (args.get! 2).getSepArgs + args.map Syntax.getId trace[Progress] "User-provided ids: {ids}" - progressAsmsOrLookupTheorem keep withArg ids (firstTac [assumptionTac, Arith.scalarTac]) + let splitPost : Bool := + let args := (args.get! 2).getArgs + (args.get! 3).getArgs.size > 0 + trace[Progress] "Split post: {splitPost}" + progressAsmsOrLookupTheorem keep withArg ids splitPost (firstTac [assumptionTac, Arith.scalarTac]) elab "progress" args:progressArgs : tactic => evalProgress args -/- -namespace Test +/-namespace Test open Primitives Result set_option trace.Progress true + set_option pp.rawOnError true #eval showStoredPSpec #eval showStoredPSpecClass @@ -306,9 +321,9 @@ namespace Test (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by -- progress keep as h with Scalar.add_spec as ⟨ z ⟩ - progress keep as h + progress keep as h as ⟨ z, h1 .. ⟩ simp [*] -end Test -/ +end Test-/ end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index f014e112..3b3d4729 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -499,7 +499,10 @@ def splitConjTac (h : Expr) (optIds : Option (Name × Name)) (k : Expr → Expr -- Try to use the user-provided names let altVarNames ← match optIds with - | none => pure #[] + | none => do + let id0 ← mkFreshUserName `h + let id1 ← mkFreshUserName `h + pure #[{ varNames := [id0, id1] }] | some (id0, id1) => do pure #[{ varNames := [id0, id1] }] let newGoals ← goal.cases h.fvarId! altVarNames @@ -518,29 +521,61 @@ def splitConjTac (h : Expr) (optIds : Option (Name × Name)) (k : Expr → Expr else throwError "Not a conjunction" -elab "split_conj " n:ident : tactic => do +-- Tactic to fully split a conjunction +partial def splitFullConjTacAux [Inhabited α] [Nonempty α] (l : List Expr) (h : Expr) (k : List Expr → TacticM α) : TacticM α := do + try + splitConjTac h none (λ h1 h2 => + splitFullConjTacAux l h1 (λ l1 => + splitFullConjTacAux l1 h2 (λ l2 => + k l2))) + catch _ => + k (h :: l) + +-- Tactic to fully split a conjunction +def splitFullConjTac [Inhabited α] [Nonempty α] (h : Expr) (k : List Expr → TacticM α) : TacticM α := do + splitFullConjTacAux [] h (λ l => k l.reverse) + +syntax optAtArgs := ("at" ident)? +def elabOptAtArgs (args : TSyntax `Utils.optAtArgs) : TacticM (Option Expr) := do withMainContext do - let decl ← Lean.Meta.getLocalDeclFromUserName n.getId - let fvar := mkFVar decl.fvarId - splitConjTac fvar none (fun _ _ => pure ()) + let args := (args.raw.getArgs.get! 0).getArgs + if args.size > 0 then do + let n := (args.get! 1).getId + let decl ← Lean.Meta.getLocalDeclFromUserName n + let fvar := mkFVar decl.fvarId + pure (some fvar) + else + pure none -elab "split_all_exists " n:ident : tactic => do +elab "split_conj" args:optAtArgs : tactic => do + withMainContext do + match ← elabOptAtArgs args with + | some fvar => + splitConjTac fvar none (fun _ _ => pure ()) + | none => + splitConjTarget + +elab "split_conjs" args:optAtArgs : tactic => do + withMainContext do + match ← elabOptAtArgs args with + | some fvar => + splitFullConjTac fvar (fun _ => pure ()) + | none => + repeatTac splitConjTarget + +elab "split_existsl" " at " n:ident : tactic => do withMainContext do let decl ← Lean.Meta.getLocalDeclFromUserName n.getId let fvar := mkFVar decl.fvarId splitAllExistsTac fvar [] (fun _ _ => pure ()) -elab "split_target_conjs" : tactic => - withMainContext do - repeatTac splitConjTarget - example (h : a ∧ b) : a := by - split_all_exists h - split_conj h + split_existsl at h + split_conj at h assumption example (h : ∃ x y z, x + y + z ≥ 0) : ∃ x, x ≥ 0 := by - split_all_exists h + split_existsl at h rename_i x y z exists x + y + z diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index dce33fa4..de6bf636 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -94,7 +94,7 @@ theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) simp only [insert_in_list] rw [insert_in_list_loop] conv => rhs; ext; simp [*] - progress keep as heq as ⟨ b hi ⟩ + progress keep as heq as ⟨ b, hi ⟩ simp only [insert_in_list] at heq exists b @@ -116,35 +116,9 @@ theorem insert_in_list_spec2 {α : Type} (key: Usize) (value: α) (ls: List α) conv => rhs; ext; left; simp [h] -- TODO: Simplify simp only [insert_in_list] at ih; -- TODO: give the possibility of using underscores - progress as ⟨ b h ⟩ + progress as ⟨ b, h ⟩ simp [*] -theorem insert_in_list_back_spec {α : Type} (key: Usize) (value: α) (l0: List α) : - ∃ l1, - insert_in_list_back α key value l0 = ret l1 ∧ - -- We update the binding - l1.lookup key = value ∧ - (∀ k, k ≠ key → l1.lookup k = l0.lookup k) - := match l0 with - | .Nil => by - simp (config := {contextual := true}) [insert_in_list_back, insert_in_list_loop_back] - | .Cons k v tl => - if h: k = key then - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - intro k1 h1 - simp [*] - else - by - simp [insert_in_list_back] - rw [insert_in_list_loop_back] - simp [h] - progress keep as heq as ⟨ tl hp1 hp2 ⟩ - simp [insert_in_list_back] at heq - simp (config := {contextual := true}) [*] - def distinct_keys (ls : Core.List (Usize × α)) := ls.pairwise_rel (λ x y => x.fst ≠ y.fst) def hash_mod_key (k : Usize) (l : Int) : Int := @@ -190,7 +164,7 @@ theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: simp [insert_in_list_back] rw [insert_in_list_loop_back] simp [h] - split_target_conjs + split_conjs . intros; simp [*] . simp [List.v, slot_s_inv_hash] at * simp [*] @@ -206,7 +180,7 @@ theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: have : distinct_keys (List.v tl0) := by checkpoint simp [distinct_keys] at hdk simp [hdk, distinct_keys] - progress keep as heq as ⟨ tl1 hp1 hp2 hp3 hp4 hp5 hp6 ⟩ + progress keep as heq as ⟨ tl1 .. ⟩ simp only [insert_in_list_back] at heq have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by checkpoint simp [List.v, slot_s_inv_hash] at * -- cgit v1.2.3 From c652e97f7ab13164150331b4aa3f2e7ef11d24b9 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 12:13:20 +0200 Subject: Add the possibility of using "_" as ident for progress --- backends/lean/Base/Progress/Progress.lean | 37 ++++++++++++++++++------------- backends/lean/Base/Utils.lean | 7 ++++-- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index c8f94e9e..c0ddc63d 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -24,7 +24,7 @@ inductive ProgressError deriving Inhabited def progressWith (fExpr : Expr) (th : TheoremOrLocal) - (keep : Option Name) (ids : Array Name) (splitPost : Bool) + (keep : Option Name) (ids : Array (Option Name)) (splitPost : Bool) (asmTac : TacticM Unit) : TacticM ProgressError := do /- Apply the theorem We try to match the theorem with the goal @@ -90,13 +90,14 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) -- For the conjunctions, we split according once to separate the equality `f ... = .ret ...` -- from the postcondition, if there is, then continue to split the postcondition if there -- are remaining ids. - let splitEqAndPost (k : Expr → Option Expr → List Name → TacticM ProgressError) : TacticM ProgressError := do + let splitEqAndPost (k : Expr → Option Expr → List (Option Name) → TacticM ProgressError) : TacticM ProgressError := do if ← isConj (← inferType h) then do let hName := (← h.fvarId!.getDecl).userName - let (optId, ids) := listTryPopHead ids - let optIds ← match optId with - | none => do pure (some (hName, ← mkFreshUserName `h)) - | some id => do pure (some (hName, id)) + let (optIds, ids) ← do + match ids with + | [] => do pure (some (hName, ← mkFreshUserName `h), []) + | none :: ids => do pure (some (hName, ← mkFreshUserName `h), ids) + | some id :: ids => do pure (some (hName, id), ids) splitConjTac h optIds (fun hEq hPost => k hEq (some hPost) ids) else k h none ids -- Simplify the target by using the equality and some monad simplifications, @@ -121,8 +122,8 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) return (.Error m!"Too many ids provided ({ids}): there is no postcondition to split") else return .Ok | some hPost => do - let rec splitPostWithIds (prevId : Name) (hPost : Expr) (ids : List Name) : TacticM ProgressError := do - match ids with + let rec splitPostWithIds (prevId : Name) (hPost : Expr) (ids0 : List (Option Name)) : TacticM ProgressError := do + match ids0 with | [] => /- We used all the user provided ids. Split the remaining conjunctions by using fresh ids if the user @@ -133,9 +134,13 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) | nid :: ids => do trace[Progress] "Splitting post: {hPost}" -- Split + let nid ← do + match nid with + | none => mkFreshUserName `h + | some nid => pure nid if ← isConj (← inferType hPost) then splitConjTac hPost (some (prevId, nid)) (λ _ nhPost => splitPostWithIds nid nhPost ids) - else return (.Error m!"Too many ids provided ({nid :: ids}) not enough conjuncts to split in the postcondition") + else return (.Error m!"Too many ids provided ({ids0}) not enough conjuncts to split in the postcondition") let curPostId := (← hPost.fvarId!.getDecl).userName splitPostWithIds curPostId hPost ids match res with @@ -168,7 +173,7 @@ def getFirstArg (args : Array Expr) : Option Expr := do /- Helper: try to lookup a theorem and apply it, or continue with another tactic if it fails -/ -def tryLookupApply (keep : Option Name) (ids : Array Name) (splitPost : Bool) +def tryLookupApply (keep : Option Name) (ids : Array (Option Name)) (splitPost : Bool) (asmTac : TacticM Unit) (fExpr : Expr) (kind : String) (th : Option TheoremOrLocal) (x : TacticM Unit) : TacticM Unit := do let res ← do @@ -191,7 +196,7 @@ def tryLookupApply (keep : Option Name) (ids : Array Name) (splitPost : Bool) -- The array of ids are identifiers to use when introducing fresh variables def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrLocal) - (ids : Array Name) (splitPost : Bool) (asmTac : TacticM Unit) : TacticM Unit := do + (ids : Array (Option Name)) (splitPost : Bool) (asmTac : TacticM Unit) : TacticM Unit := do withMainContext do -- Retrieve the goal let mgoal ← Tactic.getMainGoal @@ -258,7 +263,7 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL -- Nothing worked: failed throwError "Progress failed" -syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " ident,* " .."? " ⟩")? +syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " (ident <|> "_"),* " .."? " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw @@ -296,7 +301,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let ids := let args := (args.get! 2).getArgs let args := (args.get! 2).getSepArgs - args.map Syntax.getId + args.map (λ s => if s.isIdent then some s.getId else none) trace[Progress] "User-provided ids: {ids}" let splitPost : Bool := let args := (args.get! 2).getArgs @@ -307,7 +312,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do elab "progress" args:progressArgs : tactic => evalProgress args -/-namespace Test +/- namespace Test open Primitives Result set_option trace.Progress true @@ -321,9 +326,9 @@ elab "progress" args:progressArgs : tactic => (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by -- progress keep as h with Scalar.add_spec as ⟨ z ⟩ - progress keep as h as ⟨ z, h1 .. ⟩ + progress keep as h as ⟨ x, h1 .. ⟩ simp [*] -end Test-/ +end Test -/ end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 3b3d4729..66497a49 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -484,9 +484,12 @@ def listTryPopHead (ls : List α) : Option α × List α := If `ids` is not empty, we use it to name the introduced variables. We transmit the stripped expression and the remaining ids to the continuation. -/ -partial def splitAllExistsTac [Inhabited α] (h : Expr) (ids : List Name) (k : Expr → List Name → TacticM α) : TacticM α := do +partial def splitAllExistsTac [Inhabited α] (h : Expr) (ids : List (Option Name)) (k : Expr → List (Option Name) → TacticM α) : TacticM α := do try - let (optId, ids) := listTryPopHead ids + let (optId, ids) := + match ids with + | [] => (none, []) + | x :: ids => (x, ids) splitExistsTac h optId (fun _ body => splitAllExistsTac body ids k) catch _ => k h ids -- cgit v1.2.3 From 876137dff361620d8ade1a4ee94fa9274df0bdc6 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 14:08:44 +0200 Subject: Improve int_tac and scalar_tac --- backends/lean/Base/Arith/Int.lean | 63 +++++++++++++++++++++++++++---- backends/lean/Base/Arith/Scalar.lean | 6 +-- backends/lean/Base/IList/IList.lean | 12 ++---- backends/lean/Base/Primitives/Vec.lean | 25 ++++++------ backends/lean/Base/Progress/Progress.lean | 13 ++++++- 5 files changed, 87 insertions(+), 32 deletions(-) diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index fa957293..3415866e 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -24,12 +24,29 @@ class PropHasImp (x : Prop) where concl : Prop prop : x → concl +instance (p : Int → Prop) : HasIntProp (Subtype p) where + prop_ty := λ x => p x + prop := λ x => x.property + -- This also works for `x ≠ y` because this expression reduces to `¬ x = y` -- and `Ne` is marked as `reducible` instance (x y : Int) : PropHasImp (¬ x = y) where concl := x < y ∨ x > y prop := λ (h:x ≠ y) => ne_is_lt_or_gt h +-- Check if a proposition is a linear integer proposition. +-- We notably use this to check the goals. +class IsLinearIntProp (x : Prop) where + +instance (x y : Int) : IsLinearIntProp (x < y) where +instance (x y : Int) : IsLinearIntProp (x > y) where +instance (x y : Int) : IsLinearIntProp (x ≤ y) where +instance (x y : Int) : IsLinearIntProp (x ≥ y) where +instance (x y : Int) : IsLinearIntProp (x ≥ y) where +/- It seems we don't need to do any special preprocessing when the *goal* + has the following shape - I guess `linarith` automatically calls `intro` -/ +instance (x y : Int) : IsLinearIntProp (¬ x = y) where + open Lean Lean.Elab Lean.Meta -- Explore a term by decomposing the applications (we explore the applied @@ -189,14 +206,27 @@ def intTacPreprocess (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM U elab "int_tac_preprocess" : tactic => intTacPreprocess (do pure ()) -def intTac (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do +-- Check if the goal is a linear arithmetic goal +def goalIsLinearInt : Tactic.TacticM Bool := do + Tactic.withMainContext do + let gty ← Tactic.getMainTarget + match ← trySynthInstance (← mkAppM ``IsLinearIntProp #[gty]) with + | .some _ => pure true + | _ => pure false + +def intTac (splitGoalConjs : Bool) (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do Tactic.withMainContext do Tactic.focus do + let g ← Tactic.getMainGoal + trace[Arith] "Original goal: {g}" + -- Introduce all the universally quantified variables (includes the assumptions) + let (_, g) ← g.intros + Tactic.setGoals [g] -- Preprocess - wondering if we should do this before or after splitting -- the goal. I think before leads to a smaller proof term? Tactic.allGoals (intTacPreprocess extraPreprocess) -- Split the conjunctions in the goal - Tactic.allGoals (Utils.repeatTac Utils.splitConjTarget) + if splitGoalConjs then Tactic.allGoals (Utils.repeatTac Utils.splitConjTarget) -- Call linarith let linarith := do let cfg : Linarith.LinarithConfig := { @@ -204,10 +234,25 @@ def intTac (extraPreprocess : Tactic.TacticM Unit) : Tactic.TacticM Unit := do splitNe := false } Tactic.liftMetaFinishingTactic <| Linarith.linarith false [] cfg - Tactic.allGoals linarith - -elab "int_tac" : tactic => - intTac (do pure ()) + Tactic.allGoals do + -- We check if the goal is a linear arithmetic goal: if yes, we directly + -- call linarith, otherwise we first apply exfalso (we do this because + -- linarith is too general and sometimes fails to do this correctly). + if ← goalIsLinearInt then do + trace[Arith] "linarith goal: {← Tactic.getMainGoal}" + linarith + else do + let g ← Tactic.getMainGoal + let gs ← g.apply (Expr.const ``False.elim [.zero]) + let goals ← Tactic.getGoals + Tactic.setGoals (gs ++ goals) + Tactic.allGoals do + trace[Arith] "linarith goal: {← Tactic.getMainGoal}" + linarith + +elab "int_tac" args:(" split_goal"?): tactic => + let split := args.raw.getArgs.size > 0 + intTac split (do pure ()) example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by int_tac_preprocess @@ -219,10 +264,14 @@ example (x : Int) (h0: 0 ≤ x) (h1: x ≠ 0) : 0 < x := by -- Checking that things append correctly when there are several disjunctions example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y := by - int_tac + int_tac split_goal -- Checking that things append correctly when there are several disjunctions example (x y : Int) (h0: 0 ≤ x) (h1: x ≠ 0) (h2 : 0 ≤ y) (h3 : y ≠ 0) : 0 < x ∧ 0 < y ∧ x + y ≥ 2 := by + int_tac split_goal + +-- Checking that we can prove exfalso +example (a : Prop) (x : Int) (h0: 0 < x) (h1: x < 0) : a := by int_tac end Arith diff --git a/backends/lean/Base/Arith/Scalar.lean b/backends/lean/Base/Arith/Scalar.lean index f8903ecf..a56ea08b 100644 --- a/backends/lean/Base/Arith/Scalar.lean +++ b/backends/lean/Base/Arith/Scalar.lean @@ -28,11 +28,11 @@ elab "scalar_tac_preprocess" : tactic => intTacPreprocess scalarTacExtraPreprocess -- A tactic to solve linear arithmetic goals in the presence of scalars -def scalarTac : Tactic.TacticM Unit := do - intTac scalarTacExtraPreprocess +def scalarTac (splitGoalConjs : Bool) : Tactic.TacticM Unit := do + intTac splitGoalConjs scalarTacExtraPreprocess elab "scalar_tac" : tactic => - scalarTac + scalarTac false instance (ty : ScalarTy) : HasIntProp (Scalar ty) where -- prop_ty is inferred diff --git a/backends/lean/Base/IList/IList.lean b/backends/lean/Base/IList/IList.lean index 1773e593..2443b1a6 100644 --- a/backends/lean/Base/IList/IList.lean +++ b/backends/lean/Base/IList/IList.lean @@ -46,21 +46,18 @@ theorem indexOpt_bounds (ls : List α) (i : Int) : ls.indexOpt i = none ↔ i < 0 ∨ ls.len ≤ i := match ls with | [] => - have : ¬ (i < 0) → 0 ≤ i := by intro; linarith -- TODO: simplify (we could boost int_tac) + have : ¬ (i < 0) → 0 ≤ i := by int_tac by simp; tauto | _ :: tl => have := indexOpt_bounds tl (i - 1) if h: i = 0 then by simp [*]; - -- TODO: int_tac/scalar_tac should also explore the goal! - have := tl.len_pos - linarith + int_tac else by simp [*] constructor <;> intros <;> - -- TODO: tactic to split all disjunctions - rename_i hor <;> cases hor <;> + casesm* _ ∨ _ <;> -- splits all the disjunctions first | left; int_tac | right; int_tac theorem indexOpt_eq_index [Inhabited α] (ls : List α) (i : Int) : @@ -126,7 +123,6 @@ theorem length_update (ls : List α) (i : Int) (x : α) : (ls.update i x).length theorem len_update (ls : List α) (i : Int) (x : α) : (ls.update i x).len = ls.len := by simp [len_eq_length] - theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by revert l1' @@ -203,7 +199,7 @@ theorem index_eq (l.update i x).index i = x := fun _ _ => match l with - | [] => by simp at *; exfalso; scalar_tac -- TODO: exfalso needed. Son FIXME + | [] => by simp at *; scalar_tac | hd :: tl => if h: i = 0 then by diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index be3a0e5b..35092c29 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -16,20 +16,19 @@ open Result Error -- VECTORS -- ------------- -def Vec (α : Type u) := { l : List α // List.length l ≤ Usize.max } +def Vec (α : Type u) := { l : List α // l.length ≤ Usize.max } -- TODO: do we really need it? It should be with Subtype by default -instance Vec.cast (a : Type): Coe (Vec a) (List a) where coe := λ v => v.val +instance Vec.cast (a : Type u): Coe (Vec a) (List a) where coe := λ v => v.val -instance (a : Type) : Arith.HasIntProp (Vec a) where - prop_ty := λ v => v.val.length ≤ Scalar.max ScalarTy.Usize - prop := λ ⟨ _, l ⟩ => l +instance (a : Type u) : Arith.HasIntProp (Vec a) where + prop_ty := λ v => v.val.len ≤ Scalar.max ScalarTy.Usize + prop := λ ⟨ _, l ⟩ => by simp[Scalar.max, List.len_eq_length, *] -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by - intro_has_int_prop_instances - simp_all [Scalar.max, Scalar.min] +@[simp] +abbrev Vec.length {α : Type u} (v : Vec α) : Int := v.val.len -example {a: Type} (v : Vec a) : v.val.length ≤ Scalar.max ScalarTy.Usize := by +example {a: Type u} (v : Vec a) : v.length ≤ Scalar.max ScalarTy.Usize := by scalar_tac def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ @@ -38,9 +37,6 @@ def Vec.len (α : Type u) (v : Vec α) : Usize := let ⟨ v, l ⟩ := v Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l -@[simp] -abbrev Vec.length {α : Type u} (v : Vec α) : Int := v.val.len - -- This shouldn't be used def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () @@ -115,11 +111,14 @@ theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) simp only [*] +instance {α : Type u} (p : Vec α → Prop) : Arith.HasIntProp (Subtype p) where + prop_ty := λ x => p x + prop := λ x => x.property + def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Vec α) := match v.val.indexOpt i.val with | none => fail .arrayOutOfBounds | some _ => - -- TODO: int_tac: introduce the refinements in the context? .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ @[pspec] diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index c0ddc63d..a281f1d2 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -307,7 +307,18 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := (args.get! 2).getArgs (args.get! 3).getArgs.size > 0 trace[Progress] "Split post: {splitPost}" - progressAsmsOrLookupTheorem keep withArg ids splitPost (firstTac [assumptionTac, Arith.scalarTac]) + /- For scalarTac we have a fast track: if the goal is not a linear + arithmetic goal, we skip (note that otherwise, scalarTac would try + to prove a contradiction) -/ + let scalarTac : TacticM Unit := do + if ← Arith.goalIsLinearInt then + -- Also: we don't try to split the goal if it is a conjunction + -- (it shouldn't be) + Arith.scalarTac false + else + throwError "Not a linear arithmetic goal" + progressAsmsOrLookupTheorem keep withArg ids splitPost ( + firstTac [assumptionTac, scalarTac]) elab "progress" args:progressArgs : tactic => evalProgress args -- cgit v1.2.3 From 1854c631a6a7a3f8d45ad18e05547f9d3782c3ee Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 16:26:08 +0200 Subject: Make progress on the hashmap properties --- backends/lean/Base/Arith/Base.lean | 4 ++ backends/lean/Base/Arith/Int.lean | 2 + backends/lean/Base/Arith/Scalar.lean | 3 +- backends/lean/Base/Primitives/Scalar.lean | 48 +++++++++------- backends/lean/Base/Primitives/Vec.lean | 13 ++++- backends/lean/Base/Progress/Base.lean | 4 +- backends/lean/Base/Progress/Progress.lean | 4 +- tests/lean/Hashmap/Properties.lean | 92 +++++++++++++++++++++++++++++++ 8 files changed, 141 insertions(+), 29 deletions(-) diff --git a/backends/lean/Base/Arith/Base.lean b/backends/lean/Base/Arith/Base.lean index e008f7b9..9c11ed45 100644 --- a/backends/lean/Base/Arith/Base.lean +++ b/backends/lean/Base/Arith/Base.lean @@ -53,4 +53,8 @@ theorem int_pos_ind (p : Int → Prop) : rename_i m cases m <;> simp_all +-- We sometimes need this to make sure no natural numbers appear in the goals +-- TODO: there is probably something more general to do +theorem nat_zero_eq_int_zero : (0 : Nat) = (0 : Int) := by simp + end Arith diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index 3415866e..bc0676d8 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -225,6 +225,8 @@ def intTac (splitGoalConjs : Bool) (extraPreprocess : Tactic.TacticM Unit) : Ta -- Preprocess - wondering if we should do this before or after splitting -- the goal. I think before leads to a smaller proof term? Tactic.allGoals (intTacPreprocess extraPreprocess) + -- More preprocessing + Tactic.allGoals (Utils.simpAt [] [``nat_zero_eq_int_zero] [] .wildcard) -- Split the conjunctions in the goal if splitGoalConjs then Tactic.allGoals (Utils.repeatTac Utils.splitConjTarget) -- Call linarith diff --git a/backends/lean/Base/Arith/Scalar.lean b/backends/lean/Base/Arith/Scalar.lean index a56ea08b..6f4a8eba 100644 --- a/backends/lean/Base/Arith/Scalar.lean +++ b/backends/lean/Base/Arith/Scalar.lean @@ -21,7 +21,8 @@ def scalarTacExtraPreprocess : Tactic.TacticM Unit := do ``I8.min, ``I16.min, ``I32.min, ``I64.min, ``I128.min, ``I8.max, ``I16.max, ``I32.max, ``I64.max, ``I128.max, ``U8.min, ``U16.min, ``U32.min, ``U64.min, ``U128.min, - ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max + ``U8.max, ``U16.max, ``U32.max, ``U64.max, ``U128.max, + ``Usize.min ] [] [] .wildcard elab "scalar_tac_preprocess" : tactic => diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean index 1e9b51c2..3beb7527 100644 --- a/backends/lean/Base/Primitives/Scalar.lean +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -66,27 +66,33 @@ def U128.smin : Int := 0 def U128.smax : Int := HPow.hPow 2 128 - 1 -- The "normalized" bounds, that we use in practice -def I8.min := -128 -def I8.max := 127 -def I16.min := -32768 -def I16.max := 32767 -def I32.min := -2147483648 -def I32.max := 2147483647 -def I64.min := -9223372036854775808 -def I64.max := 9223372036854775807 -def I128.min := -170141183460469231731687303715884105728 -def I128.max := 170141183460469231731687303715884105727 -@[simp] def U8.min := 0 -def U8.max := 255 -@[simp] def U16.min := 0 -def U16.max := 65535 -@[simp] def U32.min := 0 -def U32.max := 4294967295 -@[simp] def U64.min := 0 -def U64.max := 18446744073709551615 -@[simp] def U128.min := 0 -def U128.max := 340282366920938463463374607431768211455 -@[simp] def Usize.min := 0 +def I8.min : Int := -128 +def I8.max : Int := 127 +def I16.min : Int := -32768 +def I16.max : Int := 32767 +def I32.min : Int := -2147483648 +def I32.max : Int := 2147483647 +def I64.min : Int := -9223372036854775808 +def I64.max : Int := 9223372036854775807 +def I128.min : Int := -170141183460469231731687303715884105728 +def I128.max : Int := 170141183460469231731687303715884105727 +@[simp] +def U8.min : Int := 0 +def U8.max : Int := 255 +@[simp] +def U16.min : Int := 0 +def U16.max : Int := 65535 +@[simp] +def U32.min : Int := 0 +def U32.max : Int := 4294967295 +@[simp] +def U64.min : Int := 0 +def U64.max : Int := 18446744073709551615 +@[simp] +def U128.min : Int := 0 +def U128.max : Int := 340282366920938463463374607431768211455 +@[simp] +def Usize.min : Int := 0 def Isize.refined_min : { n:Int // n = I32.min ∨ n = I64.min } := ⟨ Isize.smin, by diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index 35092c29..5a709566 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -22,20 +22,27 @@ def Vec (α : Type u) := { l : List α // l.length ≤ Usize.max } instance Vec.cast (a : Type u): Coe (Vec a) (List a) where coe := λ v => v.val instance (a : Type u) : Arith.HasIntProp (Vec a) where - prop_ty := λ v => v.val.len ≤ Scalar.max ScalarTy.Usize + prop_ty := λ v => 0 ≤ v.val.len ∧ v.val.len ≤ Scalar.max ScalarTy.Usize prop := λ ⟨ _, l ⟩ => by simp[Scalar.max, List.len_eq_length, *] @[simp] abbrev Vec.length {α : Type u} (v : Vec α) : Int := v.val.len +@[simp] +abbrev Vec.v {α : Type u} (v : Vec α) : List α := v.val + example {a: Type u} (v : Vec a) : v.length ≤ Scalar.max ScalarTy.Usize := by scalar_tac def Vec.new (α : Type u): Vec α := ⟨ [], by apply Scalar.cMax_suffices .Usize; simp ⟩ +-- TODO: very annoying that the α is an explicit parameter def Vec.len (α : Type u) (v : Vec α) : Usize := - let ⟨ v, l ⟩ := v - Usize.ofIntCore (List.length v) (by simp [Scalar.min, Usize.min]) l + Usize.ofIntCore v.val.len (by scalar_tac) (by scalar_tac) + +@[simp] +theorem Vec.len_val {α : Type u} (v : Vec α) : (Vec.len α v).val = v.length := + by rfl -- This shouldn't be used def Vec.push_fwd (α : Type u) (_ : Vec α) (_ : α) : Unit := () diff --git a/backends/lean/Base/Progress/Base.lean b/backends/lean/Base/Progress/Base.lean index b54bdf7a..6f820a84 100644 --- a/backends/lean/Base/Progress/Base.lean +++ b/backends/lean/Base/Progress/Base.lean @@ -81,8 +81,8 @@ section Methods let (fExpr, f, args) ← do if mf.isConst ∧ mf.constName = ``Bind.bind then do -- Dive into the bind - let fExpr := margs.get! 4 - fExpr.consumeMData.withApp fun f args => pure (fExpr, f, args) + let fExpr := (margs.get! 4).consumeMData + fExpr.withApp fun f args => pure (fExpr, f, args) else pure (mExpr, mf, margs) trace[Progress] "After stripping the arguments of the function call:\n- f: {f}\n- args: {args}" if ¬ f.isConst then throwError "Not a constant: {f}" diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index a281f1d2..a2c7764f 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -58,9 +58,9 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) let (thBody, _) ← destEq thBody trace[Progress] "After splitting equality: {thBody}" -- There shouldn't be any existential variables in thBody - pure thBody + pure thBody.consumeMData -- Match the body with the target - trace[Progress] "Matching `{thBody}` with `{fExpr}`" + trace[Progress] "Matching:\n- body:\n{thBody}\n- target:\n{fExpr}" let ok ← isDefEq thBody fExpr if ¬ ok then throwError "Could not unify the theorem with the target:\n- theorem: {thBody}\n- target: {fExpr}" let mgoal ← Tactic.getMainGoal diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index de6bf636..b2d5570a 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -136,6 +136,40 @@ def slot_s_inv (l i : Int) (ls : Core.List (Usize × α)) : Prop := def slot_t_inv (l i : Int) (s : List α) : Prop := slot_s_inv l i s.v +-- Interpret the hashmap as a list of lists +def v (hm : HashMap α) : Core.List (Core.List (Usize × α)) := + hm.slots.val.map List.v + +-- Interpret the hashmap as an associative list +def al_v (hm : HashMap α) : Core.List (Usize × α) := + hm.v.flatten + +-- TODO: automatic derivation +instance : Inhabited (List α) where + default := .Nil + +@[simp] +def slots_s_inv (s : Core.List (List α)) : Prop := + ∀ (i : Int), 0 ≤ i → i < s.len → slot_t_inv s.len i (s.index i) + +def slots_t_inv (s : Vec (List α)) : Prop := + slots_s_inv s.v + +@[simp] +def base_inv (hm : HashMap α) : Prop := + -- [num_entries] correctly tracks the number of entries + hm.num_entries.val = hm.al_v.len ∧ + -- Slots invariant + slots_t_inv hm.slots ∧ + -- The capacity must be > 0 (otherwise we can't resize) + 0 < hm.slots.length + -- TODO: load computation + +def inv (hm : HashMap α) : Prop := + -- Base invariant + base_inv hm + -- TODO: either the hashmap is not overloaded, or we can't resize it + theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) (hdk : distinct_keys l0.v) : @@ -191,6 +225,64 @@ theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: -- TODO: canonize addition by default? simp_all [Int.add_assoc, Int.add_comm, Int.add_left_comm] +@[pspec] +theorem insert_in_list_back_spec {α : Type} (l : Int) (key: Usize) (value: α) (l0: List α) + (hinv : slot_s_inv_hash l (hash_mod_key key l) l0.v) + (hdk : distinct_keys l0.v) : + ∃ l1, + insert_in_list_back α key value l0 = ret l1 ∧ + -- We update the binding + l1.lookup key = value ∧ + (∀ k, k ≠ key → l1.lookup k = l0.lookup k) ∧ + -- We preserve part of the key invariant + slot_s_inv_hash l (hash_mod_key key l) l1.v ∧ + -- Reasoning about the length + (match l0.lookup key with + | none => l1.len = l0.len + 1 + | some _ => l1.len = l0.len) ∧ + -- The keys are distinct + distinct_keys l1.v + := by + progress with insert_in_list_back_spec_aux as ⟨ l1 .. ⟩ + exists l1 + +def slots_t_lookup (s : Core.List (List α)) (k : Usize) : Option α := + let i := hash_mod_key k s.len + let slot := s.index i + slot.lookup k + +def lookup (hm : HashMap α) (k : Usize) : Option α := + slots_t_lookup hm.slots.val k + +@[simp] +abbrev len_s (hm : HashMap α) : Int := hm.al_v.len + +set_option trace.Progress true +/-set_option pp.explicit true +set_option pp.universes true +set_option pp.notation false-/ + +theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value : α) + (hinv : hm.inv) (hnsat : hm.lookup key = none → hm.len_s < Usize.max) : + ∃ nhm, hm.insert_no_resize α key value = ret nhm ∧ + -- We preserve the invariant + nhm.inv ∧ + -- We updated the binding for key + nhm.lookup key = some value ∧ + -- We left the other bindings unchanged + (∀ k, k ≠ key → nhm.lookup k = hm.lookup k) ∧ + -- Reasoning about the length + (match hm.lookup key with + | none => nhm.len_s = hm.len_s + 1 + | some _ => nhm.len_s = hm.len_s) := by + rw [insert_no_resize] + simp [hash_key] + have : (Vec.len (List α) hm.slots).val ≠ 0 := by + intro + simp_all [inv] + progress as ⟨ hash_mod ⟩ + progress + end HashMap end hashmap -- cgit v1.2.3 From 0cc3c78137434d848188eee2a66b1e2cacfd102e Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 19:06:05 +0200 Subject: Make progress on the proofs of the hashmap --- backends/lean/Base/Arith/Int.lean | 1 + backends/lean/Base/IList/IList.lean | 41 +++++++++++ backends/lean/Base/Primitives/Base.lean | 2 +- backends/lean/Base/Primitives/Vec.lean | 20 +++--- backends/lean/Base/Progress/Progress.lean | 34 +++++++-- backends/lean/Base/Utils.lean | 36 +++++++--- tests/lean/Hashmap/Properties.lean | 116 ++++++++++++++++++++++++++++-- 7 files changed, 216 insertions(+), 34 deletions(-) diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index bc0676d8..48a30a49 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -43,6 +43,7 @@ instance (x y : Int) : IsLinearIntProp (x > y) where instance (x y : Int) : IsLinearIntProp (x ≤ y) where instance (x y : Int) : IsLinearIntProp (x ≥ y) where instance (x y : Int) : IsLinearIntProp (x ≥ y) where +instance (x y : Int) : IsLinearIntProp (x = y) where /- It seems we don't need to do any special preprocessing when the *goal* has the following shape - I guess `linarith` automatically calls `intro` -/ instance (x y : Int) : IsLinearIntProp (¬ x = y) where diff --git a/backends/lean/Base/IList/IList.lean b/backends/lean/Base/IList/IList.lean index 2443b1a6..93047a1b 100644 --- a/backends/lean/Base/IList/IList.lean +++ b/backends/lean/Base/IList/IList.lean @@ -123,6 +123,10 @@ theorem length_update (ls : List α) (i : Int) (x : α) : (ls.update i x).length theorem len_update (ls : List α) (i : Int) (x : α) : (ls.update i x).len = ls.len := by simp [len_eq_length] +@[simp] +theorem len_map (ls : List α) (f : α → β) : (ls.map f).len = ls.len := by + simp [len_eq_length] + theorem left_length_eq_append_eq (l1 l2 l1' l2' : List α) (heq : l1.length = l1'.length) : l1 ++ l2 = l1' ++ l2' ↔ l1 = l1' ∧ l2 = l2' := by revert l1' @@ -210,6 +214,43 @@ theorem index_eq simp at * apply index_eq <;> scalar_tac +theorem update_map_eq {α : Type u} {β : Type v} (ls : List α) (i : Int) (x : α) (f : α → β) : + (ls.update i x).map f = (ls.map f).update i (f x) := + match ls with + | [] => by simp + | hd :: tl => + if h : i = 0 then by simp [*] + else + have hi := update_map_eq tl (i - 1) x f + by simp [*] + +theorem len_flatten_update_eq {α : Type u} (ls : List (List α)) (i : Int) (x : List α) + (h0 : 0 ≤ i) (h1 : i < ls.len) : + (ls.update i x).flatten.len = ls.flatten.len + x.len - (ls.index i).len := + match ls with + | [] => by simp at h1; int_tac + | hd :: tl => by + simp at h1 + if h : i = 0 then simp [*]; int_tac + else + have hi := len_flatten_update_eq tl (i - 1) x (by int_tac) (by int_tac) + simp [*] + int_tac + +@[simp] +theorem index_map_eq {α : Type u} {β : Type v} [Inhabited α] [Inhabited β] (ls : List α) (i : Int) (f : α → β) + (h0 : 0 ≤ i) (h1 : i < ls.len) : + (ls.map f).index i = f (ls.index i) := + match ls with + | [] => by simp at h1; int_tac + | hd :: tl => + if h : i = 0 then by + simp [*] + else + have hi := index_map_eq tl (i - 1) f (by int_tac) (by simp at h1; int_tac) + by + simp [*] + def allP {α : Type u} (l : List α) (p: α → Prop) : Prop := foldr (fun a r => p a ∧ r) True l diff --git a/backends/lean/Base/Primitives/Base.lean b/backends/lean/Base/Primitives/Base.lean index db462c38..7c0fa3bb 100644 --- a/backends/lean/Base/Primitives/Base.lean +++ b/backends/lean/Base/Primitives/Base.lean @@ -76,7 +76,7 @@ def eval_global {α: Type u} (x: Result α) (_: ret? x): α := /- DO-DSL SUPPORT -/ -def bind {α : Type u} {β : Type v} (x: Result α) (f: α -> Result β) : Result β := +def bind {α : Type u} {β : Type v} (x: Result α) (f: α → Result β) : Result β := match x with | ret v => f v | fail v => fail v diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index 5a709566..523372bb 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -75,10 +75,9 @@ def Vec.insert (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Vec α) := .fail arrayOutOfBounds @[pspec] -theorem Vec.insert_spec {α : Type u} (v: Vec α) (i: Usize) (x: α) : - i.val < v.length → +theorem Vec.insert_spec {α : Type u} (v: Vec α) (i: Usize) (x: α) + (hbound : i.val < v.length) : ∃ nv, v.insert α i x = ret nv ∧ nv.val = v.val.update i.val x := by - intro h simp [insert, *] def Vec.index (α : Type u) (v: Vec α) (i: Usize) : Result α := @@ -87,10 +86,9 @@ def Vec.index (α : Type u) (v: Vec α) (i: Usize) : Result α := | some x => ret x @[pspec] -theorem Vec.index_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : - i.val < v.length → +theorem Vec.index_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) + (hbound : i.val < v.length) : v.index α i = ret (v.val.index i.val) := by - intro simp only [index] -- TODO: dependent rewrite have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) @@ -109,10 +107,9 @@ def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize) : Result α := | some x => ret x @[pspec] -theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) : - i.val < v.length → +theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) + (hbound : i.val < v.length) : v.index_mut α i = ret (v.val.index i.val) := by - intro simp only [index_mut] -- TODO: dependent rewrite have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) @@ -129,12 +126,11 @@ def Vec.index_mut_back (α : Type u) (v: Vec α) (i: Usize) (x: α) : Result (Ve .ret ⟨ v.val.update i.val x, by have := v.property; simp [*] ⟩ @[pspec] -theorem Vec.index_mut_back_spec {α : Type u} (v: Vec α) (i: Usize) (x : α) : - i.val < v.length → +theorem Vec.index_mut_back_spec {α : Type u} (v: Vec α) (i: Usize) (x : α) + (hbound : i.val < v.length) : ∃ nv, v.index_mut_back α i x = ret nv ∧ nv.val = v.val.update i.val x := by - intro simp only [index_mut_back] have h := List.indexOpt_bounds v.val i.val split diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index a2c7764f..4a406bdf 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -1,6 +1,7 @@ import Lean import Base.Arith import Base.Progress.Base +import Base.Primitives -- TODO: remove? namespace Progress @@ -41,7 +42,12 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) match th with | .Theorem thName => let thDecl := env.constants.find! thName - pure thDecl.type + -- We have to introduce fresh meta-variables for the universes already + let ul : List (Name × Level) ← + thDecl.levelParams.mapM (λ x => do pure (x, ← mkFreshLevelMVar)) + let ulMap : HashMap Name Level := HashMap.ofList ul + let thTy := thDecl.type.instantiateLevelParamsCore (λ x => ulMap.find! x) + pure thTy | .Local asmDecl => pure asmDecl.type trace[Progress] "Looked up theorem/assumption type: {thTy}" -- TODO: the tactic fails if we uncomment withNewMCtxDepth @@ -129,15 +135,16 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) Split the remaining conjunctions by using fresh ids if the user instructed to fully split the post-condition, otherwise stop -/ if splitPost then - splitFullConjTac hPost (λ _ => pure .Ok) + splitFullConjTac true hPost (λ _ => pure .Ok) else pure .Ok | nid :: ids => do - trace[Progress] "Splitting post: {hPost}" + trace[Progress] "Splitting post: {← inferType hPost}" -- Split let nid ← do match nid with | none => mkFreshUserName `h | some nid => pure nid + trace[Progress] "\n- prevId: {prevId}\n- nid: {nid}\n- remaining ids: {ids}" if ← isConj (← inferType hPost) then splitConjTac hPost (some (prevId, nid)) (λ _ nhPost => splitPostWithIds nid nhPost ids) else return (.Error m!"Too many ids provided ({ids0}) not enough conjuncts to split in the postcondition") @@ -323,7 +330,7 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do elab "progress" args:progressArgs : tactic => evalProgress args -/- namespace Test +namespace Test open Primitives Result set_option trace.Progress true @@ -336,10 +343,25 @@ elab "progress" args:progressArgs : tactic => (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by --- progress keep as h with Scalar.add_spec as ⟨ z ⟩ progress keep as h as ⟨ x, h1 .. ⟩ simp [*] -end Test -/ + example {ty} {x y : Scalar ty} + (hmin : Scalar.min ty ≤ x.val + y.val) + (hmax : x.val + y.val ≤ Scalar.max ty) : + ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by + progress keep as h with Scalar.add_spec as ⟨ z ⟩ + simp [*] + + /- Checking that universe instantiation works: the original spec uses + `α : Type u` where u is quantified, while here we use `α : Type 0` -/ + example {α : Type} (v: Vec α) (i: Usize) (x : α) + (hbounds : i.val < v.length) : + ∃ nv, v.index_mut_back α i x = ret nv ∧ + nv.val = v.val.update i.val x := by + progress + simp [*] + +end Test end Progress diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index 66497a49..f6dc45c7 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -1,6 +1,7 @@ import Lean import Mathlib.Tactic.Core import Mathlib.Tactic.LeftRight +import Base.UtilsBase /- Mathlib tactics: @@ -331,13 +332,13 @@ def assumptionTac : TacticM Unit := liftMetaTactic fun mvarId => do mvarId.assumption; pure [] def isConj (e : Expr) : MetaM Bool := - e.withApp fun f args => pure (f.isConstOf ``And ∧ args.size = 2) + e.consumeMData.withApp fun f args => pure (f.isConstOf ``And ∧ args.size = 2) -- Return the first conjunct if the expression is a conjunction, or the -- expression itself otherwise. Also return the second conjunct if it is a -- conjunction. def optSplitConj (e : Expr) : MetaM (Expr × Option Expr) := do - e.withApp fun f args => + e.consumeMData.withApp fun f args => if f.isConstOf ``And ∧ args.size = 2 then pure (args.get! 0, some (args.get! 1)) else pure (e, none) @@ -345,6 +346,7 @@ def optSplitConj (e : Expr) : MetaM (Expr × Option Expr) := do def splitConjTarget : TacticM Unit := do withMainContext do let g ← getMainTarget + trace[Utils] "splitConjTarget: goal: {g}" -- The tactic was initially implemened with `_root_.Lean.MVarId.apply` -- but it tended to mess the goal by unfolding terms, even when it failed let (l, r) ← optSplitConj g @@ -525,18 +527,26 @@ def splitConjTac (h : Expr) (optIds : Option (Name × Name)) (k : Expr → Expr throwError "Not a conjunction" -- Tactic to fully split a conjunction -partial def splitFullConjTacAux [Inhabited α] [Nonempty α] (l : List Expr) (h : Expr) (k : List Expr → TacticM α) : TacticM α := do +partial def splitFullConjTacAux [Inhabited α] [Nonempty α] (keepCurrentName : Bool) (l : List Expr) (h : Expr) (k : List Expr → TacticM α) : TacticM α := do try - splitConjTac h none (λ h1 h2 => - splitFullConjTacAux l h1 (λ l1 => - splitFullConjTacAux l1 h2 (λ l2 => + let ids ← do + if keepCurrentName then do + let cur := (← h.fvarId!.getDecl).userName + let nid ← mkFreshUserName `h + pure (some (cur, nid)) + else + pure none + splitConjTac h ids (λ h1 h2 => + splitFullConjTacAux keepCurrentName l h1 (λ l1 => + splitFullConjTacAux keepCurrentName l1 h2 (λ l2 => k l2))) catch _ => k (h :: l) -- Tactic to fully split a conjunction -def splitFullConjTac [Inhabited α] [Nonempty α] (h : Expr) (k : List Expr → TacticM α) : TacticM α := do - splitFullConjTacAux [] h (λ l => k l.reverse) +-- `keepCurrentName`: if `true`, then the first conjunct has the name of the original assumption +def splitFullConjTac [Inhabited α] [Nonempty α] (keepCurrentName : Bool) (h : Expr) (k : List Expr → TacticM α) : TacticM α := do + splitFullConjTacAux keepCurrentName [] h (λ l => k l.reverse) syntax optAtArgs := ("at" ident)? def elabOptAtArgs (args : TSyntax `Utils.optAtArgs) : TacticM (Option Expr) := do @@ -553,17 +563,21 @@ def elabOptAtArgs (args : TSyntax `Utils.optAtArgs) : TacticM (Option Expr) := d elab "split_conj" args:optAtArgs : tactic => do withMainContext do match ← elabOptAtArgs args with - | some fvar => + | some fvar => do + trace[Utils] "split at {fvar}" splitConjTac fvar none (fun _ _ => pure ()) - | none => + | none => do + trace[Utils] "split goal" splitConjTarget elab "split_conjs" args:optAtArgs : tactic => do withMainContext do match ← elabOptAtArgs args with | some fvar => - splitFullConjTac fvar (fun _ => pure ()) + trace[Utils] "split at {fvar}" + splitFullConjTac false fvar (fun _ => pure ()) | none => + trace[Utils] "split goal" repeatTac splitConjTarget elab "split_existsl" " at " n:ident : tactic => do diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index b2d5570a..92285c0d 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -55,6 +55,7 @@ theorem match_lawful_beq [BEq α] [LawfulBEq α] [DecidableEq α] (x y : α) : (x == y) = (if x = y then true else false) := by split <;> simp_all +@[pspec] theorem insert_in_list_spec0 {α : Type} (key: Usize) (value: α) (ls: List α) : ∃ b, insert_in_list α key value ls = ret b ∧ @@ -126,6 +127,10 @@ def hash_mod_key (k : Usize) (l : Int) : Int := | .ret k => k.val % l | _ => 0 +@[simp] +theorem hash_mod_key_eq : hash_mod_key k l = k.val % l := by + simp [hash_mod_key, hash_key] + def slot_s_inv_hash (l i : Int) (ls : Core.List (Usize × α)) : Prop := ls.allP (λ (k, _) => hash_mod_key k l = i) @@ -246,6 +251,7 @@ theorem insert_in_list_back_spec {α : Type} (l : Int) (key: Usize) (value: α) progress with insert_in_list_back_spec_aux as ⟨ l1 .. ⟩ exists l1 +@[simp] def slots_t_lookup (s : Core.List (List α)) (k : Usize) : Option α := let i := hash_mod_key k s.len let slot := s.index i @@ -260,7 +266,15 @@ abbrev len_s (hm : HashMap α) : Int := hm.al_v.len set_option trace.Progress true /-set_option pp.explicit true set_option pp.universes true -set_option pp.notation false-/ +set_option pp.notation false -/ + +-- Remark: α and β must live in the same universe, otherwise the +-- bind doesn't work +theorem if_update_eq + {α β : Type u} (b : Bool) (y : α) (e : Result α) (f : α → Result β) : + (if b then Bind.bind e f else f y) = Bind.bind (if b then e else pure y) f + := by + split <;> simp [Pure.pure] theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value : α) (hinv : hm.inv) (hnsat : hm.lookup key = none → hm.len_s < Usize.max) : @@ -270,18 +284,112 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- We updated the binding for key nhm.lookup key = some value ∧ -- We left the other bindings unchanged - (∀ k, k ≠ key → nhm.lookup k = hm.lookup k) ∧ + (∀ k, ¬ k = key → nhm.lookup k = hm.lookup k) ∧ -- Reasoning about the length (match hm.lookup key with | none => nhm.len_s = hm.len_s + 1 | some _ => nhm.len_s = hm.len_s) := by rw [insert_no_resize] simp [hash_key] - have : (Vec.len (List α) hm.slots).val ≠ 0 := by + have _ : (Vec.len (List α) hm.slots).val ≠ 0 := by checkpoint intro simp_all [inv] - progress as ⟨ hash_mod ⟩ + -- TODO: progress keep as ⟨ ... ⟩ : conflict + progress keep as h as ⟨ hash_mod, hhm ⟩ + have _ : 0 ≤ hash_mod.val := by checkpoint scalar_tac + have _ : hash_mod.val < Vec.length hm.slots := by sorry + -- have h := Primitives.Vec.index_mut_spec hm.slots hash_mod + -- TODO: change the spec of Vec.index_mut to introduce a let-binding. + -- or: make progress introduce the let-binding by itself (this is clearer) progress + -- TODO: make progress use the names written in the goal + progress as ⟨ inserted ⟩ + rw [if_update_eq] -- TODO: necessary because we don't have a join + -- TODO: progress to ... + have hipost : + ∃ i0, (if inserted = true then hm.num_entries + Usize.ofInt 1 else pure hm.num_entries) = ret i0 ∧ + i0.val = if inserted then hm.num_entries.val + 1 else hm.num_entries.val + := by sorry + progress as ⟨ i0 ⟩ + -- TODO: progress "eager" to match premises with assumptions while instantiating + -- meta-variables + have h_slot : slot_s_inv_hash hm.slots.length hash_mod.val (hm.slots.v.index hash_mod.val).v := by sorry + have hd : distinct_keys (hm.slots.v.index hash_mod.val).v := by checkpoint + simp [inv, slots_t_inv, slot_t_inv] at hinv + have h := hinv.right.left hash_mod.val (by assumption) (by assumption) + simp [h] + -- TODO: hide the variables and only keep the props + -- TODO: allow providing terms to progress to instantiate the meta variables + -- which are not propositions + progress as ⟨ l0, _, _, _, hlen .. ⟩ + . checkpoint exact hm.slots.length + . checkpoint simp_all + . -- Finishing the proof + progress as ⟨ v ⟩ + -- TODO: update progress to automate that + let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } + exists nhm + have hupdt : lookup nhm key = some value := by checkpoint + simp [lookup, List.lookup] at * + simp_all + have hlkp : ∀ k, ¬ k = key → nhm.lookup k = hm.lookup k := by checkpoint + simp [lookup, List.lookup] at * + intro k hk + -- We have to make a case disjunction: either the hashes are different, + -- in which case we don't even lookup the same slots, or the hashes + -- are the same, in which case we have to reason about what happens + -- in one slot + let k_hash_mod := k.val % v.val.len + have _ : 0 ≤ k_hash_mod := by sorry + have _ : k_hash_mod < Vec.length hm.slots := by sorry + if h_hm : k_hash_mod = hash_mod.val then + simp_all + else + simp_all + have _ : + match hm.lookup key with + | none => nhm.len_s = hm.len_s + 1 + | some _ => nhm.len_s = hm.len_s := by checkpoint + simp only [lookup, List.lookup, len_s, al_v, HashMap.v, slots_t_lookup] at * + -- We have to do a case disjunction + simp_all + simp [_root_.List.update_map_eq] + -- TODO: dependent rewrites + have _ : key.val % hm.slots.val.len < (List.map List.v hm.slots.val).len := by + simp [*] + simp [_root_.List.len_flatten_update_eq, *] + split <;> + rename_i heq <;> + simp [heq] at hlen <;> + -- TODO: canonize addition by default? We need a tactic to simplify arithmetic equalities + -- with addition and substractions ((ℤ, +) is a ring or something - there should exist a tactic + -- somewhere in mathlib?) + simp [Int.add_assoc, Int.add_comm, Int.add_left_comm] <;> + int_tac + have hinv : inv nhm := by + simp [inv] at * + split_conjs + . match h: lookup hm key with + | none => + simp [h, lookup] at * + simp_all + | some _ => + simp_all [lookup] + . simp [slots_t_inv, slot_t_inv] at * + intro i hipos _ + have hs := hinv.right.left i hipos (by simp_all) + -- We need a case disjunction + if i = key.val % _root_.List.len hm.slots.val then + simp_all + else + simp_all + . match h: lookup hm key with + | none => + simp [h] at * + simp [*] + | some _ => + simp_all + simp_all end HashMap -- cgit v1.2.3 From 9e8fccbe4b667fc341b6544030f85af05fe89307 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Tue, 25 Jul 2023 20:12:48 +0200 Subject: Make progress on the proofs of the hashmap --- backends/lean/Base/Primitives/Scalar.lean | 47 ++++++++++++++++++++++--- tests/lean/Hashmap/Properties.lean | 58 +++++++++++++++++++++---------- 2 files changed, 83 insertions(+), 22 deletions(-) diff --git a/backends/lean/Base/Primitives/Scalar.lean b/backends/lean/Base/Primitives/Scalar.lean index 3beb7527..2e5be8bf 100644 --- a/backends/lean/Base/Primitives/Scalar.lean +++ b/backends/lean/Base/Primitives/Scalar.lean @@ -660,10 +660,8 @@ theorem Scalar.rem_unsigned_spec {ty} (s: ¬ ty.isSigned) (x : Scalar ty) {y : S simp [h] at hx hy have hmin : 0 ≤ x.val % y.val := Int.emod_nonneg x.val hnz have hmax : x.val % y.val ≤ Scalar.max ty := by - have h := @Int.ediv_emod_unique x.val y.val (x.val % y.val) (x.val / y.val) - simp at h - have : 0 < y.val := by int_tac - simp [*] at h + have h : 0 < y.val := by int_tac + have h := Int.emod_lt_of_pos x.val h have := y.hmax linarith have hs := @rem_spec ty x y hnz @@ -724,6 +722,47 @@ def U32.ofInt := @Scalar.ofInt .U32 def U64.ofInt := @Scalar.ofInt .U64 def U128.ofInt := @Scalar.ofInt .U128 +-- TODO: factor those lemmas out +@[simp] theorem Scalar.ofInt_val_eq {ty} (h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : (Scalar.ofInt x h).val = x := by + simp [Scalar.ofInt, Scalar.ofIntCore] + +@[simp] theorem Isize.ofInt_val_eq (h : Scalar.min ScalarTy.Isize ≤ x ∧ x ≤ Scalar.max ScalarTy.Isize) : (Isize.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem I8.ofInt_val_eq (h : Scalar.min ScalarTy.I8 ≤ x ∧ x ≤ Scalar.max ScalarTy.I8) : (I8.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem I16.ofInt_val_eq (h : Scalar.min ScalarTy.I16 ≤ x ∧ x ≤ Scalar.max ScalarTy.I16) : (I16.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem I32.ofInt_val_eq (h : Scalar.min ScalarTy.I32 ≤ x ∧ x ≤ Scalar.max ScalarTy.I32) : (I32.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem I64.ofInt_val_eq (h : Scalar.min ScalarTy.I64 ≤ x ∧ x ≤ Scalar.max ScalarTy.I64) : (I64.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem I128.ofInt_val_eq (h : Scalar.min ScalarTy.I128 ≤ x ∧ x ≤ Scalar.max ScalarTy.I128) : (I128.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem Usize.ofInt_val_eq (h : Scalar.min ScalarTy.Usize ≤ x ∧ x ≤ Scalar.max ScalarTy.Usize) : (Usize.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem U8.ofInt_val_eq (h : Scalar.min ScalarTy.U8 ≤ x ∧ x ≤ Scalar.max ScalarTy.U8) : (U8.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem U16.ofInt_val_eq (h : Scalar.min ScalarTy.U16 ≤ x ∧ x ≤ Scalar.max ScalarTy.U16) : (U16.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem U32.ofInt_val_eq (h : Scalar.min ScalarTy.U32 ≤ x ∧ x ≤ Scalar.max ScalarTy.U32) : (U32.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem U64.ofInt_val_eq (h : Scalar.min ScalarTy.U64 ≤ x ∧ x ≤ Scalar.max ScalarTy.U64) : (U64.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + +@[simp] theorem U128.ofInt_val_eq (h : Scalar.min ScalarTy.U128 ≤ x ∧ x ≤ Scalar.max ScalarTy.U128) : (U128.ofInt x h).val = x := by + apply Scalar.ofInt_val_eq h + + -- Comparisons instance {ty} : LT (Scalar ty) where lt a b := LT.lt a.val b.val diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 92285c0d..40b5009d 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -263,11 +263,6 @@ def lookup (hm : HashMap α) (k : Usize) : Option α := @[simp] abbrev len_s (hm : HashMap α) : Int := hm.al_v.len -set_option trace.Progress true -/-set_option pp.explicit true -set_option pp.universes true -set_option pp.notation false -/ - -- Remark: α and β must live in the same universe, otherwise the -- bind doesn't work theorem if_update_eq @@ -297,7 +292,12 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- TODO: progress keep as ⟨ ... ⟩ : conflict progress keep as h as ⟨ hash_mod, hhm ⟩ have _ : 0 ≤ hash_mod.val := by checkpoint scalar_tac - have _ : hash_mod.val < Vec.length hm.slots := by sorry + have _ : hash_mod.val < Vec.length hm.slots := by + have : 0 < hm.slots.val.len := by + simp [inv] at hinv + simp [hinv] + -- TODO: we want to automate that + simp [*, Int.emod_lt_of_pos] -- have h := Primitives.Vec.index_mut_spec hm.slots hash_mod -- TODO: change the spec of Vec.index_mut to introduce a let-binding. -- or: make progress introduce the let-binding by itself (this is clearer) @@ -309,11 +309,26 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value have hipost : ∃ i0, (if inserted = true then hm.num_entries + Usize.ofInt 1 else pure hm.num_entries) = ret i0 ∧ i0.val = if inserted then hm.num_entries.val + 1 else hm.num_entries.val - := by sorry + := by + if inserted then + simp [*] + have : hm.num_entries.val + (Usize.ofInt 1).val ≤ Usize.max := by + simp [lookup] at hnsat + simp_all + simp [inv] at hinv + int_tac + progress + simp_all + else + simp_all [Pure.pure] progress as ⟨ i0 ⟩ -- TODO: progress "eager" to match premises with assumptions while instantiating -- meta-variables - have h_slot : slot_s_inv_hash hm.slots.length hash_mod.val (hm.slots.v.index hash_mod.val).v := by sorry + have h_slot : slot_s_inv_hash hm.slots.length hash_mod.val (hm.slots.v.index hash_mod.val).v := by + simp [inv] at hinv + have h := hinv.right.left hash_mod.val (by assumption) (by assumption) + simp [slot_t_inv] at h + simp [h] have hd : distinct_keys (hm.slots.v.index hash_mod.val).v := by checkpoint simp [inv, slots_t_inv, slot_t_inv] at hinv have h := hinv.right.left hash_mod.val (by assumption) (by assumption) @@ -329,10 +344,11 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- TODO: update progress to automate that let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } exists nhm + -- TODO: later I don't want to inline nhm - we need to control simp have hupdt : lookup nhm key = some value := by checkpoint simp [lookup, List.lookup] at * simp_all - have hlkp : ∀ k, ¬ k = key → nhm.lookup k = hm.lookup k := by checkpoint + have hlkp : ∀ k, ¬ k = key → nhm.lookup k = hm.lookup k := by simp [lookup, List.lookup] at * intro k hk -- We have to make a case disjunction: either the hashes are different, @@ -340,8 +356,19 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- are the same, in which case we have to reason about what happens -- in one slot let k_hash_mod := k.val % v.val.len - have _ : 0 ≤ k_hash_mod := by sorry - have _ : k_hash_mod < Vec.length hm.slots := by sorry + have : 0 < hm.slots.val.len := by simp_all [inv] + have hvpos : 0 < v.val.len := by simp_all + have hvnz: v.val.len ≠ 0 := by + simp_all + have _ : 0 ≤ k_hash_mod := by + -- TODO: we want to automate this + simp + apply Int.emod_nonneg k.val hvnz + have _ : k_hash_mod < Vec.length hm.slots := by + -- TODO: we want to automate this + simp + have h := Int.emod_lt_of_pos k.val hvpos + simp_all if h_hm : k_hash_mod = hash_mod.val then simp_all else @@ -377,18 +404,13 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value simp_all [lookup] . simp [slots_t_inv, slot_t_inv] at * intro i hipos _ - have hs := hinv.right.left i hipos (by simp_all) + have _ := hinv.right.left i hipos (by simp_all) -- We need a case disjunction if i = key.val % _root_.List.len hm.slots.val then simp_all else simp_all - . match h: lookup hm key with - | none => - simp [h] at * - simp [*] - | some _ => - simp_all + . simp_all simp_all end HashMap -- cgit v1.2.3 From 032db82439d9b379b5435d8349c1ecf55eeb2875 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 26 Jul 2023 11:41:32 +0200 Subject: Fix a proof for the hashmap --- tests/lean/Hashmap/Properties.lean | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 40b5009d..208875a6 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -340,7 +340,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value . checkpoint exact hm.slots.length . checkpoint simp_all . -- Finishing the proof - progress as ⟨ v ⟩ + progress keep as hv as ⟨ v, h_veq ⟩ -- TODO: update progress to automate that let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } exists nhm @@ -405,12 +405,19 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value . simp [slots_t_inv, slot_t_inv] at * intro i hipos _ have _ := hinv.right.left i hipos (by simp_all) + simp [hhm, h_veq] at * -- TODO: annoying -- We need a case disjunction - if i = key.val % _root_.List.len hm.slots.val then - simp_all + if h_ieq : i = key.val % _root_.List.len hm.slots.val then + -- TODO: simp_all loops (investigate). + -- Also, it is annoying to do this kind + -- of rewritings by hand. We could have a different simp + -- which safely substitutes variables when we have an + -- equality `x = ...` and `x` doesn't appear in the rhs + simp [h_ieq] at * + simp [*] else - simp_all - . simp_all + simp [*] + . simp [*] simp_all end HashMap -- cgit v1.2.3 From 81e991822879a942af34489b7a072f31739f28f6 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 26 Jul 2023 12:37:17 +0200 Subject: Update the syntax of the progress tactic --- backends/lean/Base/Arith/Int.lean | 2 +- backends/lean/Base/Arith/Scalar.lean | 2 +- backends/lean/Base/Progress/Progress.lean | 41 +++---- backends/lean/Base/Utils.lean | 12 ++- tests/lean/Hashmap/Properties.lean | 171 +++++++++++++++--------------- 5 files changed, 117 insertions(+), 111 deletions(-) diff --git a/backends/lean/Base/Arith/Int.lean b/backends/lean/Base/Arith/Int.lean index 48a30a49..7a5bbe98 100644 --- a/backends/lean/Base/Arith/Int.lean +++ b/backends/lean/Base/Arith/Int.lean @@ -147,7 +147,7 @@ def introInstances (declToUnfold : Name) (lookup : Expr → MetaM (Option Expr)) let hs ← collectInstancesFromMainCtx lookup hs.toArray.mapM fun e => do let type ← inferType e - let name ← mkFreshUserName `h + let name ← mkFreshAnonPropUserName -- Add a declaration let nval ← Utils.addDeclTac name e type (asLet := false) -- Simplify to unfold the declaration to unfold (i.e., the projector) diff --git a/backends/lean/Base/Arith/Scalar.lean b/backends/lean/Base/Arith/Scalar.lean index 6f4a8eba..b792ff21 100644 --- a/backends/lean/Base/Arith/Scalar.lean +++ b/backends/lean/Base/Arith/Scalar.lean @@ -12,7 +12,7 @@ def scalarTacExtraPreprocess : Tactic.TacticM Unit := do -- Inroduce the bounds for the isize/usize types let add (e : Expr) : Tactic.TacticM Unit := do let ty ← inferType e - let _ ← Utils.addDeclTac (← mkFreshUserName `h) e ty (asLet := false) + let _ ← Utils.addDeclTac (← Utils.mkFreshAnonPropUserName) e ty (asLet := false) add (← mkAppM ``Scalar.cMin_bound #[.const ``ScalarTy.Isize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Usize []]) add (← mkAppM ``Scalar.cMax_bound #[.const ``ScalarTy.Isize []]) diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 4a406bdf..9300edff 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -79,7 +79,7 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) match th with | .Theorem thName => mkAppOptM thName (mvars.map some) | .Local decl => mkAppOptM' (mkFVar decl.fvarId) (mvars.map some) - let asmName ← do match keep with | none => mkFreshUserName `h | some n => do pure n + let asmName ← do match keep with | none => mkFreshAnonPropUserName | some n => do pure n let thTy ← inferType th let thAsm ← Utils.addDeclTac asmName th thTy (asLet := false) withMainContext do -- The context changed - TODO: remove once addDeclTac is updated @@ -101,8 +101,8 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) let hName := (← h.fvarId!.getDecl).userName let (optIds, ids) ← do match ids with - | [] => do pure (some (hName, ← mkFreshUserName `h), []) - | none :: ids => do pure (some (hName, ← mkFreshUserName `h), ids) + | [] => do pure (some (hName, ← mkFreshAnonPropUserName), []) + | none :: ids => do pure (some (hName, ← mkFreshAnonPropUserName), ids) | some id :: ids => do pure (some (hName, id), ids) splitConjTac h optIds (fun hEq hPost => k hEq (some hPost) ids) else k h none ids @@ -142,7 +142,7 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) -- Split let nid ← do match nid with - | none => mkFreshUserName `h + | none => mkFreshAnonPropUserName | some nid => pure nid trace[Progress] "\n- prevId: {prevId}\n- nid: {nid}\n- remaining ids: {ids}" if ← isConj (← inferType hPost) then @@ -270,23 +270,26 @@ def progressAsmsOrLookupTheorem (keep : Option Name) (withTh : Option TheoremOrL -- Nothing worked: failed throwError "Progress failed" -syntax progressArgs := ("keep" ("as" (ident))?)? ("with" ident)? ("as" " ⟨ " (ident <|> "_"),* " .."? " ⟩")? +syntax progressArgs := ("keep" (ident <|> "_"))? ("with" ident)? ("as" " ⟨ " (ident <|> "_"),* " .."? " ⟩")? def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do let args := args.raw -- Process the arguments to retrieve the identifiers to use trace[Progress] "Progress arguments: {args}" - let args := args.getArgs + let (keepArg, withArg, asArgs) ← + match args.getArgs.toList with + | [keepArg, withArg, asArgs] => do pure (keepArg, withArg, asArgs) + | _ => throwError "Unexpected: invalid arguments" let keep : Option Name ← do - let args := (args.get! 0).getArgs - if args.size > 0 then do - let args := (args.get! 1).getArgs - if args.size > 0 then pure (some (args.get! 1).getId) - else do pure (some (← mkFreshUserName `h)) - else pure none + let args := keepArg.getArgs + trace[Progress] "Keep args: {args}" + let arg := args.get! 1 + trace[Progress] "Keep arg: {arg}" + if arg.isIdent then pure (some arg.getId) + else do pure (some (← mkFreshAnonPropUserName)) trace[Progress] "Keep: {keep}" let withArg ← do - let withArg := (args.get! 1).getArgs + let withArg := withArg.getArgs if withArg.size > 0 then let id := withArg.get! 1 trace[Progress] "With arg: {id}" @@ -306,12 +309,12 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do pure (some (.Theorem id)) else pure none let ids := - let args := (args.get! 2).getArgs + let args := asArgs.getArgs let args := (args.get! 2).getSepArgs args.map (λ s => if s.isIdent then some s.getId else none) trace[Progress] "User-provided ids: {ids}" let splitPost : Bool := - let args := (args.get! 2).getArgs + let args := asArgs.getArgs (args.get! 3).getArgs.size > 0 trace[Progress] "Split post: {splitPost}" /- For scalarTac we have a fast track: if the goal is not a linear @@ -343,15 +346,15 @@ namespace Test (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by - progress keep as h as ⟨ x, h1 .. ⟩ - simp [*] + progress keep _ as ⟨ z, h1 .. ⟩ + simp [*, h1] example {ty} {x y : Scalar ty} (hmin : Scalar.min ty ≤ x.val + y.val) (hmax : x.val + y.val ≤ Scalar.max ty) : ∃ z, x + y = ret z ∧ z.val = x.val + y.val := by - progress keep as h with Scalar.add_spec as ⟨ z ⟩ - simp [*] + progress keep h with Scalar.add_spec as ⟨ z ⟩ + simp [*, h] /- Checking that universe instantiation works: the original spec uses `α : Type u` where u is quantified, while here we use `α : Type 0` -/ diff --git a/backends/lean/Base/Utils.lean b/backends/lean/Base/Utils.lean index f6dc45c7..1f8f1455 100644 --- a/backends/lean/Base/Utils.lean +++ b/backends/lean/Base/Utils.lean @@ -201,6 +201,10 @@ partial def mapVisit (k : Nat → Expr → MetaM Expr) (e : Expr) : MetaM Expr : | .proj _ _ b => return e.updateProj! (← visit (i + 1) b) visit 0 e +-- Generate a fresh user name for an anonymous proposition to introduce in the +-- assumptions +def mkFreshAnonPropUserName := mkFreshUserName `_ + section Methods variable [MonadLiftT MetaM m] [MonadControlT MetaM m] [Monad m] [MonadError m] variable {a : Type} @@ -411,7 +415,7 @@ def splitDisjTac (h : Expr) (kleft kright : TacticM Unit) : TacticM Unit := do trace[Arith] "left: {inl}: {mleft}" trace[Arith] "right: {inr}: {mright}" -- Create the match expression - withLocalDeclD (← mkFreshUserName `h) hTy fun hVar => do + withLocalDeclD (← mkFreshAnonPropUserName) hTy fun hVar => do let motive ← mkLambdaFVars #[hVar] goalType let casesExpr ← mkAppOptM ``Or.casesOn #[a, b, motive, h, inl, inr] let mgoal ← getMainGoal @@ -505,8 +509,8 @@ def splitConjTac (h : Expr) (optIds : Option (Name × Name)) (k : Expr → Expr let altVarNames ← match optIds with | none => do - let id0 ← mkFreshUserName `h - let id1 ← mkFreshUserName `h + let id0 ← mkFreshAnonPropUserName + let id1 ← mkFreshAnonPropUserName pure #[{ varNames := [id0, id1] }] | some (id0, id1) => do pure #[{ varNames := [id0, id1] }] @@ -532,7 +536,7 @@ partial def splitFullConjTacAux [Inhabited α] [Nonempty α] (keepCurrentName : let ids ← do if keepCurrentName then do let cur := (← h.fvarId!.getDecl).userName - let nid ← mkFreshUserName `h + let nid ← mkFreshAnonPropUserName pure (some (cur, nid)) else pure none diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 208875a6..96b8193d 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -95,7 +95,7 @@ theorem insert_in_list_spec1 {α : Type} (key: Usize) (value: α) (ls: List α) simp only [insert_in_list] rw [insert_in_list_loop] conv => rhs; ext; simp [*] - progress keep as heq as ⟨ b, hi ⟩ + progress keep heq as ⟨ b, hi ⟩ simp only [insert_in_list] at heq exists b @@ -219,7 +219,7 @@ theorem insert_in_list_back_spec_aux {α : Type} (l : Int) (key: Usize) (value: have : distinct_keys (List.v tl0) := by checkpoint simp [distinct_keys] at hdk simp [hdk, distinct_keys] - progress keep as heq as ⟨ tl1 .. ⟩ + progress keep heq as ⟨ tl1 .. ⟩ simp only [insert_in_list_back] at heq have : slot_s_inv_hash l (hash_mod_key key l) (List.v (List.Cons k v tl1)) := by checkpoint simp [List.v, slot_s_inv_hash] at * @@ -289,8 +289,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value have _ : (Vec.len (List α) hm.slots).val ≠ 0 := by checkpoint intro simp_all [inv] - -- TODO: progress keep as ⟨ ... ⟩ : conflict - progress keep as h as ⟨ hash_mod, hhm ⟩ + progress keep _ as ⟨ hash_mod, hhm ⟩ have _ : 0 ≤ hash_mod.val := by checkpoint scalar_tac have _ : hash_mod.val < Vec.length hm.slots := by have : 0 < hm.slots.val.len := by @@ -324,11 +323,12 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value progress as ⟨ i0 ⟩ -- TODO: progress "eager" to match premises with assumptions while instantiating -- meta-variables - have h_slot : slot_s_inv_hash hm.slots.length hash_mod.val (hm.slots.v.index hash_mod.val).v := by + have h_slot : slot_s_inv_hash hm.slots.length (hash_mod_key key hm.slots.length) + (List.v (List.index (hm.slots.val) hash_mod.val)) := by simp [inv] at hinv - have h := hinv.right.left hash_mod.val (by assumption) (by assumption) - simp [slot_t_inv] at h - simp [h] + have h := (hinv.right.left hash_mod.val (by assumption) (by assumption)).right + simp [slot_t_inv, hhm] at h + simp [h, hhm] have hd : distinct_keys (hm.slots.v.index hash_mod.val).v := by checkpoint simp [inv, slots_t_inv, slot_t_inv] at hinv have h := hinv.right.left hash_mod.val (by assumption) (by assumption) @@ -337,88 +337,87 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- TODO: allow providing terms to progress to instantiate the meta variables -- which are not propositions progress as ⟨ l0, _, _, _, hlen .. ⟩ - . checkpoint exact hm.slots.length - . checkpoint simp_all - . -- Finishing the proof - progress keep as hv as ⟨ v, h_veq ⟩ - -- TODO: update progress to automate that - let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } - exists nhm - -- TODO: later I don't want to inline nhm - we need to control simp - have hupdt : lookup nhm key = some value := by checkpoint - simp [lookup, List.lookup] at * + -- Finishing the proof + progress keep hv as ⟨ v, h_veq ⟩ + -- TODO: update progress to automate that + let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } + exists nhm + -- TODO: later I don't want to inline nhm - we need to control simp + have hupdt : lookup nhm key = some value := by checkpoint + simp [lookup, List.lookup] at * + simp_all + have hlkp : ∀ k, ¬ k = key → nhm.lookup k = hm.lookup k := by + simp [lookup, List.lookup] at * + intro k hk + -- We have to make a case disjunction: either the hashes are different, + -- in which case we don't even lookup the same slots, or the hashes + -- are the same, in which case we have to reason about what happens + -- in one slot + let k_hash_mod := k.val % v.val.len + have : 0 < hm.slots.val.len := by simp_all [inv] + have hvpos : 0 < v.val.len := by simp_all + have hvnz: v.val.len ≠ 0 := by simp_all - have hlkp : ∀ k, ¬ k = key → nhm.lookup k = hm.lookup k := by - simp [lookup, List.lookup] at * - intro k hk - -- We have to make a case disjunction: either the hashes are different, - -- in which case we don't even lookup the same slots, or the hashes - -- are the same, in which case we have to reason about what happens - -- in one slot - let k_hash_mod := k.val % v.val.len - have : 0 < hm.slots.val.len := by simp_all [inv] - have hvpos : 0 < v.val.len := by simp_all - have hvnz: v.val.len ≠ 0 := by - simp_all - have _ : 0 ≤ k_hash_mod := by - -- TODO: we want to automate this - simp - apply Int.emod_nonneg k.val hvnz - have _ : k_hash_mod < Vec.length hm.slots := by - -- TODO: we want to automate this - simp - have h := Int.emod_lt_of_pos k.val hvpos - simp_all - if h_hm : k_hash_mod = hash_mod.val then + have _ : 0 ≤ k_hash_mod := by + -- TODO: we want to automate this + simp + apply Int.emod_nonneg k.val hvnz + have _ : k_hash_mod < Vec.length hm.slots := by + -- TODO: we want to automate this + simp + have h := Int.emod_lt_of_pos k.val hvpos + simp_all + if h_hm : k_hash_mod = hash_mod.val then + simp_all + else + simp_all + have _ : + match hm.lookup key with + | none => nhm.len_s = hm.len_s + 1 + | some _ => nhm.len_s = hm.len_s := by checkpoint + simp only [lookup, List.lookup, len_s, al_v, HashMap.v, slots_t_lookup] at * + -- We have to do a case disjunction + simp_all + simp [_root_.List.update_map_eq] + -- TODO: dependent rewrites + have _ : key.val % hm.slots.val.len < (List.map List.v hm.slots.val).len := by + simp [*] + simp [_root_.List.len_flatten_update_eq, *] + split <;> + rename_i heq <;> + simp [heq] at hlen <;> + -- TODO: canonize addition by default? We need a tactic to simplify arithmetic equalities + -- with addition and substractions ((ℤ, +) is a ring or something - there should exist a tactic + -- somewhere in mathlib?) + simp [Int.add_assoc, Int.add_comm, Int.add_left_comm] <;> + int_tac + have hinv : inv nhm := by + simp [inv] at * + split_conjs + . match h: lookup hm key with + | none => + simp [h, lookup] at * simp_all + | some _ => + simp_all [lookup] + . simp [slots_t_inv, slot_t_inv] at * + intro i hipos _ + have _ := hinv.right.left i hipos (by simp_all) + simp [hhm, h_veq] at * -- TODO: annoying + -- We need a case disjunction + if h_ieq : i = key.val % _root_.List.len hm.slots.val then + -- TODO: simp_all fails: "(deterministic) timeout at 'whnf'" + -- Also, it is annoying to do this kind + -- of rewritings by hand. We could have a different simp + -- which safely substitutes variables when we have an + -- equality `x = ...` and `x` doesn't appear in the rhs + simp [h_ieq] at * + simp [*] else - simp_all - have _ : - match hm.lookup key with - | none => nhm.len_s = hm.len_s + 1 - | some _ => nhm.len_s = hm.len_s := by checkpoint - simp only [lookup, List.lookup, len_s, al_v, HashMap.v, slots_t_lookup] at * - -- We have to do a case disjunction - simp_all - simp [_root_.List.update_map_eq] - -- TODO: dependent rewrites - have _ : key.val % hm.slots.val.len < (List.map List.v hm.slots.val).len := by simp [*] - simp [_root_.List.len_flatten_update_eq, *] - split <;> - rename_i heq <;> - simp [heq] at hlen <;> - -- TODO: canonize addition by default? We need a tactic to simplify arithmetic equalities - -- with addition and substractions ((ℤ, +) is a ring or something - there should exist a tactic - -- somewhere in mathlib?) - simp [Int.add_assoc, Int.add_comm, Int.add_left_comm] <;> - int_tac - have hinv : inv nhm := by - simp [inv] at * - split_conjs - . match h: lookup hm key with - | none => - simp [h, lookup] at * - simp_all - | some _ => - simp_all [lookup] - . simp [slots_t_inv, slot_t_inv] at * - intro i hipos _ - have _ := hinv.right.left i hipos (by simp_all) - simp [hhm, h_veq] at * -- TODO: annoying - -- We need a case disjunction - if h_ieq : i = key.val % _root_.List.len hm.slots.val then - -- TODO: simp_all loops (investigate). - -- Also, it is annoying to do this kind - -- of rewritings by hand. We could have a different simp - -- which safely substitutes variables when we have an - -- equality `x = ...` and `x` doesn't appear in the rhs - simp [h_ieq] at * - simp [*] - else - simp [*] - . simp [*] - simp_all + . -- TODO: simp[*] fails: "(deterministic) timeout at 'whnf'" + simp [hinv, h_veq] + simp_all end HashMap -- cgit v1.2.3 From 3337c4ac3326c3132dcc322f55f23a7d2054ceb0 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 26 Jul 2023 15:00:11 +0200 Subject: Update some of the Vec function specs --- backends/lean/Base/Primitives/Vec.lean | 13 ++++++++---- backends/lean/Base/Progress/Progress.lean | 17 ++++++++++----- tests/lean/Hashmap/Properties.lean | 35 +++++++++++++++++-------------- 3 files changed, 40 insertions(+), 25 deletions(-) diff --git a/backends/lean/Base/Primitives/Vec.lean b/backends/lean/Base/Primitives/Vec.lean index 523372bb..a09d6ac2 100644 --- a/backends/lean/Base/Primitives/Vec.lean +++ b/backends/lean/Base/Primitives/Vec.lean @@ -85,14 +85,19 @@ def Vec.index (α : Type u) (v: Vec α) (i: Usize) : Result α := | none => fail .arrayOutOfBounds | some x => ret x +/- In the theorems below: we don't always need the `∃ ..`, but we use one + so that `progress` introduces an opaque variable and an equality. This + helps control the context. + -/ + @[pspec] theorem Vec.index_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) (hbound : i.val < v.length) : - v.index α i = ret (v.val.index i.val) := by + ∃ x, v.index α i = ret x ∧ x = v.val.index i.val := by simp only [index] -- TODO: dependent rewrite have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) - simp only [*] + simp [*] -- This shouldn't be used def Vec.index_back (α : Type u) (v: Vec α) (i: Usize) (_: α) : Result Unit := @@ -109,11 +114,11 @@ def Vec.index_mut (α : Type u) (v: Vec α) (i: Usize) : Result α := @[pspec] theorem Vec.index_mut_spec {α : Type u} [Inhabited α] (v: Vec α) (i: Usize) (hbound : i.val < v.length) : - v.index_mut α i = ret (v.val.index i.val) := by + ∃ x, v.index_mut α i = ret x ∧ x = v.val.index i.val := by simp only [index_mut] -- TODO: dependent rewrite have h := List.indexOpt_eq_index v.val i.val (by scalar_tac) (by simp [*]) - simp only [*] + simp [*] instance {α : Type u} (p : Vec α → Prop) : Arith.HasIntProp (Subtype p) where prop_ty := λ x => p x diff --git a/backends/lean/Base/Progress/Progress.lean b/backends/lean/Base/Progress/Progress.lean index 9300edff..6a4729dc 100644 --- a/backends/lean/Base/Progress/Progress.lean +++ b/backends/lean/Base/Progress/Progress.lean @@ -162,6 +162,7 @@ def progressWith (fExpr : Expr) (th : TheoremOrLocal) allGoals asmTac let newGoals ← getUnsolvedGoals setGoals (newGoals ++ curGoals) + trace[Progress] "progress: replaced the goals" -- pure .Ok @@ -281,12 +282,15 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do | [keepArg, withArg, asArgs] => do pure (keepArg, withArg, asArgs) | _ => throwError "Unexpected: invalid arguments" let keep : Option Name ← do + trace[Progress] "Keep arg: {keepArg}" let args := keepArg.getArgs - trace[Progress] "Keep args: {args}" - let arg := args.get! 1 - trace[Progress] "Keep arg: {arg}" - if arg.isIdent then pure (some arg.getId) - else do pure (some (← mkFreshAnonPropUserName)) + if args.size > 0 then do + trace[Progress] "Keep args: {args}" + let arg := args.get! 1 + trace[Progress] "Keep arg: {arg}" + if arg.isIdent then pure (some arg.getId) + else do pure (some (← mkFreshAnonPropUserName)) + else do pure none trace[Progress] "Keep: {keep}" let withArg ← do let withArg := withArg.getArgs @@ -328,7 +332,10 @@ def evalProgress (args : TSyntax `Progress.progressArgs) : TacticM Unit := do else throwError "Not a linear arithmetic goal" progressAsmsOrLookupTheorem keep withArg ids splitPost ( + withMainContext do + trace[Progress] "trying to solve assumption: {← getMainGoal}" firstTac [assumptionTac, scalarTac]) + trace[Diverge] "Progress done" elab "progress" args:progressArgs : tactic => evalProgress args diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 96b8193d..5d340b5c 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -285,7 +285,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value | none => nhm.len_s = hm.len_s + 1 | some _ => nhm.len_s = hm.len_s) := by rw [insert_no_resize] - simp [hash_key] + simp only [hash_key, bind_tc_ret] -- TODO: annoying have _ : (Vec.len (List α) hm.slots).val ≠ 0 := by checkpoint intro simp_all [inv] @@ -297,10 +297,9 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value simp [hinv] -- TODO: we want to automate that simp [*, Int.emod_lt_of_pos] - -- have h := Primitives.Vec.index_mut_spec hm.slots hash_mod -- TODO: change the spec of Vec.index_mut to introduce a let-binding. -- or: make progress introduce the let-binding by itself (this is clearer) - progress + progress as ⟨ l, h_leq ⟩ -- TODO: make progress use the names written in the goal progress as ⟨ inserted ⟩ rw [if_update_eq] -- TODO: necessary because we don't have a join @@ -311,38 +310,42 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value := by if inserted then simp [*] - have : hm.num_entries.val + (Usize.ofInt 1).val ≤ Usize.max := by + have hbounds : hm.num_entries.val + (Usize.ofInt 1).val ≤ Usize.max := by simp [lookup] at hnsat simp_all simp [inv] at hinv int_tac - progress - simp_all + -- TODO: progress fails in command line mode with "index out of bounds" + -- and I have no idea how to fix this. The error happens after progress + -- introduced the new goals. It must be when we exit the "withApp", etc. + -- helpers. + have ⟨ z, hp ⟩ := Usize.add_spec hbounds + simp [hp] else - simp_all [Pure.pure] + simp [*, Pure.pure] progress as ⟨ i0 ⟩ -- TODO: progress "eager" to match premises with assumptions while instantiating -- meta-variables - have h_slot : slot_s_inv_hash hm.slots.length (hash_mod_key key hm.slots.length) - (List.v (List.index (hm.slots.val) hash_mod.val)) := by + have h_slot : slot_s_inv_hash hm.slots.length (hash_mod_key key hm.slots.length) l.v + := by simp [inv] at hinv have h := (hinv.right.left hash_mod.val (by assumption) (by assumption)).right simp [slot_t_inv, hhm] at h - simp [h, hhm] - have hd : distinct_keys (hm.slots.v.index hash_mod.val).v := by checkpoint + simp [h, hhm, h_leq] + have hd : distinct_keys l.v := by checkpoint simp [inv, slots_t_inv, slot_t_inv] at hinv have h := hinv.right.left hash_mod.val (by assumption) (by assumption) - simp [h] + simp [h, h_leq] -- TODO: hide the variables and only keep the props -- TODO: allow providing terms to progress to instantiate the meta variables -- which are not propositions progress as ⟨ l0, _, _, _, hlen .. ⟩ - -- Finishing the proof progress keep hv as ⟨ v, h_veq ⟩ -- TODO: update progress to automate that let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } exists nhm - -- TODO: later I don't want to inline nhm - we need to control simp + -- TODO: later I don't want to inline nhm - we need to control simp: deactivate + -- zeta reduction? have hupdt : lookup nhm key = some value := by checkpoint simp [lookup, List.lookup] at * simp_all @@ -387,7 +390,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value rename_i heq <;> simp [heq] at hlen <;> -- TODO: canonize addition by default? We need a tactic to simplify arithmetic equalities - -- with addition and substractions ((ℤ, +) is a ring or something - there should exist a tactic + -- with addition and substractions ((ℤ, +) is a group or something - there should exist a tactic -- somewhere in mathlib?) simp [Int.add_assoc, Int.add_comm, Int.add_left_comm] <;> int_tac @@ -403,7 +406,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value . simp [slots_t_inv, slot_t_inv] at * intro i hipos _ have _ := hinv.right.left i hipos (by simp_all) - simp [hhm, h_veq] at * -- TODO: annoying + simp [hhm, h_veq] at * -- TODO: annoying, we do that because simp_all fails below -- We need a case disjunction if h_ieq : i = key.val % _root_.List.len hm.slots.val then -- TODO: simp_all fails: "(deterministic) timeout at 'whnf'" -- cgit v1.2.3 From 31de6eb8a82e17b4113262a18abf61e6233b55df Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 26 Jul 2023 15:00:29 +0200 Subject: Make a minor modification to a hashmap proof --- tests/lean/Hashmap/Properties.lean | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index 5d340b5c..ee63a065 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -271,6 +271,10 @@ theorem if_update_eq := by split <;> simp [Pure.pure] +-- TODO: move: small helper +def mk_opaque {α : Sort u} (x : α) : { y : α // y = x} := + ⟨ x, by simp ⟩ + theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value : α) (hinv : hm.inv) (hnsat : hm.lookup key = none → hm.len_s < Usize.max) : ∃ nhm, hm.insert_no_resize α key value = ret nhm ∧ @@ -342,10 +346,10 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value progress as ⟨ l0, _, _, _, hlen .. ⟩ progress keep hv as ⟨ v, h_veq ⟩ -- TODO: update progress to automate that - let nhm : HashMap α := { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } - exists nhm -- TODO: later I don't want to inline nhm - we need to control simp: deactivate - -- zeta reduction? + -- zeta reduction? For now I have to do this peculiar manipulation + have ⟨ nhm, nhm_eq ⟩ := @mk_opaque (HashMap α) { num_entries := i0, max_load_factor := hm.max_load_factor, max_load := hm.max_load, slots := v } + exists nhm have hupdt : lookup nhm key = some value := by checkpoint simp [lookup, List.lookup] at * simp_all @@ -406,7 +410,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value . simp [slots_t_inv, slot_t_inv] at * intro i hipos _ have _ := hinv.right.left i hipos (by simp_all) - simp [hhm, h_veq] at * -- TODO: annoying, we do that because simp_all fails below + simp [hhm, h_veq, nhm_eq] at * -- TODO: annoying, we do that because simp_all fails below -- We need a case disjunction if h_ieq : i = key.val % _root_.List.len hm.slots.val then -- TODO: simp_all fails: "(deterministic) timeout at 'whnf'" @@ -419,7 +423,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value else simp [*] . -- TODO: simp[*] fails: "(deterministic) timeout at 'whnf'" - simp [hinv, h_veq] + simp [hinv, h_veq, nhm_eq] simp_all end HashMap -- cgit v1.2.3 From 42551283ecab981b9bb646cab2e8da5491d71b17 Mon Sep 17 00:00:00 2001 From: Son Ho Date: Wed, 26 Jul 2023 15:07:09 +0200 Subject: Make minor modifications --- tests/lean/Hashmap/Properties.lean | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index ee63a065..e1bd8669 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -271,7 +271,8 @@ theorem if_update_eq := by split <;> simp [Pure.pure] --- TODO: move: small helper +-- Small helper +-- TODO: move, and introduce a better solution with nice syntax def mk_opaque {α : Sort u} (x : α) : { y : α // y = x} := ⟨ x, by simp ⟩ @@ -328,8 +329,6 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value else simp [*, Pure.pure] progress as ⟨ i0 ⟩ - -- TODO: progress "eager" to match premises with assumptions while instantiating - -- meta-variables have h_slot : slot_s_inv_hash hm.slots.length (hash_mod_key key hm.slots.length) l.v := by simp [inv] at hinv -- cgit v1.2.3 From 9b3a58e423333fc9a4a5a264c3beb0a3d951e86b Mon Sep 17 00:00:00 2001 From: Son Ho Date: Mon, 31 Jul 2023 15:56:52 +0200 Subject: Make minor modifications --- tests/lean/Hashmap/Properties.lean | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/lean/Hashmap/Properties.lean b/tests/lean/Hashmap/Properties.lean index e1bd8669..3652f608 100644 --- a/tests/lean/Hashmap/Properties.lean +++ b/tests/lean/Hashmap/Properties.lean @@ -276,6 +276,14 @@ theorem if_update_eq def mk_opaque {α : Sort u} (x : α) : { y : α // y = x} := ⟨ x, by simp ⟩ +--set_option profiler true +--set_option profiler.threshold 10 +--set_option trace.profiler true + +-- For pretty printing (useful when copy-pasting goals) +attribute [pp_dot] List.length -- use the dot notation when printing +set_option pp.coercions false -- do not print coercions with ↑ (this doesn't parse) + theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value : α) (hinv : hm.inv) (hnsat : hm.lookup key = none → hm.len_s < Usize.max) : ∃ nhm, hm.insert_no_resize α key value = ret nhm ∧ @@ -324,6 +332,7 @@ theorem insert_no_resize_spec {α : Type} (hm : HashMap α) (key : Usize) (value -- and I have no idea how to fix this. The error happens after progress -- introduced the new goals. It must be when we exit the "withApp", etc. -- helpers. + -- progress as ⟨ z, hp ⟩ have ⟨ z, hp ⟩ := Usize.add_spec hbounds simp [hp] else -- cgit v1.2.3