source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/batteries/BatteriesTest/float.lean
import Batteries.Lean.Float #guard 0.0.toRatParts == some (0, -53) #guard (2^(-1000):Float).toRatParts == some (4503599627370496, -1052) #guard (2^(-30):Float).toRatParts == some (4503599627370496, -82) #guard 0.1.toRatParts == some (7205759403792794, -56) #guard 0.5.toRatParts == some (4503599627370496, -53) #guard 5.0.toRatParts == some (5629499534213120, -50) #guard (-5.0).toRatParts == some (-5629499534213120, -50) #guard 5.5.toRatParts == some (6192449487634432, -50) #guard 500000000000000.5.toRatParts == some (8000000000000008, -4) #guard 5000000000000000.5.toRatParts == some (5000000000000000, 0) #guard 1e1000.toRatParts == none #guard (-1e1000).toRatParts == none #guard (-0/0:Float).toRatParts == none #guard 0.0.toRatParts' == some (0, 0) #guard (2^(-1000):Float).toRatParts' == some (1, -1000) #guard (2^(-30):Float).toRatParts' == some (1, -30) #guard 0.1.toRatParts' == some (3602879701896397, -55) #guard 0.5.toRatParts' == some (1, -1) #guard 5.0.toRatParts' == some (5, 0) #guard (-5.0).toRatParts' == some (-5, 0) #guard 5.5.toRatParts' == some (11, -1) #guard 500000000000000.5.toRatParts' == some (1000000000000001, -1) #guard 5000000000000000.5.toRatParts' == some (152587890625, 15) #guard 1e1000.toRatParts' == none #guard (-1e1000).toRatParts' == none #guard (-0/0:Float).toRatParts' == none #guard 0.0.toStringFull == "0" #guard (2^(-1000):Float).toStringFull.length == 1002 #guard (2^(-30):Float).toStringFull == "0.000000000931322574615478515625" #guard 0.1.toStringFull == "0.1000000000000000055511151231257827021181583404541015625" #guard 0.5.toStringFull == "0.5" #guard 5.0.toStringFull == "5" #guard (-5.0).toStringFull == "-5" #guard 5.5.toStringFull == "5.5" #guard 500000000000000.5.toStringFull == "500000000000000.5" #guard 5000000000000000.5.toStringFull == "5000000000000000" #guard 1e1000.toStringFull == "inf" #guard (-1e1000).toStringFull == "-inf" #guard (-0/0:Float).toStringFull == "NaN" #guard Nat.divFloat 1 0 == Float.inf #guard Nat.divFloat 50 0 == Float.inf #guard (Nat.divFloat 0 0).isNaN #guard Nat.divFloat 1 3 == (1 / 3 : Float) #guard Nat.divFloat 1 6 == (1 / 6 : Float) #guard Nat.divFloat 2 3 == (2 / 3 : Float) #guard Nat.divFloat 100 17 == (100 / 17 : Float) #guard Nat.divFloat 5000000000000000 1 == (5000000000000000 : Float) #guard [0,0,0,1,1,1,2,2,2,2,2,3,3,3,4,4,4].zipIdx.all fun p => Nat.divFloat (5000000000000000*4+p.2) 4 == (5000000000000000+p.1).toFloat #guard Nat.divFloat ((2^53-1)*(2^(1024-53))) 1 == ((2^53-1)*(2^(1024-53))) #guard Nat.divFloat (((2^53-1)*4+1)*(2^(1024-53))) 4 == ((2^53-1)*(2^(1024-53))) #guard Nat.divFloat (((2^53-1)*4+2)*(2^(1024-53))) 4 == Float.inf #guard Nat.divFloat (((2^53-1)*4+3)*(2^(1024-53))) 4 == Float.inf #guard Nat.divFloat (((2^53-1)*4+4)*(2^(1024-53))) 4 == Float.inf #guard Int.divFloat 1 3 == (1 / 3 : Float) #guard Int.divFloat (-1) 3 == (-1 / 3 : Float) #guard Int.divFloat 1 (-3) == (1 / -3 : Float) #guard Int.divFloat (-1) (-3) == (-1 / -3 : Float) #guard Int.divFloat (-1) 0 == -Float.inf #guard (Int.divFloat 0 0).isNaN #guard (Int.divFloat 0 1).toString == "0.000000" #guard (Int.divFloat 0 (-1)).toString == "-0.000000"
.lake/packages/batteries/BatteriesTest/absurd.lean
import Batteries.Tactic.Basic /-! Tests for `absurd` tactic -/ -- Basic example /-- error: unsolved goals p : Prop h : p ⊢ ¬p -/ #guard_msgs in example {p : Prop} (h : p) : 0 = 0 := by absurd h -- Negative example /-- error: unsolved goals p : Prop h : ¬p ⊢ p -/ #guard_msgs in example {p : Prop} (h : ¬p) : 0 = 1 := by absurd h -- Inequality example /-- error: unsolved goals n : Nat h : n ≠ 0 ⊢ n = 0 -/ #guard_msgs in example (h : n ≠ 0) : 0 = 2 := by absurd h -- Example with implies false /-- error: unsolved goals p : Prop h : p → False ⊢ p -/ #guard_msgs in example {p : Prop} (h : p → False) : 0 = 3 := by absurd h /-- error: unsolved goals p : Prop h : p ⊢ ¬p -/ #guard_msgs in example {p : Prop} {h : p} : ∀ {x : True}, 0 = 0 := by absurd h -- `·` should not be legal /-- error: invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`) --- error: unsolved goals p : Prop h : p ⊢ ∀ {x : True}, 0 = 0 -/ #guard_msgs in example {p : Prop} {h : p} : ∀ {_ : True}, 0 = 0 := by absurd ·
.lake/packages/batteries/BatteriesTest/where.lean
-- None of these imports are really necessary, except to create namespace mentioned below. import Lean.Elab.Term import Lean.Elab.Command import Batteries.Data.UnionFind.Basic -- Return to pristine state set_option linter.missingDocs false set_option internal.cmdlineSnapshots false set_option backward.privateInPublic.warn true set_option experimental.module false set_option Elab.inServer false /-- info: -- In root namespace with initial scope -/ #guard_msgs in #where noncomputable section /-- info: noncomputable section -/ #guard_msgs in #where end namespace WhereTest variable (x : Nat) (α : Type) /-- info: namespace WhereTest variable (x : Nat) (α : Type) -/ #guard_msgs in #where universe u v w /-- info: namespace WhereTest universe u v w variable (x : Nat) (α : Type) -/ #guard_msgs in #where set_option pp.piBinderTypes false /-- info: namespace WhereTest universe u v w variable (x : Nat) (α : Type) set_option pp.piBinderTypes false -/ #guard_msgs in #where end WhereTest open Lean Meta /-- info: open Lean Lean.Meta -/ #guard_msgs in #where open Elab hiding TermElabM /-- info: open Lean Lean.Meta open Lean.Elab hiding TermElabM -/ #guard_msgs in #where open Command Batteries open Array renaming map -> listMap /-- info: open Lean Lean.Meta open Lean.Elab hiding TermElabM open Lean.Elab.Command Batteries open Array renaming map → listMap -/ #guard_msgs in #where
.lake/packages/batteries/BatteriesTest/print_opaques.lean
import Batteries.Tactic.PrintOpaques partial def foo : Unit → Nat := foo def bar : Unit → Nat := foo /-- info: 'bar' depends on opaque or partial definitions: [foo] -/ #guard_msgs in #print opaques bar opaque qux : Nat def quux : Bool := qux == 0 /-- info: 'quux' depends on opaque or partial definitions: [qux] -/ #guard_msgs in #print opaques quux /-! Examples from the documentation. -/ /-- info: 'Classical.choice' depends on opaque or partial definitions: [Classical.choice] -/ #guard_msgs in #print opaques Classical.choice /-- info: 'Classical.axiomOfChoice' does not use any opaque or partial definitions -/ #guard_msgs in #print opaques Classical.axiomOfChoice /-- info: 'Std.HashMap.insert' depends on opaque or partial definitions: [System.Platform.getNumBits] -/ #guard_msgs in #print opaques Std.HashMap.insert /-- info: 'Std.Stream.forIn' depends on opaque or partial definitions: [_private.Init.Data.Stream.0.Std.Stream.forIn.visit] -/ #guard_msgs in #print opaques Std.Stream.forIn
.lake/packages/batteries/BatteriesTest/simpa.lean
set_option linter.missingDocs false example {P : Prop} (p : P) : P := by simpa example {P : Prop} (p : False) : P := by simp at p def foo (n : α) := [n] section unnecessarySimpa /-- warning: try 'simp' instead of 'simpa' Note: This linter can be disabled with `set_option linter.unnecessarySimpa false` -/ #guard_msgs in example : foo n = [n] := by simpa only [foo] /-- warning: Try `simp at h` instead of `simpa using h` Note: This linter can be disabled with `set_option linter.unnecessarySimpa false` -/ #guard_msgs in example (h : foo n ≠ [n]) : False := by simpa [foo] using h end unnecessarySimpa example (p : Nat → Prop) (h : p (a + b)) : p (b + a) := by have : a + b = b + a := Nat.add_comm _ _ simpa [this] using h def Injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂ namespace div_left_inj_issue class Inv (α : Type u) where inv : α → α class Group (α) extends Mul α, Div α, Inv α variable [Group G] axiom div_eq_mul_inv (a b : G) : a / b = a * Inv.inv b axiom mul_left_injective (a : G) : Injective (· * a) theorem div_left_injective (b : G) : Injective fun a => a / b := by simpa only [div_eq_mul_inv] using fun a a' h => mul_left_injective (Inv.inv b) h end div_left_inj_issue namespace Prod theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := Iff.of_eq (mk.injEq _ _ _ _) theorem mk.inj_left {α β : Type _} (a : α) : Injective (Prod.mk a : β → α × β) := by intro b₁ b₂ h simpa only [true_and, Prod.mk.inj_iff, eq_self] using h end Prod theorem implicit_lambda (h : ∀ {x : Nat}, a = x) : a = 2 := by simpa using h theorem implicit_lambda2 (h : a = 2) : ∀ {_ : Nat}, a = 2 := by simpa using h theorem no_implicit_lambda (h : ∀ {x : Nat}, a = x) : ∀ {x : Nat}, a = x := by simpa using @h #guard_msgs (drop warning) in theorem thm : (a : Int) ≤ b - c ↔ a + b ≤ c := sorry #guard_msgs (drop warning) in theorem thm2 : (b : Int) - c ≤ (a - b) - (a - c) := sorry example : (b - c : Int) + (a - b) + a ≤ c := by simpa only [thm] using thm2 example : (b - c : Int) + (a - b) + a ≤ c := by simpa only [thm] using @thm2 example (P : Bool) (h : ¬ ¬ P) : P := by have : ¬ ¬ P := h simpa /-- info: Try this: [apply] simpa only using h -/ #guard_msgs in example (p : Prop) (h : p) : p := by simpa? using h /-- info: Try this: [apply] simpa only [and_true] using h -/ #guard_msgs in example (p : Prop) (h : p ∧ True) : p := by simpa? using h
.lake/packages/batteries/BatteriesTest/show_term.lean
/-- info: Try this: [apply] exact (n, 37) -/ #guard_msgs in example (n : Nat) : Nat × Nat := by show_term constructor exact n exact 37 /-- info: Try this: [apply] refine (?_, ?_) -/ #guard_msgs in example : Nat × Nat := by show_term constructor repeat exact 42 /-- info: Try this: [apply] fun {X} => X -/ #guard_msgs in example : {_a : Nat} → Nat := show_term by intro X exact X
.lake/packages/batteries/BatteriesTest/OpenPrivateDefs.lean
/-! This file contains a private declaration. It's tested in `openPrivate.lean`. -/ private def secretNumber : Nat := 2
.lake/packages/batteries/BatteriesTest/ArrayMap.lean
import Batteries.Data.List.ArrayMap open List /-- info: #[3, 4, 5, 6] -/ #guard_msgs in #eval List.toArrayMap [0, 1, 2, 3] (fun n => n + 3) /-- info: #[7, 9, 15, 25] -/ #guard_msgs in #eval toArrayMap [0, 1, 2, 3] (fun n => 2 * n ^ 2 + 7)
.lake/packages/batteries/BatteriesTest/nondet.lean
import Batteries.Control.Nondet.Basic import Batteries.Lean.Meta.Basic set_option linter.missingDocs false open Lean Meta def M := StateT (List Nat) MetaM deriving instance AlternativeMonad for M instance : MonadBacktrack (List Nat) M where saveState := StateT.get restoreState := StateT.set def record (n : Nat) : M Unit := do discard <| restoreState (n :: (← saveState)) def iotaM [AlternativeMonad m] [MonadBacktrack σ m] (n : Nat) : Nondet m Nat := Nondet.ofList (List.range' 1 n).reverse /-- info: (52, []) -/ #guard_msgs in #eval show MetaM (Nat × List Nat) from StateT.run (iotaM 52 : Nondet M Nat).head [] /-- info: ((), [52]) -/ #guard_msgs in #eval show MetaM (Unit × List Nat) from StateT.run (((iotaM 52).mapM record).head) [] def x : Nondet M Nat := (iotaM 52).filterMapM fun x => do record x if x % 7 = 0 then return some (x^2) else return none /-- info: (2401, [49]) -/ #guard_msgs in #eval show MetaM (Nat × List Nat) from StateT.run x.head [] def divisors (n : Nat) : List Nat := List.range' 1 (n - 1) |>.reverse.filter fun m => n % m = 0 example : divisors 52 = [26, 13, 4, 2, 1] := rfl def divisorsM [Monad m] [MonadBacktrack σ m] (n : Nat) : Nondet m Nat := Nondet.ofList (divisors n) /-- Take the numbers `32, ..., 1`, replace each with their divisors, then replace again. -/ def y : Nondet M Nat := (iotaM 32) |>.bind fun x => do record x divisorsM x |>.bind fun x => do record x divisorsM x /-- info: [8, 4, 2, 1, 4, 2, 1, 2, 1, 1, 5, 3, 1, 5, 2, 1, 3, 2, 1, 1, 1, 1, 7] -/ #guard_msgs in #eval show MetaM (List Nat) from StateT.run' (y.toMLList'.takeAsList 23) [] -- All ways to find `4 ∣ a ∣ b`, with `b = 32, ..., 1`. /-- info: ([(4, [16, 32]), (4, [8, 32]), (4, [12, 24]), (4, [8, 24]), (4, [8, 16])], [1]) -/ #guard_msgs in #eval show MetaM (List (Nat × List Nat) × List Nat) from StateT.run (y.filter (· = 4)).toMLList.force [] /-- info: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] -/ #guard_msgs in #eval (iotaM 15 : Nondet MetaM Nat).toList' -- Depth first search of the divisors of 255. /-- info: [255, 85, 17, 1, 5, 1, 1, 51, 17, 1, 3, 1, 1, 17, 1, 15, 5, 1, 3, 1, 1, 5, 1, 3, 1, 1] -/ #guard_msgs in #eval (Nondet.iterate divisorsM 255 : Nondet Id Nat).toList'
.lake/packages/batteries/BatteriesTest/seq_focus.lean
import Batteries.Tactic.SeqFocus example : (True ∧ (∃ x : Nat, x = x)) ∧ True := by constructor constructor -- error: too many tactics fail_if_success map_tacs [trivial; exact ⟨0, rfl⟩; trivial; trivial] -- error: not enough tactics fail_if_success map_tacs [trivial; exact ⟨0, rfl⟩] map_tacs [trivial; exact ⟨0, rfl⟩; trivial] example : ((True ∧ True) ∧ (∃ x : Nat, x = x)) ∧ (True ∧ (∃ x : Nat, x = x)) := by constructor constructor map_tacs [(constructor; trivial); exact ⟨0, rfl⟩; constructor] trivial trivial exact ⟨0, rfl⟩ example : (True ∧ (∃ x : Nat, x = x)) ∧ True := by constructor -- error: not enough tactics fail_if_success constructor <;> [trivial] map_tacs [constructor <;> [trivial; exact ⟨0, rfl⟩]; constructor]
.lake/packages/batteries/BatteriesTest/lemma_cmd.lean
import Batteries.Tactic.Lemma -- lemma disabled by default /-- info: Try this: [apply] theorem --- error: `lemma` is not supported by default, please use `theorem` instead. Use `set_option lang.lemmaCmd true` to enable the use of the `lemma` command in a file. Use the command line option `-Dlang.lemmaCmd=true` to enable the use of `lemma` globally. -/ #guard_msgs in lemma test1 : 3 < 7 := by decide -- lemma enabled for one command set_option lang.lemmaCmd true in lemma test2 : 3 < 7 := by decide -- lemma disabled again /-- info: Try this: [apply] theorem --- error: `lemma` is not supported by default, please use `theorem` instead. Use `set_option lang.lemmaCmd true` to enable the use of the `lemma` command in a file. Use the command line option `-Dlang.lemmaCmd=true` to enable the use of `lemma` globally. -/ #guard_msgs in lemma test3 : 3 < 7 := by decide -- lemma enabled for rest of file set_option lang.lemmaCmd true lemma test4 : 3 < 7 := by decide lemma test5 : 3 < 7 := by decide
.lake/packages/batteries/BatteriesTest/alias.lean
import Batteries.Tactic.Alias set_option linter.unusedVariables false set_option linter.missingDocs false open Lean Meta namespace A /-- doc string for foo -/ theorem foo : 1 + 1 = 2 := rfl /-- doc string for `alias foo` -/ alias foo1 := foo @[deprecated (since := "2038-01-20")] alias foo2 := foo @[deprecated foo2 (since := "2038-01-20")] alias _root_.B.foo3 := foo @[deprecated foo2 "it was never a good idea anyway" (since := "last thursday")] alias foo4 := foo example : 1 + 1 = 2 := foo1 /-- warning: `A.foo2` has been deprecated: Use `A.foo` instead -/ #guard_msgs in example : 1 + 1 = 2 := foo2 /-- warning: `B.foo3` has been deprecated: Use `A.foo2` instead Note: The updated constant is in a different namespace. Dot notation may need to be changed (e.g., from `x.foo3` to `foo2 x`). -/ #guard_msgs in example : 1 + 1 = 2 := B.foo3 /-- warning: `A.foo4` has been deprecated: it was never a good idea anyway -/ #guard_msgs in example : 1 + 1 = 2 := foo4 /-- doc string for bar -/ def bar : Nat := 5 alias bar1 := bar alias _root_.B.bar2 := bar example : bar1 = 5 := rfl example : B.bar2 = 5 := rfl theorem baz (x : Nat) : x = x := rfl alias baz1 := baz example : 3 = 3 := baz1 3 /-- doc string for foobar -/ def foobar : Nat → Nat := id @[inherit_doc foobar] alias foobar1 := foobar @[simp] alias foobar2 := foobar /-- doc string for foobar2 -/ def foobar3 (n : Nat) := foobar1 n /-- error: `simp` made no progress -/ #guard_msgs in example : foobar1 x = foobar x := by simp example : foobar2 x = foobar x := by simp /- Test protected -/ /-- doc string for Foo.barbaz -/ protected alias Foo.barbaz := trivial /-- error: Unknown identifier `barbaz` -/ #guard_msgs in example : True := barbaz example : True := Foo.barbaz /- Test noncomputable -/ /-- doc string for foobaz -/ noncomputable def foobaz : Nat → Nat := id alias foobaz1 := foobaz /-- error: failed to compile definition, compiler IR check failed at `foobaz2`. Error: depends on declaration 'A.foobaz1', which has no executable code; consider marking definition as 'noncomputable' -/ #guard_msgs in def foobaz2 (n : Nat) := foobaz1 n noncomputable alias foobaz3 := id /-- error: failed to compile definition, compiler IR check failed at `foobaz4`. Error: depends on declaration 'A.foobaz3', which has no executable code; consider marking definition as 'noncomputable' -/ #guard_msgs in def foobaz4 (n : Nat) := foobaz3 n /- Test unsafe -/ /-- doc string for barbaz -/ unsafe def barbaz : Nat → Nat := id alias barbaz1 := barbaz /-- error: (kernel) invalid declaration, it uses unsafe declaration 'A.barbaz1' -/ #guard_msgs in def barbaz2 (n : Nat) := barbaz1 n unsafe alias barbaz3 := id /-- error: (kernel) invalid declaration, it uses unsafe declaration 'A.barbaz3' -/ #guard_msgs in def barbaz4 (n : Nat) := barbaz3 n /- iff version -/ @[deprecated (since := "2038-01-20")] alias ⟨mpId, mprId⟩ := Iff.rfl /-- info: A.mpId {a : Prop} : a → a -/ #guard_msgs in #check mpId /-- info: A.mprId {a : Prop} : a → a -/ #guard_msgs in #check mprId /-- warning: `A.mpId` has been deprecated: Use `Iff.rfl` instead Note: The updated constant has a different type: ∀ {a : Prop}, a ↔ a instead of ∀ {a : Prop}, a → a Note: The updated constant is in a different namespace. Dot notation may need to be changed (e.g., from `x.mpId` to `Iff.rfl x`). --- warning: `A.mprId` has been deprecated: Use `Iff.rfl` instead Note: The updated constant has a different type: ∀ {a : Prop}, a ↔ a instead of ∀ {a : Prop}, a → a Note: The updated constant is in a different namespace. Dot notation may need to be changed (e.g., from `x.mprId` to `Iff.rfl x`). -/ #guard_msgs in example := And.intro @mpId @mprId /- Test environment extension -/ /-- info: **Alias** of `A.foo`. -/ #guard_msgs in #eval show MetaM _ from do match ← Batteries.Tactic.Alias.getAliasInfo `A.foo1 with | some i => IO.println i.toString | none => IO.println "alias not found"
.lake/packages/batteries/BatteriesTest/lint_docBlame.lean
import Batteries.Tactic.Lint set_option linter.missingDocs false /-- A docstring is needed here -/ structure AtLeastThirtySeven where /-- and here -/ val : Nat := 1 -- but not here prop : 37 ≤ val -- or here theorem AtLeastThirtySeven.lt (x : AtLeastThirtySeven) : 36 < x.val := x.prop #lint- only docBlame
.lake/packages/batteries/BatteriesTest/list_sublists.lean
import Batteries.Data.List.Basic -- this times out with `sublistsFast` set_option maxRecDepth 562 in example : [1, 2, 3].sublists.sublists.length = 256 := rfl
.lake/packages/batteries/BatteriesTest/import_lean.lean
import Lean import Batteries /-! This file ensures that we can import all of `Lean` and `Batteries` without name conflicts. -/
.lake/packages/batteries/BatteriesTest/isIndependentOf.lean
import Batteries.Lean.Meta.Basic import Batteries.Tactic.PermuteGoals import Lean.Meta.Tactic.IndependentOf open Lean Meta Elab.Tactic elab "check_indep" : tactic => do match ← getGoals with | [] => throwError "Expected goal" | g :: l => let res := if ←g.isIndependentOf l then "" else "not " let t ← instantiateMVars (← g.getType) logWarning s!"{←ppExpr (.mvar g)} : {←ppExpr t} is {res}independent of:" l.forM fun g' => do logInfo s!" {←ppExpr (.mvar g')} : {←ppExpr (← g'.getType)}" let ppD (l : LocalDecl) : TacticM PUnit := do logInfo s!" {←ppExpr (.fvar l.fvarId)} : {←ppExpr l.type}" let _ ← (←g'.getDecl).lctx.forM ppD pure () /-- warning: ?w : Nat is not independent of: -/ #guard_msgs(warning, drop info) in example : ∃ (n : Nat), ∀(x : Fin n), x.val = 0 := by apply Exists.intro intro x swap check_indep exact 0 revert x intro ⟨x, lt⟩ contradiction -- This is a tricker one, where the dependency is via a hypothesis. /-- warning: ?w : Nat is not independent of: -/ #guard_msgs(warning, drop info) in example : ∃ (n : Nat), ∀(x : Fin n) (y : Nat), x.val = y → y = 0 := by apply Exists.intro intro x y p swap check_indep exact 0 revert x intro ⟨x, lt⟩ contradiction
.lake/packages/batteries/BatteriesTest/rfl.lean
import Lean.Elab.Tactic.Rfl -- Adaptation note: we should be able to remove this import after nightly-2024-03-19 set_option linter.missingDocs false example (a : Nat) : a = a := rfl example (a : Nat) : a = a := by rfl open Setoid universe u variable {α : Sort u} [Setoid α] @[refl] def iseqv_refl (a : α) : a ≈ a := iseqv.refl a example (a : α) : a ≈ a := by rfl example (a : Nat) : a ≤ a := by (fail_if_success rfl); apply Nat.le_refl attribute [refl] Nat.le_refl example (a : Nat) : a ≤ a := by rfl structure Foo def Foo.le (_ _ : Foo) := Unit → True instance : LE Foo := ⟨Foo.le⟩ @[refl] theorem Foo.le_refl (a : Foo) : a ≤ a := fun _ => trivial example (a : Foo) : a ≤ a := by apply Foo.le_refl example (a : Foo) : a ≤ a := by rfl example (x : Nat) : x ≤ x := by show _ rfl
.lake/packages/batteries/BatteriesTest/MLList.lean
import Lean.Meta.Basic import Batteries.Data.MLList.IO import Batteries.Data.List.Basic set_option linter.missingDocs false /-! ### Test fix to performance problem in `asArray`. -/ def g (n : Nat) : MLList Lean.Meta.MetaM Nat := do for _ in [:n] do if true then continue return n /-- info: #[3000] -/ -- This used to fail before add the `uncons?` field to the implementation of `MLList`. #guard_msgs in #eval MLList.asArray $ (g 3000) /-! ### Test `MLList.ofTaskList`. We generate three tasks which sleep for `100`, `50`, and `1` milliseconds respectively, and then verify that `MLList.ofTaskList` return their results in the order they complete. -/ /- This test is very flaky, so it's disabled for now. def sleep (n : UInt32) : BaseIO (Task UInt32) := IO.asTask (do IO.sleep n; return n) |>.map fun t => t.map fun | .ok n => n | .error _ => 0 def sleeps : MLList BaseIO UInt32 := .squash fun _ => do let r ← [100,50,1].map sleep |>.traverse id return .ofTaskList r /-- info: [1, 50, 100] -/ #guard_msgs in #eval sleeps.force -/
.lake/packages/batteries/BatteriesTest/lint_docBlameThm.lean
import Batteries.Tactic.Lint set_option linter.missingDocs false -- A docstring is not needed here structure AtLeastThirtySeven where -- or here val : Nat := 1 /-- but is needed here -/ prop : 37 ≤ val /-- and here -/ theorem AtLeastThirtySeven.lt (x : AtLeastThirtySeven) : 36 < x.val := x.prop #lint- only docBlameThm
.lake/packages/batteries/BatteriesTest/by_contra.lean
import Batteries.Tactic.Basic private def nonDecid (P : Prop) (x : P) : P := by by_contra h guard_hyp h : ¬P guard_target = False exact h x private def decid (P : Prop) [Decidable P] (x : P) : P := by by_contra h guard_hyp h : ¬P guard_target = False exact h x example (P : Prop) [Decidable P] : nonDecid P = decid P := by delta nonDecid decid guard_target =ₛ (fun x : P => Classical.byContradiction fun h => h x) = (fun x : P => Decidable.byContradiction fun h => h x) rfl example (P : Prop) : P → P := by by_contra guard_hyp ‹_› : ¬(P → P) exact ‹¬(P → P)› id example (P : Prop) : {_ : P} → P := by by_contra guard_hyp ‹_› : ¬(P → P) exact ‹¬(P → P)› id /-! https://github.com/leanprover-community/batteries/issues/1196: Previously the second error had a `Decidable True` subgoal, which only appeared in the presence of the first unclosed goal. -/ /-- error: unsolved goals case left ⊢ True --- error: unsolved goals case right x✝ : ¬True ⊢ False -/ #guard_msgs in example : True ∧ True := by constructor · skip · by_contra
.lake/packages/batteries/BatteriesTest/congr.lean
import Batteries.Tactic.Congr section congr example (c : Prop → Prop → Prop → Prop) (x x' y z z' : Prop) (h₀ : x ↔ x') (h₁ : z ↔ z') : c x y z ↔ c x' y z' := by apply Iff.of_eq -- FIXME: not needed in lean 3 congr · guard_target =ₐ x = x' apply_ext_theorem assumption · guard_target =ₐ z = z' ext assumption example {α β γ δ} {F : ∀ {α β}, (α → β) → γ → δ} {f g : α → β} {s : γ} (h : ∀ x : α, f x = g x) : F f s = F g s := by congr with x -- apply_assumption -- FIXME apply h example {α β : Type _} {f : _ → β} {x y : { x : { x : α // x = x } // x = x }} (h : x.1 = y.1) : f x = f y := by congr with : 1 exact h example {α β : Type _} {F : _ → β} {f g : { f : α → β // f = f }} (h : ∀ x : α, (f : α → β) x = (g : α → β) x) : F f = F g := by rcongr x revert x guard_target = type_of% h exact h section -- Adaptation note: the next two examples have always failed if `List.ext` was in scope, -- but until nightly-2024-04-24 (when `List.ext` was upstreamed), it wasn't in scope. -- In order to preserve the test behaviour we locally remove the `ext` attribute. attribute [-ext] List.ext_getElem? example {ls : List Nat} : (ls.map fun _ => (ls.map fun y => 1 + y).sum + 1) = (ls.map fun _ => (ls.map fun y => Nat.succ y).sum + 1) := by rcongr (_x y) guard_target =ₐ 1 + y = y.succ rw [Nat.add_comm] example {ls : List Nat} {f g : Nat → Nat} {h : ∀ x, f x = g x} : (ls.map fun x => f x + 3) = ls.map fun x => g x + 3 := by rcongr x exact h x end -- succeed when either `ext` or `congr` can close the goal example : () = () := by rcongr example : 0 = 0 := by rcongr example {α} (a : α) : a = a := by congr example : { f : Nat → Nat // f = id } := ⟨_, by congr (config := { closePre := false, closePost := false }) with x exact Nat.zero_add x⟩ -- FIXME(?): congr doesn't fail -- example {α} (a b : α) (h : False) : a = b := by -- fail_if_success congr -- cases h end congr
.lake/packages/batteries/BatteriesTest/exfalso.lean
import Batteries.Tactic.Basic private axiom test_sorry : ∀ {α}, α example {A} (h : False) : A := by exfalso exact h example {A} : False → A := by exfalso show False -- exfalso is not supposed to close the goal yet exact test_sorry
.lake/packages/batteries/BatteriesTest/conv_equals.lean
import Batteries.Tactic.Basic -- The example from the doc string, for quick comparision -- and keeping the doc up-to-date -- (only `guard_target` added) /-- warning: declaration uses 'sorry' -/ #guard_msgs in example (P : (Nat → Nat) → Prop) : P (fun n => n - n) := by conv in (_ - _) => equals 0 => -- current goal: ⊢ n - n = 0 guard_target =ₛ n - n = 0 apply Nat.sub_self guard_target =ₛ P (fun n => 0) -- current goal: P (fun n => 0) sorry -- This tests that the goal created by equals must be closed -- Using #guard_msgs below triggers this linter set_option linter.unreachableTactic false /-- error: unsolved goals P : (Nat → Nat) → Prop n : Nat ⊢ n - n = 0 --- error: No goals to be solved -/ #guard_msgs in example (P : (Nat → Nat) → Prop) : P (fun n => n - n) := by conv in (_ - _) => equals 0 => skip -- this should complain -- and at this point, there should be no goal left tactic => sorry sorry
.lake/packages/batteries/BatteriesTest/lint_empty.lean
import Batteries import Lean.Elab set_option linter.all true /-- Some syntax to elaborate in a fresh env -/ def natDef : String := "prelude set_option genCtorIdx false in inductive Nat where | zero | succ (n : Nat) : Nat def id (x : α) := x " open Lean Parser Elab in /-- Test that the linters imported from Batteries all work when run on a declaration in an empty environment. This runs the linters because there's a global IO.Ref that contains them, rather than having them be in a field of the environment itself, precisely so they can run in situations like this. However, a linter that assumes it's run in an environment with the Lean prelude available may use of things like `find!` and `get!` in linters, with the result that the linter panics. This test elaborates the definition of the natural numbers and the identity function in a fresh environment with all linters enabled. Running the tests in an environment with `LEAN_ABORT_ON_PANIC` set ensures that the linters can at least run. -/ elab "#testInEmptyEnv" : command => do let context := mkInputContext natDef "test" let (header, state, msgs) ← parseHeader context let opts := Options.empty |>.setBool `linter.all true let (env, msgs) ← processHeader header opts msgs context if msgs.hasErrors then for msg in msgs.toList do logMessage msg liftM (m := IO) <| throw <| IO.userError "Errors in header" let cmdState := Command.mkState env msgs let s ← IO.processCommands context state cmdState for t in s.commandState.infoState.trees do pushInfoTree t for msg in s.commandState.messages.toList do logMessage msg #testInEmptyEnv
.lake/packages/batteries/BatteriesTest/case.lean
import Batteries.Tactic.Case set_option linter.missingDocs false example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor fail_if_success show z = z case _ : z = _ · exact h' exact h example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor case _ : z = _ => exact h' case left => exact h example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor case _ : z = _ | left => assumption example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor case _ : _ | _ : _ => assumption example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor case left | _ : z = _ => assumption example (h : x = y) (h' : z = w) : x = y ∧ z = w := by constructor case _ : z = _ => ?foo case foo := h' case left := h example (h : x = y) (h' : z = w) : x = y ∧ z + 0 = w := by constructor case right : z = _ => guard_target =ₛ z = w exact h' case _ : x = y := h example (h : x = y) : x = y ∧ x = y := by constructor case _ : x = y | _ : x = y => ?foo -- Closes both case foo => exact h example (h : x = y) : x = y ∧ x = y ∧ x = y := by refine ⟨?foo, ?_, ?_⟩ · exact h case _ : x = y | _ : x = y => ?foo -- This metavariable was already assigned, so no more goals. /-- error: 'case' tactic failed, value ?left depends on the main goal metavariable '?left' -/ #guard_msgs in example : False ∧ True := by constructor case _ : False => ?left /-- error: Type mismatch ?right has type True but is expected to have type False -/ #guard_msgs in example : False ∧ True := by constructor case _ : False => ?right /-- error: 'case' tactic failed, value ?right depends on the main goal metavariable '?right' -/ #guard_msgs in example : False ∧ False := by constructor case left => ?right case right => ?left example (h : x = y) (h' : z = w) : x = y ∧ z + 0 = w := by constructor case _ : z = _ => guard_target =ₛ z = w exact h' case left => exact h example (x y z : α) (h : x = y) (h' : y = z) : x = z := by apply Eq.trans case _ : id α := y -- Note: `case` inserts a `let_fun` since `id α` and `α` aren't defeq with reducible transparency · guard_target =ₛ x = show id α from y exact h · guard_target = y = z exact h' example (x y z : α) (h : x = y) (h' : y = z) : x = z := by apply Eq.trans case _ : α := y -- Note: `case` detects defeq with reducible transparency, so doesn't insert type hint · guard_target =ₛ x = y exact h · guard_target = y = z exact h' def Injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂ theorem cancel_injective (h : Injective f) : f x = f y ↔ x = y := by refine ⟨fun e => h e, ?_⟩ intro h cases h rfl example (h : Injective f) (h' : f x = f y) : x = y := by rw [cancel_injective] at h' case _ : Injective f := h exact h' example (h : Injective f) (h' : f x = f y) : x = y := by rw [cancel_injective] at h' case _ : Injective f · exact h exact h' example (hf : Injective f) (hg : Injective g) (h : g (f x) = g (f y)) : x = y := by rw [cancel_injective, cancel_injective] at h case _ : Injective f | _ : Injective g => assumption exact h example (hf : Injective f) (hg : Injective g) (h : g (f x) = g (f y)) : x = y := by rw [cancel_injective, cancel_injective] at h repeat case _ : Injective _ => assumption exact h example (hf : Injective f) (hg : Injective g) (h : g (f x) = g (f y)) : x = y := by rw [cancel_injective, cancel_injective] at h case _ : Injective f | _ : Injective g · guard_target = Injective f assumption · guard_target = Injective g assumption exact h example (hf : Injective f) (hg : Injective g) (h : g (f x) = g (f y)) : x = y := by rw [cancel_injective, cancel_injective] at h case _ : Injective f | _ : Injective g => _ · guard_target = Injective f assumption · guard_target = Injective g assumption exact h example (a : Nat) : 0 + a = a := by induction a case _ n ih : 0 + (n + 1) = n + 1 => guard_target =ₛ 0 + (n + 1) = n + 1 rw [← Nat.add_assoc, ih] case _ : 0 + 0 = 0 := rfl example (a : Nat) : 0 + a = a := by induction a case _ n ih : 0 + (n + 1) = n + 1 | _ : 0 + 0 = 0 · rw [← Nat.add_assoc, ih] · rfl example : True ∧ ∀ x : Nat, x = x := by constructor case' _ : ∀ _, _ => intro z case left => trivial guard_target =ₛ z = z rfl -- Test focusing by full match, suffix match, and prefix match #guard_msgs in example : True := by have x : Bool := ?a have y : Nat := ?a.b.c have z : String := ?c.b.a case a : Bool := true case a : Nat := 0 case a : String := "" trivial -- Test priorities when focusing by full match, suffix match, and prefix match example : True := by let x : Nat := ?a let y : Nat := ?c.b.a let z : Nat := ?c'.b.a let w : Nat := ?a.b.c case a : Nat := 0 case a : Nat := 1 case a : Nat := 2 case a : Nat := 3 guard_hyp x : Nat := 0 guard_hyp y : Nat := 2 guard_hyp z : Nat := 1 guard_hyp w : Nat := 3 trivial -- Test renaming when not pattern matching example (n : Nat) : 0 ≤ n := by induction n case _ : 0 ≤ 0 | succ n ih · guard_target =ₛ 0 ≤ 0 constructor · guard_target =ₛ 0 ≤ n + 1 guard_hyp ih : 0 ≤ n simp
.lake/packages/batteries/BatteriesTest/vector.lean
import Batteries.Data.Vector /-! ### Testing decidable quantifiers for `Vector`. -/ example : ∃ v : Vector Bool 6, v.toList.count true = 3 := by decide inductive Gate : Nat → Type | const : Bool → Gate 0 | if : ∀ {n}, Gate n → Gate n → Gate (n + 1) namespace Gate def and : Gate 2 := .if (.if (.const true) (.const false)) (.if (.const false) (.const false)) def eval (g : Gate n) (v : Vector Bool n) : Bool := match g, v with | .const b, _ => b | .if g₁ g₂, v => if v.1.back! then eval g₁ v.pop else eval g₂ v.pop example : ∀ v, and.eval v = (v[0] && v[1]) := by decide example : ∃ v, and.eval v = false := by decide end Gate
.lake/packages/batteries/BatteriesTest/register_label_attr.lean
import BatteriesTest.Internal.DummyLabelAttr import Lean.LabelAttribute set_option linter.missingDocs false open Lean def f := 0 /-- info: #[] -/ #guard_msgs in #eval labelled `dummy_label_attr attribute [dummy_label_attr] f /-- info: #[`f] -/ #guard_msgs in #eval labelled `dummy_label_attr section attribute [-dummy_label_attr] f /-- info: #[] -/ #guard_msgs in #eval labelled `dummy_label_attr end /-- info: #[`f] -/ #guard_msgs in #eval labelled `dummy_label_attr -- Adding the label again is a no-op attribute [dummy_label_attr] f /-- info: #[`f] -/ #guard_msgs in #eval labelled `dummy_label_attr
.lake/packages/batteries/BatteriesTest/GeneralizeProofs.lean
import Batteries.Tactic.GeneralizeProofs private axiom test_sorry : ∀ {α}, α set_option autoImplicit true noncomputable def List.nthLe (l : List α) (n) (_h : n < l.length) : α := test_sorry -- For debugging `generalize_proofs` -- set_option trace.Tactic.generalize_proofs true example : List.nthLe [1, 2] 1 (by simp) = 2 := by generalize_proofs h guard_hyp h :ₛ 1 < List.length [1, 2] guard_target =ₛ [1, 2].nthLe 1 h = 2 exact test_sorry example (x : Nat) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2 := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (x : Nat) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : Nat) (h : x < 2) (h' : x < 1) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, (by clear h; omega)⟩ : ∃ x, x < 2) := by generalize_proofs a guard_hyp a :ₛ ∃ x, x < 2 guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : Nat) (h h' : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h'⟩ : ∃ x, x < 2) := by change _ at h' fail_if_success guard_target =ₛ Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) generalize_proofs at h' fail_if_success change _ at h' guard_target =ₛ Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, h⟩ : ∃ x, x < 2) generalize_proofs a guard_target =ₛ Classical.choose a = Classical.choose a rfl example (x : Nat) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs a a' guard_hyp a :ₛ ∃ x, x < 2 guard_hyp a' :ₛ ∃ x, x < 3 guard_target =ₛ Classical.choose a = Classical.choose a' exact test_sorry example (x : Nat) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs guard_target = Classical.choose _ = Classical.choose _ exact test_sorry example (x : Nat) (h : x < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) = Classical.choose (⟨x, Nat.lt_succ_of_lt h⟩ : ∃ x, x < 3) := by generalize_proofs _ a guard_hyp a : ∃ x, x < 3 guard_target = Classical.choose _ = Classical.choose a exact test_sorry example (a : ∃ x, x < 2) : Classical.choose a < 2 := by generalize_proofs guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (a : ∃ x, x < 2) : Classical.choose a < 2 := by generalize_proofs t guard_target =ₛ Classical.choose a < 2 exact Classical.choose_spec a example (x : Nat) (h : x < 2) (H : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2) : Classical.choose (⟨x, h⟩ : ∃ x, x < 2) < 2 := by generalize_proofs a at H ⊢ guard_hyp a :ₛ ∃ x, x < 2 guard_hyp H :ₛ Classical.choose a < 2 guard_target =ₛ Classical.choose a < 2 exact H example (H : ∀ y, ∃ (x : Nat) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y) : ∀ y, ∃ (x : Nat) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y := by generalize_proofs -abstract guard_target =ₛ ∀ y, ∃ (x : Nat) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y generalize_proofs a at H ⊢ guard_hyp a :ₛ ∀ (y w : Nat), w < y → ∃ x, x < y guard_hyp H :ₛ ∀ (y : Nat), ∃ x h, Classical.choose (a y x h) < y guard_target =ₛ ∀ (y : Nat), ∃ x h, Classical.choose (a y x h) < y exact H example (H : ∀ y, ∃ (x : Nat) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y) : ∀ y, ∃ (x : Nat) (h : x < y), Classical.choose (⟨x, h⟩ : ∃ x, x < y) < y := by generalize_proofs a at * guard_hyp a :ₛ ∀ (y w : Nat), w < y → ∃ x, x < y guard_hyp H :ₛ ∀ (y : Nat), ∃ x h, Classical.choose (a y x h) < y guard_target =ₛ ∀ (y : Nat), ∃ x h, Classical.choose (a y x h) < y exact H namespace zulip1 /-! https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60generalize_proofs.60.20sometimes.20silently.20has.20no.20effect/near/407162574 -/ theorem t (x : Option Unit) : x.isSome = true := test_sorry def p : Unit → Prop := test_sorry theorem good (x : Option Unit) : p (Option.get x test_sorry) → x.isSome = true := by generalize_proofs h exact fun _ => h theorem was_bad (x : Option Unit) : p (Option.get x (t x)) → x.isSome = true := by generalize_proofs h exact fun _ => h end zulip1 section attribute [local instance] Classical.propDecidable example (H : ∀ x, x = 1) : (if h : ∃ (k : Nat), k = 1 then Classical.choose h else 0) = 1 := by rw [dif_pos ?hc] case hc => exact ⟨1, rfl⟩ generalize_proofs h guard_hyp h :ₛ ∃ x, x = 1 guard_target =ₛ Classical.choose h = 1 apply H end section -- make sure it handles `let` declarations well -- this was https://github.com/leanprover-community/mathlib4/issues/24222 example : True := by let n : Fin 1 := ⟨0, id Nat.zero_lt_one⟩ generalize_proofs h at * guard_hyp h :ₛ 0 < 1 guard_hyp n :=ₛ ⟨0, h⟩ trivial example : True := by have h := Nat.zero_lt_one let n : Fin 1 := ⟨0, id Nat.zero_lt_one⟩ generalize_proofs at * guard_hyp h :ₛ 0 < 1 guard_hyp n :=ₛ ⟨0, h⟩ trivial example : True := by let p := id Nat.zero_lt_one generalize_proofs at * guard_hyp p :ₛ 0 < 1 trivial example : True := by let p := Nat.zero_lt_one generalize_proofs at * guard_hyp p :ₛ 0 < 1 let q := id Nat.zero_lt_one generalize_proofs at * fail_if_success change _ at q guard_hyp p :ₛ 0 < 1 trivial example (P : Sort _) (p : P) : True := by let p' : P := p generalize_proofs at * guard_hyp p :ₛ P guard_hyp p' :=ₛ p trivial example (P : True → Sort _) (p : True → P (by decide)) : True := by let p' := p (by decide) generalize_proofs h at * guard_hyp h :ₛ True guard_hyp p :ₛ True → P h guard_hyp p' :=ₛ p h exact h end /-! Extracting proofs from under let bindings -/ /-- trace: pf✝ : ∀ (n : Nat), 0 < n + 1 ⊢ have n := 0; ↑⟨0, ⋯⟩ = 0 -/ #guard_msgs in example : have n := 0; (⟨0, id (by simp)⟩ : Fin (n + 1)).val = 0 := by generalize_proofs trace_state rfl /-- trace: pf✝ : ∀ (n : Nat), 0 < n + 1 ⊢ have n := 0; ↑⟨0, ⋯⟩ = 0 -/ #guard_msgs in example : have n := 0; (⟨0, id (by simp)⟩ : Fin (n + 1)).val = 0 := by generalize_proofs trace_state rfl
.lake/packages/batteries/BatteriesTest/library_note.lean
import Batteries.Tactic.HelpCmd import BatteriesTest.Internal.DummyLibraryNote2 /-- error: Note not found -/ #guard_msgs in #help note "no note" /-- info: library_note "Other" * 1: this is a testnote with a label not starting with "te", so it shouldn't appear when looking for notes with label starting with "te". -/ #guard_msgs in #help note "Other" library_note "test"/-- 4: This note was not imported, and therefore appears below the imported notes. -/ library_note "test"/-- 5: This note was also not imported, and therefore appears below the imported notes, and the previously added note. -/ /-- info: library_note "temporary note" * 1: This is a testnote whose label also starts with "te", but gets sorted before "test" library_note "test" * 1: This is a testnote for testing the library note feature of batteries. The `#help note` command should be able to find this note when imported. * 2: This is a second testnote for testing the library note feature of batteries. * 3: this is a note in a different file importing the above testnotes, but still imported by the actual testfile. * 4: This note was not imported, and therefore appears below the imported notes. * 5: This note was also not imported, and therefore appears below the imported notes, and the previously added note. -/ #guard_msgs in #help note "te"
.lake/packages/batteries/BatteriesTest/show_unused.lean
import Batteries.Tactic.ShowUnused def foo := 1 def baz := 2 def bar := foo /-- warning: #show_unused (line 14) says: baz is not used transitively by [bar] --- warning: unused definitions in this file: baz -/ #guard_msgs in #show_unused bar
.lake/packages/batteries/BatteriesTest/on_goal.lean
import Batteries.Tactic.PermuteGoals import Batteries.Tactic.Unreachable example (p q r : Prop) : p → q → r → p ∧ q ∧ r := by intros constructor on_goal 2 => guard_target = q ∧ r constructor assumption -- Note that we have not closed all the subgoals here. guard_target = p assumption guard_target = r assumption example (p q r : Prop) : p → q → r → p ∧ q ∧ r := by intros a b c constructor fail_if_success on_goal -3 => unreachable! fail_if_success on_goal -1 => exact a fail_if_success on_goal 0 => unreachable! fail_if_success on_goal 2 => exact a fail_if_success on_goal 3 => unreachable! on_goal 1 => exact a constructor swap exact c exact b example (p q : Prop) : p → q → p ∧ q := by intros a b constructor fail_if_success pick_goal -3 fail_if_success pick_goal 0 fail_if_success pick_goal 3 pick_goal -1 exact b exact a example (p : Prop) : p → p := by intros fail_if_success swap -- can't swap with a single goal assumption
.lake/packages/batteries/BatteriesTest/kmp_matcher.lean
import Batteries.Data.String.Matcher import Batteries.Data.List.Matcher /-! # Tests for the Knuth-Morris-Pratt (KMP) matching algorithm -/ /-! ### String API -/ /-- Matcher for pattern "abba" -/ def m := String.Matcher.ofString "abba" #guard ! Option.isSome (m.find? "AbbabbA") #guard Option.isSome (m.find? "aabbaa") #guard Array.size (m.findAll "abbabba") = 2 #guard Array.size (m.findAll "abbabbabba") = 3 #guard Option.isSome ("xyyxx".findSubstr? "xy") #guard ! Option.isSome ("xyyxx".findSubstr? "xyx") #guard Array.size ("xyyxx".findAllSubstr "xyx") = 0 #guard Array.size ("xyyxxyx".findAllSubstr "xyx") = 1 #guard Array.size ("xyxyyxxyx".findAllSubstr "xyx") = 2 #guard Array.size ("xyxyxyyxxyxyx".findAllSubstr "xyx") = 4 /-! ### List API -/ def lm := List.Matcher.ofList [0,1,1,0] #guard lm.find? [2,1,1,0,1,1,2] == none #guard lm.find? [0,0,1,1,0,0] == some (1, 5) #guard (lm.findAll [0,1,1,0,1,1,0]).size == 2 #guard (lm.findAll [0,1,1,0,1,1,0,1,1,0]).size == 3
.lake/packages/batteries/BatteriesTest/solve_by_elim.lean
import Batteries.Tactic.PermuteGoals import BatteriesTest.Internal.DummyLabelAttr import Lean.Meta.Tactic.Constructor import Lean.Elab.SyntheticMVars import Lean.Elab.Tactic.SolveByElim -- FIXME we need to make SolveByElimConfig builtin set_option autoImplicit true open Lean Elab Tactic in /-- `fconstructor` is like `constructor` (it calls `apply` using the first matching constructor of an inductive datatype) except that it does not reorder goals. -/ elab "fconstructor" : tactic => withMainContext do let mvarIds' ← (← getMainGoal).constructor {newGoals := .all} Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' -- Test that `solve_by_elim*`, which works on multiple goals, -- successfully uses the relevant local hypotheses for each goal. example (f g : Nat → Prop) : (∃ k : Nat, f k) ∨ (∃ k : Nat, g k) ↔ ∃ k : Nat, f k ∨ g k := by fconstructor rintro (⟨n, fn⟩ | ⟨n, gn⟩) on_goal 3 => rintro ⟨n, hf | hg⟩ solve_by_elim* (config := {maxDepth := 13}) [Or.inl, Or.inr, Exists.intro] section «using» /-- -/ @[dummy_label_attr] axiom foo : 1 = 2 example : 1 = 2 := by fail_if_success solve_by_elim solve_by_elim using dummy_label_attr end «using» section issue1581 /-- -/ axiom mySorry {α} : α @[dummy_label_attr] theorem le_rfl [LE α] {b c : α} (_h : b = c) : b ≤ c := mySorry example : 5 ≤ 7 := by apply_rules using dummy_label_attr guard_target = 5 = 7 exact mySorry example : 5 ≤ 7 := by apply_rules [le_rfl] guard_target = 5 = 7 exact mySorry end issue1581
.lake/packages/batteries/BatteriesTest/help_cmd.lean
import Batteries.Tactic.HelpCmd /-! The `#help` command The `#help` command family currently contains these subcommands: * `#help attr` / `#help attribute` * `#help cat` * `#help cats` * `#help command` (abbrev for `#help cat command`) * `#help conv` (abbrev for `#help cat conv`) * `#help option` * `#help tactic` (abbrev for `#help cat tactic`) * `#help term` (abbrev for `#help cat term`) All forms take an optional identifier prefix to narrow the search. The `#help cat` command has a variant `#help cat+` that displays additional information, similarly for commands derived from `#help cat`. WARNING: Some of these tests will need occasional updates when new features are added and even when some documentation is edited. This type of break will be unexpected but the fix will not be unexpected! Just update the guard text to match the output after your addition. -/ /-! `#help attr` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help attr /-- error: no attributes start with foobarbaz -/ #guard_msgs in #help attr foobarbaz /-- info: [inline]: mark definition to be inlined Changes the inlining behavior. This attribute comes in several variants: - `@[inline]`: marks the definition to be inlined when it is appropriate. - `@[inline_if_reduce]`: marks the definition to be inlined if an application of it after inlining and applying reduction isn't a `match` expression. This attribute can be used for inlining structurally recursive functions. - `@[noinline]`: marks the definition to never be inlined. - `@[always_inline]`: marks the definition to always be inlined. - `@[macro_inline]`: marks the definition to always be inlined at the beginning of compilation. This makes it possible to define functions that evaluate some of their parameters lazily. Example: ``` @[macro_inline] def test (x y : Nat) : Nat := if x = 42 then x else y ⏎ #eval test 42 (2^1000000000000) -- doesn't compute 2^1000000000000 ``` Only non-recursive functions may be marked `@[macro_inline]`. [inline_if_reduce]: mark definition to be inlined when resultant term after reduction is not a `cases_on` application Changes the inlining behavior. This attribute comes in several variants: - `@[inline]`: marks the definition to be inlined when it is appropriate. - `@[inline_if_reduce]`: marks the definition to be inlined if an application of it after inlining and applying reduction isn't a `match` expression. This attribute can be used for inlining structurally recursive functions. - `@[noinline]`: marks the definition to never be inlined. - `@[always_inline]`: marks the definition to always be inlined. - `@[macro_inline]`: marks the definition to always be inlined at the beginning of compilation. This makes it possible to define functions that evaluate some of their parameters lazily. Example: ``` @[macro_inline] def test (x y : Nat) : Nat := if x = 42 then x else y ⏎ #eval test 42 (2^1000000000000) -- doesn't compute 2^1000000000000 ``` Only non-recursive functions may be marked `@[macro_inline]`. -/ #guard_msgs in #help attr inl /-! `#help cat` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help cat term /-- error: foobarbaz is not a syntax category -/ #guard_msgs in #help cat foobarbaz /-- info: syntax "("... [«prec(_)»] Parentheses are used for grouping precedence expressions. syntax "+"... [Lean.Parser.Syntax.addPrec] Addition of precedences. This is normally used only for offsetting, e.g. `max + 1`. syntax "-"... [Lean.Parser.Syntax.subPrec] Subtraction of precedences. This is normally used only for offsetting, e.g. `max - 1`. syntax "arg"... [precArg] Precedence used for application arguments (`do`, `by`, ...). syntax "lead"... [precLead] Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). syntax "max"... [precMax] Maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) syntax "min"... [precMin] Minimum precedence used in term parsers. syntax "min1"... [precMin1] `(min+1)` (we can only write `min+1` after `Meta.lean`) syntax ... [Lean.Parser.Syntax.numPrec] -/ #guard_msgs in #help cat prec /-- info: syntax "("... [«prec(_)»] Parentheses are used for grouping precedence expressions. + macro «_aux_Init_Notation___macroRules_prec(_)_1» Parentheses are used for grouping precedence expressions. syntax "+"... [Lean.Parser.Syntax.addPrec] Addition of precedences. This is normally used only for offsetting, e.g. `max + 1`. + macro Lean._aux_Init_Meta___macroRules_Lean_Parser_Syntax_addPrec_1 syntax "-"... [Lean.Parser.Syntax.subPrec] Subtraction of precedences. This is normally used only for offsetting, e.g. `max - 1`. + macro Lean._aux_Init_Meta___macroRules_Lean_Parser_Syntax_subPrec_1 syntax "arg"... [precArg] Precedence used for application arguments (`do`, `by`, ...). + macro _aux_Init_Notation___macroRules_precArg_1 Precedence used for application arguments (`do`, `by`, ...). syntax "lead"... [precLead] Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). + macro _aux_Init_Notation___macroRules_precLead_1 Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). syntax "max"... [precMax] Maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) + macro _aux_Init_Notation___macroRules_precMax_1 Maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) syntax "min"... [precMin] Minimum precedence used in term parsers. + macro _aux_Init_Notation___macroRules_precMin_1 Minimum precedence used in term parsers. syntax "min1"... [precMin1] `(min+1)` (we can only write `min+1` after `Meta.lean`) + macro _aux_Init_Notation___macroRules_precMin1_1 `(min+1)` (we can only write `min+1` after `Meta.lean`) syntax ... [Lean.Parser.Syntax.numPrec] -/ #guard_msgs in #help cat+ prec /-! `#help cats` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help cats /-- error: no syntax categories start with foobarbaz -/ #guard_msgs in #help cats foobarbaz /-- info: category prec [Lean.Parser.Category.prec] `prec` is a builtin syntax category for precedences. A precedence is a value that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is parsed as `1 + (2 * 3)` because `*` has a higher precedence than `+`. Higher numbers denote higher precedence. In addition to literals like `37`, there are some special named precedence levels: * `arg` for the precedence of function arguments * `max` for the highest precedence used in term parsers (not actually the maximum possible value) * `lead` for the precedence of terms not supposed to be used as arguments and you can also add and subtract precedences. category prio [Lean.Parser.Category.prio] `prio` is a builtin syntax category for priorities. Priorities are used in many different attributes. Higher numbers denote higher priority, and for example typeclass search will try high priority instances before low priority. In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as add and subtract priorities. -/ #guard_msgs in #help cats pr /-! `#help command` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help command /-- error: no command declarations start with foobarbaz -/ #guard_msgs in #help command foobarbaz /-- info: syntax "#eval"... [Lean.Parser.Command.eval] `#eval e` evaluates the expression `e` by compiling and evaluating it. ⏎ * The command attempts to use `ToExpr`, `Repr`, or `ToString` instances to print the result. * If `e` is a monadic value of type `m ty`, then the command tries to adapt the monad `m` to one of the monads that `#eval` supports, which include `IO`, `CoreM`, `MetaM`, `TermElabM`, and `CommandElabM`. Users can define `MonadEval` instances to extend the list of supported monads. ⏎ The `#eval` command gracefully degrades in capability depending on what is imported. Importing the `Lean.Elab.Command` module provides full capabilities. ⏎ Due to unsoundness, `#eval` refuses to evaluate expressions that depend on `sorry`, even indirectly, since the presence of `sorry` can lead to runtime instability and crashes. This check can be overridden with the `#eval! e` command. ⏎ Options: * If `eval.pp` is true (default: true) then tries to use `ToExpr` instances to make use of the usual pretty printer. Otherwise, only tries using `Repr` and `ToString` instances. * If `eval.type` is true (default: false) then pretty prints the type of the evaluated value. * If `eval.derive.repr` is true (default: true) then attempts to auto-derive a `Repr` instance when there is no other way to print the result. ⏎ See also: `#reduce e` for evaluation by term reduction. syntax "#eval!"... [Lean.Parser.Command.evalBang] `#eval e` evaluates the expression `e` by compiling and evaluating it. ⏎ * The command attempts to use `ToExpr`, `Repr`, or `ToString` instances to print the result. * If `e` is a monadic value of type `m ty`, then the command tries to adapt the monad `m` to one of the monads that `#eval` supports, which include `IO`, `CoreM`, `MetaM`, `TermElabM`, and `CommandElabM`. Users can define `MonadEval` instances to extend the list of supported monads. ⏎ The `#eval` command gracefully degrades in capability depending on what is imported. Importing the `Lean.Elab.Command` module provides full capabilities. ⏎ Due to unsoundness, `#eval` refuses to evaluate expressions that depend on `sorry`, even indirectly, since the presence of `sorry` can lead to runtime instability and crashes. This check can be overridden with the `#eval! e` command. ⏎ Options: * If `eval.pp` is true (default: true) then tries to use `ToExpr` instances to make use of the usual pretty printer. Otherwise, only tries using `Repr` and `ToString` instances. * If `eval.type` is true (default: false) then pretty prints the type of the evaluated value. * If `eval.derive.repr` is true (default: true) then attempts to auto-derive a `Repr` instance when there is no other way to print the result. ⏎ See also: `#reduce e` for evaluation by term reduction. syntax "#exit"... [Lean.Parser.Command.exit] -/ #guard_msgs in #help command "#e" /-- info: syntax "#eval"... [Lean.Parser.Command.eval] `#eval e` evaluates the expression `e` by compiling and evaluating it. ⏎ * The command attempts to use `ToExpr`, `Repr`, or `ToString` instances to print the result. * If `e` is a monadic value of type `m ty`, then the command tries to adapt the monad `m` to one of the monads that `#eval` supports, which include `IO`, `CoreM`, `MetaM`, `TermElabM`, and `CommandElabM`. Users can define `MonadEval` instances to extend the list of supported monads. ⏎ The `#eval` command gracefully degrades in capability depending on what is imported. Importing the `Lean.Elab.Command` module provides full capabilities. ⏎ Due to unsoundness, `#eval` refuses to evaluate expressions that depend on `sorry`, even indirectly, since the presence of `sorry` can lead to runtime instability and crashes. This check can be overridden with the `#eval! e` command. ⏎ Options: * If `eval.pp` is true (default: true) then tries to use `ToExpr` instances to make use of the usual pretty printer. Otherwise, only tries using `Repr` and `ToString` instances. * If `eval.type` is true (default: false) then pretty prints the type of the evaluated value. * If `eval.derive.repr` is true (default: true) then attempts to auto-derive a `Repr` instance when there is no other way to print the result. ⏎ See also: `#reduce e` for evaluation by term reduction. + command elab Lean.Elab.Command.elabEval syntax "#eval!"... [Lean.Parser.Command.evalBang] `#eval e` evaluates the expression `e` by compiling and evaluating it. ⏎ * The command attempts to use `ToExpr`, `Repr`, or `ToString` instances to print the result. * If `e` is a monadic value of type `m ty`, then the command tries to adapt the monad `m` to one of the monads that `#eval` supports, which include `IO`, `CoreM`, `MetaM`, `TermElabM`, and `CommandElabM`. Users can define `MonadEval` instances to extend the list of supported monads. ⏎ The `#eval` command gracefully degrades in capability depending on what is imported. Importing the `Lean.Elab.Command` module provides full capabilities. ⏎ Due to unsoundness, `#eval` refuses to evaluate expressions that depend on `sorry`, even indirectly, since the presence of `sorry` can lead to runtime instability and crashes. This check can be overridden with the `#eval! e` command. ⏎ Options: * If `eval.pp` is true (default: true) then tries to use `ToExpr` instances to make use of the usual pretty printer. Otherwise, only tries using `Repr` and `ToString` instances. * If `eval.type` is true (default: false) then pretty prints the type of the evaluated value. * If `eval.derive.repr` is true (default: true) then attempts to auto-derive a `Repr` instance when there is no other way to print the result. ⏎ See also: `#reduce e` for evaluation by term reduction. + command elab Lean.Elab.Command.elabEvalBang syntax "#exit"... [Lean.Parser.Command.exit] + command elab Lean.Elab.Command.elabExit -/ #guard_msgs in #help command+ "#e" /-! #help conv -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help conv /-- error: no conv declarations start with foobarbaz -/ #guard_msgs in #help conv foobarbaz /-- info: syntax "reduce"... [Lean.Parser.Tactic.Conv.reduce] Puts term in normal form, this tactic is meant for debugging purposes only. syntax "repeat"... [Lean.Parser.Tactic.Conv.convRepeat_] `repeat convs` runs the sequence `convs` repeatedly until it fails to apply. syntax "rewrite"... [Lean.Parser.Tactic.Conv.rewrite] `rw [thm]` rewrites the target using `thm`. See the `rw` tactic for more information. -/ #guard_msgs in #help conv "re" /-- info: syntax "reduce"... [Lean.Parser.Tactic.Conv.reduce] Puts term in normal form, this tactic is meant for debugging purposes only. + tactic elab Lean.Elab.Tactic.Conv.evalReduce syntax "repeat"... [Lean.Parser.Tactic.Conv.convRepeat_] `repeat convs` runs the sequence `convs` repeatedly until it fails to apply. + macro Lean.Parser.Tactic.Conv._aux_Init_Conv___macroRules_Lean_Parser_Tactic_Conv_convRepeat__1 syntax "rewrite"... [Lean.Parser.Tactic.Conv.rewrite] `rw [thm]` rewrites the target using `thm`. See the `rw` tactic for more information. + tactic elab Lean.Elab.Tactic.Conv.evalRewrite -/ #guard_msgs in #help conv+ "re" /-! `#help option` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help option /-- error: no options start with foobarbaz -/ #guard_msgs in #help option foobarbaz /-- info: option pp.instanceTypes : Bool := false (pretty printer) when printing explicit applications, show the types of inst-implicit arguments option pp.instances : Bool := true (pretty printer) if set to false, replace inst-implicit arguments to explicit applications with placeholders option pp.instantiateMVars : Bool := true (pretty printer) instantiate mvars before delaborating -/ #guard_msgs in #help option pp.ins /-! `#help tactic` -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help tactic /-- error: no tactic declarations start with foobarbaz -/ #guard_msgs in #help tactic foobarbaz /-- info: syntax "by_cases"... [«tacticBy_cases_:_»] `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. -/ #guard_msgs in #help tactic by /-- info: syntax "by_cases"... [«tacticBy_cases_:_»] `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. + macro «_aux_Init_ByCases___macroRules_tacticBy_cases_:__2» + macro «_aux_Init_ByCases___macroRules_tacticBy_cases_:__1» -/ #guard_msgs in #help tactic+ by /-! #help term -/ -- this is a long and constantly updated listing, we don't check the output #guard_msgs(error, drop info) in #help term /-- error: no term declarations start with foobarbaz -/ #guard_msgs in #help term foobarbaz /-- info: syntax "debug_assert!"... [Lean.Parser.Term.debugAssert] `debug_assert! cond` panics if `cond` evaluates to `false` and the executing code has been built with debug assertions enabled (see the `debugAssertions` option). syntax "decl_name%"... [Lean.Parser.Term.declName] A macro which evaluates to the name of the currently elaborating declaration. syntax "default_or_ofNonempty%"... [Lean.Parser.Term.defaultOrOfNonempty] -/ #guard_msgs in #help term de /-- info: syntax "debug_assert!"... [Lean.Parser.Term.debugAssert] `debug_assert! cond` panics if `cond` evaluates to `false` and the executing code has been built with debug assertions enabled (see the `debugAssertions` option). + term elab Lean.Elab.Term.elabDebugAssert syntax "decl_name%"... [Lean.Parser.Term.declName] A macro which evaluates to the name of the currently elaborating declaration. + term elab Lean.Elab.Term.elabDeclName syntax "default_or_ofNonempty%"... [Lean.Parser.Term.defaultOrOfNonempty] + term elab Lean.Elab.Term.Op.elabDefaultOrNonempty -/ #guard_msgs in #help term+ de
.lake/packages/batteries/BatteriesTest/lint_unreachableTactic.lean
import Batteries.Linter.UnreachableTactic -- The warning generated by `linter.unreachableTactic` is not suppressed by `#guard_msgs`, -- because the linter is run on `#guard_msgs` itself. This is a known issue, see -- https://leanprover.zulipchat.com/#narrow/stream/348111-batteries/topic/unreachableTactic.20linter.20not.20suppressed.20by.20.60.23guard_msgs.60 -- We jump through an extra hoop here to silence the warning. set_option linter.unreachableTactic false in #guard_msgs(drop warning) in set_option linter.unreachableTactic true in /-- warning: this tactic is never executed Note: This linter can be disabled with `set_option linter.unreachableTactic false` -/ #guard_msgs in example : 1 = 1 := by rfl <;> simp /-- warning: declaration uses 'sorry' -/ #guard_msgs in example : 1 = 1 := by stop rfl #guard_msgs (drop warning) in def t : Nat → Nat := sorry #guard_msgs (drop warning) in @[simp] theorem a : aa = 0 → t aa = 0 := sorry #guard_msgs in example (ha : aa = 0) : t aa = 0 := by simp (disch := assumption)
.lake/packages/batteries/BatteriesTest/trans.lean
import Batteries.Tactic.Trans -- testing that the attribute is recognized and used def nleq (a b : Nat) : Prop := a ≤ b @[trans] def nleq_trans : nleq a b → nleq b c → nleq a c := Nat.le_trans example (a b c : Nat) : nleq a b → nleq b c → nleq a c := by intro h₁ h₂ trans b assumption assumption example (a b c : Nat) : nleq a b → nleq b c → nleq a c := by intros; trans <;> assumption -- using `Trans` typeclass @[trans] def eq_trans {a b c : α} : a = b → b = c → a = c := by intro h₁ h₂ apply Eq.trans h₁ h₂ example (a b c : Nat) : a = b → b = c → a = c := by intros; trans <;> assumption example (a b c : Nat) : a = b → b = c → a = c := by intro h₁ h₂ trans b assumption assumption example : @Trans Nat Nat Nat (· ≤ ·) (· ≤ ·) (· ≤ ·) := inferInstance example (a b c : Nat) : a ≤ b → b ≤ c → a ≤ c := by intros h₁ h₂ trans ?b case b => exact b exact h₁ exact h₂ example (a b c : α) (R : α → α → Prop) [Trans R R R] : R a b → R b c → R a c := by intros h₁ h₂ trans ?b case b => exact b exact h₁ exact h₂ example (a b c : Nat) : a ≤ b → b ≤ c → a ≤ c := by intros h₁ h₂ trans exact h₁ exact h₂ example (a b c : Nat) : a ≤ b → b ≤ c → a ≤ c := by intros; trans <;> assumption example (a b c : Nat) : a < b → b < c → a < c := by intro h₁ h₂ trans b assumption assumption example (a b c : Nat) : a < b → b < c → a < c := by intros; trans <;> assumption example (x n p : Nat) (h₁ : n * Nat.succ p ≤ x) : n * p ≤ x := by trans · apply Nat.mul_le_mul_left; apply Nat.le_succ · apply h₁ example (a : α) (c : γ) : ∀ b : β, a ≍ b → b ≍ c → a ≍ c := by intro b h₁ h₂ trans b assumption assumption def MyLE (n m : Nat) := ∃ k, n + k = m @[trans] theorem MyLE.trans {n m k : Nat} (h1 : MyLE n m) (h2 : MyLE m k) : MyLE n k := by cases h1 cases h2 subst_vars exact ⟨_, Eq.symm <| Nat.add_assoc _ _ _⟩ example {n m k : Nat} (h1 : MyLE n m) (h2 : MyLE m k) : MyLE n k := by trans <;> assumption /-- `trans` for implications. -/ example {A B C : Prop} (h : A → B) (g : B → C) : A → C := by trans B · guard_target =ₛ A → B -- ensure we have `B` and not a free metavariable. exact h · guard_target =ₛ B → C exact g /-- `trans` for arrows between types. -/ example {A B C : Type} (h : A → B) (g : B → C) : A → C := by trans rotate_right · exact B · exact h · exact g universe u v w /-- `trans` for arrows between types. -/ example {A : Type u} {B : Type v} {C : Type w} (h : A → B) (g : B → C) : A → C := by trans rotate_right · exact B · exact h · exact g
.lake/packages/batteries/BatteriesTest/lintTC.lean
import Batteries.Tactic.Lint.TypeClass import Lean.Elab.Command open Batteries.Tactic.Lint namespace A /-- warning: unused variable `β` Note: This linter can be disabled with `set_option linter.unusedVariables false` -/ #guard_msgs in local instance impossible {α β : Type} [Inhabited α] : Nonempty α := ⟨default⟩ run_meta guard (← impossibleInstance.test ``impossible).isSome end A namespace B instance bad : Nat := 1 run_meta guard (← nonClassInstance.test ``bad).isSome instance good : Inhabited Nat := ⟨1⟩ run_meta guard (← nonClassInstance.test ``good).isNone end B
.lake/packages/batteries/BatteriesTest/openPrivate.lean
import Batteries.Tactic.OpenPrivate import BatteriesTest.OpenPrivateDefs /-- error: Unknown identifier `secretNumber` -/ #guard_msgs in #eval secretNumber -- It works with one space between the tokens /-- info: 2 -/ #guard_msgs in open private secretNumber from BatteriesTest.OpenPrivateDefs in #eval secretNumber -- It also works with other kinds of whitespace between the tokens /-- info: 2 -/ #guard_msgs in open private secretNumber from BatteriesTest.OpenPrivateDefs in #eval secretNumber /-- info: 2 -/ #guard_msgs in open private secretNumber from BatteriesTest.OpenPrivateDefs in #eval secretNumber /-- info: 2 -/ #guard_msgs in open /- Being sneaky! -/ private secretNumber from BatteriesTest.OpenPrivateDefs in #eval secretNumber /-- info: @[defeq] private theorem secretNumber.eq_def : secretNumber✝ = 2 := Eq.refl secretNumber✝ -/ #guard_msgs in open private secretNumber.eq_def from BatteriesTest.OpenPrivateDefs in #print secretNumber.eq_def
.lake/packages/batteries/BatteriesTest/mersenne_twister.lean
import Batteries.Data.Random.MersenneTwister import Batteries.Data.Stream open Batteries.Random.MersenneTwister #guard (Std.Stream.take mt19937.init 5).1 == [874448474, 2424656266, 2174085406, 1265871120, 3155244894] /- Sample output was generated using `numpy`'s implementation of MT19937: ```python from numpy import array, uint32 from numpy.random import MT19937 mt = MT19937() mt.state = { 'bit_generator' : 'MT19937', 'state' : { 'pos' : 624, 'key' : array([ 4357, 1673174024, 1301878288, 1129097449, 2180885271, 2495295730, 3729202114, 3451529139, 2624228201, 696045212, 2296245684, 4097888573, 2110311931, 1672374534, 381896678, 2887874951, 3859861197, 420983856, 1691952728, 4233606289, 1707944415, 3515687962, 4265198858, 1433261659, 1131854641, 228846788, 3811811324, 873525989, 588291779, 2854617646, 948269870, 3798261295, 3422826645, 340138072, 3671734944, 3961007161, 2839350439, 3264455490, 310719058, 2570596611, 3750039289, 648992492, 3816674884, 2210726029, 371217291, 196912982, 3046892150, 470118103, 1302935133, 362465408, 1360220904, 2946174945, 1630294895, 3570642538, 1798333338, 1196832683, 226789057, 2740096276, 1062441100, 1875507765, 2599873619, 1037523070, 4029519294, 3231722367, 2232344613, 3458909352, 2906353456, 3064815497, 3166305847, 3658630546, 3632421090, 885320275, 1621369481, 1258557244, 2827734740, 3209486301, 131295515, 2191201702, 44141830, 1183978535, 4202966509, 801836240, 2303299448, 333191985, 4114943231, 1490315450, 453120554, 759253243, 1381163601, 3455606116, 1027445020, 1144697221, 3040135651, 4176273102, 798935118, 49817807, 2492997557, 3171983608, 2742334400, 1282687705, 1047297991, 3697219554, 1400278898, 3276297123, 843040281, 354711436, 4156544868, 2873126701, 3990490795, 3966874614, 1376536470, 4189022583, 2283386237, 3645931808, 1312021512, 679663233, 3054458511, 1152865034, 1927729338, 538380875, 374984161, 2453495220, 514433452, 1271601365, 3737270131, 630101278, 1292962526, 2908018207, 1209528133, 413117768, 3762161744, 2194986537, 1414304087, 379722290, 2862208514, 3551161587, 3402627497, 2411204572, 3033657332, 4161252989, 2267825211, 963150406, 2081690150, 4014304967, 1977732365, 2412979568, 613038232, 418857425, 3682807839, 3416550746, 3692470090, 2764012443, 3255912817, 2160692740, 3914318396, 3437441061, 2828481795, 3655629678, 582770030, 2946380655, 3506851541, 612362648, 3394202848, 1530337657, 3360830183, 570641538, 153365650, 1624454723, 80526649, 1365694508, 2272925828, 34250189, 3066169803, 631734422, 3706776758, 3443270679, 659846301, 3707435456, 3573851432, 1017208097, 1100519855, 1824765866, 3284762074, 2887949547, 569464065, 3057970772, 1726477004, 3119183733, 3349922451, 4162228670, 249085950, 3854319807, 1155219045, 811161064, 207675760, 50531529, 141911159, 3819613906, 2655884066, 3517624211, 514724041, 2094583932, 3681571092, 3518053661, 2207473499, 961982182, 1423628102, 628853095, 3823741997, 1450180112, 1817911736, 384378993, 1749521215, 4080873978, 2604100714, 2468900411, 1718743185, 3679944356, 623522652, 2974445253, 351789091, 776787982, 4087231118, 395771407, 2634989045, 2547249720, 2502583808, 3550523417, 648947207, 2361409826, 2639137202, 4179155171, 3136025689, 3233151180, 3765213604, 459508845, 412632299, 3365801270, 1208603094, 1978375863, 3608769469, 2648322656, 994422344, 1463198657, 1938300111, 1983437898, 3617090298, 582545291, 604707873, 615071476, 1976468460, 4251555349, 2373160371, 4138683998, 927249694, 4178996063, 3071856005, 3264724616, 2539911824, 1383596905, 3639900055, 2590770034, 1029541954, 369472051, 3757991913, 1470517532, 2317808180, 1065978813, 3301489275, 4087716742, 2662718566, 678716423, 274451277, 1625396912, 3598469848, 3639725841, 726808159, 1490990746, 4062476682, 2411471067, 1395972017, 1390554948, 1854727292, 2494590309, 1377225539, 2540041390, 3288614830, 706906287, 1416719637, 609008344, 2311429920, 821102265, 2034260263, 3587569090, 3115591378, 3545840515, 4166871929, 139581804, 2421643972, 1250638605, 4212965387, 2794805718, 3306616566, 2466109783, 2200482525, 1496197888, 381089640, 2743249505, 4221427695, 1247199466, 1746114586, 2065302059, 1348936513, 2997505940, 3911013644, 428274869, 2816055507, 580438782, 135588414, 916674047, 445684901, 1016784680, 654791600, 1282652681, 92916407, 1411782674, 1367985506, 1207661779, 3531669257, 627085756, 1857409876, 4107311709, 1384928667, 2576697382, 2875531654, 4151312039, 116927085, 1281879888, 414036984, 3931190705, 4100135295, 1170799418, 3130902186, 4055536507, 3692691153, 480878564, 2201474460, 3663014917, 4155766371, 1987039566, 4121861326, 2525025103, 2465094709, 2536129400, 1843468352, 2926058841, 533253191, 1988389474, 1209435122, 4141112867, 2699109017, 2373614092, 1694129124, 2730600877, 2249161515, 1355638390, 3319290902, 2209534967, 1463955965, 204923808, 1025015944, 214266113, 3382305551, 2455594378, 1861944634, 1820710091, 449145441, 4119339060, 2660525612, 3515028309, 3466454003, 1024657310, 50945886, 2913140895, 721595333, 3416444872, 2701847760, 2352361641, 234184151, 3927502002, 3834792578, 3469473651, 4193637929, 2873594460, 1994191988, 1690724605, 1956524219, 476427462, 212379302, 1370380615, 327076237, 1984104432, 682581272, 2521259089, 3543809183, 3275489242, 241390538, 3496199707, 2497799665, 770560132, 1626015420, 2776148645, 3717161347, 3970592238, 710750702, 3421625839, 876972885, 2108460056, 1195168096, 1195766777, 3121053543, 2819333890, 1916084498, 717897923, 3627489721, 1970264748, 1813355780, 4148615245, 556824139, 411448086, 4228776246, 1732939415, 3206934813, 1949588544, 3291105704, 1044314017, 222045743, 3079457322, 638497370, 1849452395, 921039233, 1115861204, 3019093836, 2828923381, 4185943827, 3344827454, 3923907710, 760572735, 3828284133, 1559197800, 724485616, 1828677449, 2985767159, 4119101778, 1077348258, 3518446099, 2585587017, 1855673084, 3495712148, 3265984413, 2998815707, 760668518, 2487249862, 3060757479, 3249514669, 4222804112, 1010910776, 3893641969, 395812799, 2591540346, 1194664170, 49789115, 1363873041, 1005502756, 1164343260, 3646613829, 459869347, 3679832718, 1137706766, 4189431951, 1412889205, 622040248, 1536739968, 3066727065, 666661511, 1672188834, 2714762802, 4135248739, 35606745, 2775710540, 4083752484, 3680159469, 1950331243, 251641782, 1501029974, 486869303, 1720971325, 241603808, 28070600, 2737782337, 910469455, 3810848458, 118398842, 3078470155, 2559096993, 2933522804, 2264615020, 3793195157, 1614887475, 45727966, 3193899422, 1157273055, 2178255365, 2646663432, 724754192, 168779241, 4048503831, 3483948530, 3996648642, 939343027, 917914729, 3030111132, 3908302516, 29247037, 3568084731, 1034472966, 1408004326, 1693666951, 3712665549, 3120003376, 3374542680, 2868373905, 1362838239, 1421625626, 4275252746, 548825947, 622261297, 3152835012, 2926192892, 423356389, 151058371, 3820087086, 1673993262, 252457775, 1317185941, 2594135384, 817169312, 2016796985, 2292688295, 1654933570, 2158435154, 2703640067, 3260663801, 3267419116, 2293555012, 2721936781, 1727868043, 91884630, 265685878, 1143096279, 961294173, 403541376, 2338233320, 1725318369, 4101205103, 4268086122, 3418016922, 1065995435, 1936572353, 265163284, 3043694988, 2167402293, 2057323859, 4033232254, 3258990270, 1137868927, 2142656805, 4216785320, 1188509744, 1051071625, 196974391, 2445666962, 3092595170, 2833121107, 2474761097, 2190021692, 1852037076, 3577763037, 3794354715, 2124118694, 2641147398, 1551493415, 1913661165, 1313919440, 2232801400, 1781682225, 1340417535, 994676154, 251493162, 2162155003, 1678056273, 3810976356, 1505106460, 3361449605, 1041703651, 1727972302, 3959583054, 3140845007, 3202914485, 2878334456, 2354150592, 3334993881, 1015617735, 506838242, 4168775794, 839674019, 4238769945, 849116300, 4189642852, 1596908589, 556328875, 2369067254, 2431152278, 1004682871], dtype=uint32)}} print(mt.random_raw(5)) ``` -/
.lake/packages/batteries/BatteriesTest/lintsimp.lean
import Batteries.Tactic.Lint open Batteries.Tactic.Lint set_option linter.missingDocs false def f : Nat := 0 def g : Nat := 0 def h : Nat := 0 @[simp] theorem fg : f = g := rfl @[simp] theorem fh : f = h := rfl run_meta guard (← [``fg, ``fh].anyM fun n => return (← simpNF.test n).isSome) @[simp] theorem test_and_comm : a ∧ b ↔ b ∧ a := And.comm run_meta guard (← simpComm.test ``test_and_comm).isSome @[simp] theorem Prod.mk_fst : (a, b).1 = id a := rfl run_meta guard (← simpVarHead.test ``Prod.mk_fst).isSome def SemiconjBy [Mul M] (a x y : M) : Prop := a * x = y * a structure MulOpposite (α : Type u) : Type u where op :: unop : α postfix:max "ᵐᵒᵖ" => MulOpposite namespace MulOpposite instance [Mul α] : Mul αᵐᵒᵖ where mul x y := op (unop y * unop x) @[simp] theorem unop_inj {x y : αᵐᵒᵖ} : unop x = unop y ↔ x = y := by cases x; cases y; simp #guard_msgs (drop warning) in @[simp] theorem semiconj_by_unop [Mul α] {a x y : αᵐᵒᵖ} : SemiconjBy (unop a) (unop y) (unop x) ↔ SemiconjBy a x y := sorry run_meta guard (← simpComm.test ``unop_inj).isNone run_meta guard (← simpComm.test ``semiconj_by_unop).isNone end MulOpposite section def MyPred (_ : Nat → Nat) : Prop := True @[simp] theorem bad1 (f : Unit → Nat → Nat) : MyPred (f ()) ↔ True := by rw [MyPred] @[simp] theorem bad2 (f g : Nat → Nat) : MyPred (fun x => f (g x)) ↔ True := by rw [MyPred] -- Note, this is not a proper regression test because #671 depends on how the `MetaM` is -- executed, and `run_meta` sets the options appropriately. But setting the config -- explicitly here would amount to replicating the fix in the test itself. run_meta guard (← simpNF.test ``bad1).isNone run_meta guard (← simpNF.test ``bad2).isNone end
.lake/packages/batteries/BatteriesTest/proof_wanted.lean
import Batteries.Util.ProofWanted /-! No unused variable warnings. -/ #guard_msgs in proof_wanted foo (x : Nat) : True /-! When not a proposition, rely on `theorem` command failing. -/ /-- error: type of theorem `foo` is not a proposition Nat → Nat -/ #guard_msgs in proof_wanted foo (x : Nat) : Nat
.lake/packages/batteries/BatteriesTest/lint_dupNamespace.lean
import Batteries.Tactic.Lint -- internal names should be ignored theorem Foo.Foo._bar : True := trivial #lint- only dupNamespace
.lake/packages/batteries/BatteriesTest/Char.lean
import Batteries.Data.Char #guard Char.caseFoldAsciiOnly 'A' == 'a' #guard Char.caseFoldAsciiOnly 'a' == 'a' #guard Char.caseFoldAsciiOnly 'À' == 'À' #guard Char.caseFoldAsciiOnly 'à' == 'à' #guard Char.caseFoldAsciiOnly '$' == '$' #guard Char.beqCaseInsensitiveAsciiOnly 'a' 'A' == true #guard Char.beqCaseInsensitiveAsciiOnly 'a' 'a' == true #guard Char.beqCaseInsensitiveAsciiOnly '$' '$' == true #guard Char.beqCaseInsensitiveAsciiOnly 'a' 'b' == false #guard Char.beqCaseInsensitiveAsciiOnly 'γ' 'Γ' == false #guard Char.beqCaseInsensitiveAsciiOnly 'ä' 'Ä' == false #guard Char.cmpCaseInsensitiveAsciiOnly 'a' 'A' == .eq #guard Char.cmpCaseInsensitiveAsciiOnly 'a' 'a' == .eq #guard Char.cmpCaseInsensitiveAsciiOnly '$' '$' == .eq #guard Char.cmpCaseInsensitiveAsciiOnly 'a' 'b' == .lt #guard Char.cmpCaseInsensitiveAsciiOnly 'γ' 'Γ' == .gt #guard Char.cmpCaseInsensitiveAsciiOnly 'ä' 'Ä' == .gt
.lake/packages/batteries/BatteriesTest/array.lean
import Batteries.Data.Array section variable {α : Type _} variable [Inhabited α] variable (a : Array α) variable (i j : Nat) variable (v d : α) variable (g : i < (a.set! i v).size) variable (j_lt : j < (a.set! i v).size) #check_simp (a.set! i v)[i] ~> v #check_simp (a.set! i v)[i]! ~> (a.setIfInBounds i v)[i]! #check_simp (a.set! i v).getD i d ~> if i < a.size then v else d #check_simp (a.set! i v)[i] ~> v -- Checks with different index values. #check_simp (a.set! i v)[j]'j_lt ~> (a.setIfInBounds i v)[j]'_ #check_simp (a.setIfInBounds i v)[j]'j_lt !~> -- This doesn't work currently. -- It will be address in the comprehensive overhaul of array lemmas. -- #check_simp (a.set! i v)[i]? ~> .some v end
.lake/packages/batteries/BatteriesTest/lint_simpNF.lean
import Batteries.Tactic.Lint set_option linter.missingDocs false structure Equiv (α : Sort _) (β : Sort _) where toFun : α → β invFun : β → α infixl:25 " ≃ " => Equiv namespace Equiv instance : CoeFun (α ≃ β) fun _ => α → β := ⟨toFun⟩ protected def symm (e : α ≃ β) : β ≃ α := ⟨e.invFun, e.toFun⟩ def sumCompl {α : Type _} (p : α → Prop) [DecidablePred p] : Sum { a // p a } { a // ¬p a } ≃ α where toFun := Sum.elim Subtype.val Subtype.val invFun a := if h : p a then Sum.inl ⟨a, h⟩ else Sum.inr ⟨a, h⟩ @[simp] theorem sumCompl_apply_symm_of_pos (p : α → Prop) [DecidablePred p] (a : α) (h : p a) : (sumCompl p).symm a = Sum.inl ⟨a, h⟩ := dif_pos h def foo (n : Nat) : Nat := if n = n then n else 0 @[simp] theorem foo_eq_id : foo = id := by funext n simp [foo] -- The following `dsimp`-lemma is (correctly) not flagged by the linter @[defeq, simp] theorem foo_eq_ite (n : Nat) : foo n = if n = n then n else 0 := by rfl end Equiv namespace List private axiom test_sorry : ∀ {α}, α @[simp] theorem ofFn_getElem_eq_map {β : Type _} (l : List α) (f : α → β) : ofFn (fun i : Fin l.length => f <| l[(i : Nat)]) = l.map f := test_sorry example {β : Type _} (l : List α) (f : α → β) : ofFn (fun i : Fin l.length => f <| l[(i : Nat)]) = l.map f := by simp only [ofFn_getElem_eq_map] end List /-! This tests that `simpNF` is not accidentally using `quasiPatternApprox := true`. -/ def eqToFun {X Y : Type} (p : X = Y) : X → Y := by rw [p]; exact id @[simp] theorem eqToFun_comp_eq_self {β} {X : Type} {f : β → Type} (z : ∀ b, X → f b) {j j' : β} (w : j = j') : eqToFun (by simp [w]) ∘ z j' = z j := by cases w; rfl @[simp] theorem eqToFun_comp_iso_hom_eq_self {β} {X : Type} {f : β → Type} (z : ∀ b, X ≃ f b) {j j' : β} (w : j = j') : eqToFun (by simp [w]) ∘ (z j').toFun = (z j).toFun := by cases w; rfl #lint- only simpNF
.lake/packages/batteries/BatteriesTest/lintunused.lean
import Batteries.Tactic.Lint -- should be ignored as the proof contains sorry /-- warning: declaration uses 'sorry' -/ #guard_msgs in theorem Foo (h : 1 = 1) : True := sorry #lint- only unusedArguments
.lake/packages/batteries/BatteriesTest/tryThis.lean
import Lean.Meta.Tactic.TryThis open Lean.Meta.Tactic.TryThis /-! This test file demonstrates the `Try This:` widget and describes how certain examples should look. Note that while the evaluations here shouldn't fail, they also aren't tests in the traditional sense—CI has no way of inspecting the HTML output, and therefore no way of checking that the output is styled correctly. All clickables should dim on mouseover without changing color drastically. Both widgets should provide a (list of) `Try this: rfl` code actions. -/ /-! # Setup -/ open Lean Meta Elab Term Expr /-- Add a suggestion. -/ elab "add_suggestion" s:term : tactic => unsafe do addSuggestion (← getRef) (← evalTerm Suggestion (.const ``Suggestion []) s) /-- Add a suggestion with a header. -/ elab "add_suggestion" s:term "with_header" h:str : tactic => unsafe do addSuggestion (← getRef) (← evalTerm Suggestion (.const ``Suggestion []) s) (header := h.getString) /-- Add a suggestion. -/ elab "add_suggestions" s:term : tactic => unsafe do let s ← evalTerm (Array Suggestion) (.app (.const ``Array [.zero]) (.const ``Suggestion [])) s addSuggestions (← getRef) s /-- Add suggestions with a header. -/ elab "add_suggestions" s:term "with_header" h:str : tactic => unsafe do let s ← evalTerm (Array Suggestion) (.app (.const ``Array [.zero]) (.const ``Suggestion [])) s addSuggestions (← getRef) s (header := h.getString) /-- Demo adding a suggestion. -/ macro "#demo1" s:term : command => `(example : True := by add_suggestion $s; trivial) /-- Demo adding a suggestion with a header. -/ macro "#demo1" s:term "with_header" h:str : command => `(example : True := by add_suggestion $s with_header $h; trivial) /-- Demo adding suggestions. -/ macro "#demo" s:term : command => `(example : True := by add_suggestions $s; trivial) /-- Demo adding suggestions with a header. -/ macro "#demo" s:term "with_header" h:str : command => `(example : True := by add_suggestions $s with_header $h; trivial) /-- A basic suggestion. -/ private def s : Suggestion := Unhygienic.run `(tactic| rfl) /-! # Demos -/ /-- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` with `rfl` in text-link color. #demo1 s /-- info: Try these: [apply] rfl [apply] rfl [apply] rfl [apply] rfl -/ #guard_msgs in /- ``` Try these: • rfl • rfl • rfl • rfl ``` with `rfl` in text-link color. -/ #demo #[s,s,s,s] /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.value` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.value` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try these: [apply] rfl [apply] rfl [apply] rfl [apply] rfl [apply] rfl [apply] rfl [apply] rfl -/ #guard_msgs in /- ``` Try these: • rfl -- red • rfl -- red-orange • rfl -- orange • rfl -- yellow • rfl -- yellow-green • rfl -- light green • rfl -- green ``` -/ #demo #[0.0, 1/6, 2/6, 3/6, 4/6, 5/6, 1.0].map fun t => {s with style? := some <| .value t} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.error` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.error` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- error color, no squiggle #demo1 {s with style? := some <| .error (decorated := false)} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- gold color with warning squiggle #demo1 {s with style? := some .warning} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- gold color with no squiggle #demo1 {s with style? := some <| .warning (decorated := false)} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.success` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.success` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- Lean green #demo1 {s with style? := some .success} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.asHypothesis` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.asHypothesis` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- styled like a goal hypothesis #demo1 {s with style? := some .asHypothesis} /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.asInaccessible` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.asInaccessible` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Try this: [apply] rfl -/ #guard_msgs in -- `Try this: rfl` -- styled like an inaccessible goal hypothesis #demo1 {s with style? := some .asInaccessible} /-- info: Try this: [apply] Starfleet -/ #guard_msgs in -- `Try this: Starfleet` #demo1 {s with preInfo? := "Sta", postInfo? := "eet"} /-- info: Try this: [apply] a secret message -/ #guard_msgs in -- `Try this: a secret message` #demo1 {s with messageData? := m!"a secret message"} /-- info: Try these: [apply] a secret message [apply] another secret message -/ #guard_msgs in /- ``` Try these: • a secret message • another secret message ``` -/ #demo #[ {s with messageData? := m!"a secret message"}, {s with messageData? := m!"another secret message"} ] /-- info: Our only hope is ⏎ [apply] rfl -/ #guard_msgs in #demo1 s with_header "Our only hope is " /-- info: We've got everything here! Such as: [apply] rfl [apply] rfl [apply] rfl [apply] rfl -/ #guard_msgs in #demo #[s,s,s,s] with_header "We've got everything here! Such as:" /-- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.error` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.error` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.warning` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.success` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.success` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.value` has been deprecated: `SuggestionStyle` is not used anymore. --- warning: `Lean.Meta.Tactic.TryThis.SuggestionStyle.value` has been deprecated: `SuggestionStyle` is not used anymore. --- info: Grab bag: [apply] This is not a tactic. [apply] This could be a tactic--but watch out! [apply] rfl. Finally, a tactic that just works. [apply] I'm just link-styled. [apply] On a scale of 0 to 1, I'd put this at 0.166667. -/ #guard_msgs in #demo #[ {s with suggestion := "not a tactic", preInfo? := "This is ", postInfo? := ".", style? := some .error}, {s with suggestion := "This", postInfo? := " could be a tactic--but watch out!", style? := some .warning}, {s with postInfo? := ". Finally, a tactic that just works.", style? := some .success}, {s with preInfo? := "I'm just " suggestion := "link-styled", postInfo? := "."}, {s with preInfo? := "On a scale of 0 to 1, I'd put ", suggestion := "this", postInfo? := " at 0.166667.", style? := some (.value (1/6))} ] with_header "Grab bag:" /-- error: No suggestions available -/ #guard_msgs in #demo #[] /- The messages and suggestion should still read `Try this: rfl`, but the text in the lightbulb menu should read "Consider rfl, please" -/ /-- info: Try this: [apply] rfl -/ #guard_msgs in #demo1 { s with toCodeActionTitle? := fun text => "Consider " ++ text ++ ", please" } /-- Add suggestions with a default code action title prefix. -/ elab "add_suggestions" s:term "with_code_action_prefix" h:str : tactic => unsafe do let s ← evalTerm (Array Suggestion) (.app (.const ``Array [.zero]) (.const ``Suggestion [])) s addSuggestions (← getRef) s (codeActionPrefix? := h.getString) /-- Demo adding suggestions with a header. -/ macro "#demo" s:term "with_code_action_prefix" h:str : command => `(example : True := by add_suggestions $s with_code_action_prefix $h; trivial) /- The messages and suggestions should still read `Try these: ...`, but the text in the lightbulb menu should read "Maybe use: rfl"; "Maybe use: rfl"; "Also consider rfl, please!" -/ /-- info: Try these: [apply] rfl [apply] rfl [apply] rfl -/ #guard_msgs in #demo #[ s, s, { s with toCodeActionTitle? := fun text => "Also consider " ++ text ++ ", please!" } ] with_code_action_prefix "Maybe use: "
.lake/packages/batteries/BatteriesTest/satisfying.lean
import Batteries.Lean.SatisfiesM import Batteries.Data.Array.Monadic open Lean Meta Array Elab Term Tactic Command example (xs : Array Expr) : MetaM { ts : Array Expr // ts.size = xs.size } := do let r ← satisfying (xs.size_mapM inferType) return r
.lake/packages/batteries/BatteriesTest/simp_trace.lean
import Batteries.Tactic.SqueezeScope -- undo changes to simp set after test was written attribute [-simp] Nat.add_left_cancel_iff Nat.add_right_cancel_iff set_option linter.missingDocs false /-- info: Try this: [apply] simp only [Nat.add_comm] -/ #guard_msgs in example : x + 1 = 1 + x := by simp? [Nat.add_comm, Nat.mul_comm] /-- info: Try this: [apply] dsimp only [Nat.reduceAdd] -/ #guard_msgs in example : 1 + 1 = 2 := by dsimp? @[simp] def bar (z : Nat) := 1 + z @[simp] def baz (z : Nat) := 1 + z @[simp] def foo : Nat → Nat → Nat | 0, z => bar z | _+1, z => baz z /-- info: Try this: [apply] simp only [foo, bar] --- info: Try this: [apply] simp only [foo, baz] -/ #guard_msgs in example : foo x y = 1 + y := by cases x <;> simp? -- two printouts: -- "Try this: simp only [foo, bar]" -- "Try this: simp only [foo, baz]" /-- info: Try this: [apply] simp only [foo, bar, baz] -/ #guard_msgs in example : foo x y = 1 + y := by squeeze_scope cases x <;> simp -- only one printout: "Try this: simp only [foo, baz, bar]"
.lake/packages/batteries/BatteriesTest/print_prefix.lean
import Batteries.Tactic.PrintPrefix inductive TEmpty : Type /-- info: TEmpty : Type TEmpty.casesOn.{u} (motive : TEmpty → Sort u) (t : TEmpty) : motive t TEmpty.ctorIdx : TEmpty → Nat TEmpty.noConfusion.{u} {P : Sort u} {x1 x2 : TEmpty} (h12 : x1 = x2) : TEmpty.noConfusionType P x1 x2 TEmpty.noConfusionType.{u} (P : Sort u) (x1 x2 : TEmpty) : Sort u TEmpty.rec.{u} (motive : TEmpty → Sort u) (t : TEmpty) : motive t TEmpty.recOn.{u} (motive : TEmpty → Sort u) (t : TEmpty) : motive t -/ #guard_msgs in #print prefix TEmpty -- Test type that probably won't change much. /-- info: -/ #guard_msgs in #print prefix -imported Empty namespace EmptyPrefixTest end EmptyPrefixTest -- Note. This error message could be cleaned up, but left during migration from Mathlib /-- error: Unknown constant `EmptyPrefixTest` -/ #guard_msgs in #print prefix EmptyPrefixTest namespace Prefix.Test /-- Supress lint -/ def foo (_l:List String) : Int := 0 end Prefix.Test /-- info: Prefix.Test.foo (_l : List String) : Int -/ #guard_msgs in #print prefix Prefix.Test /-- Supress lint -/ structure TestStruct where /-- Supress lint -/ foo : Int /-- Supress lint -/ bar : Int /-- info: TestStruct : Type TestStruct.bar (self : TestStruct) : Int TestStruct.casesOn.{u} {motive : TestStruct → Sort u} (t : TestStruct) (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) : motive t TestStruct.ctorIdx : TestStruct → Nat TestStruct.foo (self : TestStruct) : Int TestStruct.mk (foo bar : Int) : TestStruct TestStruct.mk.inj {foo bar foo✝ bar✝ : Int} : { foo := foo, bar := bar } = { foo := foo✝, bar := bar✝ } → foo = foo✝ ∧ bar = bar✝ TestStruct.mk.injEq (foo bar foo✝ bar✝ : Int) : ({ foo := foo, bar := bar } = { foo := foo✝, bar := bar✝ }) = (foo = foo✝ ∧ bar = bar✝) TestStruct.mk.noConfusion.{u} (P : Sort u) (foo bar foo' bar' : Int) (h : { foo := foo, bar := bar } = { foo := foo', bar := bar' }) (k : foo = foo' → bar = bar' → P) : P TestStruct.mk.sizeOf_spec (foo bar : Int) : sizeOf { foo := foo, bar := bar } = 1 + sizeOf foo + sizeOf bar TestStruct.noConfusion.{u} {P : Sort u} {x1 x2 : TestStruct} (h12 : x1 = x2) : TestStruct.noConfusionType P x1 x2 TestStruct.noConfusionType.{u} (P : Sort u) (x1 x2 : TestStruct) : Sort u TestStruct.rec.{u} {motive : TestStruct → Sort u} (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) (t : TestStruct) : motive t TestStruct.recOn.{u} {motive : TestStruct → Sort u} (t : TestStruct) (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) : motive t -/ #guard_msgs in #print prefix TestStruct /-- info: TestStruct : Type TestStruct.bar (self : TestStruct) : Int TestStruct.casesOn.{u} {motive : TestStruct → Sort u} (t : TestStruct) (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) : motive t TestStruct.ctorIdx : TestStruct → Nat TestStruct.foo (self : TestStruct) : Int TestStruct.mk (foo bar : Int) : TestStruct TestStruct.mk.noConfusion.{u} (P : Sort u) (foo bar foo' bar' : Int) (h : { foo := foo, bar := bar } = { foo := foo', bar := bar' }) (k : foo = foo' → bar = bar' → P) : P TestStruct.noConfusion.{u} {P : Sort u} {x1 x2 : TestStruct} (h12 : x1 = x2) : TestStruct.noConfusionType P x1 x2 TestStruct.noConfusionType.{u} (P : Sort u) (x1 x2 : TestStruct) : Sort u TestStruct.rec.{u} {motive : TestStruct → Sort u} (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) (t : TestStruct) : motive t TestStruct.recOn.{u} {motive : TestStruct → Sort u} (t : TestStruct) (mk : (foo bar : Int) → motive { foo := foo, bar := bar }) : motive t -/ #guard_msgs in #print prefix -propositions TestStruct /-- info: TestStruct.mk.inj {foo bar foo✝ bar✝ : Int} : { foo := foo, bar := bar } = { foo := foo✝, bar := bar✝ } → foo = foo✝ ∧ bar = bar✝ TestStruct.mk.injEq (foo bar foo✝ bar✝ : Int) : ({ foo := foo, bar := bar } = { foo := foo✝, bar := bar✝ }) = (foo = foo✝ ∧ bar = bar✝) TestStruct.mk.sizeOf_spec (foo bar : Int) : sizeOf { foo := foo, bar := bar } = 1 + sizeOf foo + sizeOf bar -/ #guard_msgs in #print prefix +propositionsOnly TestStruct /-- info: TestStruct TestStruct.bar TestStruct.casesOn TestStruct.ctorIdx TestStruct.foo TestStruct.mk TestStruct.mk.inj TestStruct.mk.injEq TestStruct.mk.noConfusion TestStruct.mk.sizeOf_spec TestStruct.noConfusion TestStruct.noConfusionType TestStruct.rec TestStruct.recOn -/ #guard_msgs in #print prefix -showTypes TestStruct /-- Artificial test function to show #print prefix filters out internals including match_/proof_. Note. Internal names are inherently subject to change. This test case may fail regularly when the Lean version is changed. If so, we should disable the test case using this function below until a more robust solution is found. -/ def testMatchProof : (n : Nat) → Fin n → Unit | _, ⟨0, _⟩ => () | Nat.succ as, ⟨Nat.succ i, h⟩ => testMatchProof as ⟨i, Nat.le_of_succ_le_succ h⟩ /-- info: testMatchProof (n : Nat) : Fin n → Unit -/ #guard_msgs in #print prefix testMatchProof /-- info: testMatchProof (n : Nat) : Fin n → Unit testMatchProof._proof_1 (as i : Nat) (h : i.succ < as.succ) : i.succ ≤ as testMatchProof._sunfold (n : Nat) : Fin n → Unit testMatchProof._unsafe_rec (n : Nat) : Fin n → Unit testMatchProof.match_1.{u_1} (motive : (x : Nat) → Fin x → Sort u_1) (x✝ : Nat) (x✝¹ : Fin x✝) (h_1 : (n : Nat) → (isLt : 0 < n) → motive n ⟨0, isLt⟩) (h_2 : (as i : Nat) → (h : i.succ < as.succ) → motive as.succ ⟨i.succ, h⟩) : motive x✝ x✝¹ -/ #guard_msgs in #print prefix +internals testMatchProof private inductive TestInd where | foo : TestInd | bar : TestInd /-- info: TestInd : Type TestInd.bar : TestInd TestInd.bar.elim.{u} {motive : TestInd → Sort u} (t : TestInd) (h : t.ctorIdx = 1) (bar : motive TestInd.bar) : motive t TestInd.bar.sizeOf_spec : sizeOf TestInd.bar = 1 TestInd.casesOn.{u} {motive : TestInd → Sort u} (t : TestInd) (foo : motive TestInd.foo) (bar : motive TestInd.bar) : motive t TestInd.ctorElim.{u} {motive : TestInd → Sort u} (ctorIdx : Nat) (t : TestInd) (h : ctorIdx = t.ctorIdx) (k : TestInd.ctorElimType ctorIdx) : motive t TestInd.ctorElimType.{u} {motive : TestInd → Sort u} (ctorIdx : Nat) : Sort (max 1 u) TestInd.ctorIdx : TestInd → Nat TestInd.foo : TestInd TestInd.foo.elim.{u} {motive : TestInd → Sort u} (t : TestInd) (h : t.ctorIdx = 0) (foo : motive TestInd.foo) : motive t TestInd.foo.sizeOf_spec : sizeOf TestInd.foo = 1 TestInd.noConfusion.{v✝} {P : Sort v✝} {x y : TestInd} (h : x = y) : TestInd.noConfusionType P x y TestInd.noConfusionType.{v✝} (P : Sort v✝) (x y : TestInd) : Sort v✝ TestInd.rec.{u} {motive : TestInd → Sort u} (foo : motive TestInd.foo) (bar : motive TestInd.bar) (t : TestInd) : motive t TestInd.recOn.{u} {motive : TestInd → Sort u} (t : TestInd) (foo : motive TestInd.foo) (bar : motive TestInd.bar) : motive t TestInd.toCtorIdx : TestInd → Nat -/ #guard_msgs in #print prefix TestInd -- `#print prefix` does nothing if no identifier is provided #guard_msgs in #print prefix
.lake/packages/batteries/BatteriesTest/Internal/DummyLibraryNote.lean
import Batteries.Util.LibraryNote library_note "test" /-- 1: This is a testnote for testing the library note feature of batteries. The `#help note` command should be able to find this note when imported. -/ library_note "test" /-- 2: This is a second testnote for testing the library note feature of batteries. -/ library_note "temporary note" /-- 1: This is a testnote whose label also starts with "te", but gets sorted before "test" -/
.lake/packages/batteries/BatteriesTest/Internal/DummyLabelAttr.lean
import Lean.LabelAttribute /-- A dummy label attribute, which can be used for testing. -/ -- This can't live in `Batteries.Tactic.LabelAttr` -- (because we can't use the extension in the same file it is initialized) -- and it can't live in `test/`, because files there can not import other files in `test/`. register_label_attr dummy_label_attr
.lake/packages/batteries/BatteriesTest/Internal/DummyLibraryNote2.lean
import BatteriesTest.Internal.DummyLibraryNote library_note "test" /-- 3: this is a note in a different file importing the above testnotes, but still imported by the actual testfile. -/ library_note "Test" /-- 1: this is a testnote with a label starting with "Te" -/ library_note "Other" /-- 1: this is a testnote with a label not starting with "te", so it shouldn't appear when looking for notes with label starting with "te". -/
.lake/packages/batteries/BatteriesTest/omega/benchmark.lean
/-! # Benchmarking the `omega` tactic As it's important that `omega` is fast, particularly when it has nothing to do, this file maintains a benchmark suite for `omega`. It is particularly low-tech, and currently only reproducible on Kim Morrison's FRO machine; nevertheless it seems useful to keep the benchmark history in the repository. The benchmark file consists of the test suite from `omega`'s initial release, with one test removed (in which a test-for-failure succeeds with today's `omega`). The benchmark consists of `lake build && hyperfine "lake env lean test/omega/benchmark.lean"` run on a freshly rebooted machine! 2024-02-06 feat: omega uses Lean.HashMap instead of Std.Data.HashMap (#588) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.530 s ± 0.008 s [User: 2.249 s, System: 0.276 s] Range (min … max): 2.513 s … 2.542 s 10 runs 2024-02-03 feat: omega handles min, max, if (#575) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.526 s ± 0.009 s [User: 2.250 s, System: 0.272 s] Range (min … max): 2.513 s … 2.542 s 10 runs 2024-02-02 fix: revert OmegaM state when not multiplying out (#570) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.569 s ± 0.004 s [User: 2.291 s, System: 0.273 s] Range (min … max): 2.563 s … 2.574 s 10 runs 2024-01-12 feat: omega handles double negation and implication hypotheses (#522) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.575 s ± 0.004 s [User: 2.302 s, System: 0.268 s] Range (min … max): 2.570 s … 2.581 s 10 runs 2024-01-10 feat: omega understands Prod.Lex (#511) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.567 s ± 0.006 s [User: 2.295 s, System: 0.268 s] Range (min … max): 2.559 s … 2.576 s 10 runs 2024-01-10 feat: omega handles iff and implications (#503) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.348 s ± 0.007 s [User: 2.060 s, System: 0.282 s] Range (min … max): 2.335 s … 2.356 s 10 runs 2023-12-21 feat: omega (#463) kim@carica std4 % lake build && hyperfine "lake env lean test/omega/benchmark.lean" Benchmark 1: lake env lean test/omega/benchmark.lean Time (mean ± σ): 2.362 s ± 0.008 s [User: 2.080 s, System: 0.277 s] Range (min … max): 2.349 s … 2.372 s 10 runs -/ example : True := by fail_if_success omega trivial -- set_option trace.omega true example (_ : (1 : Int) < (0 : Int)) : False := by omega example (_ : (0 : Int) < (0 : Int)) : False := by omega example (_ : (0 : Int) < (1 : Int)) : True := by (fail_if_success omega); trivial example {x : Int} (_ : 0 ≤ x) (_ : x ≤ 1) : True := by (fail_if_success omega); trivial example {x : Int} (_ : 0 ≤ x) (_ : x ≤ -1) : False := by omega example {x : Int} (_ : x % 2 < x - 2 * (x / 2)) : False := by omega example {x : Int} (_ : x % 2 > 5) : False := by omega example {x : Int} (_ : 2 * (x / 2) > x) : False := by omega example {x : Int} (_ : 2 * (x / 2) ≤ x - 2) : False := by omega example {x : Nat} : x / 0 = 0 := by omega example {x : Int} : x / 0 = 0 := by omega example {x : Int} : x / 2 + x / (-2) = 0 := by omega example (_ : 7 < 3) : False := by omega example (_ : 0 < 0) : False := by omega example {x : Nat} (_ : x > 7) (_ : x < 3) : False := by omega example {x : Nat} (_ : x ≥ 7) (_ : x ≤ 3) : False := by omega example {x y : Nat} (_ : x + y > 10) (_ : x < 5) (_ : y < 5) : False := by omega example {x y : Int} (_ : x + y > 10) (_ : 2 * x < 11) (_ : y < 5) : False := by omega example {x y : Nat} (_ : x + y > 10) (_ : 2 * x < 11) (_ : y < 5) : False := by omega example {x y : Int} (_ : 2 * x + 4 * y = 5) : False := by omega example {x y : Nat} (_ : 2 * x + 4 * y = 5) : False := by omega example {x y : Int} (_ : 6 * x + 7 * y = 5) : True := by (fail_if_success omega); trivial example {x y : Nat} (_ : 6 * x + 7 * y = 5) : False := by omega example {x : Nat} (_ : x < 0) : False := by omega example {x y z : Int} (_ : x + y > z) (_ : x < 0) (_ : y < 0) (_ : z > 0) : False := by omega example {x y : Nat} (_ : x - y = 0) (_ : x > y) : False := by fail_if_success omega (config := { splitNatSub := false }) omega example {x y z : Int} (_ : x - y - z = 0) (_ : x > y + z) : False := by omega example {x y z : Nat} (_ : x - y - z = 0) (_ : x > y + z) : False := by omega example {a b c d e f : Nat} (_ : a - b - c - d - e - f = 0) (_ : a > b + c + d + e + f) : False := by omega example {x y : Nat} (h₁ : x - y ≤ 0) (h₂ : y < x) : False := by omega example {x y : Int} (_ : x / 2 - y / 3 < 1) (_ : 3 * x ≥ 2 * y + 6) : False := by omega example {x y : Nat} (_ : x / 2 - y / 3 < 1) (_ : 3 * x ≥ 2 * y + 6) : False := by omega example {x y : Nat} (_ : x / 2 - y / 3 < 1) (_ : 3 * x ≥ 2 * y + 4) : False := by omega example {x y : Nat} (_ : x / 2 - y / 3 < x % 2) (_ : 3 * x ≥ 2 * y + 4) : False := by omega example {x : Int} (h₁ : 5 ≤ x) (h₂ : x ≤ 4) : False := by omega example {x : Nat} (h₁ : 5 ≤ x) (h₂ : x ≤ 4) : False := by omega example {x : Nat} (h₁ : x / 3 ≥ 2) (h₂ : x < 6) : False := by omega example {x : Int} {y : Nat} (_ : 0 < x) (_ : x + y ≤ 0) : False := by omega example {a b c : Nat} (_ : a - (b - c) ≤ 5) (_ : b ≥ c + 3) (_ : a + c ≥ b + 6) : False := by omega example {x : Nat} : 1 < (1 + ((x + 1 : Nat) : Int) + 2) / 2 := by omega example {x : Nat} : (x + 4) / 2 ≤ x + 2 := by omega example {x : Int} {m : Nat} (_ : 0 < m) (_ : ¬x % ↑m < (↑m + 1) / 2) : -↑m / 2 ≤ x % ↑m - ↑m := by omega example (h : (7 : Int) = 0) : False := by omega example (h : (7 : Int) ≤ 0) : False := by omega example (h : (-7 : Int) + 14 = 0) : False := by omega example (h : (-7 : Int) + 14 ≤ 0) : False := by omega example (h : (1 : Int) + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 0) : False := by omega example (h : (7 : Int) - 14 = 0) : False := by omega example (h : (14 : Int) - 7 ≤ 0) : False := by omega example (h : (1 : Int) - 1 + 1 - 1 + 1 - 1 + 1 - 1 + 1 - 1 + 1 - 1 + 1 - 1 + 1 = 0) : False := by omega example (h : -(7 : Int) = 0) : False := by omega example (h : -(-7 : Int) ≤ 0) : False := by omega example (h : 2 * (7 : Int) = 0) : False := by omega example (h : (7 : Int) < 0) : False := by omega example {x : Int} (h : x + x + 1 = 0) : False := by omega example {x : Int} (h : 2 * x + 1 = 0) : False := by omega example {x y : Int} (h : x + x + y + y + 1 = 0) : False := by omega example {x y : Int} (h : 2 * x + 2 * y + 1 = 0) : False := by omega example {x : Int} (h₁ : 0 ≤ -7 + x) (h₂ : 0 ≤ 3 - x) : False := by omega example {x : Int} (h₁ : 0 ≤ -7 + x) (h₂ : 0 < 4 - x) : False := by omega example {x : Int} (h₁ : 0 ≤ 2 * x + 1) (h₂ : 2 * x + 1 ≤ 0) : False := by omega example {x : Int} (h₁ : 0 < 2 * x + 2) (h₂ : 2 * x + 1 ≤ 0) : False := by omega example {x y : Int} (h₁ : 0 ≤ 2 * x + 1) (h₂ : x = y) (h₃ : 2 * y + 1 ≤ 0) : False := by omega example {x y z : Int} (h₁ : 0 ≤ 2 * x + 1) (h₂ : x = y) (h₃ : y = z) (h₄ : 2 * z + 1 ≤ 0) : False := by omega example {x1 x2 x3 x4 x5 x6 : Int} (h : 0 ≤ 2 * x1 + 1) (h : x1 = x2) (h : x2 = x3) (h : x3 = x4) (h : x4 = x5) (h : x5 = x6) (h : 2 * x6 + 1 ≤ 0) : False := by omega example {x : Int} (_ : 1 ≤ -3 * x) (_ : 1 ≤ 2 * x) : False := by omega example {x y : Int} (_ : 2 * x + 3 * y = 0) (_ : 1 ≤ x) (_ : 1 ≤ y) : False := by omega example {x y z : Int} (_ : 2 * x + 3 * y = 0) (_ : 3 * y + 4 * z = 0) (_ : 1 ≤ x) (_ : 1 ≤ -z) : False := by omega example {x y z : Int} (_ : 2 * x + 3 * y + 4 * z = 0) (_ : 1 ≤ x + y) (_ : 1 ≤ y + z) (_ : 1 ≤ x + z) : False := by omega example {x y : Int} (_ : 1 ≤ 3 * x) (_ : y ≤ 2) (_ : 6 * x - 2 ≤ y) : False := by omega example {x y : Int} (_ : y = x) (_ : 0 ≤ x - 2 * y) (_ : x - 2 * y ≤ 1) (_ : 1 ≤ x) : False := by omega example {x y : Int} (_ : y = x) (_ : 0 ≤ x - 2 * y) (_ : x - 2 * y ≤ 1) (_ : x ≥ 1) : False := by omega example {x y : Int} (_ : y = x) (_ : 0 ≤ x - 2 * y) (_ : x - 2 * y ≤ 1) (_ : 0 < x) : False := by omega example {x y : Int} (_ : y = x) (_ : 0 ≤ x - 2 * y) (_ : x - 2 * y ≤ 1) (_ : x > 0) : False := by omega example {x : Nat} (_ : 10 ∣ x) (_ : ¬ 5 ∣ x) : False := by omega example {x y : Nat} (_ : 5 ∣ x) (_ : ¬ 10 ∣ x) (_ : y = 7) (_ : x - y ≤ 2) (_ : x ≥ 6) : False := by omega example (x : Nat) : x % 4 - x % 8 = 0 := by omega example {n : Nat} (_ : n > 0) : (2*n - 1) % 2 = 1 := by omega example (x : Int) (_ : x > 0 ∧ x < -1) : False := by omega example (x : Int) (_ : x > 7) : x < 0 ∨ x > 3 := by omega example (_ : ∃ n : Nat, n < 0) : False := by omega example (_ : { x : Int // x < 0 ∧ x > 0 }) : False := by omega example {x y : Int} (_ : x < y) (z : { z : Int // y ≤ z ∧ z ≤ x }) : False := by omega example (a b c d e : Int) (ha : 2 * a + b + c + d + e = 4) (hb : a + 2 * b + c + d + e = 5) (hc : a + b + 2 * c + d + e = 6) (hd : a + b + c + 2 * d + e = 7) (he : a + b + c + d + 2 * e = 8) : e = 3 := by omega example (a b c d e : Int) (ha : 2 * a + b + c + d + e = 4) (hb : a + 2 * b + c + d + e = 5) (hc : a + b + 2 * c + d + e = 6) (hd : a + b + c + 2 * d + e = 7) (he : a + b + c + d + 2 * e = 8 ∨ e = 3) : e = 3 := by fail_if_success omega (config := { splitDisjunctions := false }) omega example {a b : Int} (h : a < b) (w : b < a) : False := by omega example (_e b c a v0 v1 : Int) (_h1 : v0 = 5 * a) (_h2 : v1 = 3 * b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by omega example (h : (1 : Int) < 0) (_ : ¬ (37 : Int) < 42) (_ : True) (_ : (-7 : Int) < 5) : (3 : Int) < 7 := by omega example (A B : Int) (h : 0 < A * B) : 0 < 8 * (A * B) := by omega example (A B : Nat) (h : 7 < A * B) : 0 < A*B/8 := by omega example (A B : Int) (h : 7 < A * B) : 0 < A*B/8 := by omega example (ε : Int) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by omega example (x y z : Int) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : False := by omega example (ε : Int) (h1 : ε > 0) : ε / 2 < ε := by omega example (ε : Int) (_ : ε > 0) : ε - 2 ≤ ε / 3 + ε / 3 + ε / 3 := by omega example (ε : Int) (_ : ε > 0) : ε / 3 + ε / 3 + ε / 3 ≤ ε := by omega example (ε : Int) (_ : ε > 0) : ε - 2 ≤ ε / 3 + ε / 3 + ε / 3 ∧ ε / 3 + ε / 3 + ε / 3 ≤ ε := by omega example (x : Int) (h : 0 < x) : 0 < x / 1 := by omega example (x : Int) (h : 5 < x) : 0 < x/2/3 := by omega example (_a b _c : Nat) (h2 : b + 2 > 3 + b) : False := by omega example (_a b _c : Int) (h2 : b + 2 > 3 + b) : False := by omega example (g v V c h : Int) (_ : h = 0) (_ : v = V) (_ : V > 0) (_ : g > 0) (_ : 0 ≤ c) (_ : c < 1) : v ≤ V := by omega example (x y z : Int) (h1 : 2 * x < 3 * y) (h2 : -4 * x + 2 * z < 0) (h3 : 12 * y - 4 * z < 0) : False := by omega example (x y z : Int) (h1 : 2 * x < 3 * y) (h2 : -4 * x + 2 * z < 0) (_h3 : x * y < 5) (h3 : 12 * y - 4 * z < 0) : False := by omega example (a b c : Int) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : False := by omega example (_ b _ : Int) (h2 : b > 0) (h3 : ¬ b ≥ 0) : False := by omega example (x y z : Int) (hx : x ≤ 3 * y) (h2 : y ≤ 2 * z) (h3 : x ≥ 6 * z) : x = 3 * y := by omega example (x y z : Int) (h1 : 2 * x < 3 * y) (h2 : -4 * x + 2 * z < 0) (_h3 : x * y < 5) : ¬ 12 * y - 4 * z < 0 := by omega example (x y z : Int) (hx : ¬ x > 3 * y) (h2 : ¬ y > 2 * z) (h3 : x ≥ 6 * z) : x = 3 * y := by omega example (x y : Int) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : False := by omega example (a : Int) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a := by omega example (x y : Int) (h : x < y) : x ≠ y := by omega example (x y : Int) (h : x < y) : ¬ x = y := by omega example (prime : Nat → Prop) (x y z : Int) (h1 : 2 * x + ((-3) * y) < 0) (h2 : (-4) * x + 2* z < 0) (h3 : 12 * y + (-4) * z < 0) (_ : prime 7) : False := by omega example (i n : Nat) (h : (2 : Int) ^ i ≤ 2 ^ n) : (0 : Int) ≤ 2 ^ n - 2 ^ i := by omega -- Check we use `exfalso` on non-comparison goals. example (prime : Nat → Prop) (_ b _ : Nat) (h2 : b > 0) (h3 : b < 0) : prime 10 := by omega example (a b c : Nat) (h2 : (2 : Nat) > 3) : a + b - c ≥ 3 := by omega -- Verify that we split conjunctions in hypotheses. example (x y : Int) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : False := by omega example (mess : Nat → Nat) (S n : Nat) : mess S + (n * mess S + n * 2 + 1) < n * mess S + mess S + (n * 2 + 2) := by omega example (p n p' n' : Nat) (h : p + n' = p' + n) : n + p' = n' + p := by omega example (a b c : Int) (h1 : 32 / a < b) (h2 : b < c) : 32 / a < c := by omega
.lake/packages/Cli/README.md
# lean4-cli This project is maintained by [@mhuisi](https://github.com/mhuisi). ## Usage See [the documentation of Lake](https://github.com/leanprover/lean4/blob/master/src/lake/README.md). ### Configuration Commands are configured with a lightweight DSL. The following declarations define a command `exampleCmd` with two subcommands `installCmd` and `testCmd`. `runExampleCmd` denotes a handler that is called when the command is run and is described further down below in the **Command Handlers** subsection. ```Lean open Cli def installCmd := `[Cli| installCmd NOOP; "installCmd provides an example for a subcommand without flags or arguments that does nothing. \ Versions can be omitted." ] def testCmd := `[Cli| testCmd NOOP; "testCmd provides another example for a subcommand without flags or arguments that does nothing." ] def exampleCmd : Cmd := `[Cli| exampleCmd VIA runExampleCmd; ["0.0.1"] "This string denotes the description of `exampleCmd`." FLAGS: verbose; "Declares a flag `--verbose`. This is the description of the flag." i, invert; "Declares a flag `--invert` with an associated short alias `-i`." o, optimize; "Declares a flag `--optimize` with an associated short alias `-o`." p, priority : Nat; "Declares a flag `--priority` with an associated short alias `-p` \ that takes an argument of type `Nat`." module : ModuleName; "Declares a flag `--module` that takes an argument of type `ModuleName` \ which can be used to reference Lean modules like `Init.Data.Array` \ or Lean files using a relative path like `Init/Data/Array.lean`." "set-paths" : Array String; "Declares a flag `--set-paths` \ that takes an argument of type `Array Nat`. \ Quotation marks allow the use of hyphens." ARGS: input : String; "Declares a positional argument <input> \ that takes an argument of type `String`." ...outputs : String; "Declares a variable argument <output>... \ that takes an arbitrary amount of arguments of type `String`." SUBCOMMANDS: installCmd; testCmd -- The EXTENSIONS section denotes features that -- were added as an external extension to the library. -- `./Cli/Extensions.lean` provides some commonly useful examples. EXTENSIONS: author "mhuisi"; defaultValues! #[("priority", "0")] ] ``` ### Command handlers The command handler `runExampleCmd` demonstrates how to use the parsed user input. ```Lean def runExampleCmd (p : Parsed) : IO UInt32 := do let input : String := p.positionalArg! "input" |>.as! String let outputs : Array String := p.variableArgsAs! String IO.println <| "Input: " ++ input IO.println <| "Outputs: " ++ toString outputs if p.hasFlag "verbose" then IO.println "Flag `--verbose` was set." if p.hasFlag "invert" then IO.println "Flag `--invert` was set." if p.hasFlag "optimize" then IO.println "Flag `--optimize` was set." let priority : Nat := p.flag! "priority" |>.as! Nat IO.println <| "Flag `--priority` always has at least a default value: " ++ toString priority if p.hasFlag "module" then let moduleName : ModuleName := p.flag! "module" |>.as! ModuleName IO.println <| s!"Flag `--module` was set to `{moduleName}`." if let some setPathsFlag := p.flag? "set-paths" then IO.println <| toString <| setPathsFlag.as! (Array String) return 0 ``` ### Running the command Below you can find some simple examples of how to pass user input to the Cli library. ```lean def main (args : List String) : IO UInt32 := exampleCmd.validate args #eval main <| "-i -o -p 1 --module=Lean.Compiler --set-paths=path1,path2,path3 input output1 output2".splitOn " " /- Yields: Input: input Outputs: #[output1, output2] Flag `--invert` was set. Flag `--optimize` was set. Flag `--priority` always has at least a default value: 1 Flag `--module` was set to `Lean.Compiler`. #[path1, path2, path3] -/ -- Short parameterless flags can be grouped, -- short flags with parameters do not need to be separated from -- the corresponding value. #eval main <| "-io -p1 input".splitOn " " /- Yields: Input: input Outputs: #[] Flag `--invert` was set. Flag `--optimize` was set. Flag `--priority` always has at least a default value: 1 -/ #eval main <| "--version".splitOn " " /- Yields: 0.0.1 -/ ``` ### Help Upon calling `-h`, the above configuration produces the following help. ``` exampleCmd [0.0.1] mhuisi This string denotes the description of `exampleCmd`. USAGE: exampleCmd [SUBCOMMAND] [FLAGS] <input> <outputs>... FLAGS: -h, --help Prints this message. --version Prints the version. --verbose Declares a flag `--verbose`. This is the description of the flag. -i, --invert Declares a flag `--invert` with an associated short alias `-i`. -o, --optimize Declares a flag `--optimize` with an associated short alias `-o`. -p, --priority : Nat Declares a flag `--priority` with an associated short alias `-p` that takes an argument of type `Nat`. [Default: `0`] --module : ModuleName Declares a flag `--module` that takes an argument of type `ModuleName` which can be used to reference Lean modules like `Init.Data.Array` or Lean files using a relative path like `Init/Data/Array.lean`. --set-paths : Array String Declares a flag `--set-paths` that takes an argument of type `Array String`. Quotation marks allow the use of hyphens. ARGS: input : String Declares a positional argument <input> that takes an argument of type `String`. outputs : String Declares a variable argument <output>... that takes an arbitrary amount of arguments of type `String`. SUBCOMMANDS: installCmd installCmd provides an example for a subcommand without flags or arguments that does nothing. Versions can be omitted. testCmd testCmd provides another example for a subcommand without flags or arguments that does nothing. ``` The full example can be found under `./CliTest/Example.lean`. ## Ad Hoc Documentation This section documents only the most common features of the library. For the full documentation, peek into `./Cli/Basic.lean` and `./Cli/Extensions.lean`! All definitions below live in the `Cli` namespace. ```Lean -- In a `nameableStringArg`, string literals can either be used directly or an identifier can be -- supplied that references a string value. syntax nameableStringArg := str <|> ident -- In a `literalIdent`, identifiers are expanded as `String`s. syntax literalIdent := str <|> ident syntax runFun := (" VIA " ident) <|> " NOOP" syntax positionalArg := colGe literalIdent " : " term "; " nameableStringArg syntax variableArg := colGe "..." literalIdent " : " term "; " nameableStringArg syntax flag := colGe literalIdent ("," literalIdent)? (" : " term)? "; " nameableStringArg syntax "`[Cli|\n" literalIdent runFun "; " ("[" nameableStringArg "]")? nameableStringArg ("FLAGS:\n" withPosition((flag)*))? ("ARGS:\n" withPosition((positionalArg)* (variableArg)?))? ("SUBCOMMANDS: " sepBy(ident, ";", "; "))? ("EXTENSIONS: " sepBy(term, ";", "; "))? "\n]" : term ``` ```Lean /-- Validates `args` by `Cmd.process?`ing the input according to `c`. Note that `args` designates the list `<foo>` in `somebinary <foo>`. Prints the help or the version of the called (sub)command if the respective flag was passed and returns `0` for the exit code. If neither of these flags were passed and processing was successful, the `run` handler of the called command is executed. In the case of a processing error, the error is printed to stderr and an exit code of `1` is returned. -/ def validate (c : Cmd) (args : List String) : IO UInt32 := do let result := c.process args match result with | .ok (cmd, parsed) => if parsed.hasFlag "help" then parsed.printHelp return 0 if parsed.cmd.meta.hasVersion ∧ parsed.hasFlag "version" then parsed.printVersion! return 0 cmd.run parsed | .error (cmd, err) => cmd.printError err return 1 ``` ```Lean /-- Represents parsed user input data. -/ structure Parsed where /-- Recursive meta-data of the associated command. -/ cmd : Parsed.Cmd /-- Parent of the associated command. -/ parent? : Option Parsed.Cmd /-- Parsed flags. -/ flags : Array Parsed.Flag /-- Parsed positional arguments. -/ positionalArgs : Array Parsed.Arg /-- Parsed variable arguments. -/ variableArgs : Array Parsed.Arg deriving Inhabited namespace Parsed /-- Parent of the associated command. -/ def parent! (p : Parsed) : Parsed.Cmd /-- Checks whether the associated command has a parent, i.e. whether it is not the root command. -/ def hasParent (p : Parsed) : Bool /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag? (p : Parsed) (longName : String) : Option Flag /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg? (p : Parsed) (name : String) : Option Arg /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag! (p : Parsed) (longName : String) : Flag /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg! (p : Parsed) (name : String) : Arg /-- Checks whether `p` has a parsed flag with the corresponding `longName`. -/ def hasFlag (p : Parsed) (longName : String) : Bool /-- Checks whether `p` has a positional argument with the corresponding `longName`. -/ def hasPositionalArg (p : Parsed) (name : String) : Bool /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs? (p : Parsed) (τ) [ParseableType τ] : Option (Array τ) /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs! (p : Parsed) (τ) [Inhabited τ] [ParseableType τ] : Array τ end Parsed ``` ```Lean namespace Parsed /-- Represents a flag and its parsed value. Use `Parsed.Flag.as!` to convert the value to some `ParseableType`. -/ structure Flag where /-- Associated flag meta-data. -/ flag : Flag /-- Parsed value that was validated and conforms to `flag.type`. -/ value : String namespace Flag /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as? (f : Flag) (τ) [ParseableType τ] : Option τ /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as! (f : Flag) (τ) [Inhabited τ] [ParseableType τ] : τ end Flag /-- Represents an argument and its parsed value. Use `Parsed.Arg.as!` to convert the value to some `ParseableType`. -/ structure Arg where /-- Associated argument meta-data. -/ arg : Arg /-- Parsed value that was validated and conforms to `arg.type`. -/ value : String namespace Arg /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as? (a : Arg) (τ) [ParseableType τ] : Option τ /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as! (a : Arg) (τ) [Inhabited τ] [ParseableType τ] : τ end Arg end Parsed ``` ```Lean /-- Creates a new command. Adds a `-h, --help` and a `--version` flag if a version is designated. Updates the `parentNames` of all subcommands. - `name`: Name that is displayed in the help. - `version?`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ def mk (name : String) (version? : Option String) (description : String) (furtherInformation? : Option String := none) (flags : Array Flag := #[]) (positionalArgs : Array Arg := #[]) (variableArg? : Option Arg := none) (run : Parsed → IO UInt32) (subCmds : Array Cmd := #[]) (extension? : Option Extension := none) : Cmd ```
.lake/packages/Cli/Cli.lean
module public import Cli.Basic public import Cli.Extensions
.lake/packages/Cli/CliTest/Tests.lean
import Cli.Basic import Cli.Extensions namespace Cli section Utils instance [BEq α] [BEq β] : BEq (Except α β) where beq | Except.ok a, Except.ok a' => a == a' | Except.error b, Except.error b' => b == b' | _, _ => false instance [Repr α] [Repr β] : Repr (Except α β) where reprPrec | Except.ok a, _ => s!"Except.ok ({repr a})" | Except.error b, _ => s!"Except.error ({repr b})" def Cmd.processParsed (c : Cmd) (args : String) : String := Id.run do let mut args := args.splitOn if args = [""] then args := [] match c.process args with | Except.ok (_, parsed) => return toString parsed | Except.error (_, error) => return error def Cmd.extendedHelp (c : Cmd) : String := c.extension!.extend (.ofFullCmd c) |>.toFullCmd c |>.help end Utils def doNothing (_ : Parsed) : IO UInt32 := return 0 def testSubSubCmd : Cmd := `[Cli| testsubsubcommand VIA doNothing; "does this even do anything?" ] def testSubCmd1 : Cmd := `[Cli| testsubcommand1 NOOP; ["0.0.1"] "a properly short description" FLAGS: "launch-the-nukes"; "please avoid passing this flag at all costs.\nif you like, you can have newlines in descriptions." ARGS: "city-location" : String; "can also use hyphens" SUBCOMMANDS: testSubSubCmd EXTENSIONS: helpSubCommand; versionSubCommand! ] def testSubCmd2 : Cmd := `[Cli| testsubcommand2 VIA doNothing; ["0.0.-1"] "does not do anything interesting" FLAGS: r, run; "really, this does not do anything. trust me." ARGS: "ominous-input" : Array String; "what could this be for?" ] def testCmd : Cmd := `[Cli| testcommand VIA doNothing; ["0.0.0"] "some short description that happens to be much longer than necessary and hence needs to be wrapped to fit into an 80 character width limit" FLAGS: verbose; "a very verbose flag description that also needs to be wrapped to fit into an 80 character width limit" x, unknown1; "this flag has a short name" xn, unknown2; "short names do not need to be prefix-free" ny, unknown3; "-xny will parse as -x -ny and not fail to parse as -xn -y" t, typed1 : String; "flags can have typed parameters" ty, typed2; "-ty parsed as --typed2, not -t=y" "p-n", "level-param" : Nat; "hyphens work, too" ARGS: input1 : String; "another very verbose description that also needs to be wrapped to fit into an 80 character width limit" input2 : Array Nat; "arrays!" ...outputs : Nat; "varargs!" SUBCOMMANDS: testSubCmd1; testSubCmd2 EXTENSIONS: author "mhuisi"; longDescription "this could be really long, but i'm too lazy to type it out."; defaultValues! #[⟨"level-param", "0"⟩]; require! #["typed1"] ] section ValidInputs /-- info: "cmd: testcommand; flags: #[--typed1=a, --level-param=0]; positionalArgs: #[<input1=foo>, <input2=1>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "foo 1 -ta" /-- info: "cmd: testcommand; flags: #[--help, --level-param=0]; positionalArgs: #[]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "-h" /-- info: "cmd: testcommand; flags: #[--version, --level-param=0]; positionalArgs: #[]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "--version" /-- info: "cmd: testcommand; flags: #[--verbose, --level-param=2, --unknown2, --unknown1, --typed1=foo]; positionalArgs: #[<input1=foo>, <input2=1,2,3>]; variableArgs: #[<outputs=1>, <outputs=2>, <outputs=3>]" -/ #guard_msgs in #eval testCmd.processParsed "foo --verbose -p-n 2 1,2,3 1 -xnx 2 --typed1=foo 3" /-- info: "cmd: testcommand; flags: #[--unknown1, --unknown3, --typed1=3, --level-param=0]; positionalArgs: #[<input1=foo>, <input2=1>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "foo -xny 1 -t 3" /-- info: "cmd: testcommand; flags: #[--typed1=3, --level-param=0]; positionalArgs: #[<input1=--input>, <input2=2>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "-t 3 -- --input 2" /-- info: "cmd: testcommand; flags: #[--typed1=1, --level-param=0]; positionalArgs: #[<input1=->, <input2=2>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "-t1 - 2" /-- info: "cmd: testcommand; flags: #[--typed2, --typed1=1, --level-param=0]; positionalArgs: #[<input1=foo>, <input2=1,2>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "-ty -t1 foo 1,2" /-- info: "cmd: testcommand testsubcommand1; flags: #[]; positionalArgs: #[<city-location=testsubsubcommand>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 -- testsubsubcommand" /-- info: "cmd: testcommand testsubcommand1; flags: #[--launch-the-nukes]; positionalArgs: #[<city-location=x>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 --launch-the-nukes x" /-- info: "cmd: testcommand testsubcommand1; flags: #[]; positionalArgs: #[<city-location=--launch-the-nukes>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 -- --launch-the-nukes" /-- info: "cmd: testcommand testsubcommand1 testsubsubcommand; flags: #[]; positionalArgs: #[]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 testsubsubcommand" /-- info: "cmd: testcommand testsubcommand2; flags: #[--run]; positionalArgs: #[<ominous-input=asdf,geh>]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand2 --run asdf,geh" /-- info: "cmd: testcommand testsubcommand1 help; flags: #[]; positionalArgs: #[]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 help" /-- info: "cmd: testcommand testsubcommand1 version; flags: #[]; positionalArgs: #[]; variableArgs: #[]" -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 version" end ValidInputs section InvalidInputs /-- info: "Missing positional argument `<input1>.`" -/ #guard_msgs in #eval testCmd.processParsed "" /-- info: "Missing positional argument `<input2>.`" -/ #guard_msgs in #eval testCmd.processParsed "foo" /-- info: "Invalid type of argument `asdf` for positional argument `<input2 : Array Nat>`." -/ #guard_msgs in #eval testCmd.processParsed "foo asdf" /-- info: "Missing required flag `--typed1`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3" /-- info: "Missing argument for flag `-t`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t" /-- info: "Invalid type of argument `` for flag `--level-param : Nat`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 --level-param=" /-- info: "Invalid type of argument `` for flag `-p-n : Nat`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 -p-n=" /-- info: "Unknown flag `--asdf`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 --asdf" /-- info: "Duplicate flag `-t` (`--typed1`)." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 -t2" /-- info: "Duplicate flag `--typed1` (`-t`)." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 --typed1=2" /-- info: "Unknown flag `--typed12`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 --typed12" /-- info: "Redundant argument `1` for flag `-x` that takes no arguments." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 -x=1" /-- info: "Invalid type of argument `bar` for variable argument `<outputs : Nat>...`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 bar" /-- info: "Unknown flag `-xxn`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 -t1 -xxn=1" /-- info: "Unknown flag `--t`." -/ #guard_msgs in #eval testCmd.processParsed "foo 1,2,3 --t=1" /-- info: "Redundant positional argument `geh`." -/ #guard_msgs in #eval testCmd.processParsed "testsubcommand1 asdf geh" end InvalidInputs section Info /-- info: "testcommand [0.0.0]\nsome short description that happens to be much longer than necessary and hence\nneeds to be wrapped to fit into an 80 character width limit\n\nUSAGE:\n testcommand [SUBCOMMAND] [FLAGS] <input1> <input2> <outputs>...\n\nFLAGS:\n -h, --help Prints this message.\n --version Prints the version.\n --verbose a very verbose flag description that also needs\n to be wrapped to fit into an 80 character width\n limit\n -x, --unknown1 this flag has a short name\n -xn, --unknown2 short names do not need to be prefix-free\n -ny, --unknown3 -xny will parse as -x -ny and not fail to parse\n as -xn -y\n -t, --typed1 : String flags can have typed parameters\n -ty, --typed2 -ty parsed as --typed2, not -t=y\n -p-n, --level-param : Nat hyphens work, too\n\nARGS:\n input1 : String another very verbose description that also needs to be\n wrapped to fit into an 80 character width limit\n input2 : Array Nat arrays!\n outputs : Nat varargs!\n\nSUBCOMMANDS:\n testsubcommand1 a properly short description\n testsubcommand2 does not do anything interesting" -/ #guard_msgs in #eval testCmd.help /-- info: "0.0.0" -/ #guard_msgs in #eval testCmd.meta.version! /-- info: "some exceedingly long error that needs to be wrapped to fit within an 80\ncharacter width limit. none of our errors are really that long, but flag names\nmight be.\nRun `testcommand -h` for further information." -/ #guard_msgs in #eval testCmd.error "some exceedingly long error that needs to be wrapped to fit within an 80 character width limit. none of our errors are really that long, but flag names might be." /-- info: "testsubcommand2 [0.0.-1]\ndoes not do anything interesting\n\nUSAGE:\n testsubcommand2 [FLAGS] <ominous-input>\n\nFLAGS:\n -h, --help Prints this message.\n --version Prints the version.\n -r, --run really, this does not do anything. trust me.\n\nARGS:\n ominous-input : Array String what could this be for?" -/ #guard_msgs in #eval testSubCmd2.help /-- info: "testcommand testsubcommand2 [0.0.-1]\ndoes not do anything interesting\n\nUSAGE:\n testcommand testsubcommand2 [FLAGS] <ominous-input>\n\nFLAGS:\n -h, --help Prints this message.\n --version Prints the version.\n -r, --run really, this does not do anything. trust me.\n\nARGS:\n ominous-input : Array String what could this be for?" -/ #guard_msgs in #eval (testCmd.subCmd! "testsubcommand2").help /-- info: "testcommand testsubcommand1 testsubsubcommand\ndoes this even do anything?\n\nUSAGE:\n testcommand testsubcommand1 testsubsubcommand [FLAGS]\n\nFLAGS:\n -h, --help Prints this message." -/ #guard_msgs in #eval (testCmd.subCmd! "testsubcommand1" |>.subCmd! "testsubsubcommand").help /-- info: "testcommand [0.0.0]\nmhuisi\nsome short description that happens to be much longer than necessary and hence\nneeds to be wrapped to fit into an 80 character width limit\n\nUSAGE:\n testcommand [SUBCOMMAND] [FLAGS] <input1> <input2> <outputs>...\n\nFLAGS:\n -h, --help Prints this message.\n --version Prints the version.\n --verbose a very verbose flag description that also needs\n to be wrapped to fit into an 80 character width\n limit\n -x, --unknown1 this flag has a short name\n -xn, --unknown2 short names do not need to be prefix-free\n -ny, --unknown3 -xny will parse as -x -ny and not fail to parse\n as -xn -y\n -t, --typed1 : String [Required] flags can have typed parameters\n -ty, --typed2 -ty parsed as --typed2, not -t=y\n -p-n, --level-param : Nat hyphens work, too [Default: `0`]\n\nARGS:\n input1 : String another very verbose description that also needs to be\n wrapped to fit into an 80 character width limit\n input2 : Array Nat arrays!\n outputs : Nat varargs!\n\nSUBCOMMANDS:\n testsubcommand1 a properly short description\n testsubcommand2 does not do anything interesting\n\nDESCRIPTION:\n this could be really long, but i'm too lazy to type it out." -/ #guard_msgs in #eval testCmd.extendedHelp /-- info: "testsubcommand1 [0.0.1]\na properly short description\n\nUSAGE:\n testsubcommand1 [SUBCOMMAND] [FLAGS] <city-location>\n\nFLAGS:\n -h, --help Prints this message.\n --version Prints the version.\n --launch-the-nukes please avoid passing this flag at all costs.\n if you like, you can have newlines in descriptions.\n\nARGS:\n city-location : String can also use hyphens\n\nSUBCOMMANDS:\n testsubsubcommand does this even do anything?\n version Prints the version.\n help Prints this message." -/ #guard_msgs in #eval testSubCmd1.extendedHelp end Info section ModuleName def ModuleName.parse? : String → Option ModuleName := ParseableType.parse? section ValidInputs /-- info: some `Lean.Mathlib.Data -/ #guard_msgs in #eval ModuleName.parse? "Lean.Mathlib.Data" /-- info: some `F00Bar.BarF00 -/ #guard_msgs in #eval ModuleName.parse? "F00Bar.BarF00" /-- info: some `foo_bar -/ #guard_msgs in #eval ModuleName.parse? "foo_bar" /-- info: some `asdf.«foo bar» -/ #guard_msgs in #eval ModuleName.parse? "asdf.«foo bar»" /-- info: some `«1».«2» -/ #guard_msgs in #eval ModuleName.parse? "«1».«2»" /-- info: some `« » -/ #guard_msgs in #eval ModuleName.parse? "« »" /-- info: some `Lean.Mathlib.Data.Afile -/ #guard_msgs in #eval ModuleName.parse? "Lean/Mathlib/Data/Afile.lean" /-- info: some `Foo -/ #guard_msgs in #eval ModuleName.parse? "Foo.lean" /-- info: some `«.» -/ #guard_msgs in #eval ModuleName.parse? "..lean" /-- info: some `« » -/ #guard_msgs in #eval ModuleName.parse? " .lean" /-- info: some `« ».Foo -/ #guard_msgs in #eval ModuleName.parse? " /Foo.lean" end ValidInputs section InvalidInputs /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "." /-- info: none -/ #guard_msgs in #eval ModuleName.parse? ".asdf" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "asdf." /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "1.asdf" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "asdf.1" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "1asdf" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "foo bar" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "foo,bar" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "«»" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "x.«»" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? ".lean" /-- info: none -/ #guard_msgs in #eval ModuleName.parse? "/foo.lean" end InvalidInputs end ModuleName end Cli
.lake/packages/Cli/CliTest/Example.lean
import Cli open Cli def runExampleCmd (p : Parsed) : IO UInt32 := do let input : String := p.positionalArg! "input" |>.as! String let outputs : Array String := p.variableArgsAs! String IO.println <| "Input: " ++ input IO.println <| "Outputs: " ++ toString outputs if p.hasFlag "verbose" then IO.println "Flag `--verbose` was set." if p.hasFlag "invert" then IO.println "Flag `--invert` was set." if p.hasFlag "optimize" then IO.println "Flag `--optimize` was set." let priority : Nat := p.flag! "priority" |>.as! Nat IO.println <| "Flag `--priority` always has at least a default value: " ++ toString priority if p.hasFlag "module" then let moduleName : ModuleName := p.flag! "module" |>.as! ModuleName IO.println <| s!"Flag `--module` was set to `{moduleName}`." if let some setPathsFlag := p.flag? "set-paths" then IO.println <| toString <| setPathsFlag.as! (Array String) return 0 def installCmd := `[Cli| installCmd NOOP; "installCmd provides an example for a subcommand without flags or arguments that does nothing. \ Versions can be omitted." ] def testCmd := `[Cli| testCmd NOOP; "testCmd provides another example for a subcommand without flags or arguments that does nothing." ] def exampleCmd : Cmd := `[Cli| exampleCmd VIA runExampleCmd; ["0.0.1"] "This string denotes the description of `exampleCmd`." FLAGS: verbose; "Declares a flag `--verbose`. This is the description of the flag." i, invert; "Declares a flag `--invert` with an associated short alias `-i`." o, optimize; "Declares a flag `--optimize` with an associated short alias `-o`." p, priority : Nat; "Declares a flag `--priority` with an associated short alias `-p` \ that takes an argument of type `Nat`." module : ModuleName; "Declares a flag `--module` that takes an argument of type `ModuleName` \ which can be used to reference Lean modules like `Init.Data.Array` \ or Lean files using a relative path like `Init/Data/Array.lean`." "set-paths" : Array String; "Declares a flag `--set-paths` \ that takes an argument of type `Array Nat`. \ Quotation marks allow the use of hyphens." ARGS: input : String; "Declares a positional argument <input> \ that takes an argument of type `String`." ...outputs : String; "Declares a variable argument <output>... \ that takes an arbitrary amount of arguments of type `String`." SUBCOMMANDS: installCmd; testCmd -- The EXTENSIONS section denotes features that -- were added as an external extension to the library. -- `./Cli/Extensions.lean` provides some commonly useful examples. EXTENSIONS: author "mhuisi"; defaultValues! #[("priority", "0")] ] def main (args : List String) : IO UInt32 := exampleCmd.validate args #eval main <| "-i -o -p 1 --module=Lean.Compiler --set-paths=path1,path2,path3 input output1 output2".splitOn " " /- Yields: Input: input Outputs: #[output1, output2] Flag `--invert` was set. Flag `--optimize` was set. Flag `--priority` always has at least a default value: 1 Flag `--module` was set to `Lean.Compiler`. #[path1, path2, path3] -/ -- Short parameterless flags can be grouped, -- short flags with parameters do not need to be separated from -- the corresponding value. #eval main <| "-io -p1 input".splitOn " " /- Yields: Input: input Outputs: #[] Flag `--invert` was set. Flag `--optimize` was set. Flag `--priority` always has at least a default value: 1 -/ #eval main <| "--version".splitOn " " /- Yields: 0.0.1 -/ #eval main <| "-h".splitOn " " /- Yields: exampleCmd [0.0.1] mhuisi This string denotes the description of `exampleCmd`. USAGE: exampleCmd [SUBCOMMAND] [FLAGS] <input> <outputs>... FLAGS: -h, --help Prints this message. --version Prints the version. --verbose Declares a flag `--verbose`. This is the description of the flag. -i, --invert Declares a flag `--invert` with an associated short alias `-i`. -o, --optimize Declares a flag `--optimize` with an associated short alias `-o`. -p, --priority : Nat Declares a flag `--priority` with an associated short alias `-p` that takes an argument of type `Nat`. [Default: `0`] --module : ModuleName Declares a flag `--module` that takes an argument of type `ModuleName` which can be used to reference Lean modules like `Init.Data.Array` or Lean files using a relative path like `Init/Data/Array.lean`. --set-paths : Array String Declares a flag `--set-paths` that takes an argument of type `Array Nat`. Quotation marks allow the use of hyphens. ARGS: input : String Declares a positional argument <input> that takes an argument of type `String`. outputs : String Declares a variable argument <output>... that takes an arbitrary amount of arguments of type `String`. SUBCOMMANDS: installCmd installCmd provides an example for a subcommand without flags or arguments that does nothing. Versions can be omitted. testCmd testCmd provides another example for a subcommand without flags or arguments that does nothing. -/
.lake/packages/Cli/Cli/Extensions.lean
module public import Cli.Basic public import Std.Data.TreeMap.Basic public import Std.Data.TreeSet.Basic section namespace Cli public section Utils namespace Array /-- Appends those elements of `right` to `left` whose `key` is not already contained in `left`. -/ def leftUnionBy [Ord α] (key : β → α) (left : Array β) (right : Array β) : Array β := Id.run do let leftMap := left.map (fun v => (key v, v)) |> Std.TreeMap.ofArray let mut result := left for v in right do if ¬ leftMap.contains (key v) then result := result.push v return result /-- Prepends those elements of `left` to `right` whose `key` is not already contained in `right`. -/ def rightUnionBy [Ord α] (key : β → α) (left : Array β) (right : Array β) : Array β := Id.run do let rightMap := right.map (fun v => (key v, v)) |> Std.TreeMap.ofArray let mut result := right for v in left.reverse do if ¬ rightMap.contains (key v) then result := #[v] ++ result return result /-- Deletes all elements from `left` whose `key` is in `right`. -/ def diffBy [Ord α] (key : β → α) (left : Array β) (right : Array α) : Array β := let rightMap := Std.TreeSet.ofArray right left.filter fun v => ¬ (rightMap.contains <| key v) end Array end Utils public section Extensions /-- Prepends an author name to the description of the command. -/ def author (author : String) : Extension := { extend := fun cmd => cmd.update (description := s!"{author}\n{cmd.description}") } /-- Appends a longer description to the end of the help. -/ def longDescription (description : String) : Extension := { extend := fun cmd => cmd.update (furtherInformation? := some <| Option.optStr cmd.furtherInformation? ++ lines #[ Option.optStr cmd.furtherInformation?, (if cmd.hasFurtherInformation then "\n" else "") ++ renderSection "DESCRIPTION" description ] ) } /-- Adds a `help` subcommand. -/ def helpSubCommand : Extension := { priority := 0 extend := fun cmd => let helpCmd := .mk (parent := cmd) (name := "help") (version? := none) (description := "Prints this message.") (run := fun _ => pure 0) -- adding it once without a command handler ensures that the help will include -- the help subcommand itself let cmd := cmd.update (subCmds := cmd.subCmds.push helpCmd) let helpCmd := helpCmd.update (run := fun _ => do cmd.toFullCmdWithoutExtensions.printHelp return 0) let subCmds := cmd.subCmds.set! (cmd.subCmds.size - 1) helpCmd cmd.update (subCmds := subCmds) } /-- Adds a `version` subcommand. -/ def versionSubCommand! : Extension := { extend := fun cmd => if cmd.version?.isNone then panic! "Cli.versionSubCommand!: Cannot add `version` subcommand to command without a version." else let helpCmd := .mk (parent := cmd) (name := "version") (version? := none) (description := "Prints the version.") (run := fun _ => do cmd.toFullCmdWithoutExtensions.printVersion! return 0) cmd.update (subCmds := cmd.subCmds.push helpCmd) } /-- Sets default values for flags that were not set by the user according to `defaults := #[(long flag name, default value), ...]` and denotes the default value in the flag description of the help. Panics if one of the designated long flag names cannot be found in the command. -/ def defaultValues! (defaults : Array (String × String)) : Extension := let findDefaultFlags cmd := defaults.map <| fun (longName, defaultValue) => ⟨cmd.flag! longName, defaultValue⟩ { extend := fun cmd => let defaultFlags := findDefaultFlags cmd let newMetaFlags := cmd.flags.map fun flag => if let some defaultFlag := defaultFlags.find? (·.flag.longName = flag.longName) then { flag with description := flag.description ++ s!" [Default: `{defaultFlag.value}`]" } else flag cmd.update (flags := newMetaFlags) postprocess := fun cmd parsed => let defaultFlags := findDefaultFlags cmd return { parsed with flags := Array.leftUnionBy (·.flag.longName) parsed.flags defaultFlags } } /-- Errors if one of `requiredFlags := #[long flag name, ...]` were not passed by the user. Denotes that the flag is required in the flag description of the help. Panics if one of the designated long flag names cannot be found in the command. -/ def require! (requiredFlags : Array String) : Extension := let findRequiredFlags cmd := requiredFlags.map (cmd.flag! ·) { extend := fun cmd => let requiredFlags := findRequiredFlags cmd let newMetaFlags := cmd.flags.map fun flag => if requiredFlags.find? (·.longName = flag.longName) |>.isSome then { flag with description := "[Required] " ++ flag.description } else flag cmd.update (flags := newMetaFlags) postprocess := fun cmd parsed => do if parsed.hasFlag "help" ∨ parsed.hasFlag "version" then return parsed let requiredFlags := findRequiredFlags cmd let missingFlags := Array.diffBy (·.longName) requiredFlags <| parsed.flags.map (·.flag.longName) if let some missingFlag ← pure <| missingFlags[0]? then throw s!"Missing required flag `--{missingFlag.longName}`." return parsed } end Extensions end Cli
.lake/packages/Cli/Cli/Basic.lean
module public import Std.Data.TreeSet public section namespace Cli section Utils /-- Matches the lengths of lists `a` and `b` by filling the shorter one with `unit` elements at the tail end. The matched lists are returned in the same order as they were passed. -/ def List.matchLength (a : List α) (b : List α) (unit : α) : List α × List α := if a.length < b.length then (a ++ .replicate (b.length - a.length) unit, b) else (a, b ++ .replicate (a.length - b.length) unit) namespace String /-- Inserts newlines `\n` into `s` after every `maxWidth` characters so that the result contains no line longer than `maxWidth` characters. Retains newlines `\n` in `s`. Yields `none` if `maxWidth = 0`. -/ def wrapAt? (s : String) (maxWidth : Nat) : Option String := Id.run do if maxWidth = 0 then return none let lines := s.splitOn "\n" |>.map fun line => Id.run do let resultLineCount := if line.length % maxWidth = 0 then line.length / maxWidth else line.length / maxWidth + 1 let mut line := line let mut result := #[] for _ in [:resultLineCount] do result := result.push <| line.take maxWidth line := line.drop maxWidth return "\n".intercalate result.toList return "\n".intercalate lines /-- Inserts newlines `\n` into `s` after every `maxWidth` characters so that the result contains no line longer than `maxWidth` characters. Retains newlines `\n` in `s`. Panics if `maxWidth = 0`. -/ def wrapAt! (s : String) (maxWidth : Nat) : String := wrapAt? s maxWidth |>.get! /-- Deletes all trailing spaces at the end of every line, as seperated by `\n`. -/ def trimTrailingSpaces (s : String) : String := s.splitOn "\n" |>.map (·.dropRightWhile (· = ' ')) |> "\n".intercalate /-- Inserts newlines `\n` into `s` after every `maxWidth` characters before words that would otherwise be broken apart by the newline. The result will contain no line longer than `maxWidth` characters and no words except those already longer than `maxWidth` characters will be broken up in the middle. Removes trailing whitespace before each inserted newline. Retains newlines `\n` in `s`. Returns `none` if `maxWidth = 0`. -/ def wrapWordsAt? (s : String) (maxWidth : Nat) : Option String := Id.run do if maxWidth = 0 then return none let wordWrappedLines : List String := s.splitOn "\n" |>.map fun s => Id.run do let words : Array String := s.splitOn.toArray let mut currentLineWidth : Nat := 0 let mut result : Array String := #[] for i in [:words.size] do let w := words[i]! -- `w = ""`: we will never insert a newline on a space. this has the effect -- of inserting the newline only after a bunch of trailing whitespace, which we remove later. -- similarly, `currentLineWidth + w.length ≤ maxWidth` does not count the space after `w` so that -- we do not insert a newline before a word that fits except for a trailing space. if w = "" ∨ currentLineWidth + w.length ≤ maxWidth then -- `+ 1` because we count the space after `w` to accurately keep track of spaces. currentLineWidth := currentLineWidth + w.length + 1 result := result.push w continue -- if `w` is the first proper word, this will insert a `\n` before the text, which we remove later. -- `w.wrapAt! maxWidth` ensures that our new line is not already too large. let wordOnNewLine := "\n" ++ wrapAt! w maxWidth result := result.push wordOnNewLine let wrappedLines : Array String := wordOnNewLine.splitOn "\n" |>.toArray currentLineWidth := wrappedLines[wrappedLines.size - 1]!.length + 1 return " ".intercalate result.toList let trimmed : List String := wordWrappedLines.map trimTrailingSpaces |>.map fun line => Id.run do if line = "" then return "" if String.Pos.Raw.get! line 0 ≠ '\n' then return line return line.drop 1 return "\n".intercalate trimmed /-- Inserts newlines `\n` into `s` after every `maxWidth` characters before words that would otherwise be broken apart by the newline. The result will contain no line longer than `maxWidth` characters and no words except those already longer than `maxWidth` characters will be broken up in the middle. Removes trailing whitespace before each inserted newline. Retains newlines `\n` in `s`. Panics if `maxWidth = 0`. -/ def wrapWordsAt! (s : String) (maxWidth : Nat) : String := wrapWordsAt? s maxWidth |>.get! /-- Inserts `n` spaces before each line as seperated by `\n` in `s`. Does not indent `s = ""`. -/ def indent (s : String) (n : Nat := 4) : String := Id.run do if s = "" then return "" return s.splitOn "\n" |>.map ("".pushn ' ' n ++ ·) |> "\n".intercalate /-- Intercalates elements `≠ ""` in `xs` using `sep`. -/ def optJoin (xs : Array String) (sep : String) : String := xs.filter (· ≠ "") |>.toList |> sep.intercalate end String namespace Array /-- Renders `rows` as a table with a maximum row width of `maxWidth` and a margin of `margin` between the columns. Wraps words according to `String.wrapWordsAt?` to ensure that no rendered row of the table is longer than `maxWidth`. Returns `none` if `(maxWidth-margin)/2` < 1, i.e. if there is not enough space for text in both columns. -/ def renderTable? (rows : Array (String × String)) (maxWidth : Nat) (margin : Nat := 2) : Option String := Id.run do if rows.isEmpty then return "" let rightColumnWidth := rows.map (·.2.length) |>.getMax? (· < ·) |>.get! let minRightColumnWidth := Nat.min rightColumnWidth <| Nat.max ((maxWidth-margin)/2) 1 if maxWidth - margin - minRightColumnWidth < 1 then return none let rows : Array (List String × String) := rows.map fun (left, right) => (maxWidth - margin - minRightColumnWidth |> String.wrapWordsAt! left |>.splitOn "\n", right) let leftColumnWidth := rows.flatMap (·.1.map (·.length) |>.toArray) |>.getMax? (· < ·) |>.get! let leftColumnWidth := leftColumnWidth + margin let rows : Array (List String × List String) := rows.map fun (left, right) => (left, maxWidth - leftColumnWidth |> String.wrapWordsAt! right |>.splitOn "\n") let rows : Array (String × String) := rows.flatMap fun (left, right) => let (left, right) : List String × List String := List.matchLength left right "" left.zip right |>.toArray let rows : Array String := rows.map fun (left, right) => if right = "" then left else let padding := "".pushn ' ' (leftColumnWidth - left.length) left ++ padding ++ right return "\n".intercalate rows.toList /-- Renders `rows` as a table with a maximum row width of `maxWidth` and a margin of `margin` between the columns. Wraps words according to `String.wrapWordsAt?` to ensure that no rendered row of the table is longer than `maxWidth`. Panics if `(maxWidth-margin)/2` < 1, i.e. if there is not enough space for text in both columns. -/ def renderTable! (rows : Array (String × String)) (maxWidth : Nat) (margin : Nat := 2) : String := renderTable? rows maxWidth margin |>.get! end Array namespace Option /-- Returns `""` if the passed `Option` is `none`, otherwise converts the contained value using a `ToString` instance. -/ def optStr [ToString α] : Option α → String | none => "" | some v => toString v end Option end Utils section Configuration /-- Represents a type that can be parsed to a string and the corresponding name of the type. Used for converting parsed user input to the respective expected type. -/ class ParseableType (τ) where /-- Name of the type, used when displaying the help. -/ name : String /-- Function to parse a value to the type that returns `none` if it cannot be parsed. -/ parse? : String → Option τ instance : ParseableType Unit where name := "Unit" parse? _ := () instance : ParseableType Bool where name := "Bool" parse? | "true" => true | "false" => false | _ => none instance : ParseableType String where name := "String" parse? s := s instance : ParseableType Nat where name := "Nat" parse? -- HACK: temporary workaround for minor bug in String.toNat? | "" => none | s => s.toNat? instance : ParseableType Int where name := "Int" parse? -- HACK: temporary workaround for minor bug in String.toInt? | "" => none | s => s.toInt? /-- A type synonym for `Name`, which will carry a `ParseableType ModuleName` instance, supporting parsing either a module name (e.g. `Mathlib.Topology.Basic`) or a relative path to a Lean file (e.g. `Mathlib/Topology/Basic.lean`). -/ @[expose] def ModuleName := Lean.Name deriving Inhabited, BEq, Repr, ToString /-- Check that a `ModuleName` has no `.num` or empty components, and is not `.anonymous`. -/ def ModuleName.isValid : ModuleName → Bool | .anonymous => false | m => loop m true where loop : ModuleName → Bool → Bool | .anonymous, allValid => allValid | .str pre s, allValid => loop pre <| allValid ∧ ¬s.isEmpty | .num .., _ => false open Lean System in /-- A custom command-line argument parser that allows either relative paths to Lean files, (e.g. `Mathlib/Topology/Basic.lean`) or the module name (e.g. `Mathlib.Topology.Basic`). -/ instance : ParseableType ModuleName where name := "ModuleName" parse? s := do if s == ".lean" then none let name := if s.endsWith ".lean" then let pathComponents := (s : FilePath).withExtension "" |>.components pathComponents.foldl .mkStr .anonymous else s.toName guard <| ModuleName.isValid name return name instance [inst : ParseableType α] : ParseableType (Array α) where name := if inst.name.contains ' ' then s!"Array ({inst.name})" else s!"Array {inst.name}" parse? | "" => some #[] | s => do return (← s.splitOn "," |>.mapM inst.parse?).toArray /-- Represents the type of some flag or argument parameter. Typically coerced from types with `ParseableType` instances such that `isValid := (ParseableType.parse? · |>.isSome)`. -/ structure ParamType where /-- Name of the type, used when displaying the help. -/ name : String /-- Function to check whether a value conforms to the type. -/ isValid : String → Bool deriving Inhabited instance : BEq ParamType where beq a b := a.name == b.name instance : Repr ParamType where reprPrec p _ := p.name instance [inst : ParseableType τ] : CoeDep Type τ ParamType where coe := ⟨inst.name, (inst.parse? · |>.isSome)⟩ /-- Represents a flag, usually known as "option" in standard terminology. -/ structure Flag where /-- Designates `x` in `-x`. -/ shortName? : Option String := none /-- Designates `x` in `--x`. -/ longName : String /-- Description that is displayed in the help. -/ description : String /-- Type according to which the parameter is validated. `Unit` is used to designate flags without a parameter. -/ type : ParamType deriving Inhabited, BEq, Repr namespace Flag /-- Initializes a flag without a parameter. Parameterless flags are designated by the `Unit` type. - `shortName?`: Designates `x` in `-x`. - `longName`: Designates `x` in `--x`. - `description`: Description that is displayed in the help. -/ def paramless (shortName? : Option String := none) (longName : String) (description : String) : Flag := { shortName? := shortName? longName := longName description := description type := Unit } /-- Designates `x` in `-x`. -/ def shortName! (f : Flag) : String := f.shortName?.get! /-- Checks whether `f` has an associated short flag name `x` in `-x`. -/ def hasShortName (f : Flag) : Bool := f.shortName?.isSome /-- Checks whether `f` has a `Unit` type. -/ def isParamless (f : Flag) : Bool := f.type == Unit end Flag /-- Represents an argument (either positional or variable), usually known as "operand" in standard terminology -/ structure Arg where /- Name that is displayed in the help. -/ name : String /- Description that is displayed in the help. -/ description : String /- Description that is displayed in the help. -/ type : ParamType deriving Inhabited, BEq, Repr namespace Parsed /-- Represents a flag and its parsed value. Use `Parsed.Flag.as!` to convert the value to some `ParseableType`. -/ structure Flag where /-- Associated flag meta-data. -/ flag : Cli.Flag /-- Parsed value that was validated and conforms to `flag.type`. -/ value : String deriving Inhabited, BEq, Repr instance : ToString Flag where toString f := s!"--{f.flag.longName}" ++ (if f.value ≠ "" then s!"={f.value}" else "") namespace Flag /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as? (f : Flag) (τ) [ParseableType τ] : Option τ := ParseableType.parse? f.value /-- Converts `f.value` to `τ`, which should be the same type that was designated in `f.flag.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `f.flag.type`. -/ def as! (f : Flag) (τ) [Inhabited τ] [ParseableType τ] : τ := f.as? τ |>.get! end Flag /-- Represents an argument and its parsed value. Use `Parsed.Arg.as!` to convert the value to some `ParseableType`. -/ structure Arg where /-- Associated argument meta-data. -/ arg : Cli.Arg /-- Parsed value that was validated and conforms to `arg.type`. -/ value : String deriving Inhabited, BEq, Repr instance : ToString Arg where toString a := s!"<{a.arg.name}={a.value}>" namespace Arg /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as? (a : Arg) (τ) [ParseableType τ] : Option τ := ParseableType.parse? a.value /-- Converts `a.value` to `τ`, which should be the same type that was designated in `a.arg.type`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in `a.arg.type`. -/ def as! (a : Arg) (τ) [Inhabited τ] [ParseableType τ] : τ := a.as? τ |>.get! end Arg end Parsed /-- Represents all the non-recursive meta-data of a command. -/ structure Cmd.Meta where /-- Name that is displayed in the help. -/ name : String /-- Names of the commands of which this command is a subcommand. Corresponds to the path from the root to this command. -/ parentNames : Array String /-- Version of the command that is displayed in the help and when the version is queried. -/ version? : Option String /-- Description that is displayed in the help. -/ description : String /-- Information appended to the end of the help. Useful for command extensions. -/ furtherInformation? : Option String := none /-- Supported flags ("options" in standard terminology). -/ flags : Array Flag /-- Supported positional arguments ("operands" in standard terminology). -/ positionalArgs : Array Arg /-- Variable argument after the end of the positional arguments. -/ variableArg? : Option Arg deriving Inhabited, BEq, Repr namespace Cmd.Meta /-- Full name from the root to this command, including the name of the command itself. -/ def fullName (m : Meta) : String := m.parentNames.push m.name |>.toList |> " ".intercalate /-- Version of the command that is displayed in the help and when the version is queried. -/ def version! (m : Meta) : String := m.version?.get! /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation! (m : Meta) : String := m.furtherInformation?.get! /-- Variable argument after the end of the positional arguments. -/ def variableArg! (m : Meta) : Arg := m.variableArg?.get! /-- Checks whether `m` has a version. -/ def hasVersion (m : Meta) : Bool := m.version?.isSome /-- Checks whether `m` has information appended to the end of the help. -/ def hasFurtherInformation (m : Meta) : Bool := m.furtherInformation?.isSome /-- Checks whether `m` supports a variable argument. -/ def hasVariableArg (m : Meta) : Bool := m.variableArg?.isSome /-- Finds the flag in `m` with the corresponding `longName`. -/ def flag? (m : Meta) (longName : String) : Option Flag := m.flags.find? (·.longName = longName) /-- Finds the positional argument in `m` with the corresponding `name`. -/ def positionalArg? (m : Meta) (name : String) : Option Arg := m.positionalArgs.find? (·.name = name) /-- Finds the flag in `m` with the corresponding `longName`. -/ def flag! (m : Meta) (longName : String) : Flag := m.flag? longName |>.get! /-- Finds the positional argument in `m` with the corresponding `name`. -/ def positionalArg! (m : Meta) (name : String) : Arg := m.positionalArg? name |>.get! /-- Checks whether `m` contains a flag with the corresponding `longName`. -/ def hasFlag (m : Meta) (longName : String) : Bool := m.flag? longName |>.isSome /-- Checks whether `m` contains a positional argument with the corresponding `name`. -/ def hasPositionalArg (m : Meta) (name : String) : Bool := m.positionalArg? name |>.isSome /-- Finds the flag in `m` with the corresponding `shortName`. -/ def flagByShortName? (m : Meta) (name : String) : Option Flag := m.flags.findSome? fun flag => do let shortName ← flag.shortName? guard <| shortName = name return flag /-- Finds the flag in `m` with the corresponding `shortName`. -/ def flagByShortName! (m : Meta) (name : String) : Flag := m.flagByShortName? name |>.get! /-- Checks whether `m` has a flag with the corresponding `shortName`. -/ def hasFlagByShortName (m : Meta) (name : String) : Bool := m.flagByShortName? name |>.isSome /-- Adds help (`-h, --help`) and version (`--version`) flags to `m`. Does not add a version flag if `m` does not designate a version. -/ def addHelpAndVersionFlags (m : Meta) : Meta := Id.run do let helpFlag := .paramless (shortName? := "h") (longName := "help") (description := "Prints this message.") let mut fixedFlags := #[helpFlag] if m.hasVersion then let versionFlag := .paramless (longName := "version") (description := "Prints the version.") fixedFlags := fixedFlags.push versionFlag { m with flags := fixedFlags ++ m.flags } end Cmd.Meta /-- Represents a recursive variant of `Cmd.Meta` that is used in `Parsed` to replicate the recursive subcommand structure of a command without referring to the command itself. -/ inductive Parsed.Cmd | init («meta» : Cmd.Meta) (subCmds : Array Parsed.Cmd) deriving Inhabited namespace Parsed.Cmd /-- Meta of this command. -/ def «meta» : Parsed.Cmd → Cmd.Meta | init v _ => v /-- Subcommands. -/ def subCmds : Parsed.Cmd → Array Parsed.Cmd | init _ v => v /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd? (c : Parsed.Cmd) (name : String) : Option Parsed.Cmd := c.subCmds.find? (·.meta.name = name) /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd! (c : Parsed.Cmd) (name : String) : Parsed.Cmd := c.subCmd? name |>.get! /-- Checks whether `c` contains a subcommand with the corresponding `name`. -/ def hasSubCmd (c : Parsed.Cmd) (name : String) : Bool := c.subCmd? name |>.isSome end Parsed.Cmd /-- Represents parsed user input data. -/ structure Parsed where /-- Recursive meta-data of the associated command. -/ cmd : Parsed.Cmd /-- Parent of the associated command. -/ parent? : Option Parsed.Cmd /-- Parsed flags. -/ flags : Array Parsed.Flag /-- Parsed positional arguments. -/ positionalArgs : Array Parsed.Arg /-- Parsed variable arguments. -/ variableArgs : Array Parsed.Arg deriving Inhabited namespace Parsed /-- Parent of the associated command. -/ def parent! (p : Parsed) : Parsed.Cmd := p.parent?.get! /-- Checks whether the associated command has a parent, i.e. whether it is not the root command. -/ def hasParent (p : Parsed) : Bool := p.parent?.isSome /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag? (p : Parsed) (longName : String) : Option Flag := p.flags.find? (·.flag.longName = longName) /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg? (p : Parsed) (name : String) : Option Arg := p.positionalArgs.find? (·.arg.name = name) /-- Finds the parsed flag in `p` with the corresponding `longName`. -/ def flag! (p : Parsed) (longName : String) : Flag := p.flag? longName |>.get! /-- Finds the parsed positional argument in `p` with the corresponding `name`. -/ def positionalArg! (p : Parsed) (name : String) : Arg := p.positionalArg? name |>.get! /-- Checks whether `p` has a parsed flag with the corresponding `longName`. -/ def hasFlag (p : Parsed) (longName : String) : Bool := p.flag? longName |>.isSome /-- Checks whether `p` has a positional argument with the corresponding `longName`. -/ def hasPositionalArg (p : Parsed) (name : String) : Bool := p.positionalArg? name |>.isSome /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Yields `none` if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs? (p : Parsed) (τ) [ParseableType τ] : Option (Array τ) := p.variableArgs.mapM (·.as? τ) /-- Converts all `p.variableArgs` values to `τ`, which should be the same type that was designated in the corresponding `Cli.Arg`. Panics if the conversion was unsuccessful, which can only happen if `τ` is not the same type as the one designated in the corresponding `Cli.Arg`. -/ def variableArgsAs! (p : Parsed) (τ) [Inhabited τ] [ParseableType τ] : Array τ := p.variableArgsAs? τ |>.get! instance : ToString Parsed where toString p := s!"cmd: {p.cmd.meta.fullName}; flags: {toString p.flags}; positionalArgs: {toString p.positionalArgs}; " ++ s!"variableArgs: {toString p.variableArgs}" end Parsed open Cmd in /-- Represents a view of `Cmd` that can be passed to `Extension`s, i.e. it does not itself reference the `Extension` provided for each `Cmd`. -/ inductive ExtendableCmd | init («meta» : Meta) (run : Parsed → IO UInt32) (subCmds : Array ExtendableCmd) (originalFullName? : Option String) deriving Inhabited namespace ExtendableCmd /-- Non-recursive meta-data. -/ def «meta» : ExtendableCmd → Cmd.Meta | init v _ _ _ => v /-- Handler to run when the command is called and flags/arguments have been successfully processed. -/ def run : ExtendableCmd → (Parsed → IO UInt32) | init _ v _ _ => v /-- Subcommands. May be mutated by extensions. -/ def subCmds : ExtendableCmd → Array ExtendableCmd | init _ _ v _ => v private def originalFullName? : ExtendableCmd → Option String | init _ _ _ v => v /-- Updates the designated fields in `c`. - `«meta»`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def update' (c : ExtendableCmd) («meta» : Cmd.Meta := c.meta) (run : Parsed → IO UInt32 := c.run) (subCmds : Array ExtendableCmd := c.subCmds) : ExtendableCmd := .init «meta» run subCmds c.originalFullName? /-- Updates the designated fields in `c`. - `name`: Name that is displayed in the help. - `version?`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def update (c : ExtendableCmd) (name : String := c.meta.name) (version? : Option String := c.meta.version?) (description : String := c.meta.description) (furtherInformation? : Option String := c.meta.furtherInformation?) (flags : Array Flag := c.meta.flags) (positionalArgs : Array Arg := c.meta.positionalArgs) (variableArg? : Option Arg := c.meta.variableArg?) (run : Parsed → IO UInt32 := c.run) (subCmds : Array ExtendableCmd := c.subCmds) : ExtendableCmd := .init ⟨name, c.meta.parentNames, version?, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds c.originalFullName? /-- Creates a new `ExtendableCmd`. The resulting `ExtendableCmd` will not have an extension. - `«meta»`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def mk' («meta» : Cmd.Meta) (run : Parsed → IO UInt32) (subCmds : Array ExtendableCmd := #[]) : ExtendableCmd := .init «meta» run subCmds none /-- Creates a new `ExtendableCmd`. The resulting `ExtendableCmd` will not have an extension. Adds a `-h, --help` and a `--version` flag if `«meta»` designates a version. - `«meta»`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def mkWithHelpAndVersionFlags' («meta» : Cmd.Meta) (run : Parsed → IO UInt32) (subCmds : Array ExtendableCmd := #[]) : ExtendableCmd := .mk' meta.addHelpAndVersionFlags run subCmds /-- Creates a new `ExtendableCmd`. The resulting `ExtendableCmd` will not have an extension. - `parent`: Parent of this command. - `name`: Name that is displayed in the help. - `version?`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def mk (parent : ExtendableCmd) (name : String) (version? : Option String) (description : String) (furtherInformation? : Option String := none) (flags : Array Flag := #[]) (positionalArgs : Array Arg := #[]) (variableArg? : Option Arg := none) (run : Parsed → IO UInt32) (subCmds : Array ExtendableCmd := #[]) : ExtendableCmd := .mk' ⟨name, parent.meta.parentNames.push parent.meta.name, version?, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds /-- Creates a new `ExtendableCmd`. The resulting `ExtendableCmd` will not have an extension. Adds a `-h, --help` and a `--version` flag if `version?` is present. - `parent`: Parent of this command. - `name`: Name that is displayed in the help. - `version?`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. -/ def mkWithHelpAndVersionFlags (parent : ExtendableCmd) (name : String) (version? : Option String) (description : String) (furtherInformation? : Option String := none) (flags : Array Flag := #[]) (positionalArgs : Array Arg := #[]) (variableArg? : Option Arg := none) (run : Parsed → IO UInt32) (subCmds : Array ExtendableCmd := #[]) : ExtendableCmd := .mkWithHelpAndVersionFlags' ⟨name, parent.meta.parentNames.push parent.meta.name, version?, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds /-- Name that is displayed in the help. -/ def name (c : ExtendableCmd) : String := c.meta.name /-- Version of the command that is displayed in the help and when the version is queried. -/ def version? (c : ExtendableCmd) : Option String := c.meta.version? /-- Description that is displayed in the help. -/ def description (c : ExtendableCmd) : String := c.meta.description /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation? (c : ExtendableCmd) : Option String := c.meta.furtherInformation? /-- Supported flags ("options" in standard terminology). -/ def flags (c : ExtendableCmd) : Array Flag := c.meta.flags /-- Supported positional arguments ("operands" in standard terminology). -/ def positionalArgs (c : ExtendableCmd) : Array Arg := c.meta.positionalArgs /-- Variable argument after the end of the positional arguments. -/ def variableArg? (c : ExtendableCmd) : Option Arg := c.meta.variableArg? /-- Full name from the root to this command, including the name of the command itself. -/ def fullName (c : ExtendableCmd) : String := c.meta.fullName /-- Version of the command that is displayed in the help and when the version is queried. -/ def version! (c : ExtendableCmd) : String := c.meta.version! /-- Information appended to the end of the help. Useful for command extensions. -/ def furtherInformation! (c : ExtendableCmd) : String := c.meta.furtherInformation! /-- Variable argument after the end of the positional arguments. -/ def variableArg! (c : ExtendableCmd) : Arg := c.meta.variableArg! /-- Checks whether `c` has a version. -/ def hasVersion (c : ExtendableCmd) : Bool := c.meta.hasVersion /-- Checks whether `c` has information appended to the end of the help. -/ def hasFurtherInformation (c : ExtendableCmd) : Bool := c.meta.hasFurtherInformation /-- Checks whether `c` supports a variable argument. -/ def hasVariableArg (c : ExtendableCmd) : Bool := c.meta.hasVariableArg /-- Finds the flag in `c` with the corresponding `longName`. -/ def flag? (c : ExtendableCmd) (longName : String) : Option Flag := c.meta.flag? longName /-- Finds the positional argument in `c` with the corresponding `name`. -/ def positionalArg? (c : ExtendableCmd) (name : String) : Option Arg := c.meta.positionalArg? name /-- Finds the flag in `c` with the corresponding `longName`. -/ def flag! (c : ExtendableCmd) (longName : String) : Flag := c.meta.flag! longName /-- Finds the positional argument in `c` with the corresponding `name`. -/ def positionalArg! (c : ExtendableCmd) (name : String) : Arg := c.meta.positionalArg! name /-- Checks whether `c` contains a flag with the corresponding `longName`. -/ def hasFlag (c : ExtendableCmd) (longName : String) : Bool := c.meta.hasFlag longName /-- Checks whether `c` contains a positional argument with the corresponding `name`. -/ def hasPositionalArg (c : ExtendableCmd) (name : String) : Bool := c.meta.hasPositionalArg name /-- Finds the flag in `c` with the corresponding `shortName`. -/ def flagByShortName? (c : ExtendableCmd) (name : String) : Option Flag := c.meta.flagByShortName? name /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd? (c : ExtendableCmd) (name : String) : Option ExtendableCmd := c.subCmds.find? (·.meta.name = name) /-- Finds the flag in `c` with the corresponding `shortName`. -/ def flagByShortName! (c : ExtendableCmd) (name : String) : Flag := c.meta.flagByShortName! name /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd! (c : ExtendableCmd) (name : String) : ExtendableCmd := c.subCmd? name |>.get! /-- Checks whether `c` has a flag with the corresponding `shortName`. -/ def hasFlagByShortName (c : ExtendableCmd) (name : String) : Bool := c.meta.hasFlagByShortName name /-- Checks whether `c` contains a subcommand with the corresponding `name`. -/ def hasSubCmd (c : ExtendableCmd) (name : String) : Bool := c.subCmd? name |>.isSome end ExtendableCmd /-- Allows user code to extend the library in two ways: - A command can be replaced or extended with new components. - The output of the parser can be postprocessed and validated. -/ structure Extension where /-- Priority that dictates how early an extension is applied. The lower the priority, the later it is applied. -/ priority : Nat := 1024 /-- Extends a command to adjust the displayed help. The recursive subcommand structure may be mutated. -/ extend : ExtendableCmd → ExtendableCmd := id /-- Processes and validates the output of the parser for the given `ExtendableCmd`. Takes the `ExtendableCmd` that results from all extensions being applied. If postprocessing mutates the subcommand structure in `Parsed.cmd`, care must be taken to update `Parsed.parent?` accordingly as well. -/ postprocess : ExtendableCmd → Parsed → Except String Parsed := fun _ => pure deriving Inhabited /-- Composes both extensions so that the `Cmd`s are extended in succession and postprocessed in succession. Postprocessing errors if any of the two `postprocess` functions errors. -/ def Extension.then (a : Extension) (b : Extension) : Extension := { extend := b.extend ∘ a.extend postprocess := fun cmd parsed => do b.postprocess cmd <| ← a.postprocess cmd parsed } open Cmd in /-- Represents a command, i.e. either the application root or some subcommand of the root. -/ inductive Cmd | init («meta» : Meta) (run : Parsed → IO UInt32) (subCmds : Array Cmd) (extension? : Option Extension) deriving Inhabited namespace Cmd /-- Non-recursive meta-data. -/ def «meta» : Cmd → Cmd.Meta | init v _ _ _ => v /-- Handler to run when the command is called and flags/arguments have been successfully processed. -/ def run : Cmd → (Parsed → IO UInt32) | init _ v _ _ => v /-- Subcommands. -/ def subCmds : Cmd → Array Cmd | init _ _ v _ => v /-- Extension of the Cli library. -/ def extension? : Cmd → Option Extension | init _ _ _ v => v private def update (c : Cmd) («meta» : Meta := c.meta) (run : Parsed → IO UInt32 := c.run) (subCmds : Array Cmd := c.subCmds) (extension? : Option Extension := c.extension?) : Cmd := .init «meta» run subCmds extension? /-- Recomputes all the parent names of subcommands in `c` with `c` as the root command. -/ partial def updateParentNames (c : Cmd) : Cmd := loop c #[] where loop (c : Cmd) (parentNames : Array String) : Cmd := let subCmdParentNames := parentNames.push c.meta.name let subCmds := c.subCmds.map (loop · subCmdParentNames) .init { c.meta with parentNames := parentNames } c.run subCmds c.extension? /-- Creates a new command. Adds a `-h, --help` and a `--version` flag if `«meta»` designates a version. Updates the `parentNames` of all subcommands. - `«meta»`: Non-recursive meta-data. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ partial def mk' («meta» : Meta) (run : Parsed → IO UInt32) (subCmds : Array Cmd := #[]) (extension? : Option Extension := none) : Cmd := let «meta» := meta.addHelpAndVersionFlags let c := .init «meta» run subCmds extension? updateParentNames c /-- Creates a new command. Adds a `-h, --help` and a `--version` flag if a version is designated. Updates the `parentNames` of all subcommands. - `name`: Name that is displayed in the help. - `version?`: Version that is displayed in the help and when the version is queried. - `description`: Description that is displayed in the help. - `furtherInformation?`: Information appended to the end of the help. Useful for command extensions. - `flags`: Supported flags ("options" in standard terminology). - `positionalArgs`: Supported positional arguments ("operands" in standard terminology). - `variableArg?`: Variable argument at the end of the positional arguments. - `run`: Handler to run when the command is called and flags/arguments have been successfully processed. - `subCmds`: Subcommands. - `extension?`: Extension of the Cli library. -/ def mk (name : String) (version? : Option String) (description : String) (furtherInformation? : Option String := none) (flags : Array Flag := #[]) (positionalArgs : Array Arg := #[]) (variableArg? : Option Arg := none) (run : Parsed → IO UInt32) (subCmds : Array Cmd := #[]) (extension? : Option Extension := none) : Cmd := mk' ⟨name, #[], version?, description, furtherInformation?, flags, positionalArgs, variableArg?⟩ run subCmds extension? /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd? (c : Cmd) (name : String) : Option Cmd := c.subCmds.find? (·.meta.name = name) /-- Extension of the Cli library. -/ def extension! (c : Cmd) : Extension := c.extension?.get! /-- Finds the subcommand in `c` with the corresponding `name`. -/ def subCmd! (c : Cmd) (name : String) : Cmd := c.subCmd? name |>.get! /-- Checks whether `c` contains a subcommand with the corresponding `name`. -/ def hasSubCmd (c : Cmd) (name : String) : Bool := c.subCmd? name |>.isSome /-- Checks whether `c` is being extended. -/ def hasExtension (c : Cmd) : Bool := c.extension?.isSome end Cmd namespace Parsed namespace Cmd /-- Extracts `«meta»` and the recursive subcommand structure from `c` to create a `Parsed.Cmd`. -/ partial def ofFullCmd (c : Cli.Cmd) : Cmd := .init c.meta (c.subCmds.map ofFullCmd) /-- Embeds `c` into a `Cli.Cmd` that does nothing. -/ partial def toFullCmd (c : Cmd) : Cli.Cmd := let «meta» := c.meta let run := fun _ => pure 0 let subCmds := c.subCmds.map toFullCmd let extension? := { : Extension } .init «meta» run subCmds extension? end Cmd /-- Embeds `p.cmd` into a `Cli.Cmd` that does nothing. -/ def toCmd (p : Parsed) : Cli.Cmd := p.cmd.toFullCmd end Parsed namespace ExtendableCmd /-- Creates a view of `c` that can be extended by extensions. -/ partial def ofFullCmd (c : Cli.Cmd) : ExtendableCmd := .init c.meta c.run (c.subCmds.map ofFullCmd) c.meta.fullName /-- Converts `c` back into a `Cli.Cmd`, using the extensions denoted in `original`. -/ partial def toFullCmd (c : ExtendableCmd) (original : Cli.Cmd) : Cli.Cmd := Id.run do let extensions := collectExtensions original let mut extensionIndex : Std.TreeMap String (Option Extension) := ∅ for ⟨fullName, extension?⟩ in extensions do extensionIndex := extensionIndex.insert fullName extension? let rec loop (c : ExtendableCmd) : Cli.Cmd := let extension? := do extensionIndex.get? (← c.originalFullName?) |> Option.join let subCmds := c.subCmds.map loop .init c.meta c.run subCmds extension? loop c |>.updateParentNames |> prependOriginalParentNames where collectExtensions (currentCmd : Cli.Cmd) : Array (String × Option Extension) := Id.run do let mut extensions := #[(currentCmd.meta.fullName, currentCmd.extension?)] for subCmd in currentCmd.subCmds do extensions := extensions ++ collectExtensions subCmd return extensions prependOriginalParentNames (currentCmd : Cli.Cmd) : Cli.Cmd := Id.run do let parentNames := original.meta.parentNames ++ currentCmd.meta.parentNames let «meta» := { currentCmd.meta with parentNames := parentNames } let subCmds := currentCmd.subCmds.map prependOriginalParentNames currentCmd.update («meta» := «meta») (subCmds := subCmds) /-- Converts `c` back into `Cli.Cmd` while retaining none of the extensions. -/ partial def toFullCmdWithoutExtensions (c : ExtendableCmd) : Cli.Cmd := Cmd.init c.meta c.run (c.subCmds.map toFullCmdWithoutExtensions) none end ExtendableCmd end Configuration section Macro open Lean syntax nameableStringArg := str <|> ident syntax literalIdent := str <|> ident syntax runFun := (" VIA " ident) <|> " NOOP" syntax positionalArg := colGe literalIdent " : " term "; " nameableStringArg syntax variableArg := colGe "..." literalIdent " : " term "; " nameableStringArg syntax flag := colGe literalIdent ("," literalIdent)? (" : " term)? "; " nameableStringArg syntax "`[Cli|\n" literalIdent runFun "; " ("[" nameableStringArg "]")? nameableStringArg ("FLAGS:\n" withPosition((flag)*))? ("ARGS:\n" withPosition((positionalArg)* (variableArg)?))? ("SUBCOMMANDS: " sepBy(ident, ";", "; "))? ("EXTENSIONS: " sepBy(term, ";", "; "))? "\n]" : term meta def expandNameableStringArg (t : TSyntax `Cli.nameableStringArg) : MacroM Term := pure ⟨t.raw[0]⟩ meta def expandLiteralIdent (t : TSyntax `Cli.literalIdent) : MacroM Term := let s := t.raw[0] if s.getKind == identKind then pure <| quote s.getId.toString else pure ⟨s⟩ meta def expandRunFun (runFun : TSyntax `Cli.runFun) : MacroM Term := match runFun with | `(Cli.runFun| VIA $run) => `($run) | `(Cli.runFun| NOOP) => `(fun _ => pure 0) | _ => Macro.throwUnsupported meta def expandPositionalArg (positionalArg : TSyntax `Cli.positionalArg) : MacroM Term := do let `(Cli.positionalArg| $name : $type; $description) := positionalArg | Macro.throwUnsupported `(Arg.mk $(← expandLiteralIdent name) $(← expandNameableStringArg description) $type) meta def expandVariableArg (variableArg : TSyntax `Cli.variableArg) : MacroM Term := do let `(Cli.variableArg| ...$name : $type; $description) := variableArg | Macro.throwUnsupported `(Arg.mk $(← expandLiteralIdent name) $(← expandNameableStringArg description) $type) meta def expandFlag (flag : TSyntax `Cli.flag) : MacroM Term := do let `(Cli.flag| $flagName1 $[, $flagName2]? $[ : $type]?; $description) := flag | Macro.throwUnsupported let mut shortName := quote (none : Option String) let mut longName := flagName1 if let some flagName2 := flagName2 then shortName ← `(some $(← expandLiteralIdent flagName1)) longName := flagName2 let unitType : Term ← `(Unit) let type := match type with | none => unitType | some type => type `(Flag.mk $shortName $(← expandLiteralIdent longName) $(← expandNameableStringArg description) $type) macro_rules | `(`[Cli| $name $run:runFun; $[[$version?]]? $description $[FLAGS: $flags* ]? $[ARGS: $positionalArgs* $[$variableArg]? ]? $[SUBCOMMANDS: $subCommands;*]? $[EXTENSIONS: $extensions;*]? ]) => do `(Cmd.mk (name := $(← expandLiteralIdent name)) (version? := $(quote (← version?.mapM expandNameableStringArg))) (description := $(← expandNameableStringArg description)) (flags := $(quote (← flags.getD #[] |>.mapM expandFlag))) (positionalArgs := $(quote (← positionalArgs.getD #[] |>.mapM expandPositionalArg))) (variableArg? := $(quote (← (Option.join variableArg).mapM expandVariableArg))) (run := $(← expandRunFun run)) (subCmds := $(quote ((subCommands.getD ⟨#[]⟩).getElems : TSyntaxArray `term))) (extension? := some <| Array.foldl Extension.then { : Extension } <| Array.qsort $(quote (extensions.getD ⟨#[]⟩).getElems) (·.priority > ·.priority))) end Macro section Info open Cli.String open Cli.Option /-- Maximum width within which all formatted text should fit. -/ def maxWidth : Nat := 80 /-- Amount of spaces with which section content is indented. -/ def indentation : Nat := 4 /-- Maximum width within which all formatted text should fit, after indentation. -/ def maxIndentedWidth : Nat := maxWidth - indentation /-- Formats `xs` by `String.optJoin`ing the components with a single space. -/ def line (xs : Array String) : String := optJoin xs " " /-- Formats `xs` by `String.optJoin`ing the components with a newline `\n`. -/ def lines (xs : Array String) : String := optJoin xs "\n" /-- Renders a help section with the designated `title` and `content`. If `content = ""`, `emptyContentPlaceholder?` will be used instead. If `emptyContentPlaceholder? = none`, neither the title nor the content will be rendered. -/ def renderSection (title : String) (content : String) (emptyContentPlaceholder? : Option String := none) : String := let titleLine? : Option String := do if content = "" then return s!"{title}: {← emptyContentPlaceholder?}" else return s!"{title}:" lines #[ optStr titleLine?, wrapWordsAt! content maxIndentedWidth |> indent (n := indentation) ] /-- Renders a table using `Cli.Array.renderTable!` and then renders a section with the designated `title` and the rendered table as content. -/ def renderTable (title : String) (columns : Array (String × String)) (emptyTablePlaceholder? : Option String := none) : String := let table := Array.renderTable! columns (maxWidth := maxIndentedWidth) renderSection title table emptyTablePlaceholder? namespace Cmd private def metaDataInfo (c : Cmd) : String := let version? : Option String := do return s!"[{← c.meta.version?}]" lines #[ line #[c.meta.fullName, optStr version?] |> wrapWordsAt! (maxWidth := maxWidth), wrapWordsAt! c.meta.description maxWidth ] private def usageInfo (c : Cmd) : String := let subCmdTitle? : Option String := if ¬c.subCmds.isEmpty then "[SUBCOMMAND]" else none let posArgNames : String := line <| c.meta.positionalArgs.map (s!"<{·.name}>") let varArgName? : Option String := do return s!"<{(← c.meta.variableArg?).name}>..." let info := line #[c.meta.fullName, optStr subCmdTitle?, "[FLAGS]", posArgNames, optStr varArgName?] renderSection "USAGE" info private def flagInfo (c : Cmd) : String := let columns : Array (String × String) := c.meta.flags.map fun flag => let shortName? : Option String := do return s!"-{← flag.shortName?}" let names : String := optJoin #[optStr shortName?, s!"--{flag.longName}"] ", " let type? : Option String := if ¬ flag.isParamless then s!": {flag.type.name}" else none (line #[names, optStr type?], flag.description) renderTable "FLAGS" columns (emptyTablePlaceholder? := "None") private def positionalArgInfo (c : Cmd) : String := let args := if let some variableArg := c.meta.variableArg? then c.meta.positionalArgs ++ #[variableArg] else c.meta.positionalArgs args.map (fun arg => (line #[arg.name, s!": {arg.type.name}"], arg.description)) |> renderTable "ARGS" private def subCommandInfo (c : Cmd) : String := c.subCmds.map (fun subCmd => (subCmd.meta.name, subCmd.meta.description)) |> renderTable "SUBCOMMANDS" /-- Renders the help for `c`. -/ def help (c : Cmd) : String := lines #[ c.metaDataInfo, "\n" ++ c.usageInfo, "\n" ++ c.flagInfo, (if ¬c.meta.positionalArgs.isEmpty ∨ c.meta.hasVariableArg then "\n" else "") ++ c.positionalArgInfo, (if ¬c.subCmds.isEmpty then "\n" else "") ++ c.subCommandInfo, (if c.meta.hasFurtherInformation then "\n" else "") ++ optStr c.meta.furtherInformation? ] /-- Renders an error for `c` with the designated message `msg`. -/ def error (c : Cmd) (msg : String) : String := lines #[ wrapWordsAt! msg maxWidth, wrapWordsAt! s!"Run `{c.meta.fullName} -h` for further information." maxWidth ] /-- Prints the help for `c`. -/ def printHelp (c : Cmd) : IO Unit := IO.println c.help /-- Prints an error for `c` with the designated message `msg`. -/ def printError (c : Cmd) (msg : String) : IO Unit := IO.eprintln <| c.error msg /-- Prints the version of `c`. Panics if `c` has no version. -/ def printVersion! (c : Cmd) : IO Unit := IO.println c.meta.version! end Cmd namespace Parsed /-- Renders the help for `p.cmd`. -/ def help (p : Parsed) : String := p.toCmd.help /-- Renders an error for `p.cmd` with the designated message `msg`. -/ def error (p : Parsed) (msg : String) : String := p.toCmd.error msg /-- Prints the help for `p.cmd`. -/ def printHelp (p : Parsed) : IO Unit := p.toCmd.printHelp /-- Prints an error for `p.cmd` with the designated message `msg`. -/ def printError (p : Parsed) (msg : String) : IO Unit := p.toCmd.printError msg /-- Prints the version of `p.cmd`. Panics if `p.cmd` has no version. -/ def printVersion! (p : Parsed) : IO Unit := p.toCmd.printVersion! end Parsed end Info section Parsing /-- Represents the exact representation of a flag as input by the user. -/ structure InputFlag where /-- Flag name input by the user. -/ name : String /-- Whether the flag input by the user was a short one. -/ isShort : Bool instance : ToString InputFlag where toString f := let pre := if f.isShort then "-" else "--" s!"{pre}{f.name}" namespace ParseError /-- Represents the kind of error that occured during parsing. -/ inductive Kind | unknownFlag (inputFlag : InputFlag) (msg : String := s!"Unknown flag `{inputFlag}`.") | missingFlagArg (flag : Flag) (inputFlag : InputFlag) (msg : String := s!"Missing argument for flag `{inputFlag}`.") | duplicateFlag (flag : Flag) (inputFlag : InputFlag) (msg : String := let complementaryName? : Option String := do if inputFlag.isShort then return s!" (`--{flag.longName}`)" else return s!" (`-{← flag.shortName?}`)" s!"Duplicate flag `{inputFlag}`{Option.optStr complementaryName?}.") | redundantFlagArg (flag : Flag) (inputFlag : InputFlag) (inputValue : String) (msg : String := s!"Redundant argument `{inputValue}` for flag `{inputFlag}` that takes no arguments.") | invalidFlagType (flag : Flag) (inputFlag : InputFlag) (inputValue : String) (msg : String := s!"Invalid type of argument `{inputValue}` for flag `{inputFlag} : {flag.type.name}`.") | missingPositionalArg (arg : Arg) (msg : String := s!"Missing positional argument `<{arg.name}>.`") | invalidPositionalArgType (arg : Arg) (inputArg : String) (msg : String := s!"Invalid type of argument `{inputArg}` for positional argument `<{arg.name} : {arg.type.name}>`.") | redundantPositionalArg (inputArg : String) (msg : String := s!"Redundant positional argument `{inputArg}`.") | invalidVariableArgType (arg : Arg) (inputArg : String) (msg : String := s!"Invalid type of argument `{inputArg}` for variable argument `<{arg.name} : {arg.type.name}>...`.") /-- Associated message of the error. -/ def Kind.msg : Kind → String | unknownFlag _ msg | missingFlagArg _ _ msg | duplicateFlag _ _ msg | redundantFlagArg _ _ _ msg | invalidFlagType _ _ _ msg | missingPositionalArg _ msg | invalidPositionalArgType _ _ msg | redundantPositionalArg _ msg | invalidVariableArgType _ _ msg => msg end ParseError open ParseError in /-- Error that occured during parsing. Contains the command that the error occured in and the kind of the error. -/ structure ParseError where /-- Command that the error occured in. -/ cmd : Cmd /-- Kind of error that occured. -/ kind : Kind private structure ParseState where idx : Nat cmd : Cmd parent? : Option Cmd parsedFlags : Array Parsed.Flag parsedPositionalArgs : Array Parsed.Arg parsedVariableArgs : Array Parsed.Arg private abbrev ParseM := ExceptT ParseError (ReaderT (Array String) (StateM ParseState)) namespace ParseM open ParseError.Kind private def args : ParseM (Array String) := read private def idx : ParseM Nat := do return (← get).idx private def cmd : ParseM Cmd := do return (← get).cmd private def parent? : ParseM (Option Cmd) := do return (← get).parent? private def parsedFlags : ParseM (Array Parsed.Flag) := do return (← get).parsedFlags private def parsedPositionalArgs : ParseM (Array Parsed.Arg) := do return (← get).parsedPositionalArgs private def parsedVariableArgs : ParseM (Array Parsed.Arg) := do return (← get).parsedVariableArgs private def peek? : ParseM (Option String) := do return (← args)[← idx]? private def peekNext? : ParseM (Option String) := do return (← args)[(← idx) + 1]? private def flag? (inputFlag : InputFlag) : ParseM (Option Flag) := do if inputFlag.isShort then return (← cmd).meta.flagByShortName? inputFlag.name else return (← cmd).meta.flag? inputFlag.name private def setIdx (idx : Nat) : ParseM Unit := do set { ← get with idx := idx } private def setCmd (c : Cmd) : ParseM Unit := do set { ← get with cmd := c } private def setParent (c? : Option Cmd) : ParseM Unit := do set { ← get with parent? := c? } private def pushParsedFlag (parsedFlag : Parsed.Flag) : ParseM Unit := do set { ← get with parsedFlags := (← parsedFlags).push parsedFlag } private def pushParsedPositionalArg (parsedPositionalArg : Parsed.Arg) : ParseM Unit := do set { ← get with parsedPositionalArgs := (← parsedPositionalArgs).push parsedPositionalArg } private def pushParsedVariableArg (parsedVariableArg : Parsed.Arg) : ParseM Unit := do set { ← get with parsedVariableArgs := (← parsedVariableArgs).push parsedVariableArg } private def skip : ParseM Unit := do setIdx <| (← idx) + 1 private def parseError (kind : ParseError.Kind) : ParseM ParseError := do return ⟨← cmd, kind⟩ private partial def parseSubCmds : ParseM Unit := do let mut parent? := none let mut lastSubCmd ← cmd repeat let some arg ← peek? | break let some subCmd := lastSubCmd.subCmd? arg | break skip parent? := lastSubCmd lastSubCmd := subCmd setCmd lastSubCmd setParent parent? private def parseEndOfFlags : ParseM Bool := do let some arg ← peek? | return false if arg = "--" then skip return true return false private def readFlagContent? : ParseM (Option (String × Bool)) := do let some arg ← peek? | return none if arg = "--" ∨ arg = "-" then return none if arg.take 2 = "--" then return (arg.drop 2, false) if arg.take 1 = "-" then return (arg.drop 1, true) return none private def ensureFlagUnique (flag : Flag) (inputFlag : InputFlag) : ParseM Unit := do if (← parsedFlags).find? (·.flag.longName = flag.longName) |>.isSome then throw <| ← parseError <| duplicateFlag flag inputFlag private def ensureFlagWellTyped (flag : Flag) (inputFlag : InputFlag) (value : String) : ParseM Unit := do if ¬ flag.type.isValid value then throw <| ← parseError <| invalidFlagType flag inputFlag value private partial def readMultiFlag? : ParseM (Option (Array Parsed.Flag)) := do let some (flagContent, true) ← readFlagContent? | return none let some (parsedFlags : Array (String × Parsed.Flag)) ← loop flagContent ∅ | return none for (inputFlagName, parsedFlag) in parsedFlags do ensureFlagUnique parsedFlag.flag ⟨inputFlagName, true⟩ skip return some <| parsedFlags.map (·.2) where loop (flagContent : String) (matched : Std.TreeSet String compare) : ParseM (Option (Array (String × Parsed.Flag))) := do -- this is not tail recursive, but that's fine: `loop` will only recurse further if the corresponding -- flag has not been matched yet, meaning that this can only overflow if the application has an -- astronomical amount of short flags. if flagContent = "" then return some #[] let parsedFlagsCandidates : Array (Array (String × Parsed.Flag)) ← (← cmd).meta.flags.filter (·.isParamless) |>.filter (·.hasShortName) |>.filter (·.shortName!.isPrefixOf flagContent) |>.filter (¬ matched.contains ·.shortName!) |>.qsort (·.shortName!.length > ·.shortName!.length) |>.filterMapM fun flag => do let inputFlagName := flagContent.take flag.shortName!.length let restContent := flagContent.drop flag.shortName!.length let newMatched := matched.insert flag.shortName! let some tail ← loop restContent newMatched | return none return some <| #[(inputFlagName, ⟨flag, ""⟩)] ++ tail return parsedFlagsCandidates[0]? private def readEqFlag? : ParseM (Option Parsed.Flag) := do let some (flagContent, isShort) ← readFlagContent? | return none match flagContent.splitOn "=" with | [] => panic! "Cli.readEqFlag?: String.splitOn returned empty list" | [_] => return none | (flagName :: flagArg :: rest) => let flagValue := "=".intercalate <| flagArg :: rest let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | throw <| ← parseError <| unknownFlag inputFlag if flag.isParamless then throw <| ← parseError <| redundantFlagArg flag inputFlag flagValue ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip return some ⟨flag, flagValue⟩ private def readWsFlag? : ParseM (Option Parsed.Flag) := do let some (flagName, isShort) ← readFlagContent? | return none let some flagValue ← peekNext? | return none let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | return none if flag.isParamless then return none ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip; skip return some ⟨flag, flagValue⟩ private def readPrefixFlag? : ParseM (Option Parsed.Flag) := do let some (flagContent, true) ← readFlagContent? | return none let some flag := ((← cmd).meta.flags.filter (¬ ·.isParamless) |>.filter (·.hasShortName) |>.filter (·.shortName!.isPrefixOf flagContent) |>.filter (·.shortName!.length < flagContent.length) |>.qsort (·.shortName!.length > ·.shortName!.length))[0]? | return none let flagName := flag.shortName! let flagValue := flagContent.drop flagName.length let inputFlag : InputFlag := ⟨flagName, true⟩ ensureFlagUnique flag inputFlag ensureFlagWellTyped flag inputFlag flagValue skip return some ⟨flag, flagValue⟩ private def readParamlessFlag? : ParseM (Option Parsed.Flag) := do let some (flagName, isShort) ← readFlagContent? | return none let inputFlag : InputFlag := ⟨flagName, isShort⟩ let some flag ← flag? inputFlag | throw <| ← parseError <| unknownFlag inputFlag if ¬ flag.isParamless then throw <| ← parseError <| missingFlagArg flag inputFlag ensureFlagUnique flag inputFlag skip return some ⟨flag, ""⟩ private def parseFlag : ParseM Bool := do if let some parsedFlags ← readMultiFlag? then for parsedFlag in parsedFlags do pushParsedFlag parsedFlag return true let tryRead parse : OptionT ParseM Parsed.Flag := parse let some parsedFlag ← tryRead readEqFlag? <|> tryRead readWsFlag? <|> tryRead readPrefixFlag? <|> tryRead readParamlessFlag? | return false pushParsedFlag parsedFlag return true private def parsePositionalArg : ParseM Bool := do let some positionalArgValue ← peek? | return false let some positionalArg := (← cmd).meta.positionalArgs[(← parsedPositionalArgs).size]? | return false if ¬ positionalArg.type.isValid positionalArgValue then throw <| ← parseError <| invalidPositionalArgType positionalArg positionalArgValue skip pushParsedPositionalArg ⟨positionalArg, positionalArgValue⟩ return true private def parseVariableArg : ParseM Bool := do let some variableArgValue ← peek? | return false let some variableArg := (← cmd).meta.variableArg? | throw <| ← parseError <| redundantPositionalArg variableArgValue if ¬ variableArg.type.isValid variableArgValue then throw <| ← parseError <| invalidVariableArgType variableArg variableArgValue skip pushParsedVariableArg ⟨variableArg, variableArgValue⟩ return true private partial def parseArgs : ParseM Unit := do let mut parseEverythingAsArg := false let mut noEndOfInput := true while noEndOfInput do if ← (pure !parseEverythingAsArg) <&&> parseEndOfFlags then parseEverythingAsArg := true noEndOfInput := ← (pure !parseEverythingAsArg) <&&> parseFlag <||> parsePositionalArg <||> parseVariableArg private def parse (c : Cmd) (args : List String) : Except ParseError (Cmd × Parsed) := parse' args.toArray |>.run' { idx := 0 cmd := c parent? := none parsedFlags := #[] parsedPositionalArgs := #[] parsedVariableArgs := #[] } where parse' : ParseM (Cmd × Parsed) := do parseSubCmds parseArgs let parsed : Parsed := { cmd := .ofFullCmd (← cmd) parent? := (← parent?).map .ofFullCmd flags := ← parsedFlags positionalArgs := ← parsedPositionalArgs variableArgs := ← parsedVariableArgs } if parsed.hasFlag "help" ∨ parsed.cmd.meta.hasVersion ∧ parsed.hasFlag "version" then return (← cmd, parsed) if (← parsedPositionalArgs).size < (← cmd).meta.positionalArgs.size then throw <| ← parseError <| missingPositionalArg <| (← cmd).meta.positionalArgs[(← parsedPositionalArgs).size]! return (← cmd, parsed) end ParseM namespace Cmd /-- Parses `args` according to the specification provided in `c`, returning either a `ParseError` or the (sub)command that was called and the parsed content of the input. Note that `args` designates the list `<foo>` in `somebinary <foo>`. -/ def parse (c : Cmd) (args : List String) : Except ParseError (Cmd × Parsed) := ParseM.parse c args /-- Recursively applies extensions in all subcommands in `c` bottom-up and `c` itself. -/ partial def applyExtensions (c : Cmd) : Cmd := Id.run do let subCmds := c.subCmds.map applyExtensions let c := c.update (subCmds := subCmds) let some extension := c.extension? | return c extension.extend (.ofFullCmd c) |>.toFullCmd c /-- Processes `args` by applying all extensions in `c`, `Cmd.parse?`ing the input according to `c` and then applying the postprocessing extension of the respective (sub)command that was called. Note that `args` designates the list `<foo>` in `somebinary <foo>`. Returns either the (sub)command that an error occured in and the corresponding error message or the (sub)command that was called and the parsed input after postprocessing. -/ def process (c : Cmd) (args : List String) : Except (Cmd × String) (Cmd × Parsed) := do let c := c.applyExtensions let result := c.parse args match result with | .ok (cmd, parsed) => let some ext := cmd.extension? | return (cmd, parsed) match ext.postprocess (.ofFullCmd cmd) parsed with | .ok newParsed => return (cmd, newParsed) | .error msg => throw (cmd, msg) | .error err => throw (err.cmd, err.kind.msg) end Cmd end Parsing section IO namespace Cmd /-- Validates `args` by `Cmd.process?`ing the input according to `c`. Note that `args` designates the list `<foo>` in `somebinary <foo>`. Prints the help or the version of the called (sub)command if the respective flag was passed and returns `0` for the exit code. If neither of these flags were passed and processing was successful, the `run` handler of the called command is executed. In the case of a processing error, the error is printed to stderr and an exit code of `1` is returned. -/ def validate (c : Cmd) (args : List String) : IO UInt32 := do let result := c.process args match result with | .ok (cmd, parsed) => if parsed.hasFlag "help" then parsed.printHelp return 0 if parsed.cmd.meta.hasVersion ∧ parsed.hasFlag "version" then parsed.printVersion! return 0 cmd.run parsed | .error (cmd, err) => cmd.printError err return 1 end Cmd end IO end Cli
.lake/packages/aesop/Aesop.lean
module public import Aesop.Main public import Aesop.Frontend.Command public import Aesop.Frontend.Saturate public import Aesop.BuiltinRules
.lake/packages/aesop/README.md
# Aesop Aesop (Automated Extensible Search for Obvious Proofs) is a proof search tactic for Lean 4. It is broadly similar to Isabelle's `auto`. In essence, Aesop works like this: - As with `simp`, you tag a (large) collection of definitions with the `@[aesop]` attribute, registering them as Aesop _rules_. Rules can be arbitrary tactics. We provide convenient ways to create common types of rules, e.g. rules which apply a lemma. - Aesop takes these rules and tries to apply each of them to the initial goal. If a rule succeeds and generates subgoals, Aesop recursively applies the rules to these subgoals, building a _search tree_. - The search tree is explored in a _best-first_ manner. You can mark rules as more or less likely to be useful. Based on this information, Aesop prioritises the goals in the search tree, visiting more promising goals before less promising ones. - Before any rules are applied to a goal, it is _normalised_, using a special (customisable) set of _normalisation rules_. An important built-in normalisation rule runs `simp_all`, so your `@[simp]` lemmas are taken into account by Aesop. - Rules can be marked as _safe_ to optimise Aesop's performance. A safe rule is applied eagerly and is never backtracked. For example, Aesop's built-in rules safely split a goal `P ∧ Q` into goals for `P` and `Q`. After this split, the original goal `P ∧ Q` is never revisited. - Aesop provides a set of built-in rules which perform logical operations (e.g. case-split on hypotheses `P ∨ Q`) and some other straightforward deductions. - Aesop uses indexing methods similar to those of `simp` and other Lean tactics. This means it should remain reasonably fast even with a large rule set. - When called as `aesop?`, Aesop prints a tactic script that proves the goal, similar to `simp?`. This way you can avoid the performance penalty of running Aesop all the time. However, the script generation is currently not fully reliable, so you may have to adjust the generated script. Aesop is suitable for two main use cases: - General-purpose automation, where Aesop is used to dispatch 'trivial' goals. By registering enough lemmas as Aesop rules, you can turn Aesop into a much more powerful `simp`. - Special-purpose automation, where specific Aesop rule sets are built to address a certain class of goals. Mathlib tactics such as `measurability` and `continuity` are implemented by Aesop. I only occasionally update this README, so details may be out of date. If you have questions, please create an issue or ping me (Jannis Limperg) on the [Lean Zulip](https://leanprover.zulipchat.com). Pull requests are very welcome! There's also [a paper about Aesop](https://zenodo.org/record/7430233) which covers many of the topics discussed here, sometimes in more detail. ## Building With [elan](https://github.com/leanprover/elan) installed, `lake build` should suffice. ## Adding Aesop to Your Project To use Aesop in a Lean 4 project, first add this package as a dependency. In your `lakefile.lean`, add ```lean require aesop from git "https://github.com/leanprover-community/aesop" ``` You also need to make sure that your `lean-toolchain` file contains the same version of Lean 4 as Aesop's, and that your versions of Aesop's dependencies (currently only `std4`) match. We unfortunately can't support version ranges at the moment. Now the following test file should compile: ```lean import Aesop example : α → α := by aesop ``` ## Quickstart To get you started, I'll explain Aesop's major concepts with a series of examples. A more thorough, reference-style discussion follows in the next section. We first define our own version of lists (so as not to clash with the standard library) and an `append` function: ``` lean inductive MyList (α : Type _) | nil | cons (hd : α) (tl : MyList α) namespace MyList protected def append : (_ _ : MyList α) → MyList α | nil, ys => ys | cons x xs, ys => cons x (MyList.append xs ys) instance : Append (MyList α) := ⟨MyList.append⟩ ``` We also tell `simp` to unfold applications of `append`: ```lean @[simp] theorem nil_append : nil ++ xs = xs := rfl @[simp] theorem cons_append : cons x xs ++ ys = cons x (xs ++ ys) := rfl ``` When Aesop first encounters a goal, it normalises it by running a customisable set of normalisation rules. One such normalisation rule effectively runs `simp_all`, so Aesop automatically takes `simp` lemmas into account. Now we define the `NonEmpty` predicate on `MyList`: ``` lean @[aesop safe [constructors, cases]] inductive NonEmpty : MyList α → Prop | cons : NonEmpty (cons x xs) ``` Here we see the first proper Aesop feature: we use the **`@[aesop]`** attribute to construct two Aesop rules related to the `NonEmpty` type. These rules are added to a global rule set. When Aesop searches for a proof, it systematically applies each available rule, then recursively searches for proofs of the subgoals generated by the rule, and so on, building a search tree. A goal is proved when Aesop applies a rule that generates no subgoals. In general, rules can be arbitrary tactics. But since you probably don't want to write a tactic for every rule, the `aesop` attribute provides several **rule builders** which construct common sorts of rules. In our example, we construct: - A **`constructors`** rule. This rule tries to apply each constructor of `NonEmpty` whenever a goal has target `NonEmpty _`. - A **`cases`** rule. This rule searches for hypotheses `h : NonEmpty _` and performs case analysis on them (like the `cases` tactic). Both rules above are added as **safe** rules. When a safe rule succeeds on a goal encountered during the proof search, it is applied and the goal is never visited again. In other words, the search does not backtrack safe rules. We will later see **unsafe** rules, which can backtrack. With these rules, we can prove a theorem about `NonEmpty` and `append`: ``` lean @[aesop unsafe 50% apply] theorem nonEmpty_append₁ {xs : MyList α} ys : NonEmpty xs → NonEmpty (xs ++ ys) := by aesop ``` Aesop finds this proof in four steps: - A built-in rule introduces the hypothesis `h : NonEmpty xs`. By default, Aesop's rule set contains a number of straightforward rules for handling the logical connectives `→`, `∧`, `∨` and `¬` as well as the quantifiers `∀` and `∃` and some other basic types. - The `cases` rule for `NonEmpty` performs case analysis on `h`. - The `simp` rule `cons_append`, which we added earlier, unfolds the `++` operation. - The `constructor` rule for `NonEmpty` applies `NonEmpty.cons`. If you want to see how Aesop proves your goal (or why it doesn't prove your goal, or why it takes too long to prove your goal), you can enable tracing: ``` lean set_option trace.aesop true ``` This makes Aesop print out the steps it takes while searching for a proof. You can also look at the search tree Aesop constructed by enabling the `trace.aesop.tree` option. For more tracing options, type `set_option trace.aesop` and see what auto-completion suggests. If, in the example above, you call `aesop?` instead, then Aesop prints a proof script. At time of writing, it looks like this: ``` lean intro a obtain @⟨x, xs_1⟩ := a simp_all only [cons_append] apply MyList.NonEmpty.cons ``` With a bit of post-processing, you can use this script instead of the Aesop call. This way you avoid the performance penalty of making Aesop search for a proof over and over again. The proof script generation currently has some known bugs, but it produces usable scripts most of the time. The `@[aesop]` attribute on `nonEmpty_append₁` adds this lemma as an **unsafe** rule to the default rule set. For this rule we use the **`apply`** rule builder, which generates a rule that tries to apply `nonEmpty_append₁` whenever the target is of the form `NonEmpty (_ ++ _)`. Unsafe rules are rules which can backtrack, so after they have been applied to a goal, Aesop may still try other rules to solve the same goal. This makes sense for `nonEmpty_append₁`: if we have a goal `NonEmpty (xs ++ ys)`, we may prove it either by showing `NonEmpty xs` (i.e., by applying `nonEmpty_append₁`) or by showing `NonEmpty ys`. If `nonEmpty_append₁` were registered as a safe rule, we would always choose `NonEmpty xs` and never investigate `NonEmpty ys`. Each unsafe rule is annotated with a **success probability**, here 50%. This is a very rough estimate of how likely it is that the rule will to lead to a successful proof. It is used to prioritise goals: the initial goal starts with a priority of 100% and whenever we apply an unsafe rule, the priority of its subgoals is the priority of its parent goal multiplied with the success probability of the applied rule. So applying `nonEmpty_append₁` repeatedly would give us goals with priority 50%, 25%, etc. Aesop always considers the highest-priority unsolved goal first, so it prefers proof attempts involving few and high-probability rules. Additionally, when Aesop has a choice between multiple unsafe rules, it prefers the one with the highest success probability. (Ties are broken arbitrarily but deterministically.) After adding `nonEmpty_append`, Aesop can prove some consequences of this lemma: ``` lean example {α : Type u} {xs : MyList α} ys zs : NonEmpty xs → NonEmpty (xs ++ ys ++ zs) := by aesop ``` Next, we prove another simple theorem about `NonEmpty`: ``` lean theorem nil_not_nonEmpty (xs : MyList α) : xs = nil → ¬ NonEmpty xs := by aesop (add 10% cases MyList) ``` Here we use an **`add`** clause to add a rule which is only used in this specific Aesop call. The rule is an unsafe `cases` rule for `MyList`. (As you can see, you can leave out the `unsafe` keyword and specify only a success probability.) This rule is dangerous: when we apply it to a hypothesis `xs : MyList α`, we get `x : α` and `ys : MyList α`, so we can apply the `cases` rule again to `ys`, and so on. We therefore give this rule a very low success probability, to make sure that Aesop applies other rules if possible. Here are some examples where Aesop's normalisation phase is particularly useful: ``` lean @[simp] theorem append_nil {xs : MyList α} : xs ++ nil = xs := by induction xs <;> aesop theorem append_assoc {xs ys zs : MyList α} : (xs ++ ys) ++ zs = xs ++ (ys ++ zs) := by induction xs <;> aesop ``` Since we previously added unfolding lemmas for `append` to the global `simp` set, Aesop can prove theorems about this function more or less by itself (though in fact `simp_all` would already suffice.) However, we still need to perform induction explicitly. This is a deliberate design choice: techniques for automating induction exist, but they are complex, somewhat slow and not entirely reliable, so we prefer to do it manually. Many more examples can be found in the `AesopTest` folder of this repository. In particular, the file `AesopTest/List.lean` contains an Aesop-ified port of 200 basic list lemmas from the Lean 3 version of mathlib, and the file `AesopTest/SeqCalcProver.lean` shows how Aesop can help with the formalisation of a simple sequent calculus prover. ## Reference This section contains a systematic and fairly comprehensive account of how Aesop operates. ### Rules A rule is a tactic plus some associated metadata. Rules come in three flavours: - **Normalisation rules** (keyword `norm`) must generate zero or one subgoal. (Zero means that the rule closed the goal). Each normalisation rule is associated with an integer **penalty** (default 1). Normalisation rules are applied in a fixpoint loop in order of penalty, lowest first. For rules with equal penalties, the order is unspecified. See below for details on the normalisation algorithm. Normalisation rules can also be simp lemmas. These are constructed with the `simp` builder. They are used by a special `simp` call during the normalisation process. - **Safe rules** (keyword `safe`) are applied after normalisation but before any unsafe rules. When a safe rule is successfully applied to a goal, the goal becomes *inactive*, meaning no other rules are considered for it. Like normalisation rules, safe rules are associated with a penalty (default 1) which determines the order in which the rules are tried. Safe rules should be provability-preserving, meaning that if a goal is provable and we apply a safe rule to it, the generated subgoals should still be provable. This is a less precise notion than it may appear since what is provable depends on the entire Aesop rule set. - **Unsafe rules** (keyword `unsafe`) are tried only if all available safe rules have failed on a goal. When an unsafe rule is applied to a goal, the goal is not marked as inactive, so other (unsafe) rules may be applied to it. These rule applications are considered independently until one of them proves the goal (or until we've exhausted all available rules and determine that the goal is not provable with the current rule set). Each unsafe rule has a **success probability** between 0% and 100%. These probabilities are used to determine the priority of a goal. The initial goal has priority 100% and whenever we apply an unsafe rule, the priorities of its subgoals are the priority of the rule's parent goal times the rule's success probability. Safe rules are treated as having 100% success probability. Rules can also be **multi-rules**. These are rules which add multiple rule applications to a goal. For example, registering the constructors of the `Or` type will generate a multi-rule that, given a goal with target `A ∨ B`, generates one rule application with goal `A` and one with goal `B`. This is equivalent to registering one rule for each constructor, but multi-rules can be both slightly more efficient and slightly more natural. ### Search Tree Aesop's central data structure is a search tree. This tree alternates between two kinds of nodes: - **Goal nodes**: these nodes store a goal, plus metadata relevant to the search. The parent and children of a goal node are rule application nodes. In particular, each goal node has a **priority** between 0% and 100%. - **Rule application ('rapp') nodes**: these goals store a rule (plus metadata). The parent and children of a rapp node are goal nodes. When the search tree contains a rapp node with rule `r`, parent `p` and children `c₁, ..., cₙ`, this means that the tactic of rule `r` was applied to the goal of `p`, generating the subgoals of the `cᵢ`. When a goal node has multiple child rapp nodes, we have a choice of how to solve the goals. This makes the tree an AND-OR tree: to prove a rapp, *all* its child goals must be proved; to prove a goal, *any* of its child rapps must be proved. ### Search We start with a search tree containing a single goal node. This node's goal is the goal which Aesop is supposed to solve. Then we perform the following steps in a loop, stopping if (a) the root goal has been proved; (b) the root goal becomes unprovable; or (c) one of Aesop's rule limits has been reached. (There are configurable limits on, e.g., the total number of rules applied or the search depth.) - Pick the highest-priority active goal node `G`. Roughly speaking, a goal node is active if it is not proved and we haven't yet applied all possible rules to it. - If the goal of `G` has not been normalised yet, normalise it. That means we run the following normalisation loop: - Run the normalisation rules with negative penalty (lowest penalty first). If any of these rules is successful, restart the normalisation loop with the goal produced by the rule. - Run `simp` on all hypotheses and the target, using the global simp set (i.e. lemmas tagged `@[simp]`) plus Aesop's `simp` rules. - Run the normalisation rules with positive penalty (lowest penalty first). If any of these rules is successful, restart the normalisation loop. The loop ends when all normalisation rules fail. It destructively updates the goal of `G` (and may prove it outright). - If we haven't tried to apply the safe rules to the goal of `G` yet, try to apply each safe rule (lowest penalty first). As soon as a rule succeeds, add the corresponding rapp and child goals to the tree and mark `G` as inactive. The child goals receive the same priority as `G`. - Otherwise there is at least one unsafe rule that hasn't been tried on `G` yet (or else `G` would have been inactive). Try the unsafe rule with the highest success probability and if it succeeds, add the corresponding rapp and child goals to the tree. The child goals receive the priority of `G` times the success probability of the applied rule. A goal is **unprovable** if we have applied all possible rules to it and all resulting child rapps are unprovable. A rapp is unprovable if any of its subgoals is unprovable. During the search, a goal or rapp can also become **irrelevant**. This means that we don't have to visit it again. Informally, goals and rapps are irrelevant if they are part of a branch of the search tree which has either successfully proved its goal already or which can never prove its goal. More formally: - A goal is irrelevant if its parent rapp is unprovable. (This means that a sibling of the goal is already unprovable, in which case we know that the parent rapp will never be proved.) - A rapp is irrelevant if its parent goal is proved. (This means that a sibling of the rapp is already proved, and we only need one proof.) - A goal or rapp is irrelevant if any of its ancestors is irrelevant. ### Rule Builders A **rule builder** is a metaprogram that turns an expression into an Aesop rule. When you tag a declaration with the `@[aesop]` attribute, the builder is applied to the declared constant. When you use the `add` clause, as in `(add <phase> <builder> (<term>))`, the builder is applied to the given term, which may involve hypotheses from the goal. However, some builders only support global constants. If the `term` is a single identifier, e.g. the name of a hypothesis, the parentheses around it are optional. Currently available builders are: - **`apply`**: generates a rule which acts like the `apply` tactic. - **`forward`**: when applied to a term of type `A₁ → ... Aₙ → B`, generates a rule which looks for hypotheses `h₁ : A₁`, ..., `hₙ : Aₙ` in the goal and, if they are found, adds a new hypothesis `fwd : B`. As an example, consider the lemma `even_or_odd`: ```lean even_or_odd : ∀ (n : Nat), Even n ∨ Odd n ``` Registering this as a forward rule will cause the goal ```lean n : Nat m : Nat ⊢ T ``` to be transformed into this: ```lean n : Nat hn : Even n ∨ Odd n m : Nat hm : Even m ∨ Odd m ⊢ T ``` The forward builder may also be given a list of *immediate names*: ``` forward (immediate := [n]) even_or_odd ``` The immediate names, here `n`, refer to the arguments of `even_or_odd`. When Aesop applies a forward rule with explicit immediate names, it only matches the corresponding arguments to hypotheses. (Here, `even_or_odd` has only one argument, so there is no difference.) When no immediate names are given, Aesop considers every argument immediate, except for instance arguments and dependent arguments (i.e. those that can be inferred from the types of later arguments). A forward rules will never add a hypothesis to the context if another hypothesis of the same type already exists. - **`destruct`**: works like `forward`, but after the rule has been applied, propositional hypotheses (i.e., hypotheses whose types are `Prop`s) that were used as immediate arguments are cleared. This is useful when you want to eliminate a hypothesis. E.g. the rule ``` @[aesop norm destruct] theorem and_elim_right : α ∧ β → α := ... ``` will cause the goal ``` h₁ : (α ∧ β) ∧ γ h₂ : δ ∧ ε ``` to be transformed into ``` h₁ : α h₂ : δ ``` If a hypothesis `h` is used as an immediate argument for a `destruct` rule and another hypothesis `h'` depends on `h`, but is not also an immediate argument for the same rule, then `h` is not cleared. This is because we can't clear `h` without also clearing `h'`. - **`constructors`**: when applied to an inductive type or structure `T`, generates a rule which tries to apply each constructor of `T` to the target. This is a multi-rule, so if multiple constructors apply, they are considered in parallel. If you use this constructor to build an unsafe rule, each constructor application receives the same success probability; if this is not what you want, add separate `apply` rules for the constructors. - **`cases`**: when applied to an inductive type or structure `T`, generates a rule that performs case analysis on every hypothesis `h : T` in the context. The rule recurses into subgoals, so `cases Or` will generate 6 goals when applied to a goal with hypotheses `h₁ : A ∨ B ∨ C` and `h₂ : D ∨ E`. However, if `T` is a recursive type (e.g. `List`), we only perform case analysis once on each hypothesis. Otherwise we would loop infinitely. The `cases_patterns` option can be used to apply the rule only on hypotheses of a certain shape. E.g. the rule `cases (cases_patterns := [Fin 0]) Fin` will perform case analysis only on hypotheses of type `Fin 0`. Patterns can contain underscores, e.g. `0 ≤ _`. Multiple patterns can be given (separated by commas); the rule is then applied whenever at least one of the patterns matches a hypothesis. - **`simp`**: when applied to an equation `eq : A₁ → ... Aₙ → x = y`, registers `eq` as a simp lemma for the built-in simp pass during normalisation. As such, this builder can only build normalisation rules. - **`unfold`**: when applied to a definition or `let` hypothesis `f`, registers `f` to be unfolded (i.e. replaced with its definition) during normalisation. As such, this builder can only build normalisation rules. The unfolding happens in a separate `simp` pass. The `simp` builder can also be used to unfold definitions. The difference is that `simp` rules perform smart unfolding (like the `simp` tactic) and `unfold` rules perform non-smart unfolding (like the `unfold` tactic). Non-smart unfolding unfolds functions even when none of their equations match, so `unfold` rules would lead to looping and are forbidden. - **`tactic`**: takes a tactic and directly turns it into a rule. When this builder is used in an `add` clause, you can use e.g. `(add safe (by norm_num))` to register `norm_num` as a safe rule. The `by` block can also contain multiple tactics as well as references to the hypotheses. When you use `(by ...)` in an `add` clause, Aesop automatically uses the tactic builder, unless you specify a different builder. When this builder is used in the `@[aesop]` attribute, the declaration tagged with the attribute must have type `TacticM Unit`, `Aesop.SingleRuleTac` or `Aesop.RuleTac`. The latter are Aesop data types which associate a tactic with additional metadata; using them may allow the rule to operate somewhat more efficiently. Rule tactics should not be 'no-ops': if a rule tactic is not applicable to a goal, it should fail rather than return the goal unchanged. All no-op rules waste time; no-op `norm` rules will send normalisation into an infinite loop; and no-op `safe` rules will prevent unsafe rules from being applied. Normalisation rules may not assign metavariables (other than the goal metavariable) or introduce new metavariables (other than the new goal metavariable). This can be a problem because some Lean tactics, e.g. `cases`, do so even in situations where you probably would not expect them to. I'm afraid there is currently no good solution for this. - **`default`**: The default builder. This is the builder used when you register a rule without specifying a builder, but you can also use it explicitly. Depending on the rule's phase, the default builder tries different builders, using the first one that works. These builders are: - For `safe` and `unsafe` rules: `constructors`, `tactic`, `apply`. - For `norm` rules: `constructors`, `tactic`, `simp`, `apply`. #### Transparency Options The rule builders `apply`, `constructors` and `cases` each have a `transparency` option. This option controls the transparency at which the rule is executed. For example, registering a rule with the builder `apply (transparency := reducible)` makes the rule act like the tactic `with_reducible apply`. However, even if you change the transparency of a rule, it is still indexed at `reducible` transparency (since the data structure we use for indexing only supports `reducible` transparency). So suppose you register an `apply` rule with `default` transparency. Further suppose the rule concludes `A ∧ B` and your target is `T` with `def T := A ∧ B`. Then the rule could apply to the target since it can unfold `T` at `default` transparency to discover `A ∧ B`. However, the rule is never applied because the indexing procedure sees only `T` and does not consider the rule potentially applicable. To override this behaviour, you can write `apply (transparency! := default)` (note the bang). This disables indexing, so the rule is tried on every goal. ### Rule Sets Rule sets are declared with the command ``` lean declare_aesop_rule_sets [r₁, ..., rₙ] (default := <bool>) ``` where the `rᵢ` are arbitrary names. To avoid clashes, pick names in the namespace of your package. Setting `default := true` makes the rule set active by default. The `default` clause can be omitted and defaults to `false`. Within a rule set, rules are identified by their name, builder and phase (safe/unsafe/norm). This means you can add the same declaration as multiple rules with different builders or in different phases, but not with different priorities or different builder options (if the rule's builder has any options). Rules can appear in multiple rule sets, but in this case you should make sure that they have the same priority and use the same builder options. Otherwise, Aesop will consider these rules the same and arbitrarily pick one. Out of the box, Aesop uses the default rule sets `builtin` and `default`. The `builtin` set contains built-in rules for handling various constructions (see below). The `default` set contains rules which were added by Aesop users without specifying a rule set. ### The `@[aesop]` Attribute Declarations can be added to rule sets by annotating them with the `@[aesop]` attribute. As with other attributes, you can use `@[local aesop]` to add a rule only within the current section or namespace and `@[scoped aesop]` to add a rule only when the current namespace is open. #### Single Rule In most cases, you'll want to add one rule for the declaration. The syntax for this is ``` lean @[aesop <phase>? <priority>? <builder>? <builder_option>* <rule_sets>?] ``` where - `<phase>` is `safe`, `norm` or `unsafe`. Cannot be omitted except under the conditions in the next bullets. - `<priority>` is: - For `simp` rules, a natural number. This is used as the priority of the `simp` generated `simp` lemmas, so registering a `simp` rule with priority `n` is roughly equivalent to the attribute `@[simp n]`. If omitted, defaults to Lean's default `simp` priority. - For `safe` and `norm` rules (except `simp` rules), an integer penalty. If omitted, defaults to 1. - For `unsafe` rules, a percentage between 0% and 100%. Cannot be omitted. You may omit the `unsafe` phase specification when giving a percentage. - For `unfold` rules, a penalty can be given, but it is currently ignored. - `<builder>` is one of the builders given above. If no builder is specified, the default builder for the given phase is used. When the `simp` builder is used, the `norm` phase may be omitted since this builder can only generate normalisation rules. - `<builder_option>*` is a list of zero or more builder options. See above for the different builders' options. - `<rule_sets>` is a clause of the form ```text (rule_sets := [r₁, ..., rₙ]) ``` where the `rᵢ` are declared rule sets. (Parentheses are mandatory.) The rule is added exactly to the specified rule sets. If this clause is omitted, it defaults to `(rule_sets := [default])`. #### Multiple Rules It is occasionally useful to add multiple rules for a single declaration, e.g. a `cases` and a `constructors` rule for the same inductive type. In this case, you can write for example ``` lean @[aesop unsafe [constructors 75%, cases 90%]] inductive T ... @[aesop apply [safe (rule_sets := [A]), 70% (rule_sets := [B])]] def foo ... @[aesop [80% apply, safe 5 forward (immediate := x)]] def bar (x : T) ... ``` In the first example, two unsafe rules for `T` are registered, one with success probability 75% and one with 90%. In the second example, two rules are registered for `foo`. Both use the `apply` builder. The first, a `safe` rule with default penalty, is added to rule set `A`. The second, an `unsafe` rule with 70% success probability, is added to rule set `B`. In the third example, two rules are registered for `bar`: an `unsafe` rule with 80% success probability using the `apply` builder and a `safe` rule with penalty 5 using the `forward` builder. In general, the grammar for the `@[aesop]` attribute is ``` lean attr ::= @[aesop <rule_expr>] | @[aesop [<rule_expr,+>]] rule_expr ::= feature | feature <rule_expr> | feature [<rule_expr,+>] ``` where `feature` is a phase, priority, builder or `rule_sets` clause. This grammar yields one or more trees of features and each branch of these trees specifies one rule. (A branch is a list of features.) ### Adding External Rules You can use the `attribute` command to add rules for constants which were declared previously, either in your own development or in a package you import: ```lean attribute [aesop norm unfold] List.all -- List.all is from Init ``` You can also use the `add_aesop_rules` command: ``` lean add_aesop_rules safe [(by linarith), Nat.add_comm 0] ``` As you can see, this command can be used to add tactics and composite terms as well. Use `local add_aesop_rules` and `scoped add_aesop_rules` to obtain the equivalent of `@[local aesop]` and `@[scoped aesop]`. ### Erasing Rules There are two ways to erase rules. Usually it suffices to remove the `@[aesop]` attribute: ``` lean attribute [-aesop] foo ``` This will remove all rules associated with the declaration `foo` from all rule sets. However, this erasing is not persistent, so the rule will reappear at the end of the file. This is a fundamental limitation of Lean's attribute system: once a declaration is tagged with an attribute, it cannot be permanently untagged. If you want to remove only certain rules, you can use the `erase_aesop_rules` command: ``` lean erase_aesop_rules [safe apply foo, bar (rule_sets := [A])] ``` This will remove: - all safe rules for `foo` with the `apply` builder from all rule sets (but not other, for example, unsafe rules or `forward` rules); - all rules for `bar` from rule set `A`. In general, the syntax is ``` lean erase_aesop_rules [<rule_expr,+>] ``` i.e. rules are specified in the same way as for the `@[aesop]` attribute. However, each rule must also specify the name of the declaration whose rules should be erased. The `rule_expr` grammar is therefore extended such that a `feature` can also be the name of a declaration. Note that a rule added with one of the default builders (`safe_default`, `norm_default`, `unsafe_default`) will be registered under the name of the builder that is ultimately used, e.g. `apply` or `simp`. So if you want to erase such a rule, you may have to specify that builder instead of the default builder. ### The `aesop` Tactic In its most basic form, you can call the Aesop tactic just by writing ``` lean example : α → α := by aesop ``` This will use the rules in the default rule sets. Out of the box, these are the `default` rule set, containing rules tagged with the `@[aesop]` attribute without mentioning a specific rule set, and the `builtin` rule set, containing rules built into Aesop. However, other rule sets can also be enabled by default; see the `declare_aesop_rule_sets` command. The tactic's behaviour can also be customised with various options. A more involved Aesop call might look like this: ``` text aesop (add safe foo, 10% cases Or, safe cases Empty) (erase A, baz) (rule_sets := [A, B]) (config := { maxRuleApplicationDepth := 10 }) ``` Here we add some rules with an `add` clause, erase other rules with an `erase` clause, limit the used rule sets and set some options. Each of these clauses is discussed in more detail below. #### Adding Rules to an Aesop Call Rules can be added to an Aesop call with an `add` clause. This won't affect any declared rule sets. The syntax of the `add` clause is ``` text (add <rule_expr,+>) ``` i.e. rules can be specified in the same way as for the `@[aesop]` attribute. As with the `erase_aesop_rules` command, each rule must specify the name of declaration from which the rule should be built; for example ``` text (add safe [foo 1, bar 5]) ``` will add the declaration `foo` as a safe rule with penalty 1 and `bar` as a safe rule with penalty 5. The rule names can also refer to hypotheses in the goal context, but not all builders support this. #### Erasing Rules From an Aesop Call Rules can be removed from an Aesop call with an `erase` clause. Again, this affects only the current Aesop call and not the declared rule sets. The syntax of the `erase` clause is ``` text (erase <rule_expr,+>) ``` and it works exactly like the `erase_aesop_rules` command. To erase all rules associated with `x` and `y`, write ``` lean (erase x, y) ``` #### Selecting Rule Sets By default, Aesop uses the `default` and `builtin` rule sets, as well as rule sets which are declared as default rule sets. A `rule_sets` clause can be given to include additional rule sets, e.g. ``` text (rule_sets := [A, B]) ``` This will use rule sets `A`, `B`, `default` and `builtin` (and any rule sets declared as default rule sets). Rule sets can also be disabled with `rule_sets := [-default, -builtin]`. #### Setting Options Various options can be set with a `config` clause, whose syntax is: ``` text (config := <term>) ``` The term is an arbitrary Lean expression of type `Aesop.Options`; see there for details. Notable options include: - `strategy` selects a best-first, depth-first or breadth-first search strategy. The default is best-first. - `useSimpAll := false` makes the built-in `simp` rule use `simp at *` rather than `simp_all`. - `enableSimp := false` disables the built-in `simp` rule altogether. Similarly, options for the built-in norm simp rule can be set with ``` text (simp_config := <term>) ``` You can give the same options here as in `simp (config := ...)`. ### Built-In Rules The set of built-in rules (those in the `builtin` rule set) is a bit unstable, so for now I won't document them in detail. See `Aesop/BuiltinRules.lean` and `Aesop/BuiltinRules/*.lean` ### Proof Scripts By calling `aesop?` instead of `aesop`, you can instruct Aesop to generate a tactic script which proves the goal (if Aesop succeeds). The script is printed as a `Try this:` suggestion, similar to `simp?`. The scripts generated by Aesop are currently a bit idiosyncratic. For example, they may contain the `aesop_cases` tactic, which is a slight variation of the standard `cases`. Additionally, Aesop occasionally generates buggy scripts which do not solve the goal. We hope to eventually fix these issues; until then, you may have to lightly adjust the proof scripts by hand. ### Tracing To see how Aesop proves a goal -- or why it doesn't prove a goal, or why it's slow to prove a goal -- it is useful to see what it's doing. To that end, you can enable various tracing options. These use the usual syntax, e.g. ``` lean set_option trace.aesop true ``` The main options are: - `trace.aesop`: print a step-by-step log of which goals Aesop tried to solve, which rules it tried to apply (successfully or unsuccessfully), etc. - `trace.aesop.ruleSet`: print the rule set used for an Aesop call. - `trace.aesop.proof`: if Aesop is successful, print the proof that was generated (as a Lean term). You should be able to copy-and-paste this proof to replace Aesop. ### Profiling To get an idea of where Aesop spends its time, use ``` lean set_option trace.aesop.stats true ``` Aesop then prints some statistics about this particular Aesop run. To get statistics for multiple Aesop invocations, activate the option `aesop.collectStats` for the relevant files (or for certain invocations) and run the command `#aesop_stats` in a file which imports all relevant files. E.g. to evaluate Aesop's performance in Mathlib, set the option `aesop.collectStats` in Mathlib's `lakefile.lean`, recompile Mathlib from scratch and create a new Lean file with contents ``` lean import Mathlib #aesop_stats ``` You can also activate the `profiler` option, which augments the trace produced by `trace.aesop` with information about how much time each step took. Note that only the timing information pertaining to goal expansions and rule applications is relevant. Other timings, such as those attached to new rapps and goals, are just artefacts of the Lean tracing API. ### Checking Internal Invariants If you encounter behaviour that looks like an internal error in Aesop, it may help to set the option `aesop.check.all` (or the more fine-grained `aesop.check.*` options). This makes Aesop check various invariants while the tactic is running. These checks are somewhat expensive, so remember to unset the option after you've reported the bug. ### Handling Metavariables Rules which create metavariables must be handled specially by Aesop. For example, suppose we register transitivity of `<` as an Aesop rule. Then we may get a goal state of this form: ``` lean n k : Nat ⊢ n < ?m n k : Nat ⊢ ?m < k ``` We may now solve the first goal by applying different rules. We could, for example, apply the theorem `∀ n, n < n + 1`. We could also use an assumption `n < a`. Both proofs close the first goal, but crucially, they modify the second goal: in the first case, it becomes `n + 1 < k`; in the second case, `a < k`. And of course one of these could be provable while the other is not. In other words, the second subgoal now depends on the *proof* of the first subgoal (whereas usually we don't care *how* a goal was proven, only *that* it was proven). Aesop could also decide to work on the second subgoal first, in which case the situation is symmetric. Due to this dependency, Aesop in effect treats the instantiations of the second subgoal as *additional goals*. Thus, when we apply the theorem `∀ n, n < n + 1`, which closes the first goal, Aesop realises that because this theorem was applied, we must now prove `n + 1 < k` as well. So it adds this goal as an additional subgoal of the rule application `∀ n, n < n + 1` (which otherwise would not have any subgoals). Similarly, when the assumption `n < a` is applied, its rule application gains an additional subgoal `a < k`. This mechanism makes sure that we consider all potential proofs. The downside is that it's quite explosive: when there are multiple metavariables in multiple goals, which Aesop may visit in any order, Aesop may spend a lot of time copying goals with shared metavariables. It may even try to prove the same goal more than once since different rules may yield the same metavariable instantiations. For these reasons, rules which create metavariables are best kept out of the global rule set and added to individual Aesop calls on an ad-hoc basis. It is also worth noting that when a safe rule assigns a metavariable, it is treated as an unsafe rule (with success probability 90%). This is because assigning metavariables is almost never safe, for the same reason as above: the usually perfectly safe rule `∀ n, n < n + 1` would, if treated as safe, force us to commit to one particular instantiation of the metavariable `?m`. For more details on the handling of metavariables, see the [Aesop paper](https://zenodo.org/record/7430233).
.lake/packages/aesop/AesopTest/TryThisIndentation.lean
import Aesop /-- info: Try this: [apply] intro a_1 a_2 simp_all only [ne_eq, List.mem_cons, or_self, not_false_eq_true] -/ #guard_msgs in example {a y : α} {l : List α} : a ≠ y → a ∉ l → a ∉ y::l := by aesop? /-- info: Try this: [apply] simp_all only [ne_eq, List.mem_cons, or_self, not_false_eq_true] -/ #guard_msgs in example {a y : α} {l : List α} : a ≠ y → a ∉ l → a ∉ y::l := by intros have : ¬ a ∈ y :: l := by aesop? exact this
.lake/packages/aesop/AesopTest/ForwardUnknownFVar.lean
import Aesop attribute [aesop safe forward 1] Nat.le_trans attribute [-aesop] Aesop.BuiltinRules.applyHyps variable (a b c d e f : Nat) /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in set_option aesop.smallErrorMessages true in example (h₃ : c ≤ d) (h₄ : d ≤ e) (h₅ : e ≤ f) (h : a = f) : False := by aesop (config := { terminal := true })
.lake/packages/aesop/AesopTest/12.lean
import Aesop set_option aesop.check.all true attribute [aesop unsafe 50% constructors] List.Mem @[aesop safe [constructors, cases (cases_patterns := [All _ [], All _ (_ :: _)])]] inductive All (P : α → Prop) : List α → Prop where | none : All P [] | more (x xs) : P x → All P xs → All P (x :: xs) theorem weaken (P Q : α → Prop) (wk : ∀ x, P x → Q x) (xs : List α) (h : All P xs) : All Q xs := by induction h <;> aesop theorem in_self (xs : List α) : All (· ∈ xs) xs := by induction xs case nil => aesop case cons x xs ih => have wk : ∀ a, a ∈ xs → a ∈ x :: xs := by aesop have ih' : All (fun a => a ∈ x :: xs) xs := by aesop (add unsafe 1% weaken) aesop
.lake/packages/aesop/AesopTest/EraseUnfold.lean
-- Thanks to Jireh Loreaux for reporting this MWE. import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true @[irreducible] def foo : Nat := 37 /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : foo = 37 := by aesop (config := { terminal := true }) (erase Aesop.BuiltinRules.rfl) example : foo = 37 := by unfold foo rfl attribute [aesop norm unfold] foo example : foo = 37 := by aesop (erase Aesop.BuiltinRules.rfl) attribute [-aesop] foo /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : foo = 37 := by aesop (config := { terminal := true }) (erase Aesop.BuiltinRules.rfl) example : foo = 37 := by unfold foo rfl
.lake/packages/aesop/AesopTest/2.lean
import Aesop -- This option would make Aesop time out. set_option aesop.check.all false inductive Even : Nat → Prop | zero : Even Nat.zero | plus_two {n} : Even n → Even (n + 2) attribute [aesop safe] Even.zero Even.plus_two example : Even 500 := by aesop (config := { maxRuleApplications := 0, maxRuleApplicationDepth := 0 })
.lake/packages/aesop/AesopTest/MVarsInInitialGoal.lean
import Aesop set_option aesop.check.all true example {n m k : Nat} (h : n < m) (h₂ : m < k) : n < k := by apply Nat.lt_trans <;> aesop
.lake/packages/aesop/AesopTest/Persistence3.lean
import AesopTest.Persistence1 import AesopTest.Persistence2 set_option aesop.check.all true namespace Aesop @[aesop 50% (rule_sets := [test_persistence2])] def test (b : Bool) : NatOrBool := by aesop (rule_sets := [test_persistence1]) end Aesop
.lake/packages/aesop/AesopTest/Intros.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true def Injective₁ (f : α → β) := ∀ x y, f x = f y → x = y abbrev Injective₂ (f : α → β) := ∀ x y, f x = f y → x = y /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : Injective₁ (@id Nat) := by aesop (config := { terminal := true }) /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : Injective₁ (@id Nat) := by aesop (config := { introsTransparency? := some .reducible, terminal := true }) example : Injective₁ (@id Nat) := by aesop (config := { introsTransparency? := some .default }) /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : Injective₂ (@id Nat) := by aesop (config := { terminal := true }) example : Injective₂ (@id Nat) := by aesop (config := { introsTransparency? := some .reducible }) example : Injective₂ (@id Nat) := by aesop (config := { introsTransparency? := some .default })
.lake/packages/aesop/AesopTest/Jesse.lean
import Aesop set_option aesop.check.all true axiom Ring : Type axiom Morphism (R S : Ring) : Type @[aesop 99%] axiom ZZ : Ring @[aesop 99%] axiom f : Morphism ZZ ZZ noncomputable example : Σ (R : Ring), Morphism R R := by aesop axiom domain (R : Ring) : Prop @[aesop 99%] axiom ZZ_domain : domain ZZ noncomputable example : ∃ (R : Ring), domain R := by aesop
.lake/packages/aesop/AesopTest/NormSimp.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true -- A basic test for local simp rules. example {α : Prop} (h : α) : α := by aesop (rule_sets := [-builtin,-default]) (add h norm simp) -- This test checks that we don't 'self-simplify' hypotheses: `h` should not -- be used to simplify itself. example (h : (α ∧ β) ∨ γ) : α ∨ γ := by aesop (add h norm simp) -- Ditto, but we can omit the 'norm'. example (h : (α ∧ β) ∨ γ) : α ∨ γ := by aesop (add h simp) -- This test checks that the norm simp config is passed around properly. /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example {α β : Prop} (ha : α) (h : α → β) : β := by aesop (rule_sets := [-builtin,-default]) (simp_config := { maxDischargeDepth := 0 }) (config := { terminal := true, useDefaultSimpSet := false }) example {α β : Prop} (ha : α) (h : α → β) : β := by aesop (rule_sets := [-builtin,-default]) -- Ditto. /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : true && false = false := by aesop (rule_sets := [-default,-builtin]) (simp_config := { decide := false }) (config := { terminal := true, useDefaultSimpSet := false }) example : true && false = false := by aesop (rule_sets := [-default,-builtin]) (simp_config := { decide := true }) -- We can use the `useSimpAll` config option to switch between `simp_all` and -- `simp at *`. /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example {α : Prop} (ha : α) : α := by aesop (rule_sets := [-builtin,-default]) (config := { useSimpAll := false, terminal := true }) example {α : Prop} (ha : α) : α := by aesop (rule_sets := [-builtin,-default]) -- We can give priorities to `simp` rules, corresponding to the priorities of -- `simp` lemmas. opaque T : Prop @[aesop simp 1] axiom TF : T ↔ False @[aesop simp 2] axiom TT : T ↔ True example : T := by aesop attribute [-aesop] TF attribute [aesop simp 3] TF /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : T := by aesop (config := { terminal := true }) example : T := by rw [TT]; trivial
.lake/packages/aesop/AesopTest/203.lean
import Aesop.Frontend -- Thank to Damiano Testa for this bug report. /-- info: @[aesop (rule_sets := [builtin✝]) safe✝ apply✝] example : True✝ := trivial✝ -/ #guard_msgs in #eval do let stx ← `(@[aesop (rule_sets := [builtin]) safe apply] example : True := trivial) Lean.logInfo stx
.lake/packages/aesop/AesopTest/Cases.lean
import Aesop set_option aesop.check.all true @[aesop 50% cases] inductive FancyAnd (α β : Prop) : Prop | dummy (p : Empty) | and (a : α) (b : β) attribute [aesop safe -51 cases] Empty example {α β} (h : FancyAnd α β) : α ∧ β := by aesop @[aesop safe cases (cases_patterns := [All _ [], All _ (_ :: _)])] inductive All (P : α → Prop) : List α → Prop | nil : All P [] | cons : P x → All P xs → All P (x :: xs) @[aesop 99% constructors] structure MyTrue : Prop -- Without the patterns on the `cases` rule for `All`, this test would loop -- since the `constructors` rule would never be applied. example {P : α → Prop} (h : All P (x :: xs)) : MyTrue := by aesop
.lake/packages/aesop/AesopTest/Persistence2.lean
import Aesop set_option aesop.check.all true declare_aesop_rule_sets [test_persistence2]
.lake/packages/aesop/AesopTest/RecursiveUnfoldRule.lean
import Aesop set_option aesop.check.all true -- We forbid `unfold` rules for recursive functions since they would lead to -- infinite unfolding. @[aesop norm unfold] def f₁ : Nat → Nat := λ _ => 0 /-- error: Recursive definition 'f₂' cannot be used as an unfold rule (it would be unfolded infinitely often). Try adding a simp rule for it. -/ #guard_msgs in @[aesop norm unfold] def f₂ : Nat → Nat | 0 => 0 | n + 1 => f₂ n /-- error: Recursive definition 'f₃' cannot be used as an unfold rule (it would be unfolded infinitely often). Try adding a simp rule for it. -/ #guard_msgs in @[aesop norm unfold] def f₃ : Nat → Nat := λ n => match n with | 0 => 0 | n + 1 => f₃ n /-- error: Recursive definition 'f₄' cannot be used as an unfold rule (it would be unfolded infinitely often). Try adding a simp rule for it. -/ #guard_msgs in @[aesop norm unfold] def f₄ : Nat → Nat | 0 => 0 | n + 1 => f₄ n -- A limitation of our approach to checking for recursive `unfold` rules: -- mutually recursive rules are not detected. But that's probably fine in -- practice. mutual @[aesop norm unfold] def f₅ : Nat → Nat | 0 => 0 | n + 1 => f₆ n @[aesop norm unfold] def f₆ : Nat → Nat | 0 => 0 | n + 1 => f₅ n end -- We also forbid `unfold` rules for declarations that don't unfold. /-- error: Declaration 'test' cannot be unfolded. -/ #guard_msgs in @[aesop norm unfold] axiom test : Nat
.lake/packages/aesop/AesopTest/DefaultRuleSets.lean
import AesopTest.DefaultRuleSetsInit set_option aesop.check.all true set_option aesop.smallErrorMessages true @[aesop norm unfold (rule_sets := [regular₁])] def T := True /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : T := by aesop (config := { terminal := true }) example : T := by aesop (rule_sets := [regular₁]) @[aesop norm unfold (rule_sets := [regular₂, dflt₁])] def U := True /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : U := by aesop (rule_sets := [-dflt₁]) (config := { terminal := true }) example : U := by aesop
.lake/packages/aesop/AesopTest/DestructProducts.lean
-- This file tests the builtin rules that destruct hypotheses with product-like -- types. import Aesop set_option aesop.check.all true @[aesop safe constructors] inductive Ex (α : Sort u) (β : α → Prop) : Prop | intro (fst : α) (snd : β fst) @[aesop safe constructors] structure Sig (α : Sort u) (β : α → Sort v) : Sort _ where fst : α snd : β fst example (h : α ∧ β) : Sig α (λ _ => β) := by aesop example (h : α × β) : Sig α (λ _ => β) := by aesop example (h : PProd α β) : Sig α (λ _ => β) := by aesop example (h : MProd α β) : Sig α (λ _ => β) := by aesop example {p : α → Prop} (h : ∃ a, p a) : Ex α p := by aesop example {p : α → Prop} (h : { a // p a }) : Sig α p := by aesop example {p : α → Type} (h : Σ a, p a) : Sig α p := by aesop example {p : α → Type} (h : Σ' a, p a) : Sig α p := by aesop -- Test case for a bug reported by Jakob von Raumer. example (x y : α × α) (h: p ∧ (x = y)) : x = y := by aesop (config := { enableSimp := false })
.lake/packages/aesop/AesopTest/SaturatePerformance.lean
import Aesop @[aesop safe forward (pattern := l)] theorem th1 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th2 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th3 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th4 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th5 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th6 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th7 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th8 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th9 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th10 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th11 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th12 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th13 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th14 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th15 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th16 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th17 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th18 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th19 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th20 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th21 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th22 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th23 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th24 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th25 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th26 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th27 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th28 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th29 (l : List α) : l.length ≥ 0 := by simp @[aesop safe forward (pattern := l)] theorem th30 (l : List α) : l.length ≥ 0 := by simp /-- error: unsolved goals α : Type u_1 l0 l1 l2 : List α fwd : l0.length ≥ 0 fwd_1 : l1.length ≥ 0 fwd_2 : l2.length ≥ 0 fwd_3 : (l0 ++ l1).length ≥ 0 fwd_4 : (l0 ++ l1 ++ l2).length ≥ 0 ⊢ (l0 ++ l1 ++ l2).length = l0.length + l1.length + l2.length -/ #guard_msgs in theorem test (l0 l1 l2 : List α) : (l0 ++ l1 ++ l2).length = l0.length + l1.length + l2.length := by saturate
.lake/packages/aesop/AesopTest/SeqCalcProver.lean
import Aesop set_option aesop.check.script true set_option aesop.check.script.steps true --- Decidable attribute [aesop unsafe [50% constructors, 50% cases]] Decidable attribute [aesop safe apply] instDecidableAnd --- Mem attribute [aesop safe cases (cases_patterns := [List.Mem _ []])] List.Mem attribute [aesop unsafe 50% constructors] List.Mem attribute [aesop unsafe 50% cases (cases_patterns := [List.Mem _ (_ :: _)])] List.Mem theorem Mem.map {x : α} {xs : List α} (f : α → β) (h : x ∈ xs) : f x ∈ xs.map f := by induction h <;> aesop theorem Mem.split [DecidableEq α] {xs : List α} {v : α} (h : v ∈ xs) : ∃ l r, xs = l ++ v :: r := by induction xs case nil => aesop case cons x xs ih => have dec : Decidable (x = v) := inferInstance cases dec case isFalse no => let ⟨l, r, eq⟩ : ∃ l r, xs = l ++ v :: r := by aesop rw [eq] exact ⟨x :: l, r, rfl⟩ case isTrue yes => rw [yes] exact ⟨[], xs, rfl⟩ --- All @[aesop safe [constructors, cases (cases_patterns := [All _ [], All _ (_ :: _)])]] inductive All (P : α → Prop) : List α → Prop | nil : All P [] | cons {x xs} : P x → All P xs → All P (x :: xs) namespace All @[simp] theorem split_cons (P : α → Prop) (x : α) (xs : List α) : All P (x :: xs) ↔ (P x ∧ All P xs) := by aesop theorem mem (P : α → Prop) (xs : List α) : All P xs ↔ ∀ a : α, a ∈ xs → P a := by induction xs <;> aesop theorem weaken (P Q : α → Prop) (wk : ∀ x, P x → Q x) (xs : List α) (h : All P xs) : All Q xs := by induction h <;> aesop -- TODO: the trace.aesop.proof does not work here theorem in_self (xs : List α) : All (· ∈ xs) xs := by induction xs <;> aesop (add unsafe apply weaken) theorem map (P : β → Prop) (f : α → β) (xs : List α) : All P (xs.map f) ↔ All (fun x => P (f x)) xs := by induction xs <;> aesop end All --- Any @[aesop safe cases (cases_patterns := [Any _ []]), aesop unsafe [50% constructors, 50% cases (cases_patterns := [Any _ (_ :: _ )])]] inductive Any (P : α → Prop) : List α → Prop | here {x xs} : P x → Any P (x :: xs) | there {x xs} : Any P xs → Any P (x :: xs) namespace Any @[simp] theorem cons (P : α → Prop) (x : α) (xs : List α) : Any P (x :: xs) ↔ (P x ∨ Any P xs) := by aesop theorem mem (P : α → Prop) (xs : List α) : Any P xs ↔ ∃ a : α, P a ∧ a ∈ xs := by apply Iff.intro case mp => intro AnyPxs induction AnyPxs <;> aesop case mpr => intro ⟨a, Pa, Ea⟩ induction Ea <;> aesop theorem map (P : β → Prop) (f : α → β) (xs : List α) : Any P (xs.map f) ↔ Any (fun x => P (f x)) xs := by induction xs <;> aesop instance instDecidablePred (P : α → Prop) [d : DecidablePred P] : DecidablePred (Any P) := by intro xs match xs with | [] => aesop | x :: xs => have ih : Decidable (Any P xs) := instDecidablePred P xs cases d x <;> aesop end Any --- Common @[simp] def Common (xs ys : List α) : Prop := Any (· ∈ ys) xs namespace Common theorem mem {xs ys : List α} (h : Common xs ys) : ∃ a : α, a ∈ xs ∧ a ∈ ys := by induction h <;> aesop theorem sym {xs ys : List α} (h : Common xs ys) : Common ys xs := by have other : ∃ a, a ∈ ys ∧ a ∈ xs := Iff.mp (Any.mem (· ∈ ys) xs) h apply Iff.mpr (Any.mem (· ∈ xs) ys) aesop instance instDecidable [DecidableEq α] (xs ys : List α) : Decidable (Common xs ys) := by apply Any.instDecidablePred end Common --- List Permutations -- From https://github.com/agda/agda-stdlib/blob/master/src/Data/List/Relation/Binary/Permutation/Propositional.agda @[aesop unsafe [50% constructors, 25% cases (cases_patterns := [Perm (_ :: _) (_ :: _ )])]] inductive Perm : (xs ys : List α) → Prop | refl {xs} : Perm xs xs | prep {xs ys} x : Perm xs ys → Perm (x :: xs) (x :: ys) | swap {xs ys} x y : Perm xs ys → Perm (x :: y :: xs) (y :: x :: ys) | tran {xs ys zs} : Perm xs ys → Perm ys zs → Perm xs zs infix:45 " ↭ " => Perm namespace Perm noncomputable section def sym {xs ys : List α} (perm : xs ↭ ys) : ys ↭ xs := by induction perm <;> aesop def shift (v : α) (xs ys : List α) : xs ++ v :: ys ↭ v :: xs ++ ys := by induction xs <;> aesop def map {xs ys : List α} (f : α → β) (perm : xs ↭ ys) : xs.map f ↭ ys.map f := by induction perm <;> aesop theorem all {xs ys : List α} (perm : xs ↭ ys) (P : α → Prop) : All P xs → All P ys := by induction perm <;> aesop theorem any {xs ys : List α} (perm : xs ↭ ys) (P : α → Prop) : Any P xs → Any P ys := by induction perm <;> aesop end end Perm --- Syntax inductive Form (Φ : Type) | pro : Φ → Form Φ | fls : Form Φ | imp (φ ψ : Form Φ) : Form Φ prefix:80 "♩" => Form.pro notation "⊥" => Form.fls infixr:75 " ⇒ " => Form.imp --- Semantics @[simp] def Val (i : Φ → Prop) : Form Φ → Prop | ♩n => i n | ⊥ => false | φ ⇒ ψ => Val i φ → Val i ψ instance Val.instDecidable (i : Φ → Prop) [d : DecidablePred i] (φ : Form Φ) : Decidable (Val i φ) := by match φ with | ♩n => aesop | ⊥ => aesop | φ ⇒ ψ => have ihφ : Decidable (Val i φ) := instDecidable i φ have ihψ : Decidable (Val i ψ) := instDecidable i ψ aesop abbrev Valid (φ : Form Φ) : Prop := ∀ i, DecidablePred i → Val i φ @[simp] def SC (i : Φ → Prop) (Γ Δ : List (Form Φ)) : Prop := All (Val i) Γ → Any (Val i) Δ namespace SC theorem all {i : Φ → Prop} {Γ Γ' Δ : List (Form Φ)} (perm : Γ' ↭ Γ) (h : SC i Γ Δ) : SC i Γ' Δ := by aesop (add unsafe apply Perm.all) theorem any {i : Φ → Prop} {Γ Δ Δ' : List (Form Φ)} (perm : Δ ↭ Δ') (h : SC i Γ Δ) : SC i Γ Δ' := by aesop (add unsafe apply Perm.any) end SC --- Prover @[simp] def sum : List Nat → Nat | [] => 0 | x :: xs => sum xs + x @[simp] def Cal (l r : List Φ) : (Γ Δ : List (Form Φ)) → Prop | [], [] => Common l r | ⊥ :: _, [] => true | Γ, ⊥ :: Δ => Cal l r Γ Δ | ♩n :: Γ, [] => Cal (n :: l) r Γ [] | Γ, ♩n :: Δ => Cal l (n :: r) Γ Δ | φ ⇒ ψ :: Γ, [] => Cal l r Γ [φ] ∧ Cal l r (ψ :: Γ) [] | Γ, φ ⇒ ψ :: Δ => Cal l r (φ :: Γ) (ψ :: Δ) termination_by Γ Δ => sum (Γ.map sizeOf) + sum (Δ.map sizeOf) instance Cal.instDecidable [DecidableEq Φ] (l r : List Φ) (Γ Δ : List (Form Φ)) : Decidable (Cal l r Γ Δ) := by match Γ, Δ with | [], [] => unfold Cal; apply Common.instDecidable l r | ⊥ :: Γ, [] => aesop | Γ, ⊥ :: Δ => have ih : Decidable (Cal l r Γ Δ) := instDecidable l r Γ Δ aesop | ♩n :: Γ, [] => have ih : Decidable (Cal (n :: l) r Γ []) := instDecidable (n :: l) r Γ [] aesop | Γ, ♩n :: Δ => have ih : Decidable (Cal l (n :: r) Γ Δ) := instDecidable l (n :: r) Γ Δ aesop | φ ⇒ ψ :: Γ, [] => have ih₁ : Decidable (Cal l r Γ [φ]) := instDecidable l r Γ [φ] have ih₂ : Decidable (Cal l r (ψ :: Γ) []) := instDecidable l r (ψ :: Γ) [] aesop | Γ, φ ⇒ ψ :: Δ => have ih : Decidable (Cal l r (φ :: Γ) (ψ :: Δ)) := instDecidable l r (φ :: Γ) (ψ :: Δ) aesop termination_by sum (Γ.map sizeOf) + sum (Δ.map sizeOf) decreasing_by all_goals simp_wf <;> simp +arith abbrev Prove (φ : Form Φ) : Prop := Cal [] [] [] [φ] example : Prove (⊥ ⇒ ♩0) := by simp example : Prove (♩0 ⇒ ♩0) := by simp example : Prove (♩0 ⇒ ♩1 ⇒ ♩0) := by simp example : ¬ Prove (♩0 ⇒ ♩1) := by simp (config := {decide := true}) --- Soundness and Completeness @[simp] def SC' (i : Φ → Prop) (l r : List Φ) (Γ Δ : List (Form Φ)) : Prop := SC i (Γ ++ l.map (♩·)) (Δ ++ r.map (♩·)) theorem Cal_sound_complete [DecidableEq Φ] (l r : List Φ) (Γ Δ : List (Form Φ)) : Cal l r Γ Δ ↔ ∀ i : Φ → Prop, DecidablePred i → SC' i l r Γ Δ := by match Γ, Δ with | [], [] => apply Iff.intro case mp => intro h i _ A let ⟨a, al, ar⟩ : ∃ a, a ∈ l ∧ a ∈ r := by unfold Cal at h exact Common.mem h have ml : ♩a ∈ l.map (♩·) := Mem.map (♩·) al have Va : Val i (♩a) := Iff.mp (All.mem (Val i) (l.map (♩·))) A (♩a) ml have mr : ♩a ∈ r.map (♩·) := Mem.map (♩·) ar apply Iff.mpr (Any.mem (Val i) _) ⟨♩a, ⟨Va, mr⟩⟩ case mpr => intro h let i a := a ∈ l have dec : DecidablePred i := inferInstance have h' : All (Val i) (l.map (♩·)) → Any (Val i) (r.map (♩·)) := h i dec have All_l : All (Val i) (l.map (♩·)) := Iff.mpr (All.map (Val i) (♩·) l) (All.in_self l) have Any_r : Any (Val (· ∈ l)) (r.map (♩·)) := h' All_l have Any_r' : Any (fun n => Val (· ∈ l) (♩n)) r := Iff.mp (Any.map (Val i) (♩·) r) Any_r unfold Cal apply Common.sym Any_r' | ⊥ :: Γ, [] => simp | Γ, ⊥ :: Δ => have ih : Cal l r Γ Δ ↔ ∀ i, DecidablePred i → SC' i l r Γ Δ := Cal_sound_complete l r Γ Δ aesop | ♩n :: Γ, [] => have ih : Cal (n :: l) r Γ [] ↔ ∀ i, DecidablePred i → SC' i (n :: l) r Γ [] := Cal_sound_complete (n :: l) r Γ [] have perm : (Γ ++ ♩n :: l.map (♩·)) ↭ (♩n :: Γ ++ l.map (♩·)) := Perm.shift (♩n) Γ _ apply Iff.intro case mp => intro h i dec unfold Cal at h have ihr : SC' i (n :: l) r Γ [] := Iff.mp ih h i dec apply SC.all (Perm.sym perm) ihr case mpr => intro h have hSC : ∀ i, DecidablePred i → SC' i (n :: l) r Γ [] := by intro i dec apply SC.all perm (h i dec) unfold Cal apply Iff.mpr ih hSC | Γ, ♩n :: Δ => have ih : Cal l (n :: r) Γ Δ ↔ ∀ i, DecidablePred i → SC' i l (n :: r) Γ Δ := Cal_sound_complete l (n :: r) Γ Δ have perm : (Δ ++ ♩n :: r.map (♩·)) ↭ (♩n :: Δ ++ r.map (♩·)) := Perm.shift (♩n) Δ _ apply Iff.intro case mp => intro h i dec simp at h have ihr : SC' i l (n :: r) Γ Δ := Iff.mp ih h i dec apply SC.any perm ihr case mpr => intro h have hSC : ∀ i, DecidablePred i → SC' i l (n :: r) Γ Δ := by intro i dec apply SC.any (Perm.sym perm) (h i dec) simp [Iff.mpr ih hSC] | φ ⇒ ψ :: Γ, [] => have ih₁ : Cal l r Γ [φ] ↔ ∀ i, DecidablePred i → SC' i l r Γ [φ] := Cal_sound_complete l r Γ [φ] have ih₂ : Cal l r (ψ :: Γ) [] ↔ ∀ i, DecidablePred i → SC' i l r (ψ :: Γ) [] := Cal_sound_complete l r (ψ :: Γ) [] apply Iff.intro case mp => intro h i dec simp at h have ih₁' : SC' i l r Γ [φ] := Iff.mp ih₁ h.left i dec cases (Val.instDecidable i φ) <;> simp_all case mpr => intro h simp apply And.intro case left => apply Iff.mpr ih₁ intro i dec cases (Val.instDecidable i φ) <;> simp_all case right => apply Iff.mpr ih₂ intro i dec cases (Val.instDecidable i φ) <;> simp_all | Γ, φ ⇒ ψ :: Δ => have ih : Cal l r (φ :: Γ) (ψ :: Δ) ↔ ∀ i, DecidablePred i → SC' i l r (φ :: Γ) (ψ :: Δ) := Cal_sound_complete l r (φ :: Γ) (ψ :: Δ) apply Iff.intro case mp => intro h i dec cases (Val.instDecidable i φ) <;> simp_all case mpr => intro h simp apply Iff.mpr ih intro i dec cases (Val.instDecidable i φ) case isFalse no => simp_all case isTrue yes => intro AllφΓ have AllΓ : All (Val i) (Γ ++ l.map (♩·)) := by simp_all have AnyφψΔ : Any (Val i) (φ ⇒ ψ :: Δ ++ r.map (♩·)) := h i dec AllΓ simp_all termination_by sum (Γ.map sizeOf) + sum (Δ.map sizeOf) decreasing_by all_goals simp_wf <;> simp +arith theorem Prove_sound_complete [DecidableEq Φ] (φ : Form Φ) : Prove φ ↔ Valid φ := by have h : Prove φ ↔ ∀ i : Φ → Prop, DecidablePred i → SC' i [] [] [] [φ] := Cal_sound_complete [] [] [] [φ] apply Iff.intro case mp => intro Pφ i dec have h' : Any (Val i) (φ :: [].map (♩·)) := Iff.mp h Pφ i dec All.nil aesop case mpr => aesop (add simp Valid) --- Proof System inductive Proof : (Γ Δ : List (Form Φ)) → Prop | basic Γ Δ n : Proof (♩n :: Γ) (♩n :: Δ) | fls_l Γ Δ : Proof (⊥ :: Γ) Δ | imp_l Γ Δ φ ψ : Proof Γ (φ :: Δ) → Proof (ψ :: Γ) Δ → Proof (φ ⇒ ψ :: Γ) Δ | imp_r Γ Δ φ ψ: Proof (φ :: Γ) (ψ :: Δ) → Proof Γ (φ ⇒ ψ :: Δ) | per_l Γ Γ' Δ : Proof Γ Δ → Γ' ↭ Γ → Proof Γ' Δ | per_r Γ Δ Δ' : Proof Γ Δ → Δ ↭ Δ' → Proof Γ Δ' attribute [aesop safe apply] Proof.basic Proof.fls_l attribute [aesop unsafe 50% apply] Proof.imp_l Proof.imp_r attribute [aesop unsafe 20% apply] Proof.per_l Proof.per_r namespace Proof theorem weaken (Γ Δ : List (Form Φ)) (prf : Proof Γ Δ) (δ : Form Φ) : Proof Γ (δ :: Δ) := by induction prf with | imp_r Γ Δ φ ψ => have ih' : Proof (φ :: Γ) (ψ :: δ :: Δ) := by aesop aesop | _ => aesop (config := { maxRuleApplications := 250 }) --- Soundness theorem sound (i : Φ → Prop) [DecidablePred i] (prf : Proof Γ Δ) : SC i Γ Δ := by induction prf with | imp_r Γ Δ φ ψ _ ih => have d : Decidable (Val i φ) := inferInstance aesop | _ => aesop (add unsafe apply [Perm.all, Perm.any]) end Proof @[simp] def Proof' (l r : List Φ) (Γ Δ : List (Form Φ)) : Prop := Proof (Γ ++ l.map (♩·)) (Δ ++ r.map (♩·)) theorem Cal_Proof [DecidableEq Φ] (l r : List Φ) (Γ Δ : List (Form Φ)) (h : Cal l r Γ Δ) : Proof' l r Γ Δ := by match Γ, Δ with | [], [] => let ⟨a, al, ar⟩ : ∃ a, a ∈ l ∧ a ∈ r := by unfold Cal at h exact Common.mem h let ⟨ll, lr, leq⟩ : ∃ ll lr, l = ll ++ a :: lr := Mem.split al let ⟨rl, rr, req⟩ : ∃ rl rr, r = rl ++ a :: rr := Mem.split ar rw [leq, req] have p : Proof' (a :: ll ++ lr) (a :: rl ++ rr) [] [] := by apply Proof.basic have p' : Proof' (ll ++ a :: lr) (a :: rl ++ rr) [] [] := by aesop (add unsafe apply [Perm.map, Perm.shift]) aesop (add unsafe apply [Perm.map, Perm.shift, Perm.sym]) | ⊥ :: Γ, [] => aesop | Γ, ⊥ :: Δ => simp at h have ih : Proof' l r Γ Δ := Cal_Proof l r Γ Δ h apply Proof.weaken _ _ ih ⊥ | ♩n :: Γ, [] => unfold Cal at h have ih : Proof' (n :: l) r Γ [] := Cal_Proof (n :: l) r Γ [] h apply Proof.per_l _ _ _ ih aesop (add unsafe apply [Perm.shift, Perm.sym]) | Γ, ♩n :: Δ => simp at h have ih : Proof' l (n :: r) Γ Δ := Cal_Proof l (n :: r) Γ Δ h aesop (add unsafe apply [Perm.shift]) | φ ⇒ ψ :: Γ, [] => simp at h have ih₁ : Proof' l r Γ [φ] := Cal_Proof l r Γ [φ] h.left have ih₂ : Proof' l r (ψ :: Γ) [] := Cal_Proof l r (ψ :: Γ) [] h.right aesop | Γ, φ ⇒ ψ :: Δ => simp at h have ih : Proof' l r (φ :: Γ) (ψ :: Δ) := Cal_Proof l r (φ :: Γ) (ψ :: Δ) h aesop termination_by sum (Γ.map sizeOf) + sum (Δ.map sizeOf) decreasing_by all_goals simp_wf <;> simp +arith theorem Proof_sound_complete [DecidableEq Φ] (φ : Form Φ) : Proof [] [φ] ↔ Valid φ := by apply Iff.intro case mp => intro prf i dec have h : Any (Val i) [φ] := Proof.sound i prf All.nil aesop case mpr => intro h have c : Prove φ := Iff.mpr (Prove_sound_complete φ) h have prf : Proof' [] [] [] [φ] := Cal_Proof [] [] [] [φ] c exact prf
.lake/packages/aesop/AesopTest/CasesTypeSynonym.lean
import Aesop inductive T abbrev U := T def V := T abbrev W := V def X := V example (h : T) : False := by fail_if_success aesop (config := { terminal := true }) aesop (add safe cases T) example (h : T) : False := by aesop (add safe cases U) example (h : U) : False := by aesop (add safe cases U) example (h : V) : False := by fail_if_success aesop (config := { terminal := true }) fail_if_success aesop (add safe cases T) (config := { terminal := true }) fail_if_success aesop (add safe cases U) (config := { terminal := true }) aesop (add safe cases V) example (h : W) : False := by fail_if_success aesop (config := { terminal := true }) fail_if_success aesop (add safe cases T) (config := { terminal := true }) fail_if_success aesop (add safe cases U) (config := { terminal := true }) aesop (add safe cases V) example (h : V) : False := by aesop (add safe cases W) example (h : X) : False := by fail_if_success aesop (config := { terminal := true }) fail_if_success aesop (add safe cases T) (config := { terminal := true }) fail_if_success aesop (add safe cases U) (config := { terminal := true }) fail_if_success aesop (add safe cases V) (config := { terminal := true }) fail_if_success aesop (add safe cases W) (config := { terminal := true }) aesop (add safe cases X) example (h : T) : False := by aesop (add safe cases (transparency! := default) X) inductive A (α : Type) : Prop abbrev B β := A β example (h : A Unit) : False := by fail_if_success aesop (config := { terminal := true }) aesop (add safe cases A) example (h : A Unit) : False := by aesop (add safe cases B) example (h : B Unit) : False := by fail_if_success aesop (config := { terminal := true }) aesop (add safe cases A) example (h : B Unit) : False := by aesop (add safe cases B)
.lake/packages/aesop/AesopTest/DestructProductsTransparency.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true @[aesop safe constructors] structure Sig (α : Sort u) (β : α → Sort v) : Sort _ where fst : α snd : β fst def T α β := α ∧ β /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example (h : T α β) : Sig α (λ _ => β) := by aesop (config := { terminal := true }) example (h : T α β) : Sig α (λ _ => β) := by aesop (config := { destructProductsTransparency := .default }) def U := T /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example (h : U α β) : Sig α (λ _ => β) := by aesop (config := { terminal := true }) example (h : U α β) : Sig α (λ _ => β) := by aesop (config := { destructProductsTransparency := .default }) /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example (h : U α β ∧ U γ δ) : Sig α (λ _ => γ) := by aesop (config := { terminal := true }) example (h : U α β ∧ U γ δ) : Sig α (λ _ => γ) := by aesop (config := { destructProductsTransparency := .default })
.lake/packages/aesop/AesopTest/Logic.lean
import Aesop set_option aesop.check.all true example : True := by aesop example : Unit := by aesop example : PUnit.{u} := by aesop example (h : False) : α := by aesop example (h : Empty) : α := by aesop example (h : PEmpty.{u}) : α := by aesop
.lake/packages/aesop/AesopTest/126.lean
import Aesop set_option aesop.check.all true -- TODO simp_all introduces spurious metavariables in this example set_option aesop.check.rules false set_option aesop.check.tree false theorem foo {a : Nat → Nat} (ha : a 0 = 37) : (match h : a 0 with | 42 => by simp_all | n => n) = 37 := by aesop
.lake/packages/aesop/AesopTest/Com.lean
import Aesop set_option aesop.check.all false -- With this option, the test becomes unbearably slow. abbrev State := String → Int inductive Com where | Skip : Com | Seq : Com → Com → Com declare_syntax_cat com syntax "SKIP" : com syntax com ";" com : com syntax "(" com ")" : com syntax term : com syntax "[Com|" com "]" : term macro_rules | `([Com| SKIP]) => `(Com.Skip) | `([Com| $x ; $y]) => `(Com.Seq [Com| $x] [Com| $y]) | `([Com| ( $x:com )]) => `([Com| $x]) | `([Com| $x:term ]) => `($x) @[aesop safe [constructors, -100 cases (index := [hyp BigStep Com.Skip _ _, hyp BigStep [Com| _;_] _ _])]] inductive BigStep : Com → State → State → Prop where | Skip : BigStep Com.Skip s s | Seq (h1 : BigStep c₁ s t) (h2 : BigStep c₂ t u) : BigStep [Com| c₁;c₂] s u theorem seq_assoc : BigStep [Com| (c1;c2);c3] s s' ↔ BigStep [Com| c1;c2;c3] s s' := by aesop
.lake/packages/aesop/AesopTest/ExtScript.lean
import Aesop set_option aesop.check.all true @[ext] structure MyProd (α β : Type _) where fst : α snd : β variable {α β γ δ ι: Type} /-- info: Try this: [apply] ext : 1 · sorry · sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example {p q : MyProd α β} : p = q := by aesop? (add safe Aesop.BuiltinRules.ext) (config := { warnOnNonterminal := false }) all_goals sorry /-- info: Try this: [apply] ext : 1 · sorry · ext : 1 · sorry · sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example {p q : MyProd α (MyProd β γ)} : p = q := by aesop? (add safe Aesop.BuiltinRules.ext) (config := { warnOnNonterminal := false }) all_goals sorry /-- info: Try this: [apply] ext : 1 · ext x : 1 sorry · sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example {p q : MyProd (α → β) γ} : p = q := by aesop? (add safe Aesop.BuiltinRules.ext) (config := { warnOnNonterminal := false }) all_goals sorry /-- info: Try this: [apply] ext : 1 · ext x : 1 sorry · ext x x_1 : 2 sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example {p q : (α → β) × (γ → δ → ι)} : p = q := by aesop? (add safe Aesop.BuiltinRules.ext) (erase Aesop.BuiltinRules.destructProducts) (config := { warnOnNonterminal := false }) all_goals sorry -- This test case checks script generation for ext calls which generate subgoals -- with different numbers of new hypotheses. axiom T : Type axiom U : Type axiom u : U axiom v : U @[ext (iff := false)] axiom T_ext : ∀ x y : T, u = v → (∀ u v : U, u = v) → x = y /-- info: Try this: [apply] ext u v : 1 · sorry · sorry --- warning: declaration uses 'sorry' -/ #guard_msgs in example (x y : T) : x = y := by aesop? (add safe Aesop.BuiltinRules.ext) (config := { warnOnNonterminal := false }) all_goals sorry
.lake/packages/aesop/AesopTest/List.lean
-- Ported from mathlib3, file src/data/list/basic.lean, -- commit a945b3769cb82bc238ee004b4327201a6864e7e0 import Aesop set_option aesop.check.script true -- We use this constant to 'prove' theorems which Aesop can't solve. We don't -- use `sorry` because it generates lots of warnings. axiom ADMIT : ∀ {α : Sort _}, α class IsEmpty (α : Sort _) where false : α → False @[aesop safe forward] def IsEmpty.false' (h : IsEmpty α) (a : α) : False := h.false a @[aesop safe constructors] structure Unique (α : Sort _) extends Inhabited α where uniq : ∀ a : α, a = toInhabited.default class IsLeftId (α : Type _) (op : α → α → α) (o : outParam α) : Prop where leftId : ∀ a, op o a = a def Injective (f : α → β) : Prop := ∀ x y, f x = f y → x = y @[aesop safe forward] theorem injective_elim (h₁ : Injective f) (h₂ : f a = f b) : a = b := h₁ _ _ h₂ @[aesop 99%] theorem injective_intro (h : ∀ a b, f a = f b → a = b) : Injective f := h def Surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b @[aesop norm forward (immediate := [h])] theorem surjective_elim (h : Surjective f) : ∀ b, ∃ a, f a = b := h @[aesop 99%] theorem surjective_intro (h : ∀ b, ∃ a, f a = b) : Surjective f := h @[aesop norm unfold] def Bijective (f : α → β) : Prop := Injective f ∧ Surjective f def Involutive (f : α → α) : Prop := ∀ x, f (f x) = x @[aesop norm forward] theorem involutive_elim {f : α → α} (h : Involutive f) (a : α) : f (f a) = a := h a @[aesop 99%] theorem involutive_intro (h : ∀ a, f (f a) = a) : Involutive f := h @[aesop 25%] theorem Involutive.injective : Involutive f → Injective f := λ h x y hxy => by rw [← h x, ← h y, hxy] @[aesop 25%] theorem Involutive.surjective : Involutive f → Surjective f := λ h x => ⟨f x, h x⟩ theorem Involutive.bijective (h : Involutive f) : Bijective f := ⟨h.injective, h.surjective⟩ namespace Option @[aesop safe [constructors, cases]] inductive Mem (a : α) : Option α → Prop | some : Mem a (some a) instance : Membership α (Option α) := ⟨λ a o => Option.Mem a o⟩ @[simp] theorem mem_spec {o : Option α} : a ∈ o ↔ o = some a := by aesop (add norm simp Membership.mem) @[simp] theorem mem_none : a ∈ none ↔ False := by aesop @[simp] def iget [Inhabited α] : Option α → α | none => default | some a => a end Option namespace List -- The `ext` rule for lists says that `l₁ = l₂ ↔ (∀ a, a ∈ l₁ ↔ a ∈ l₂)`. This -- is not particularly helpful for this file. attribute [-aesop] Aesop.BuiltinRules.ext attribute [simp] map List.flatMap instance : Pure List where pure x := [x] def init : List α → List α | [] => [] | [_] => [] | a :: as => a :: init as @[simp] def last : (l : List α) → l ≠ [] → α | [], h => nomatch h | [a], _ => a | _ :: a :: as, _ => last (a :: as) (by aesop) -- The unnecessarily complicated case split in this definition is inherited from -- Lean 3. @[simp] def ilast [Inhabited α] : List α → α | [] => default | [a] => a | [_, b] => b | _ :: _ :: l => ilast l @[simp] def head' : List α → Option α | [] => none | a :: _ => some a @[simp] def ihead [Inhabited α] : List α → α | [] => default | a :: _ => a @[simp] def nth_le : ∀ (l : List α) (n), n < l.length → α | [], n, h => absurd h n.not_lt_zero | (a :: _), 0, _ => a | (_ :: l), (n+1), h => nth_le l n (by simp_all +arith) @[simp] def modify_head (f : α → α) : List α → List α | [] => [] | (a :: as) => f a :: as @[simp] def Empty : List α → Prop | [] => True | _ :: _ => False @[simp] theorem mem_eq_mem : Mem x xs ↔ x ∈ xs := Iff.rfl theorem subset_trans {l₁ l₂ l₃ : List α} : l₁ ⊆ l₂ → l₂ ⊆ l₃ → l₁ ⊆ l₃ := by intro h₁ h₂ a ha cases l₁ with | nil => cases ha | cons x xs => cases ha with | head => apply h₂ apply h₁ constructor | tail _ hxs => apply h₂ apply h₁ constructor assumption -- END PRELUDE instance unique_of_is_empty [IsEmpty α] : Unique (List α) := by aesop (add 1% cases List) -- instance : is_left_id (list α) has_append.append [] := -- ⟨ nil_append ⟩ -- instance : is_right_id (list α) has_append.append [] := -- ⟨ append_nil ⟩ -- instance : is_associative (list α) has_append.append := -- ⟨ append_assoc ⟩ -- attribute [-simp] cons_ne_nil theorem X.cons_ne_nil (a : α) (l : List α) : a::l ≠ [] := by aesop -- attribute [-simp] cons_ne_self theorem X.cons_ne_self (a : α) (l : List α) : a::l ≠ l := by aesop (add 1% cases Eq) -- attribute [-simp] head_eq_of_cons_eq theorem X.head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : List α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := by aesop -- attribute [-simp] tail_eq_of_cons_eq theorem X.tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : List α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := by aesop @[simp] theorem cons_injective {a : α} : Injective (cons a) := by aesop -- attribute [-simp] cons_inj theorem X.cons_inj (a : α) {l l' : List α} : a::l = a::l' ↔ l = l' := by aesop -- attribute [-simp] exists_cons_of_ne_nil theorem X.exists_cons_of_ne_nil : l ≠ nil → ∃ b L, l = b :: L := by aesop (add 1% cases List) -- theorem set_of_mem_cons (l : list α) (a : α) : {x | x ∈ a :: l} = insert a {x | x ∈ l} := rfl /-! ### mem -/ attribute [aesop safe constructors] List.Mem attribute [aesop safe cases (cases_patterns := [List.Mem _ [], List.Mem _ (_ :: _)])] List.Mem -- attribute [-simp] mem_singleton_self @[simp] theorem X.mem_singleton_self (a : α) : a ∈ [a] := by aesop -- attribute [-simp] eq_of_mem_singleton theorem X.eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := by aesop @[simp] theorem X.mem_singleton {a b : α} : a ∈ [b] ↔ a = b := by aesop -- attribute [-simp] mem_of_mem_cons_of_mem theorem X.mem_of_mem_cons_of_mem {a b : α} {l : List α} : a ∈ b::l → b ∈ l → a ∈ l := by aesop set_option linter.unusedVariables false in theorem _root_.decidable.list.eq_or_ne_mem_of_mem [deq : DecidableEq α] {a b : α} {l : List α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := ADMIT -- cases deq a b <;> aesop -- attribute [-simp] eq_or_ne_mem_of_mem theorem X.eq_or_ne_mem_of_mem {a b : α} {l : List α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) := by open Classical in aesop (add safe [decidable.list.eq_or_ne_mem_of_mem]) -- attribute [-simp] not_mem_append theorem X.not_mem_append {a : α} {s t : List α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := by induction s <;> aesop -- attribute [-simp] ne_nil_of_mem theorem X.ne_nil_of_mem {a : α} {l : List α} (h : a ∈ l) : l ≠ [] := by aesop set_option linter.unusedVariables false in theorem mem_split {a : α} {l : List α} (h : a ∈ l) : ∃ s t : List α, l = s ++ a :: t := ADMIT -- Nontrivial existential. -- attribute [-simp] mem_of_ne_of_mem theorem X.mem_of_ne_of_mem {a y : α} {l : List α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := by aesop -- attribute [-simp] ne_of_not_mem_cons theorem X.ne_of_not_mem_cons {a b : α} {l : List α} : a ∉ b::l → a ≠ b := by aesop -- attribute [-simp] not_mem_of_not_mem_cons theorem X.not_mem_of_not_mem_cons {a b : α} {l : List α} : a ∉ b::l → a ∉ l := by aesop -- attribute [-simp] not_mem_cons_of_ne_of_not_mem theorem X.not_mem_cons_of_ne_of_not_mem {a y : α} {l : List α} : a ≠ y → a ∉ l → a ∉ y::l := by aesop -- attribute [-simp] ne_and_not_mem_of_not_mem_cons theorem X.ne_and_not_mem_of_not_mem_cons {a y : α} {l : List α} : a ∉ y::l → a ≠ y ∧ a ∉ l := by aesop -- attribute [-simp] mem_map @[simp] theorem X.mem_map {f : α → β} {b : β} {l : List α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := by induction l <;> aesop -- attribute [-simp] mem_map_of_mem @[aesop safe] theorem X.mem_map_of_mem (f : α → β) {a : α} {l : List α} (h : a ∈ l) : f a ∈ map f l := by aesop theorem mem_map_of_injective {f : α → β} (H : Injective f) {a : α} {l : List α} : f a ∈ map f l ↔ a ∈ l := by set_option aesop.check.script false in -- TODO pp.analyze bug? aesop @[simp] theorem _root_.function.involutive.exists_mem_and_apply_eq_iff {f : α → α} (hf : Involutive f) (x : α) (l : List α) : (∃ (y : α), y ∈ l ∧ f y = x) ↔ f x ∈ l := by aesop theorem mem_map_of_involutive {f : α → α} (hf : Involutive f) {a : α} {l : List α} : a ∈ map f l ↔ f a ∈ l := by aesop -- attribute [-simp] forall_mem_map_iff theorem X.forall_mem_map_iff {f : α → β} {l : List α} {P : β → Prop} : (∀ i, i ∈ l.map f → P i) ↔ ∀ j, j ∈ l → P (f j) := by aesop -- attribute [-simp] map_eq_nil @[simp] theorem X.map_eq_nil {f : α → β} {l : List α} : map f l = [] ↔ l = [] := by aesop (add 1% cases List) attribute [-simp] mem_flatten @[simp] theorem X.mem_flatten {a : α} : ∀ {L : List (List α)}, a ∈ flatten L ↔ ∃ l, l ∈ L ∧ a ∈ l := by intro L; induction L <;> aesop -- attribute [-simp] exists_of_mem_flatten theorem X.exists_of_mem_flatten {a : α} {L : List (List α)} : a ∈ flatten L → ∃ l, l ∈ L ∧ a ∈ l := by aesop -- attribute [-simp] mem_flatten_of_mem theorem X.mem_flatten_of_mem {a : α} {L : List (List α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ flatten L := by aesop -- attribute [-simp] mem_flatMap @[simp] theorem X.mem_flatMap {b : β} {l : List α} {f : α → List β} : b ∈ l.flatMap f ↔ ∃ a, a ∈ l ∧ b ∈ f a := by induction l <;> aesop -- attribute [-simp] exists_of_mem_flatMap theorem X.exists_of_mem_flatMap {l : List α} : b ∈ l.flatMap f → ∃ a, a ∈ l ∧ b ∈ f a := by aesop -- attribute [-simp] mem_flatMap_of_mem theorem X.mem_flatMap_of_mem {l : List α} : (∃ a, a ∈ l ∧ b ∈ f a) → b ∈ l.flatMap f := by induction l <;> aesop -- attribute [-simp] flatMap_map theorem X.flatMap_map {g : α → List β} {f : β → γ} : ∀ l : List α, map f (l.flatMap g) = l.flatMap (λa => (g a).map f) := by intro l; induction l <;> aesop theorem map_flatMap' (g : β → List γ) (f : α → β) : ∀ l : List α, (map f l).flatMap g = l.flatMap (λ a => g (f a)) := by intro l; induction l <;> aesop -- theorem range_map (f : α → β) : set.range (map f) = {l | ∀ x ∈ l, x ∈ set.range f} := -- theorem range_map_coe (s : set α) : set.range (map (coe : s → α)) = {l | ∀ x ∈ l, x ∈ s} := -- instance [h : can_lift α β] : can_lift (list α) (list β) := /-! ### length -/ -- attribute [-simp] length_eq_zero theorem X.length_eq_zero {l : List α} : length l = 0 ↔ l = [] := by aesop (add 1% cases List) attribute [-simp] length_singleton @[simp] theorem X.length_singleton (a : α) : length [a] = 1 := rfl -- attribute [-simp] length_pos_of_mem theorem X.length_pos_of_mem {a : α} : ∀ {l : List α}, a ∈ l → 0 < length l := by aesop (add 1% cases List) (simp_config := { arith := true }) -- attribute [-simp] exists_mem_of_length_pos theorem X.exists_mem_of_length_pos : ∀ {l : List α}, 0 < length l → ∃ a, a ∈ l := by aesop (add 1% cases List) -- attribute [-simp] length_pos_iff_exists_mem theorem X.length_pos_iff_exists_mem {l : List α} : 0 < length l ↔ ∃ a, a ∈ l := by aesop (add unsafe [length_pos_of_mem, exists_mem_of_length_pos]) -- attribute [-simp] ne_nil_of_length_pos theorem X.ne_nil_of_length_pos {l : List α} : 0 < length l → l ≠ [] := by aesop (add 1% cases List) theorem length_pos_of_ne_nil {l : List α} : l ≠ [] → 0 < length l := by aesop (add 1% cases List) (simp_config := { arith := true }) theorem length_pos_iff_ne_nil {l : List α} : 0 < length l ↔ l ≠ [] := by aesop (add unsafe [ne_nil_of_length_pos, length_pos_of_ne_nil]) -- attribute [-simp] exists_mem_of_ne_nil theorem X.exists_mem_of_ne_nil (l : List α) (h : l ≠ []) : ∃ x, x ∈ l := by aesop (add 1% cases List) -- attribute [-simp] length_eq_one theorem X.length_eq_one : length l = 1 ↔ ∃ a, l = [a] := by aesop (add 1% cases List) theorem exists_of_length_succ {n} : ∀ l : List α, l.length = n + 1 → ∃ h t, l = h :: t := by intro l; induction l <;> aesop (simp_config := { arith := true }) @[simp] theorem length_injective_iff : Injective (length : List α → Nat) ↔ Subsingleton α := ADMIT -- Requires induction after case split. @[simp] theorem length_injective [Subsingleton α] : Injective (length : List α → Nat) := by aesop theorem length_eq_two {l : List α} : l.length = 2 ↔ ∃ a b, l = [a, b] := by aesop (add 50% cases List) theorem length_eq_three {l : List α} : l.length = 3 ↔ ∃ a b c, l = [a, b, c] := by aesop (add 50% cases List) /-! ### set-theoretic notation of lists -/ attribute [-simp] empty_eq theorem X.empty_eq : (∅ : List α) = [] := rfl -- theorem singleton_eq (x : α) : ({x} : List α) = [x] -- theorem insert_neg [DecidableEq α] {x : α} {l : List α} (h : x ∉ l) : -- has_insert.insert x l = x :: l -- theorem insert_pos [DecidableEq α] {x : α} {l : List α} (h : x ∈ l) : -- has_insert.insert x l = l -- theorem doubleton_eq [DecidableEq α] {x y : α} (h : x ≠ y) : ({x, y} : List α) = [x, y] /-! ### bounded quantifiers over lists -/ -- The notation used in Lean 3 (`∀ x ∈ xs, P x` and `∃ x ∈ xs, P x`) does not -- exist in Lean 4. We've expanded it manually. -- attribute [-simp] forall_mem_nil theorem X.forall_mem_nil (p : α → Prop) : ∀ x, x ∈ @nil α → p x := by aesop -- attribute [-simp] forall_mem_cons theorem X.forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : List α}, (∀ x, x ∈ a :: l → p x) ↔ p a ∧ ∀ x, x ∈ l → p x := by aesop theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : List α} (h : ∀ x, x ∈ a :: l → p x) : ∀ x, x ∈ l → p x := by aesop -- attribute [-simp] forall_mem_singleton theorem X.forall_mem_singleton {p : α → Prop} {a : α} : (∀ x, x ∈ [a] → p x) ↔ p a := by aesop -- attribute [-simp] forall_mem_append theorem X.forall_mem_append {p : α → Prop} {l₁ l₂ : List α} : (∀ x, x ∈ l₁ ++ l₂ → p x) ↔ (∀ x, x ∈ l₁ → p x) ∧ (∀ x, x ∈ l₂ → p x) := by aesop theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x, x ∈ @nil α ∧ p x := by aesop theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : List α) (h : p a) : ∃ x, x ∈ a :: l ∧ p x := by aesop theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : List α} (h : ∃ x, x ∈ l ∧ p x) : ∃ x, x ∈ a :: l ∧ p x := by aesop theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : List α} (h : ∃ x, x ∈ a :: l ∧ p x) : p a ∨ ∃ x, x ∈ l ∧ p x := by aesop theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : List α) : (∃ x, x ∈ a :: l ∧ p x) ↔ p a ∨ ∃ x, x ∈ l ∧ p x := by aesop /-! ### list subset -/ -- attribute [-simp] subset_def theorem X.subset_def {l₁ l₂ : List α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := by aesop -- attribute [-simp] subset_append_of_subset_left theorem X.subset_append_of_subset_left (l l₁ l₂ : List α) : l ⊆ l₁ → l ⊆ l₁++l₂ := by aesop (add 1% subset_trans) -- attribute [-simp] subset_append_of_subset_right theorem X.subset_append_of_subset_right (l l₁ l₂ : List α) : l ⊆ l₂ → l ⊆ l₁ ++ l₂ := by aesop (add 1% subset_trans) attribute [-simp] cons_subset @[simp] theorem X.cons_subset {a : α} {l m : List α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by aesop (add norm simp [HasSubset.Subset, List.Subset]) theorem cons_subset_of_subset_of_mem {a : α} {l m : List α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := by aesop theorem append_subset_of_subset_of_subset {l₁ l₂ l : List α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := by aesop (add norm simp [HasSubset.Subset, List.Subset]) @[simp] theorem append_subset_iff {l₁ l₂ l : List α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := by aesop (add norm simp [HasSubset.Subset, List.Subset]) @[aesop safe destruct] theorem eq_nil_of_subset_nil' {l : List α} : l ⊆ [] → l = [] := by aesop (add 1% cases List) -- attribute [-simp] eq_nil_iff_forall_not_mem theorem X.eq_nil_iff_forall_not_mem {l : List α} : l = [] ↔ ∀ a, a ∉ l := ADMIT -- used to be by `aesop (add 1% cases List)` until simp changes around nightly -- 2024-03-11 -- attribute [-simp] map_subset theorem X.map_subset {l₁ l₂ : List α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := by aesop (add norm simp [HasSubset.Subset, List.Subset]) theorem map_subset_iff {l₁ l₂ : List α} (f : α → β) (h : Injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := by induction l₁ <;> induction l₂ · aesop · aesop · aesop · set_option aesop.check.script false in aesop -- TODO timeout in script generation /-! ### append -/ theorem append_eq_has_append {L₁ L₂ : List α} : List.append L₁ L₂ = L₁ ++ L₂ := rfl attribute [-simp] singleton_append @[simp] theorem X.singleton_append {x : α} {l : List α} : [x] ++ l = x :: l := rfl -- attribute [-simp] append_ne_nil_of_ne_nil_left theorem X.append_ne_nil_of_ne_nil_left (s t : List α) : s ≠ [] → s ++ t ≠ [] := by induction s <;> aesop -- attribute [-simp] append_ne_nil_of_ne_nil_right theorem X.append_ne_nil_of_ne_nil_right (s t : List α) : t ≠ [] → s ++ t ≠ [] := by induction s <;> aesop @[simp] theorem X.append_eq_nil {p q : List α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by aesop (add 1% cases List) -- attribute [-simp] nil_eq_append_iff @[simp] theorem X.nil_eq_append_iff {a b : List α} : [] = a ++ b ↔ a = [] ∧ b = [] := by induction a <;> aesop -- attribute [-simp] append_eq_cons_iff theorem X.append_eq_cons_iff {a b c : List α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by aesop (add 1% cases List) -- attribute [-simp] cons_eq_append_iff theorem X.cons_eq_append_iff {a b c : List α} {x : α} : (x :: c : List α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by aesop (add norm simp [append_eq_cons_iff, eq_comm]) -- attribute [-simp] append_eq_append_iff theorem X.append_eq_append_iff {a b c d : List α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := ADMIT -- Nontrivial existential. attribute [-simp] take_append_drop @[simp] theorem X.take_append_drop : ∀ (n : Nat) (l : List α), take n l ++ drop n l = l | 0 , a => by aesop | (.succ _), [] => by aesop | (.succ n), (_ :: xs) => by have ih := take_append_drop n xs aesop @[aesop safe forward] theorem X.append_inj : ∀ {s₁ s₂ t₁ t₂ : List α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] , [] , t₁, t₂, h, _ => by aesop | (a::s₁), [] , t₁, t₂, _, hl => by aesop | [] , (b::s₂), t₁, t₂, _, hl => by aesop | (a::s₁), (b::s₂), t₁, t₂, h, hl => by have ih := @append_inj _ s₁ s₂ t₁ t₂ aesop -- attribute [-simp] append_inj_right theorem X.append_inj_right {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := by aesop -- attribute [-simp] append_inj_left theorem X.append_inj_left {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := by aesop -- attribute [-simp] append_inj' set_option linter.unusedVariables false in @[aesop safe forward] theorem X.append_inj' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := by induction s₁ generalizing s₂ <;> induction s₂ <;> aesop (simp_config := { arith := true }) -- attribute [-simp] append_inj_right' theorem X.append_inj_right' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := by aesop -- attribute [-simp] append_inj_left' theorem X.append_inj_left' {s₁ s₂ t₁ t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := by aesop theorem append_left_cancel {s t₁ t₂ : List α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := by aesop theorem append_right_cancel {s₁ s₂ t : List α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := by aesop theorem append_right_injective (s : List α) : Injective (λ t => s ++ t) := by aesop -- attribute [-simp] append_right_inj theorem X.append_right_inj {t₁ t₂ : List α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := by aesop theorem append_left_injective (t : List α) : Injective (λ s => s ++ t) := by aesop -- attribute [-simp] append_left_inj theorem X.append_left_inj {s₁ s₂ : List α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := by aesop -- attribute [-simp] map_eq_append_split set_option linter.unusedVariables false in theorem X.map_eq_append_split {f : α → β} {l : List α} {s₁ s₂ : List β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := ADMIT -- Nontrivial existential. /-! ### replicate/repeat -/ -- Note: `replicate` is called `repeat` in Lean 3 and has flipped arguments. -- attribute [-simp] replicate_succ @[simp] theorem X.replicate_succ (a : α) (n) : replicate (n + 1) a = a :: replicate n a := rfl -- attribute [-simp] mem_replicate @[simp] theorem X.mem_replicate {a b : α} {n} : b ∈ replicate n a ↔ n ≠ 0 ∧ b = a := by induction n <;> aesop -- attribute [-simp] eq_of_mem_replicate @[aesop safe destruct] theorem X.eq_of_mem_replicate {a b : α} {n} (h : b ∈ replicate n a) : b = a := by aesop -- attribute [-simp] eq_replicate_of_mem theorem X.eq_replicate_of_mem {a : α} {l : List α} : (∀ b, b ∈ l → b = a) → l = replicate l.length a := by induction l <;> aesop (config := { useSimpAll := false }) theorem eq_replicate' {a : α} {l : List α} : l = replicate l.length a ↔ ∀ b, b ∈ l → b = a := by induction l <;> aesop -- attribute [-simp] eq_replicate theorem X.eq_replicate {a : α} {n} {l : List α} : l = replicate n a ↔ length l = n ∧ ∀ b, b ∈ l → b = a := by aesop (add norm simp eq_replicate') theorem replicate_add (a : α) (m n) : replicate (m + n) a = replicate m a ++ replicate n a := ADMIT -- Need to apply associativity of addition to let `replicate` reduce. theorem replicate_subset_singleton (a : α) (n) : replicate n a ⊆ [a] := by aesop (add norm simp [HasSubset.Subset, List.Subset]) theorem subset_singleton_iff {a : α} {L : List α} : L ⊆ [a] ↔ ∃ n, L = replicate n a := ADMIT -- Nontrivial existential. attribute [-simp] map_const -- attribute [-simp] map_const' @[simp] theorem map_const'' (l : List α) (b : β) : map (λ _ => b) l = replicate l.length b := by induction l <;> aesop theorem eq_of_mem_map_const {b₁ b₂ : β} {l : List α} (h : b₁ ∈ map (λ _ => b₂) l) : b₁ = b₂ := by aesop attribute [-simp] map_replicate @[simp] theorem map_replicate' (f : α → β) (a : α) (n) : map f (replicate n a) = replicate n (f a) := by induction n <;> aesop attribute [-simp] tail_replicate @[simp] theorem tail_replicate' (a : α) (n) : tail (replicate n a) = replicate n.pred a := by aesop (add 1% cases Nat) attribute [-simp] flatten_replicate_nil @[simp] theorem flatten_replicate_nil' (n : Nat) : flatten (replicate n []) = @nil α := by induction n <;> aesop theorem replicate_left_injective {n : Nat} (hn : n ≠ 0) : Injective (λ a : α => replicate n a) := by induction n <;> aesop @[simp] theorem replicate_left_inj' {a b : α} : ∀ {n}, replicate n a = replicate n b ↔ n = 0 ∨ a = b := by intro n; induction n <;> aesop theorem replicate_right_injective (a : α) : Injective (λ n => replicate n a) := by unfold Injective; intro x y induction x generalizing y <;> induction y <;> aesop (config := { useSimpAll := false }) @[simp] theorem replicate_right_inj {a : α} {n m : Nat} : replicate n a = replicate m a ↔ n = m := by aesop /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : List α) ↔ x = y := by aesop (add norm simp pure) /-! ### flatMap -/ instance : Bind List where bind l f := List.flatMap f l @[simp] theorem bind_eq_flatMap {α β} (f : α → List β) (l : List α) : l >>= f = l.flatMap f := rfl attribute [-simp] flatMap_append theorem X.flatMap_append (f : α → List β) (l₁ l₂ : List α) : (l₁ ++ l₂).flatMap f = l₁.flatMap f ++ l₂.flatMap f := by induction l₁ <;> aesop attribute [-simp] flatMap_singleton' @[simp] theorem X.flatMap_singleton' (f : α → List β) (x : α) : [x].flatMap f = f x := by aesop @[simp] theorem X.flatMap_singleton'' (l : List α) : l.flatMap (λ x => [x]) = l := by induction l <;> aesop theorem map_eq_flatMap' {α β} (f : α → β) (l : List α) : map f l = l.flatMap (λ x => [f x]) := by induction l <;> aesop theorem flatMap_assoc' {α β γ : Type u} (l : List α) (f : α → List β) (g : β → List γ) : (l.flatMap f).flatMap g = l.flatMap (λ x => (f x).flatMap g) := ADMIT -- have aux {δ : Type u} (xs ys : List (List δ)) : flatten (xs ++ ys) = flatten xs ++ flatten ys := by -- induction xs <;> aesop -- induction l <;> aesop (add norm [simp [flatMap_append], unfold [flatMap]]) /-! ### concat -/ -- attribute [-simp] concat_nil @[simp] theorem X.concat_nil (a : α) : concat [] a = [a] := rfl -- attribute [-simp] concat_cons @[simp] theorem X.concat_cons (a b : α) (l : List α) : concat (a :: l) b = a :: concat l b := rfl attribute [-simp] concat_eq_append @[simp] theorem X.concat_eq_append (a : α) (l : List α) : concat l a = l ++ [a] := by induction l <;> aesop -- attribute [-simp] init_eq_of_concat_eq theorem X.init_eq_of_concat_eq {a : α} {l₁ l₂ : List α} : concat l₁ a = concat l₂ a → l₁ = l₂ := by aesop -- attribute [-simp] last_eq_of_concat_eq theorem X.last_eq_of_concat_eq {a b : α} {l : List α} : concat l a = concat l b → a = b := by aesop -- attribute [-simp] concat_ne_nil theorem X.concat_ne_nil (a : α) (l : List α) : concat l a ≠ [] := by aesop attribute [simp] append_assoc -- attribute [-simp] concat_append theorem X.concat_append (a : α) (l₁ l₂ : List α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by aesop -- attribute [-simp] length_concat theorem X.length_concat (a : α) (l : List α) : length (concat l a) = .succ (length l) := by aesop -- attribute [-simp] append_concat theorem X.append_concat (a : α) (l₁ l₂ : List α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by aesop /-! ### reverse -/ attribute [-simp] reverse_nil @[simp] theorem X.reverse_nil : reverse (@nil α) = [] := rfl attribute [-simp] reverse_cons @[simp] theorem X.reverse_cons (a : α) (l : List α) : reverse (a::l) = reverse l ++ [a] := ADMIT -- have aux : ∀ l₁ l₂, reverseAux l₁ l₂ ++ [a] = reverseAux l₁ (l₂ ++ [a]) := by -- intro l₁; induction l₁ <;> aesop (add norm unfold reverseAux) -- aesop (add norm unfold reverse) -- Note: reverse_core is called reverseAux in Lean 4. attribute [-simp] reverseAux_eq @[simp] theorem X.reverseAux_eq (l₁ l₂ : List α) : reverseAux l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂ <;> aesop theorem reverse_cons' (a : α) (l : List α) : reverse (a::l) = concat (reverse l) a := by aesop @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl -- TODO: after nightly-2024-08-27, `aesop` can not prove this anymore! attribute [-simp] reverse_append in @[simp] theorem X.reverse_append (s t : List α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := ADMIT -- induction s <;> aesop -- attribute [-simp] reverse_concat theorem X.reverse_concat (l : List α) (a : α) : reverse (concat l a) = a :: reverse l := by aesop attribute [-simp] reverse_reverse @[simp] theorem X.reverse_reverse (l : List α) : reverse (reverse l) = l := by induction l <;> aesop @[simp] theorem reverse_involutive : Involutive (@reverse α) := by aesop @[simp] theorem reverse_injective {α : Type u} : Injective (@reverse α) := by aesop @[simp] theorem reverse_surjective {α : Type u} : Surjective (@reverse α) := by aesop @[simp] theorem reverse_bijective : Bijective (@reverse α) := by aesop @[simp] theorem reverse_inj' {l₁ l₂ : List α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := by aesop (add safe forward reverse_injective) -- attribute [-simp] reverse_eq_iff theorem X.reverse_eq_iff {l l' : List α} : l.reverse = l' ↔ l = l'.reverse := by aesop @[simp] theorem reverse_eq_nil {l : List α} : reverse l = [] ↔ l = [] := by aesop (add norm simp reverse_eq_iff) theorem concat_eq_reverse_cons (a : α) (l : List α) : concat l a = reverse (a :: reverse l) := by induction l <;> aesop attribute [-simp] length_reverse @[simp] theorem X.length_reverse (l : List α) : length (reverse l) = length l := by induction l <;> aesop theorem map_reverse' (f : α → β) (l : List α) : map f (reverse l) = reverse (map f l) := by induction l <;> aesop -- attribute [-simp] map_reverseAux theorem map_reverse_core (f : α → β) (l₁ l₂ : List α) : map f (reverseAux l₁ l₂) = reverseAux (map f l₁) (map f l₂) := by aesop (add norm simp map_reverse') attribute [-simp] mem_reverse @[simp] theorem X.mem_reverse {a : α} {l : List α} : a ∈ reverse l ↔ a ∈ l := by induction l <;> aesop @[simp] theorem reverse_replicate' (a : α) (n) : reverse (replicate n a) = replicate n a := ADMIT -- Several missing lemmas. /-! ### empty -/ theorem empty_iff_eq_nil {l : List α} : Empty l ↔ l = [] := by aesop /-! ### init -/ @[simp] theorem length_init : ∀ (l : List α), length (init l) = length l - 1 | [] => by aesop | [_] => by aesop | (_ :: y :: zs) => by have ih := length_init (y :: zs) aesop (add norm simp [init, Nat.add_sub_cancel]) /-! ### last -/ @[simp] theorem last_cons {a : α} {l : List α} : ∀ (h : l ≠ nil), last (a :: l) (cons_ne_nil a l) = last l h := by aesop (add 1% cases List) @[simp] theorem last_append_singleton {a : α} (l : List α) : last (l ++ [a]) (append_ne_nil_of_right_ne_nil l (cons_ne_nil a _)) = a := by induction l <;> aesop theorem last_append (l₁ l₂ : List α) (h : l₂ ≠ []) : last (l₁ ++ l₂) (append_ne_nil_of_right_ne_nil l₁ h) = last l₂ h := by induction l₁ <;> aesop theorem last_concat {a : α} (l : List α) : last (concat l a) (X.concat_ne_nil a l) = a := by aesop @[simp] theorem last_singleton (a : α) : last [a] (cons_ne_nil a []) = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : List α) : last (a₁::a₂::l) (cons_ne_nil _ _) = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem init_append_last : ∀ {l : List α} (h : l ≠ []), init l ++ [last l h] = l | [] => by aesop | [_] => by aesop | x :: y :: zs => by have ih := init_append_last (l := y :: zs) aesop (add norm simp [init, last]) theorem last_congr {l₁ l₂ : List α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by aesop theorem last_mem : ∀ {l : List α} (h : l ≠ []), last l h ∈ l := by intro l; induction l <;> aesop (add norm simp last, 1% cases List) theorem last_replicate_succ (a m : Nat) : (replicate m.succ a).last (ne_nil_of_length_eq_add_one (show (replicate m.succ a).length = m.succ by rw [length_replicate])) = a := by induction m <;> aesop /-! ### getLast? -/ section getLast? @[simp] theorem getLast?_is_none : ∀ {l : List α}, (getLast? l).isNone ↔ l = [] | [] => by aesop | [a] => by aesop | a :: a' :: as => by have ih := getLast?_is_none (l := a' :: as) aesop @[simp] theorem getLast?_is_some : ∀ {l : List α}, l.getLast?.isSome ↔ l ≠ [] | [] => by aesop | [a] => by aesop | a :: a' :: as => by have ih := getLast?_is_some (l := a' :: as) aesop theorem mem_getLast?_eq_last : ∀ {l : List α} {x : α}, x ∈ l.getLast? → ∃ h, x = last l h | [], _, h => by aesop | [_], _, h => by aesop | a :: a' :: as, x, h => by have ih := mem_getLast?_eq_last (l := a' :: as) (x := x) aesop (add norm simp getLast?) theorem getLast?_eq_last_of_ne_nil : ∀ {l : List α} (h : l ≠ []), l.getLast? = some (l.last h) | [], h => by aesop | [a], _ => by aesop | _ :: b :: l, _ => by have ih := getLast?_eq_last_of_ne_nil (l := b :: l) aesop theorem mem_getLast?_cons {x y : α} : ∀ {l : List α} (_ : x ∈ l.getLast?), x ∈ (y :: l).getLast? := by intro l; induction l <;> aesop -- attribute [-simp] mem_of_mem_getLast? theorem X.mem_of_mem_getLast? {l : List α} {a : α} (ha : a ∈ l.getLast?) : a ∈ l := by match l with | [] => aesop | [_] => aesop | x :: y :: zs => have ih := X.mem_of_mem_getLast? (l := y :: zs) (a := a) aesop theorem init_append_getLast? : ∀ {l : List α} {a}, a ∈ l.getLast? → init l ++ [a] = l | [], _ => by aesop | [_], _ => by aesop | x :: y :: zs, a => by have ih := init_append_getLast? (l := y :: zs) (a := a) aesop (add norm simp init) theorem ilast_eq_getLast? [Inhabited α] : ∀ l : List α, l.ilast = l.getLast?.iget | [] => by aesop | [a] => by aesop | [_, _] => by aesop | [_, _, _] => by aesop | (_ :: _ :: c :: l) => by have ih := ilast_eq_getLast? (c :: l) aesop @[simp] theorem getLast?_append_cons : ∀ (l₁ : List α) (a : α) (l₂ : List α), getLast? (l₁ ++ a :: l₂) = getLast? (a :: l₂) | [], a, l₂ => by aesop | [_], a, l₂ => by aesop | _ :: c :: l₁, a, l₂ => have ih := getLast?_append_cons (c :: l₁) a by aesop @[simp] theorem getLast?_cons_cons' (x y : α) (l : List α) : getLast? (x :: y :: l) = getLast? (y :: l) := rfl theorem getLast?_append_of_ne_nil (l₁ : List α) : ∀ {l₂ : List α} (_ : l₂ ≠ []), getLast? (l₁ ++ l₂) = getLast? l₂ | [], hl₂ => by aesop | b :: l₂, _ => by aesop theorem getLast?_append' {l₁ l₂ : List α} {x : α} (h : x ∈ l₂.getLast?) : x ∈ (l₁ ++ l₂).getLast? := by aesop (add 1% cases List) end getLast? /-! ### head(') and tail -/ -- Note: Lean 3 head is Lean 4 ihead. -- attribute [-simp] ihead_eq_head' theorem head_eq_head' [Inhabited α] (l : List α) : ihead l = (head' l).iget := by aesop (add 1% cases List) theorem mem_of_mem_head' {x : α} : ∀ {l : List α}, x ∈ l.head' → x ∈ l := by intro l; induction l <;> aesop -- attribute [-simp] head'_cons @[simp] theorem X.head'_cons [Inhabited α] (a : α) (l : List α) : head' (a::l) = a := rfl attribute [-simp] tail_nil @[simp] theorem X.tail_nil : tail (@nil α) = [] := rfl attribute [-simp] tail_cons @[simp] theorem X.tail_cons (a : α) (l : List α) : tail (a::l) = l := rfl -- attribute [-simp] head_append @[simp] theorem X.head_append [Inhabited α] (t : List α) {s : List α} (h : s ≠ []) : ihead (s ++ t) = ihead s := by aesop (add 1% cases List) theorem head'_append {s t : List α} {x : α} (h : x ∈ s.head') : x ∈ (s ++ t).head' := by aesop (add 1% cases List) theorem head'_append_of_ne_nil : ∀ (l₁ : List α) {l₂ : List α} (_ : l₁ ≠ []), head' (l₁ ++ l₂) = head' l₁ := by aesop (add 1% cases List) theorem tail_append_singleton_of_ne_nil {a : α} {l : List α} (h : l ≠ nil) : tail (l ++ [a]) = tail l ++ [a] := by induction l <;> aesop theorem cons_head'_tail : ∀ {l : List α} {a : α} (_ : a ∈ head' l), a :: tail l = l := by aesop -- attribute [-simp] ihead_mem_head' theorem head_mem_head' [Inhabited α] : ∀ {l : List α} (_ : l ≠ []), ihead l ∈ head' l := by aesop -- attribute [-simp] cons_ihead_tail theorem cons_head_tail' [Inhabited α] {l : List α} (h : l ≠ []) : (ihead l)::(tail l) = l := by aesop end List
.lake/packages/aesop/AesopTest/13.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true inductive Any (P : α → Prop) : List α → Prop where | here (x xs) : P x → Any P (x :: xs) inductive Perm : (xs ys : List α) → Type where | refl xs : Perm xs xs | prep (x xs ys) : Perm xs ys → Perm (x :: xs) (x :: ys) theorem Perm.any {xs ys : List α} (perm : Perm xs ys) (P : α → Prop) : Any P xs → Any P ys := by induction perm <;> aesop (add safe [constructors Any, cases Any]) /-- error: tactic 'aesop' failed, maximum number of rule applications (100) reached. Set the 'maxRuleApplications' option to increase the limit. -/ #guard_msgs in theorem error (P : Nat → Prop) (Δ : List Nat) : Any P Δ := by aesop (add 50% [constructors Perm, constructors Any, Perm.any]) (config := { maxRuleApplications := 100, terminal := true }) /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in theorem fine (P : α → Prop) (Δ : List α) : Any P Δ := by aesop (add unsafe [50% constructors Perm, 50% constructors Any, apply 50% Perm.any]) (config := { maxRuleApplications := 10, terminal := true })
.lake/packages/aesop/AesopTest/18.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true attribute [aesop safe cases (cases_patterns := [List.Mem _ []])] List.Mem attribute [aesop unsafe 50% cases (cases_patterns := [List.Mem _ (_ :: _)])] List.Mem /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in theorem Mem.split [DecidableEq α] (xs : List α) (v : α) (h : v ∈ xs) : ∃ l r, xs = l ++ v :: r := by induction xs case nil => aesop case cons x xs ih => have dec : Decidable (x = v) := inferInstance cases dec case isFalse no => aesop (config := { terminal := true }) (erase Aesop.BuiltinRules.ext) case isTrue yes => apply Exists.intro [] apply Exists.intro xs rw [yes] rfl
.lake/packages/aesop/AesopTest/Nonterminal.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true structure MyTrue₁ structure MyTrue₂ @[aesop safe] structure MyTrue₃ where tt : MyTrue₁ /-- warning: aesop: failed to prove the goal after exhaustive search. -/ #guard_msgs in example : MyTrue₃ := by aesop apply MyTrue₁.mk @[aesop safe] structure MyFalse where falso : False /-- warning: aesop: failed to prove the goal after exhaustive search. --- error: unsolved goals ⊢ False -/ #guard_msgs in example : MyFalse := by aesop /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : MyFalse := by aesop (config := { terminal := true }) /-- error: unsolved goals ⊢ False -/ #guard_msgs in example : MyFalse := by aesop (config := { warnOnNonterminal := false }) @[aesop safe] structure MyFalse₂ where falso : False tt : MyTrue₃ /-- warning: aesop: failed to prove the goal after exhaustive search. --- error: unsolved goals case falso ⊢ False case tt ⊢ MyTrue₁ -/ #guard_msgs in example : MyFalse₂ := by aesop /-- error: unsolved goals ⊢ False -/ #guard_msgs in set_option aesop.warn.nonterminal false in example : MyFalse := by aesop /-- error: unsolved goals ⊢ False -/ #guard_msgs in set_option aesop.warn.nonterminal true in example : MyFalse := by aesop (config := { warnOnNonterminal := false })
.lake/packages/aesop/AesopTest/Split.lean
import Aesop set_option aesop.check.all true -- Tests the builtin split rules. @[aesop norm unfold] def id' (n : Nat) : Nat := match n with | .zero => .zero | .succ n => .succ n -- First, the rule for splitting targets. example : id' n = n := by aesop -- Second, the rule for splitting hypotheses. We introduce a custom equality to -- make sure that in the following example, Aesop doesn't just substitute the -- hypothesis during norm simp. inductive MyEq (x : α) : α → Prop | rfl : MyEq x x @[aesop unsafe] def MyEq.elim : MyEq x y → x = y | rfl => by rfl example (h : MyEq n (id' m)) : n = m := by aesop
.lake/packages/aesop/AesopTest/ForwardRedundantHypsWithMVars.lean
-- Regression test for a failure of the `forward` rule builder to realise that -- it had already added certain hypotheses. The `saturate` loop below adds the -- same hyp over and over again, only with different level mvars. Thanks to Son -- Ho for providing this test case. import Aesop set_option aesop.check.all true axiom len {α} (ls : List α) : Int @[aesop safe forward (pattern := len ls)] axiom len_pos {α} {ls : List α} : 0 ≤ len (ls : List α) /-- error: unsolved goals a : Type u_1 l : List a fwd : 0 ≤ len l ⊢ 0 ≤ len l -/ #guard_msgs in example (l: List a): 0 ≤ len l := by saturate
.lake/packages/aesop/AesopTest/Unfold.lean
-- Inspired by this Zulip discussion: -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Goal.20state.20not.20updating.2C.20bugs.2C.20etc.2E/near/338356062 import Aesop set_option aesop.check.all true structure WalkingPair def WidePullbackShape A B := Sum A B abbrev WalkingCospan : Type := WidePullbackShape Empty Empty @[aesop norm destruct] def WalkingCospan_elim : WalkingCospan → Sum Empty Empty := id /-- info: Try this: [apply] unfold WalkingCospan at h unfold WidePullbackShape at h cases h with | inl val => have fwd : False := Aesop.BuiltinRules.empty_false val simp_all only | inr val_1 => have fwd : False := Aesop.BuiltinRules.empty_false val_1 simp_all only -/ #guard_msgs in example (h : WalkingCospan) : α := by aesop? (add norm unfold [WidePullbackShape, WalkingCospan]) example (h : WalkingCospan) : α := by aesop (add norm simp [WidePullbackShape, WalkingCospan]) @[aesop norm unfold] def Foo := True @[aesop norm unfold] def Bar := False /-- info: Try this: [apply] unfold Bar Foo unfold Foo at h₁ unfold Foo Bar at h₂ simp_all only cases h₂ with | inl val => simp_all only apply PSum.inr simp_all only | inr val_1 => simp_all only -/ #guard_msgs in example (h₁ : Foo) (h₂ : PSum Foo Bar) : PSum Bar Foo := by aesop?
.lake/packages/aesop/AesopTest/TacticConfig.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true inductive Even : Nat → Prop | zero : Even 0 | plus_two {n} : Even n → Even (n + 2) inductive Odd : Nat → Prop | one : Odd 1 | plus_two {n} : Odd n → Odd (n + 2) inductive EvenOrOdd : Nat → Prop | even {n} : Even n → EvenOrOdd n | odd {n} : Odd n → EvenOrOdd n -- We can add constants as rules. example : EvenOrOdd 3 := by aesop (add safe [Even.zero, Even.plus_two, Odd.one, Odd.plus_two], unsafe [apply 50% EvenOrOdd.even, 50% EvenOrOdd.odd]) -- Same with local hypotheses, or a mix. example : EvenOrOdd 3 := by have h : ∀ n, Odd n → EvenOrOdd n := λ _ p => EvenOrOdd.odd p aesop (add safe [Odd.one, Odd.plus_two], unsafe [EvenOrOdd.even 50%, h 50%]) (erase Aesop.BuiltinRules.applyHyps) -- This rule subsumes h. attribute [aesop 50%] Even.zero Even.plus_two -- We can also erase global rules... /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : EvenOrOdd 2 := by aesop (add safe EvenOrOdd.even) (erase Even.zero) (config := { terminal := true }) example : EvenOrOdd 2 := by aesop (add safe EvenOrOdd.even) -- ... as well as local ones (but what for?). /-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/ #guard_msgs in example : EvenOrOdd 2 := by have h : ∀ n, Even n → EvenOrOdd n := λ _ p => EvenOrOdd.even p aesop (add safe h) (erase Aesop.BuiltinRules.applyHyps, h) (config := { terminal := true }) example : EvenOrOdd 2 := by have h : ∀ n, Even n → EvenOrOdd n := λ _ p => EvenOrOdd.even p aesop (add safe h) (erase Aesop.BuiltinRules.applyHyps)
.lake/packages/aesop/AesopTest/DefaultRuleSetsInit.lean
import Aesop set_option aesop.check.all true declare_aesop_rule_sets [regular₁, regular₂] declare_aesop_rule_sets [dflt₁, dflt₂] (default := true)
.lake/packages/aesop/AesopTest/IncompleteScript.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true -- set_option aesop.check.script.steps false /-- info: Try this: [apply] intro a simp_all only [Nat.add_zero] sorry --- warning: aesop: failed to prove the goal after exhaustive search. --- error: unsolved goals n : Nat P : Nat → Prop a : P n ⊢ P (n + 1) -/ #guard_msgs in example {P : Nat → Prop} : P (n + 0) → P (n + 1) := by aesop? inductive Even : Nat → Prop where | zero : Even 0 | add_two : Even n → Even (n + 2) /-- info: Try this: [apply] sorry --- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : Even 5 := by aesop? attribute [aesop safe constructors] Even /-- info: Try this: [apply] apply Even.add_two apply Even.add_two sorry --- warning: aesop: failed to prove the goal after exhaustive search. --- error: unsolved goals case a.a ⊢ Even 1 -/ #guard_msgs in example : Even 5 := by aesop?
.lake/packages/aesop/AesopTest/43.lean
import Aesop set_option aesop.check.all true structure A open Lean.Elab.Tactic in @[aesop norm] def tac : TacticM Unit := do evalTactic $ ← `(tactic| exact A.mk) example : A := by set_option aesop.check.script false in set_option aesop.check.script.steps false in aesop
.lake/packages/aesop/AesopTest/Strategy.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true @[aesop 50% constructors] inductive I₁ | ofI₁ : I₁ → I₁ | ofTrue : True → I₁ example : I₁ := by aesop example : I₁ := by aesop (config := { strategy := .bestFirst }) example : I₁ := by aesop (config := { strategy := .breadthFirst }) /-- error: tactic 'aesop' failed, maximum number of rule applications (10) reached. Set the 'maxRuleApplications' option to increase the limit. -/ #guard_msgs in example : I₁ := by aesop (config := { strategy := .depthFirst maxRuleApplicationDepth := 0 maxRuleApplications := 10, terminal := true }) example : I₁ := by aesop (config := { strategy := .depthFirst, maxRuleApplicationDepth := 10 })
.lake/packages/aesop/AesopTest/AddRulesCommand.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true -- Basic examples structure TT₁ where /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : TT₁ := by aesop add_aesop_rules safe TT₁ example : TT₁ := by aesop -- Local rules structure TT₂ where namespace Test local add_aesop_rules safe TT₂ example : TT₂ := by aesop end Test /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : TT₂ := by aesop -- Scoped rules structure TT₃ where namespace Test scoped add_aesop_rules safe TT₃ example : TT₃ := by aesop end Test /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : TT₃ := by aesop def Test.example : TT₃ := by aesop -- Tactics structure TT₄ where /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : TT₄ := by aesop add_aesop_rules safe (by exact TT₄.mk) example : TT₄ := by aesop -- Multiple rules axiom T : Type axiom U : Type axiom f : T → U axiom t : T /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example : U := by aesop add_aesop_rules safe [(by apply f), t] noncomputable example : U := by aesop
.lake/packages/aesop/AesopTest/CompositeLocalRuleTerm.lean
import Aesop set_option aesop.check.all true set_option aesop.smallErrorMessages true -- Composite terms are supported by the `apply` and `forward` builders... structure A where /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example (h : A → β → γ) (b : β) : γ := by aesop example (h : A → β → γ) (b : β) : γ := by aesop (add safe apply (h {})) example (h : A → β → γ) (b : β) : γ := by aesop (add safe forward (h {})) -- ... and also by the `simp` builder. /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example {P : α → Prop} (h : A → x = y) (p : P x) : P y := by aesop example {P : α → Prop} (h : A → x = y) (p : P x) : P y := by aesop (add simp (h {})) /-- error: tactic 'aesop' failed, made no progress -/ #guard_msgs in example {P : α → Prop} (h₁ : A → x = y) (h₂ : A → y = z) (p : P x) : P z := by aesop example {P : α → Prop} (h₁ : A → x = y) (h₂ : A → y = z) (p : P x) : P z := by aesop (add simp [(h₁ {}), (h₂ {})])