source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/aesop/AesopTest/Stats.lean | import Aesop
/-
Regression test for a bug involving the stats extension and async elaboration.
The commands below should not panic and should show non-zero stats.
-/
set_option aesop.collectStats true
set_option trace.aesop.stats true
#guard_msgs (drop trace) in
theorem mem_spec {o : Option α} : a ∈ o ↔ o = some a := by
aesop (add norm simp Membership.mem)
#guard_msgs (drop info) in
#aesop_stats |
.lake/packages/aesop/AesopTest/TerminalError.lean | import Aesop
set_option aesop.check.all true
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
Initial goal:
⊢ False
Remaining goals after safe rules:
⊢ False
-/
#guard_msgs in
example : False := by
aesop (config := { terminal := true }) |
.lake/packages/aesop/AesopTest/DroppedMVars.lean | -- Thanks to Jesse Vogel for this test case. It demonstrates the handling of
-- 'dropped' mvars. A rapp drops an mvar if the mvar appears in the parent goal
-- of the rapp, but not in any of its subgoals. In this case, we add an
-- additional regular goal for the mvar.
import Aesop
set_option aesop.check.all true
axiom Ring : Type
axiom RingHom (R S : Ring) : Type
@[aesop 99%]
axiom RingId (R : Ring) : RingHom R R
@[aesop 99%]
axiom ZZ : Ring
example : ∃ (R : Ring) (_ : RingHom R R), True := by
aesop (add safe True.intro) (config := { enableSimp := false }) |
.lake/packages/aesop/AesopTest/CasesScript.lean | import Aesop
set_option aesop.check.all true
@[aesop 50% cases]
inductive FancyAnd (α β : Prop) : Prop
| dummy (p : Empty)
| and (a : α) (b : β)
/--
info: Try this:
[apply] apply And.intro
·
cases h with
| dummy p =>
have fwd : False := Aesop.BuiltinRules.empty_false p
simp_all only
| and a b => simp_all only
·
cases h with
| dummy p =>
have fwd : False := Aesop.BuiltinRules.empty_false p
simp_all only
| and a b => simp_all only
-/
#guard_msgs in
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
/--
info: Try this:
[apply] rcases h with ⟨⟩ | @⟨x_1, xs_1, a, a_1⟩
apply MyTrue.mk
-/
#guard_msgs in
example {P : α → Prop} (h : All P (x :: xs)) : MyTrue := by
aesop? |
.lake/packages/aesop/AesopTest/RuleSets0.lean | import Aesop
set_option aesop.check.all true
declare_aesop_rule_sets [test_A, test_B, test_C, test_D] |
.lake/packages/aesop/AesopTest/ApplyHypsTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def T := Unit → Nat
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : Nat := by
aesop (config := { applyHypsTransparency := .reducible, terminal := true })
example (h : T) : Nat := by
aesop
@[irreducible] def U := Empty
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : Unit → Empty) : U := by
aesop (config := { applyHypsTransparency := .reducible, terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : Unit → Empty) : U := by
aesop (config := { terminal := true })
example (h : Unit → Empty) : U := by
aesop (config := { applyHypsTransparency := .all }) |
.lake/packages/aesop/AesopTest/RulePattern.lean | import Aesop
set_option aesop.check.all true
macro "aesop!" : tactic =>
`(tactic| aesop (config := { warnOnNonterminal := false }))
axiom falso : ∀ {α : Sort _}, α
macro "falso" : tactic => `(tactic| exact falso)
@[aesop norm -100 forward (pattern := (↑n : Int))]
axiom nat_pos (n : Nat) : 0 ≤ (↑n : Int)
example (m n : Nat) : (↑m : Int) < 0 ∧ (↑n : Int) > 0 := by
set_option aesop.check.script.steps false in -- TODO lean4#4315
set_option aesop.check.script false in
aesop (config := { enableSimp := false, warnOnNonterminal := false })
all_goals
guard_hyp fwd : 0 ≤ (m : Int)
guard_hyp fwd_1 : 0 ≤ (n : Int)
falso
@[aesop safe forward (pattern := min x y)]
axiom foo : ∀ {x y : Nat} (_ : 0 < x) (_ : 0 < y), 0 < min x y
example (hx : 0 < x) (hy : 0 < y) (_ : min x y < z): False := by
aesop!
guard_hyp fwd : 0 < min x y
falso
axiom abs (n : Int) : Nat
notation "|" t "|" => abs t
@[aesop safe forward (pattern := |a + b|)]
axiom triangle (a b : Int) : |a + b| ≤ |a| + |b|
@[aesop safe apply (pattern := (0 : Nat))]
axiom falso' : True → False
/--
error: tactic 'aesop' failed, made no progress
Initial goal:
⊢ False
-/
#guard_msgs in
example : False := by
aesop
example (h : n = 0) : False := by
aesop (rule_sets := [-builtin])
-- Patterns may only contain variables mentioned in the rule.
/-- error: Unknown identifier `z` -/
#guard_msgs in
@[aesop safe forward (pattern := z)]
axiom quuz (x y : Nat) : True
-- When a premise of a forward rule is mentioned in a pattern, it can't also
-- be an immediate argument.
@[aesop safe forward (pattern := (↑x : Int)) (immediate := [y])]
axiom bar (x y : Nat) : True
/--
error: aesop: forward builder: argument 'x' cannot be immediate since it is already determined by a pattern
-/
#guard_msgs in
@[aesop safe forward (pattern := (↑x : Int)) (immediate := [y, x])]
axiom baz (x y : Nat) : True
-- For types with 'reducibly hidden' forall binders, the pattern can only refer
-- to the syntactically visible variables.
abbrev T := (tt : True) → False
/-- error: Unknown identifier `tt` -/
#guard_msgs in
@[aesop safe forward (pattern := tt)]
axiom falso₁ : T
-- We support dependencies in patterns. E.g. in the following pattern, only the
-- premise `x` occurs syntactically, but the type of `x` depends on `a` and `p`,
-- so these premises are also determined by the pattern substitution.
-- (Thanks to Son Ho for this test case.)
@[aesop safe forward (pattern := x)]
theorem get_prop {a : Type} {p : a → Prop} (x : Subtype p) : p x.val :=
x.property
example {a : Type} {p : a → Prop} (x : Subtype p × Subtype p)
(h : x.1.val = x.2.val) : p x.1.val ∧ p x.2.val := by
saturate
apply And.intro <;> assumption |
.lake/packages/aesop/AesopTest/WarnApplyIff.lean | import Aesop
set_option aesop.check.all true
/--
warning: Apply builder was used for a theorem with conclusion A ↔ B.
You probably want to use the simp builder or create an alias that applies the theorem in one direction.
Use `set_option aesop.warn.applyIff false` to disable this warning.
-/
#guard_msgs in
@[aesop safe apply]
axiom foo : True ↔ True
@[aesop simp]
axiom bar : True ↔ True
set_option aesop.warn.applyIff false in
@[aesop 1% apply]
axiom baz : True ↔ True |
.lake/packages/aesop/AesopTest/Safe.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop 50%]
inductive Even : Nat → Prop
| zero : Even 0
| plus_two {n} : Even n → Even (n + 2)
structure Even' (n) : Prop where
even : Even n
theorem even'_of_false : False → Even' n
| h => nomatch h
theorem even'_of_even' : Even' n → Even' n :=
id
-- Once a safe rule is applied, the corresponding goal is marked as inactive
-- and never visited again.
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : Even' 2 := by
aesop (add safe [even'_of_false 0, Even'.mk 1])
(config := { terminal := true })
/--
error: tactic 'aesop' failed, maximum number of rule applications (10) reached. Set the 'maxRuleApplications' option to increase the limit.
-/
#guard_msgs in
example : Even' 2 := by
aesop (add safe [even'_of_even'], unsafe [Even'.mk 100%])
(config := { maxRuleApplications := 10, terminal := true })
example : Even' 2 := by
aesop (add safe [even'_of_false 1, Even'.mk 0]) |
.lake/packages/aesop/AesopTest/RuleSets1.lean | import AesopTest.RuleSets0
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop safe (rule_sets := [test_A])]
inductive A : Prop where
| intro
@[aesop safe (rule_sets := [test_B])]
inductive B : Prop where
| intro
@[aesop safe]
inductive C : Prop where
| intro
inductive D : Prop where
| intro
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : A := by
aesop (config := { terminal := true })
example : A := by
aesop (rule_sets := [test_A])
example : B := by
aesop (rule_sets := [test_A, test_B])
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : C := by
aesop (rule_sets := [-default]) (config := { terminal := true })
example : C := by
aesop
attribute [aesop safe (rule_sets := [test_C])] C
-- Removing the attribute removes all rules associated with C from all rule
-- sets.
attribute [-aesop] C
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : C := by
aesop (rule_sets := [test_C]) (config := { terminal := true })
example : C := by
aesop (add safe C)
@[aesop norm simp]
theorem ad : D ↔ A :=
⟨λ _ => A.intro, λ _ => D.intro⟩
example : D := by
aesop (rule_sets := [test_A])
attribute [-aesop] ad
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : D := by
aesop (rule_sets := [test_A]) (config := { terminal := true })
example : D := by
aesop (add norm ad) (rule_sets := [test_A])
-- Rules can also be local.
inductive E : Prop where
| intro
section
attribute [local aesop safe] E
example : E := by
aesop
end
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : E := by
aesop (config := { terminal := true })
example : E := by
constructor
-- Rules can also be scoped.
namespace EScope
attribute [scoped aesop safe] E
example : E := by
aesop
end EScope
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : E := by
aesop (config := { terminal := true })
example : E := by
open EScope in aesop |
.lake/packages/aesop/AesopTest/CustomTactic.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def Foo := True
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : Foo := by
aesop (config := { terminal := true })
example : Foo := by
simp [Foo]
open Lean.Elab.Tactic in
@[aesop safe]
def myTactic : TacticM Unit := do
evalTactic $ ← `(tactic| rw [Foo])
example : Foo := by
set_option aesop.check.script false in
set_option aesop.check.script.steps false in
aesop |
.lake/packages/aesop/AesopTest/RulePatternUniverseBug.lean | -- A regression test for an issue where universe mvars were not correctly
-- assigned during rule pattern matching. Thanks to Son Ho for reporting this
-- issue.
import Aesop.Frontend.Attribute
import Aesop.Frontend.Saturate
set_option aesop.check.all true
namespace List
@[simp]
def len (ls : List α) : Int :=
match ls with
| [] => 0
| _ :: tl => 1 + len tl
@[aesop safe forward (pattern := len ls)]
theorem len_pos : 0 ≤ len (ls : List α) := by
induction ls <;> simp [*]
omega
def indexOpt (ls : List α) (i : Int) : Option α :=
match ls with
| [] => none
| hd :: tl => if i = 0 then some hd else indexOpt tl (i - 1)
theorem indexOpt_bounds (ls : List α) (i : Int) :
ls.indexOpt i = none ↔ i < 0 ∨ ls.len ≤ i := by
match ls with
| [] => simp [indexOpt]; omega
| _ :: tl =>
have := indexOpt_bounds tl (i - 1)
if h : i = 0 then
simp [indexOpt, *]
saturate
omega
else
simp [indexOpt, len, *]
constructor <;> intro a <;> cases a
. left
saturate
omega
. right; omega
. left; omega
. right; omega |
.lake/packages/aesop/AesopTest/SafePrefixInTerminalError.lean | import Aesop
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
Initial goal:
⊢ ∀ (a b : Nat), a + b = b + 2 * a
Remaining goals after safe rules:
a b : Nat
⊢ a + b = b + 2 * a
-/
#guard_msgs in
example : ∀ (a b : Nat), a + b = b + 2 * a := by
aesop (config := { terminal := true }) |
.lake/packages/aesop/AesopTest/205.lean | -- Thanks to Bruno Dutertre for reporting this bug.
import Aesop
axiom R {α} : α → α → Prop
@[aesop safe forward] axiom sym : R x y → R y x
@[aesop safe forward] axiom tran : R x y → R y z → R x z
/--
info: Try this:
[apply] have fwd : R b y := sym h₃
have fwd_1 : R a x := sym h₂
have fwd_2 : R b b := tran (y := y) fwd h₃
have fwd_3 : R y y := tran (y := b) h₃ fwd
have fwd_4 : R a a := tran (y := x) fwd_1 h₂
have fwd_5 : R x x := tran (y := a) h₂ fwd_1
sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (α : Type u_1) (x y a b : α) (h₂ : R x a) (h₃ : R y b) : False := by
aesop? (rule_sets := [-builtin]) (config := { warnOnNonterminal := false })
sorry |
.lake/packages/aesop/AesopTest/Aesop.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
open Lean
open Lean.Meta
open Lean.Elab.Tactic
section EvenOdd
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
attribute [aesop unsafe] EvenOrOdd.even EvenOrOdd.odd
attribute [aesop safe] Even.zero Even.plus_two
attribute [aesop 100%] Odd.one Odd.plus_two
@[aesop norm unfold]
def EvenOrOdd' (n : Nat) : Prop := EvenOrOdd n
example : EvenOrOdd' 3 := by
aesop
end EvenOdd
-- In this example, the goal is solved already during normalisation.
example : 0 = 0 := by aesop
-- An intentionally looping Aesop call, to test the limiting options
section Loop
structure Wrap (α) where
unwrap : α
/--
error: tactic 'aesop' failed, maximum number of rule applications (20) reached. Set the 'maxRuleApplications' option to increase the limit.
-/
#guard_msgs in
example (h : α → α) (h' : Wrap α) : α := by
aesop (add safe h)
(config := { maxRuleApplications := 20, maxGoals := 0, maxRuleApplicationDepth := 0, terminal := true })
/--
error: tactic 'aesop' failed, maximum number of goals (20) reached. Set the 'maxGoals' option to increase the limit.
-/
#guard_msgs in
example (h : α → α) (h' : Wrap α) : α := by
aesop (add safe h)
(config := { maxGoals := 20, maxRuleApplications := 0, maxRuleApplicationDepth := 0, terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal. Some goals were not explored because the maximum rule application depth (20) was reached. Set option 'maxRuleApplicationDepth' to increase the limit.
-/
#guard_msgs in
example (h : α → α) (h' : Wrap α) : α := by
aesop (add safe h)
(config := { maxRuleApplicationDepth := 20, maxGoals := 0, maxRuleApplications := 0, terminal := true })
end Loop
-- This example tests the builtin rule that applies local hypotheses.
example (Even : Nat → Prop) (zero : Even 0)
(plusTwo : ∀ n, Even n → Even (n + 2)) : Even 20 := by
aesop |
.lake/packages/aesop/AesopTest/23.lean | import Aesop
set_option aesop.check.all true
def Involutive (f : α → α) : Prop :=
∀ x, f (f x) = x
example : Involutive not := by
aesop (add norm simp Involutive)
example : Involutive not := by
aesop (add norm unfold Involutive) |
.lake/packages/aesop/AesopTest/ScriptWithOptions.lean | import Aesop
set_option aesop.check.all true
/--
info: Try this:
[apply] simp_all (config := { }) only
-/
#guard_msgs in
example : True := by
aesop? (config := {}) (simp_config := {}) |
.lake/packages/aesop/AesopTest/SimpLetHypotheses.lean | import Aesop
set_option aesop.check.all true
-- Aesop `simp` substitutes `let` hypotheses even when `zetaDelta` is disabled
-- (which is the default).
/--
error: unsolved goals
P : Nat → Type
h : P 0
x : Nat := 0
⊢ P 0
-/
#guard_msgs in
example (P : Nat → Type) (h : P 0) : let x := 0; P x := by
intro x
aesop (rule_sets := [-builtin,-default])
(config := { warnOnNonterminal := false })
/--
error: unsolved goals
P : Nat → Type
h : P 0
x : Nat := 0
⊢ P 0
-/
#guard_msgs in
example (P : Nat → Type) (h : P 0) : let x := 0; P x := by
intro x
aesop (rule_sets := [-builtin,-default])
(config := { useSimpAll := false, warnOnNonterminal := false }) |
.lake/packages/aesop/AesopTest/EraseSimp.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
example (n : Nat) : n + m = m + n := by
aesop (add simp Nat.add_comm)
attribute [local simp] Nat.add_comm
example (n : Nat) : n + m = m + n := by
aesop
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example (n : Nat) : n + m = m + n := by
aesop (erase Nat.add_comm) (config := { warnOnNonterminal := false })
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example (n : Nat) : n + m = m + n := by
aesop (erase norm simp Nat.add_comm) (config := { warnOnNonterminal := false })
/--
error: aesop: 'Nat.add_comm' is not registered (with the given features) in any rule set.
-/
#guard_msgs in
example (n : Nat) : n + m = m + n := by
aesop (erase apply Nat.add_comm) |
.lake/packages/aesop/AesopTest/SafeExtractionCopyIntroducedMVars.lean | import Aesop
set_option aesop.check.all true
axiom P : Prop
axiom T : Prop
axiom Q : Nat → Prop
axiom R : Nat → Prop
axiom S : Nat → Prop
@[aesop safe]
axiom q_r_p : ∀ x, Q x → R x → P
@[aesop safe]
axiom s_q : ∀ x y, S y → Q x
@[aesop safe]
axiom s_r : ∀ x y, S y → R x
axiom s : S 0
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
case a.a
⊢ S ?a.y✝
case a.a
⊢ S ?a.y✝
case x
⊢ Nat
case a.a
⊢ S ?a.y✝
case a.a
⊢ S ?a.y✝
case x
⊢ Nat
---
error: (kernel) declaration has metavariables '_example'
-/
#guard_msgs in
example : P := by
aesop |
.lake/packages/aesop/AesopTest/NoProgress.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def T := True
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : T := by
aesop
@[aesop norm simp]
def F := False
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
⊢ False
-/
#guard_msgs in
example : F := by
aesop
def F' := False
@[aesop safe apply]
theorem F'_def : False → F' := id
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
⊢ False
-/
#guard_msgs in
example : F' := by
aesop
attribute [-aesop] F'_def
attribute [aesop 100%] F'_def
-- When an unsafe rule is applied, we don't count this as progress because the
-- remaining goal that the user gets to see is exactly the same as the initial
-- goal.
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : F' := by
aesop |
.lake/packages/aesop/AesopTest/Tauto.lean | import Aesop
set_option aesop.check.all true
-- This is an example which is currently challenging for Lean 4 `tauto`.
example {α : Type} [LE α] (a b c : α) (x₀ x₁ x₂ : Prop)
(this1 : x₀ → x₁ → a ≤ c)
(this2 : x₁ → x₂ → b ≤ a)
(this3 : x₂ → x₀ → c ≤ b) :
((x₀ ∧ ¬b ≤ a) ∧ x₁ ∧ ¬c ≤ b ∨
(x₁ ∧ ¬c ≤ b) ∧ x₂ ∧ ¬a ≤ c ∨ (x₂ ∧ ¬a ≤ c) ∧ x₀ ∧ ¬b ≤ a ↔
(x₀ ∧ x₁ ∨ x₁ ∧ x₂ ∨ x₂ ∧ x₀) ∧
¬(c ≤ b ∧ b ≤ a ∨ b ≤ a ∧ a ≤ c ∨ a ≤ c ∧ c ≤ b)) :=
by aesop |
.lake/packages/aesop/AesopTest/CasesTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
example (h : False) : α := by
aesop
def T := False
variable {α : Type}
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : α := by
aesop (config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : α := by
aesop (add safe cases (transparency! := reducible) False)
(config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : α := by
aesop (add safe cases (transparency := default) False)
(config := { terminal := true })
example (h : T) : α := by
aesop (add safe cases (transparency! := default) False)
def U := T
example (h : U) : α := by
aesop (add safe cases (transparency! := default) False) |
.lake/packages/aesop/AesopTest/20.lean | import Aesop
set_option aesop.check.all true
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
@[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)
@[simp]
theorem All.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
case nil => aesop
case cons x xs ih => aesop (config := { useSimpAll := false })
theorem mem' (P : α → Prop) (xs : List α)
: All P xs ↔ ∀ a : α, a ∈ xs → P a := by
induction xs <;> aesop |
.lake/packages/aesop/AesopTest/Filter.lean | import Aesop
set_option aesop.check.all true
namespace TBA
inductive List (α : Type) where
| nil : List α
| cons (head : α) (tail : List α) : List α
notation (priority := high) "[" "]" => List.nil
infixr:67 (priority := high) " :: " => List.cons
def filter (p : α → Prop) [DecidablePred p] (as : List α) : List α :=
match as with
| [] => []
| a::as => if p a then a :: filter p as else filter p as
variable {p : α → Prop} [DecidablePred p] {as bs : List α}
@[simp]
theorem filter_cons_true (h : p a) : filter p (a :: as) = a :: filter p as := by
simp [filter, h]
@[simp]
theorem filter_cons_false (h : ¬ p a) : filter p (a :: as) = filter p as := by
simp [filter, h]
@[aesop 50% [constructors, cases]]
inductive Mem (a : α) : List α → Prop where
| head {as} : Mem a (a::as)
| tail {as} : Mem a as → Mem a (a'::as)
infix:50 " ∈ " => Mem
theorem mem_filter : a ∈ filter p as ↔ a ∈ as ∧ p a := by
apply Iff.intro
case mp =>
intro h
induction as with
| nil => cases h
| cons a' as ih => by_cases ha' : p a' <;> aesop
case mpr =>
intro h
induction as with
| nil => cases h.1
| cons a' as ih =>
cases h.1 with
| head =>
rw [filter_cons_true h.2]
constructor
| tail ha =>
have : a ∈ filter p as := ih ⟨ha, h.2⟩
by_cases hpa' : p a'
case pos =>
rw [filter_cons_true hpa']
exact Mem.tail this
case neg =>
rw [filter_cons_false hpa']
exact this
end TBA |
.lake/packages/aesop/AesopTest/LocalRuleSet.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
-- We used to add local rules to the `default` rule set, but this doesn't work
-- well when the default rule set is disabled.
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : Unit := by
aesop (rule_sets := [-default, -builtin]) (config := { terminal := true })
example : Unit := by
aesop (add safe PUnit.unit) (rule_sets := [-default, -builtin]) |
.lake/packages/aesop/AesopTest/TacGen.lean | import Aesop
open Lean
open Lean.Meta
theorem foo (a b c : Nat) : a + b + c = c + b + a := by
rw [Nat.add_assoc, Nat.add_comm, Nat.add_comm b]
@[aesop 100%]
def tacGen₁ : Aesop.TacGen := λ _ => do
return #[("apply foo", 1.0)]
example (a b c : Nat) : a + b + c = c + b + a := by
aesop
@[aesop 100%]
def tacGen₂ : Aesop.TacGen := λ _ =>
return #[
("rw [Nat.add_comm b]", 0.5),
("rw [Nat.add_assoc]", 0.9),
("rw [Nat.add_comm]", 0.8)
]
example (a b c : Nat) : a + b + c = c + b + a := by
aesop (erase tacGen₁) |
.lake/packages/aesop/AesopTest/TraceProof.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
set_option trace.aesop.proof true
/--
error: tactic 'aesop' failed, made no progress
---
trace: [aesop.proof] <no proof>
-/
#guard_msgs in
example : α := by
aesop
@[aesop norm simp]
def F := False
set_option pp.mvars false in
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
⊢ False
---
trace: [aesop.proof] id ?_
-/
#guard_msgs in
example : F := by
aesop |
.lake/packages/aesop/AesopTest/DocLists.lean | -- NOTE: This file contains examples for, and therefore should be kept in sync
-- with, the README.
import Aesop
set_option aesop.check.all true
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⟩
@[simp]
theorem nil_append : nil ++ xs = xs := rfl
@[simp]
theorem cons_append : cons x xs ++ ys = cons x (xs ++ ys) := rfl
@[aesop safe [constructors, cases]]
inductive NonEmpty : MyList α → Prop
| cons : NonEmpty (cons x xs)
@[aesop 50%]
theorem nonEmpty_append₁ {xs : MyList α} ys :
NonEmpty xs → NonEmpty (xs ++ ys) := by
aesop
/--
info: Try this:
[apply] intro a
obtain @⟨x, xs_1⟩ := a
simp_all only [cons_append]
apply MyList.NonEmpty.cons
-/
#guard_msgs in
theorem nonEmpty_append₁' {xs : MyList α} ys :
NonEmpty xs → NonEmpty (xs ++ ys) := by
aesop?
example {α : Type _} {xs : MyList α} ys zs :
NonEmpty xs → NonEmpty (xs ++ ys ++ zs) := by
aesop
theorem nil_not_nonEmpty (xs : MyList α) : xs = nil → ¬ NonEmpty xs := by
aesop (add unsafe 10% cases MyList)
@[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
end MyList |
.lake/packages/aesop/AesopTest/Ext.lean | import Aesop
example (f g : α → β) (h : ∀ a, f a = g a) : f = g := by
aesop
example (x y : α × β) (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := by
aesop |
.lake/packages/aesop/AesopTest/RulePatternLooseBVar.lean | -- A regression test for a bug in rule pattern matching. Thanks to Son Ho for
-- the bug report.
import Aesop
inductive ScalarTy
| U32
@[simp]
def U32.min : Int := 0
def U32.max : Int := 4294967295
def Scalar.min (ty : ScalarTy) : Int :=
match ty with
| .U32 => U32.min
def Scalar.max (ty : ScalarTy) : Int :=
match ty with
| .U32 => U32.max
structure Scalar (ty : ScalarTy) where
val : Int
hmin : Scalar.min ty ≤ val
hmax : val ≤ Scalar.max ty
@[reducible] def U32 := Scalar .U32
def Scalar.ofIntCore {ty : ScalarTy} (x : Int)
(h : Scalar.min ty ≤ x ∧ x ≤ Scalar.max ty) : Scalar ty :=
{ val := x, hmin := h.left, hmax := h.right }
def U32.ofIntCore := @Scalar.ofIntCore .U32
@[aesop safe forward (pattern := x)]
theorem Scalar.bounds {ty : ScalarTy} (x : Scalar ty) :
Scalar.min ty ≤ x.val ∧ x.val ≤ Scalar.max ty :=
And.intro x.hmin x.hmax
/--
error: unsolved goals
x : Int
h0 : 0 ≤ x
h1 : x ≤ U32.max
fwd : Scalar.min ScalarTy.U32 ≤ (U32.ofIntCore x ⋯).val ∧ (U32.ofIntCore x ⋯).val ≤ Scalar.max ScalarTy.U32
⊢ (U32.ofIntCore x ⋯).val ≤ U32.max
-/
#guard_msgs in
example (x : Int) (h0 : 0 ≤ x) (h1 : x ≤ U32.max) :
(U32.ofIntCore x
(⟨Eq.mp (congrArg (fun x_1 => x_1 ≤ x) rfl) h0, h1⟩)).val ≤ U32.max := by
saturate |
.lake/packages/aesop/AesopTest/NoNormSimp.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : 1 = 2 → False := by
aesop (config := { enableSimp := false, terminal := true })
example : 1 = 2 → False := by
aesop |
.lake/packages/aesop/AesopTest/ForwardConstant.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
structure Foo where
foo ::
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : Foo := by
aesop
example : Foo := by
aesop (add safe forward Foo.foo) |
.lake/packages/aesop/AesopTest/RuleSetNameHygiene0.lean | import Aesop
set_option aesop.check.all true
declare_aesop_rule_sets [test] |
.lake/packages/aesop/AesopTest/41.lean | import Aesop
set_option aesop.check.all true
/--
error: no such rule set: 'Nonexistent'
(Use 'declare_aesop_rule_set' to declare rule sets.
Declared rule sets are not visible in the current file; they only become visible once you import the declaring file.)
-/
#guard_msgs in
example : True := by
aesop (rule_sets := [Nonexistent]) |
.lake/packages/aesop/AesopTest/RuleSetNameHygiene1.lean | import AesopTest.RuleSetNameHygiene0
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
macro "aesop_test" : tactic => `(tactic| aesop (rule_sets := [test]))
@[aesop safe (rule_sets := [test])]
structure TT where
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : TT := by
aesop (config := { terminal := true })
example : TT := by
aesop_test |
.lake/packages/aesop/AesopTest/SplitScript.lean | import Aesop
set_option aesop.check.all true
open Classical
inductive MyFalse : Prop
/--
info: Try this:
[apply] split
next h => sorry
next h => sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example {A B : Prop} : if P then A else B := by
aesop? (config := { warnOnNonterminal := false })
all_goals sorry
/--
info: Try this:
[apply] split at h
next h_1 => simp_all only [true_or]
next h_1 => simp_all only [or_true]
-/
#guard_msgs in
example (h : if P then A else B) : A ∨ B := by
aesop?
/--
info: Try this:
[apply] split at h
next n => simp_all only [true_or]
next n => simp_all only [true_or, or_true]
next n_1 x x_1 => simp_all only [imp_false, or_true]
-/
#guard_msgs in
theorem foo (n : Nat) (h : match n with | 0 => A | 1 => B | _ => C) :
A ∨ B ∨ C := by
set_option aesop.check.rules false in -- TODO simp introduces mvar
set_option aesop.check.tree false in
aesop? |
.lake/packages/aesop/AesopTest/ConstructorEquations.lean | import Aesop
set_option aesop.check.all true
-- From an equation where both sides contain only constructor applications
-- and variables, Aesop should derive equations about the variables.
example (h : Nat.zero = Nat.succ n) : False := by
aesop
example (h : Nat.succ (Nat.succ n) = Nat.succ Nat.zero) : False := by
aesop
example (h : (Nat.succ m, Nat.succ n) = (Nat.succ a, Nat.succ b)) :
m = a ∧ n = b := by
aesop
structure MyProd (A B : Type _) where
toProd : A × B
example (h : MyProd.mk (x, y) = .mk (a, b)) : x = a ∧ y = b := by
aesop |
.lake/packages/aesop/AesopTest/AllWeaken.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
inductive All (P : α → Prop) : List α → Prop where
| none : All P []
| more {x xs} : P x → All P xs → All P (x :: xs)
@[aesop unsafe]
axiom weaken {α} (P Q : α → Prop) (wk : ∀ x, P x → Q x) (xs : List α)
(h : All P xs) : All Q xs
/--
error: tactic 'aesop' failed, maximum number of rule applications (50) reached. Set the 'maxRuleApplications' option to increase the limit.
-/
#guard_msgs in
example : All (· ∈ []) (@List.nil α) := by
aesop (config := { maxRuleApplications := 50, terminal := true }) |
.lake/packages/aesop/AesopTest/NameResolution.lean | import Aesop
set_option aesop.check.all true
-- When parsing the names of declarations for local rules, Aesop should take the
-- currently opened namespaces into account.
example : List α := by
aesop (add safe List.nil)
namespace List
example : List α := by
aesop (add safe List.nil)
example : List α := by
aesop (add safe nil)
end List |
.lake/packages/aesop/AesopTest/LocalTactic.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example (m n : Nat) : m * n = n * m := by
aesop
example (m n : Nat) : m * n = n * m := by
aesop (add safe (by rw [Nat.mul_comm]))
example (m n : Nat) : m * n = n * m := by
aesop (add safe tactic (by rw [Nat.mul_comm m n]))
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example (m n : Nat) : m * n = n * m := by
aesop (add safe (by rw [Nat.mul_comm m m]))
example (m n : Nat) : m * n = n * m := by
aesop (add safe (by apply Nat.mul_comm; done)) |
.lake/packages/aesop/AesopTest/ForwardTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
-- Forward rules always operate at reducible transparency.
def T := Unit → Empty
variable {α : Type}
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) (u : Unit) : α := by
aesop (config := { terminal := true })
def U := Unit
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) (u : U) : α := by
aesop (config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) (u : U) : α := by
aesop (add forward safe h) (config := { terminal := true })
abbrev V := Unit
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : Unit → Empty) (u : V) : α := by
aesop (config := { terminal := true })
example (h : Unit → Empty) (u : V) : α := by
aesop (add forward safe h) |
.lake/packages/aesop/AesopTest/SafePrefixExpansionRappLimit.lean | import Aesop
@[aesop safe]
axiom loopy {α : Prop} : α ∨ α → α
/--
warning: aesop: failed to prove the goal. Some goals were not explored because the maximum rule application depth (30) was reached. Set option 'maxRuleApplicationDepth' to increase the limit.
---
warning: aesop: safe prefix was not fully expanded because the maximum number of rule applications (50) was reached.
---
error: unsolved goals
case a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a
⊢ False
-/
#guard_msgs in
example : False := by
aesop
/--
error: tactic 'aesop' failed, failed to prove the goal. Some goals were not explored because the maximum rule application depth (30) was reached. Set option 'maxRuleApplicationDepth' to increase the limit.
Initial goal:
⊢ False
Remaining goals after safe rules:
case a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a
⊢ False
The safe prefix was not fully expanded because the maximum number of rule applications (50) was reached.
-/
#guard_msgs in
example : False := by
aesop (config := { terminal := true }) |
.lake/packages/aesop/AesopTest/Simprocs.lean | import Aesop
open Lean Lean.Meta
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def unfoldConst («from» to : Name) : Simp.Simproc := λ e =>
if e.isConstOf «from» then
return .done { expr := .const to [] }
else
return .continue
@[irreducible] def T₁ := True
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : T₁ := by
aesop
simproc unfoldT₁ (T₁) := unfoldConst ``T₁ ``True
example : T₁ := by
aesop
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : T₁ := by
aesop (config := { useDefaultSimpSet := false })
@[irreducible] def T₂ := True
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : T₂ := by
aesop
simproc [aesop_builtin] unfoldT₂ (T₂) := unfoldConst ``T₂ ``True
/--
error: tactic 'aesop' failed, made no progress
-/
#guard_msgs in
example : T₂ := by
aesop (rule_sets := [-builtin])
example : T₂ := by
aesop |
.lake/packages/aesop/AesopTest/ApplyTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def T := True
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : T := by
aesop (add safe apply True.intro) (config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : T := by
aesop (add safe apply (transparency := default) True.intro)
(config := { terminal := true })
example : T := by
aesop (add safe apply (transparency! := default) True.intro)
@[irreducible] def U := T
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : U := by
aesop (add safe apply True.intro) (config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : U := by
aesop (add safe apply (transparency := default) True.intro)
(config := { terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : U := by
aesop (add safe apply (transparency! := default) True.intro)
(config := { terminal := true })
example : U := by
aesop (add safe apply (transparency! := all) True.intro) |
.lake/packages/aesop/AesopTest/AssumptionTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
def T := Empty
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : Empty := by
aesop (erase Aesop.BuiltinRules.applyHyps)
(config := { assumptionTransparency := .reducible, terminal := true })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : T) : Empty := by
aesop (erase Aesop.BuiltinRules.applyHyps)
(config := { assumptionTransparency := .reducible, terminal := true })
example (h : T) : Empty := by
aesop (erase Aesop.BuiltinRules.applyHyps)
@[irreducible] def U := False
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : U) : False := by
aesop (config := { terminal := true })
example (h : U) : False := by
aesop (config := { assumptionTransparency := .all }) |
.lake/packages/aesop/AesopTest/AuxDecl.lean | import Aesop
import Std.Tactic.BVDecide
/-
This test case checks whether tactics that make use of auxiliary declarations,
such as `omega` and `bv_decide`, work with Aesop. Auxiliary declarations are
problematic because we can't allows tactics on different branches of the search
tree to add auxiliary declarations with the same name.
-/
theorem foo (m n : Nat) : n + m = m + n ∧ m + n = n + m := by
fail_if_success aesop (config := { terminal := true })
aesop (add safe (by omega))
local instance [Add α] [Add β] : Add (α × β) :=
⟨λ (a, b) (a', b') => (a + a', b + b')⟩
theorem bar
(fst snd fst_1 snd_1 fst_2 snd_2 w w_1 w_2 w_3 : BitVec 128)
(left : w_1.uaddOverflow w_3 = true)
(left_1 : w.uaddOverflow w_2 = true)
(right : (w_1 + w_3).uaddOverflow 1#128 = true) :
(fst_2, snd_2) = (fst, snd) + (fst_1, snd_1) := by
aesop (add safe (by bv_decide))
theorem baz (a b : BitVec 1) : (a = 0 ∨ a = 1) ∧ (b = 0 ∨ b = 1) := by
aesop (add safe 1000 (by bv_decide)) |
.lake/packages/aesop/AesopTest/207.lean | -- Thanks to Jireh Loreaux for reporting this bug.
import Aesop
def Set α := α → Prop
instance : Membership α (Set α) :=
⟨λ s a => s a⟩
instance : Singleton α (Set α) :=
⟨λ a b => b = a⟩
axiom EqOn : (f₁ f₂ : α → α) → Set α → Prop
@[aesop safe forward]
axiom EqOn.eq_of_mem (h : EqOn f₁ f₂ s) (ha : a ∈ s) : f₁ a = f₂ a
@[simp]
axiom eqOn_singleton : EqOn f₁ f₂ {x} ↔ f₁ x = f₂ x
example (s : Set Nat) (x : Nat) (hx : x ∈ s) (f : Nat → Nat)
(h_eqOn_x : EqOn f (λ _ => 1) {x}) (this : EqOn f (λ _ => 0) s) :
False := by
aesop
example (s : Set Nat) (x : Nat) (hx : x ∈ s) (f : Nat → Nat)
(this : EqOn f (λ _ => 0) s) (h_eqOn_x : EqOn f (λ _ => 1) {x}) :
False := by
aesop |
.lake/packages/aesop/AesopTest/GlobalRuleIdentErrorChecking.lean | import Aesop
/--
error: duplicate rule 'Nat.add_assoc'; rule 'bar' was already given.
Use [<term>,...] to give multiple rules.
-/
#guard_msgs in
@[aesop norm simp Nat.add_assoc]
theorem bar : True := trivial |
.lake/packages/aesop/AesopTest/Constructors.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop safe]
inductive Even : Nat → Type
| zero : Even 0
| plusTwo : Even n → Even (n + 2)
example : Even 6 := by
aesop
attribute [-aesop] Even
def T n := Even n
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : T 6 := by
aesop (config := { terminal := true })
example : T 6 := by
aesop (add safe constructors (transparency! := default) Even) |
.lake/packages/aesop/AesopTest/UnreachableTacticLinter.lean | import Aesop
set_option aesop.check.all true
add_aesop_rules safe (by simp) |
.lake/packages/aesop/AesopTest/125.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop 90%]
def myTacGen : Aesop.TacGen := fun _ => do
return #[("exact ⟨val - f { val := val, property := property }, fun a ha => by simpa⟩",
0.9)]
/-- error: tactic 'aesop' failed, made no progress -/
#guard_msgs in
theorem foo (f : { x // 0 < x } → { x // 0 < x }) (val : Nat)
(property : 0 < val) :
∃ w x, ∀ (a : Nat) (b : 0 < a), ↑(f { val := a, property := b }) = w * a + x := by
constructor
aesop |
.lake/packages/aesop/AesopTest/CustomIndexing.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
variable {α : Type}
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h : α) : α := by
aesop (rule_sets := [-builtin,-default])
(add safe h apply (index := [target False]))
(config := { terminal := true })
example (h : α) : α := by
aesop (rule_sets := [-builtin,-default]) (add safe h apply)
-- See Com test for a more realistic scenario. |
.lake/packages/aesop/AesopTest/10.lean | import Aesop
set_option aesop.check.all true
attribute [aesop unsafe [50% constructors, 50% cases]] List.Mem
theorem Mem.map (f : α → β) (x : α) (xs : List α) (h : x ∈ xs) :
f x ∈ xs.map f := by
induction h <;> aesop |
.lake/packages/aesop/AesopTest/Forward.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
set_option pp.mvars false
/--
info: Try this:
[apply] have fwd : γ₁ ∧ γ₂ := r₁ a b
have fwd_1 : δ₁ ∧ δ₂ := r₂ a
---
error: unsolved goals
α : Sort u_1
β : Sort u_2
γ₁ γ₂ δ₁ δ₂ : Prop
a : α
b : β
r₁ : ∀ (a : α) (b : β), γ₁ ∧ γ₂
r₂ : ∀ (a : α), δ₁ ∧ δ₂
fwd : γ₁ ∧ γ₂
fwd_1 : δ₁ ∧ δ₂
⊢ γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂
-/
#guard_msgs in
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
have fwd_1 : γ := h₂ fwd
---
error: unsolved goals
α β γ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : α
fwd : β
fwd_1 : γ
⊢ γ
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
---
error: unsolved goals
α β γ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : α
fwd : β
⊢ γ
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
forward? [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
---
error: unsolved goals
α β γ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : α
fwd : β
⊢ γ
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
saturate? 1 [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₄
have fwd_1 : γ := h₂ fwd
---
error: unsolved goals
α β γ δ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : γ → δ
h₄ : α
fwd : β
fwd_1 : γ
⊢ δ
-/
#guard_msgs in
example {α β γ δ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : γ → δ) (h₄ : α) : δ := by
saturate? 2 [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₄
have fwd_1 : γ := h₂ h₄
---
error: unsolved goals
α β γ δ : Prop
h₁ : α → β
h₂ : α → γ
h₃ : β → γ → δ
h₄ : α
fwd : β
fwd_1 : γ
⊢ δ
-/
#guard_msgs in
example {α β γ δ : Prop} (h₁ : α → β) (h₂ : α → γ) (h₃ : β → γ → δ) (h₄ : α) : δ := by
saturate? 1 [*]
example {P : Nat → Prop} (hP : P 0) (hPn : ∀ n, P n → P (n + 1)) : P 20 := by
saturate 20 [*]
assumption
section
axiom A : Type
axiom B : Type
axiom C : Type
@[local aesop safe forward]
axiom ab : A → B
@[local aesop norm forward]
axiom bc : B → C
/--
info: Try this:
[apply] have fwd : P := rule P (Q ∧ R) h
-/
#guard_msgs in
example (rule : ∀ α β, α ∧ β → α) (h : P ∧ Q ∧ R) : P := by
forward? [*]
guard_hyp fwd : P
assumption
/--
info: Try this:
[apply] have fwd : B := ab a
have fwd_1 : C := bc fwd
---
error: unsolved goals
a : A
fwd : B
fwd_1 : C
⊢ C
-/
#guard_msgs in
noncomputable example : A → C := by
intro a
saturate?
end
/--
info: Try this:
[apply] have fwd : R a b := h₁ a b h₂ h₃
---
error: unsolved goals
α : Sort u_1
β : Sort u_2
a : α
b : β
P Q R : α → β → Prop
h₁ : ∀ (a : α) (b : β), P a b → Q a b → R a b
h₂ : P a b
h₃ : Q a b
fwd : R a b
⊢ R a b
-/
#guard_msgs in
example {P Q R : α → β → Prop} (h₁ : ∀ a b, P a b → Q a b → R a b)
(h₂ : P a b) (h₃ : Q a b) : R a b := by
saturate? [h₁]
/--
info: Try this:
[apply] have fwd : R a b := h₁ a b h₂ h₄
---
error: unsolved goals
α : Sort u_1
a b : α
P Q R : α → α → Prop
h₁ : ∀ (a b : α), P a b → Q b a → R a b
h₂ : P a b
h₃ : Q a b
h₄ : Q b a
fwd : R a b
⊢ R a b
-/
#guard_msgs in
example {P Q R : α → α → Prop} (h₁ : ∀ a b, P a b → Q b a → R a b)
(h₂ : P a b) (h₃ : Q a b) (h₄ : Q b a) : R a b := by
saturate? [*]
/--
error: unsolved goals
α : Sort u_1
a b : α
P Q R : α → α → Prop
h₁ : ∀ (a b : α), P a b → Q b a → R a b
h₂ : P a b
h₃ : Q a b
⊢ R a b
-/
#guard_msgs in
example {P Q R : α → α → Prop} (h₁ : ∀ a b, P a b → Q b a → R a b)
(h₂ : P a b) (h₃ : Q a b) : R a b := by
saturate [*]
/--
info: Try this:
[apply] have fwd : R b a := h₁ b a h₄ h₃
---
error: unsolved goals
α : Sort u_1
c d a b : α
P Q R : α → α → Prop
h₁ : ∀ (a b : α), P a b → Q b a → R a b
h₂ : P c d
h₃ : Q a b
h₄ : P b a
fwd : R b a
⊢ R b a
-/
#guard_msgs in
example {P Q R : α → α → Prop} (h₁ : ∀ a b, P a b → Q b a → R a b)
(h₂ : P c d) (h₃ : Q a b) (h₄ : P b a) : R b a := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : R c c := h₁ c d d c h₂ h₅
have fwd_1 : R c b := h₁ c d a b h₂ h₃
have fwd_2 : R b c := h₁ b a d c h₄ h₅
have fwd_3 : R b b := h₁ b a a b h₄ h₃
---
error: unsolved goals
α : Sort u_1
c d a b : α
P Q R : α → α → Prop
h₁ : ∀ (a b c d : α), P a b → Q c d → R a d
h₂ : P c d
h₃ : Q a b
h₄ : P b a
h₅ : Q d c
fwd : R c c
fwd_1 : R c b
fwd_2 : R b c
fwd_3 : R b b
⊢ R c b
-/
#guard_msgs in
example {P Q R : α → α → Prop} (h₁ : ∀ a b c d, P a b → Q c d → R a d)
(h₂ : P c d) (h₃ : Q a b) (h₄ : P b a) (h₅ : Q d c) : R c b := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : S a d := h₁ a b c d h₂ h₃ h₄
have fwd_1 : S a c := h₁ a b d c h₂ h₃ h₅
---
error: unsolved goals
α : Sort u_1
a b c d : α
P Q R S : α → α → Prop
h₁ : ∀ (a b c d : α), P a b → Q b a → R c d → S a d
h₂ : P a b
h₃ : Q b a
h₄ : R c d
h₅ : R d c
fwd : S a d
fwd_1 : S a c
⊢ S a d
-/
#guard_msgs in
example {P Q R S : α → α → Prop} (h₁ : ∀ a b c d, P a b → Q b a → R c d → S a d)
(h₂ : P a b) (h₃ : Q b a) (h₄ : R c d) (h₅ : R d c) : S a d := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : R b a := h₁ a b h₂ h₃ h₄
---
error: unsolved goals
α : Sort u_1
a b : α
P : α → Prop
Q R : α → α → Prop
h₁ : ∀ (a b : α), P a → P b → Q a b → R b a
h₂ : P a
h₃ : P b
h₄ : Q a b
fwd : R b a
⊢ Q b a
-/
#guard_msgs in
example {P : α → Prop} {Q R : α → α → Prop}
(h₁ : ∀ a b, P a → P b → Q a b → R b a)
(h₂ : P a) (h₃ : P b) (h₄ : Q a b) : Q b a := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : R b a := h₁ a b h₆ h₅ h₄
---
error: unsolved goals
α : Sort u_1
c d a b : α
P : α → Prop
Q R : α → α → Prop
h₁ : ∀ (a b : α), P a → P b → Q a b → R b a
h₂ : P c
h₃ : P d
h₄ : Q a b
h₅ : P b
h₆ : P a
fwd : R b a
⊢ Q b a
-/
#guard_msgs in
example {P : α → Prop} {Q R : α → α → Prop}
(h₁ : ∀ a b, P a → P b → Q a b → R b a)
(h₂ : P c) (h₃ : P d) (h₄ : Q a b) (h₅ : P b) (h₆ : P a) : Q b a := by
saturate? [*]
/--
info: Try this:
[apply] have fwd : R c d := h₁ d c h₃ h₂ h₇
have fwd_1 : R b a := h₁ a b h₆ h₅ h₄
---
error: unsolved goals
α : Sort u_1
c d a b : α
P : α → Prop
Q R : α → α → Prop
h₁ : ∀ (a b : α), P a → P b → Q a b → R b a
h₂ : P c
h₃ : P d
h₄ : Q a b
h₅ : P b
h₆ : P a
h₇ : Q d c
fwd : R c d
fwd_1 : R b a
⊢ Q b a
-/
#guard_msgs in
example {P : α → Prop} {Q R : α → α → Prop}
(h₁ : ∀ a b, P a → P b → Q a b → R b a)
(h₂ : P c) (h₃ : P d) (h₄ : Q a b) (h₅ : P b) (h₆ : P a) (h₇ : Q d c) : Q b a := by
saturate? [*]
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop (add safe [forward r₁, forward (immediate := [a]) r₂])
section MatchRedundancy
-- Complete matches are considered redundant (and hence do not produce new
-- hypotheses) if they agree on all variables that appear in the conclusion.
/--
error: unsolved goals
γ : Sort u_1
α : Prop
β : Type
r : α → β → γ
a₁ a₂ : α
b₁ b₂ : β
fwd : γ
⊢ True
-/
#guard_msgs in
example {α : Prop} {β : Type} (r : α → β → γ) (a₁ a₂ : α) (b₁ b₂ : β) : True := by
saturate [r]
-- Only one new hypothesis.
/--
error: unsolved goals
α : Sort u_1
a₁ a₂ : α
P Q : α → Prop
r : ∀ (a : α), P a → Q a
p₁ : P a₁
p₂ p₂' : P a₂
fwd : Q a₁
fwd_1 : Q a₂
⊢ True
-/
#guard_msgs in
example {P Q : α → Prop} (r : ∀ a, P a → Q a) (p₁ : P a₁) (p₂ : P a₂)
(p₂' : P a₂) : True := by
saturate [r]
-- Two new hypotheses, one for `a₁` and one for `a₂` (but not two).
-- When a hypothesis already exists in the context, it is not added again.
/--
error: unsolved goals
α : Sort u_1
β : Sort u_2
r₁ r₂ : α → β
a₁ a₂ : α
fwd : β
⊢ True
-/
#guard_msgs in
example (r₁ r₂ : α → β) (a₁ a₂ : α) : True := by
saturate [r₁, r₂]
-- Two new hypotheses (but not four).
end MatchRedundancy
/--
info: Try this:
[apply] have fwd : γ₁ ∧ γ₂ := r₁ a b
simp_all only [and_self, implies_true, true_and]
obtain ⟨left, right⟩ := fwd
have fwd : δ₁ ∧ δ₂ := r₂ a
simp_all only [and_self, implies_true]
-/
#guard_msgs in
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop? (add safe [forward r₁, forward (immediate := [a]) r₂])
-- `destruct` rules only clear propositional hypotheses. So this succeeds:
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ)
(r₂ : (a : α) → δ) : γ ∧ δ := by
aesop (add safe [destruct r₁, destruct (immediate := [a]) r₂])
(config := { enableSimp := false, terminal := true })
-- ... but this fails:
/-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/
#guard_msgs in
example {α : Prop} (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ)
(r₂ : (a : α) → δ) : γ ∧ δ := by
aesop (add safe [destruct r₁, destruct (immediate := [a]) r₂])
(config := { enableSimp := false, terminal := true })
-- Same examples with `saturate`. Note: We currently can't make local `saturate`
-- rules into `destruct` rules.
namespace SaturateEx₁
axiom α : Type
axiom β : Type
axiom γ₁ : Prop
axiom γ₂ : Prop
axiom δ₁ : Prop
axiom δ₂ : Prop
@[aesop safe destruct]
axiom r₁ : α → β → γ₁ ∧ γ₂
@[aesop safe destruct]
axiom r₂ : α → δ₁ ∧ δ₂
/--
error: unsolved goals
a : α
b : β
fwd : γ₁ ∧ γ₂
fwd_1 : δ₁ ∧ δ₂
⊢ γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂
-/
#guard_msgs in
example (a : α) (b : β) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
saturate
end SaturateEx₁
namespace SaturateEx₂
axiom α : Prop
axiom β : Type
axiom γ₁ : Prop
axiom γ₂ : Prop
axiom δ₁ : Prop
axiom δ₂ : Prop
@[aesop safe destruct]
axiom r₁ : α → β → γ₁ ∧ γ₂
@[aesop safe destruct]
axiom r₂ : α → δ₁ ∧ δ₂
/--
error: unsolved goals
b : β
fwd : γ₁ ∧ γ₂
⊢ γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂
-/
#guard_msgs in
example (a : α) (b : β) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
saturate
end SaturateEx₂
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop (add safe [forward r₁], 90% destruct r₂)
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
α β γ : Prop
h₁ : α
h₂ : β
fwd : γ
⊢ False
-/
#guard_msgs in
example {α β γ : Prop} (h : α → β → γ) (h₁ : α) (h₂ : β) : False := by
aesop (add norm -1 forward h)
-- In the following example, `h` does not apply because `simp_all` discharges
-- the premises `α` and `β`. The stateful implementation of forward reasoning
-- can't reasonably deal with local rules whose types change during the course
-- of the search; the best we can do is try to detect when this happens.
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
α β γ : Prop
h : γ
h₁ : α
h₂ : β
⊢ False
-/
#guard_msgs in
example {α β γ : Prop} (h : α → β → γ) (h₁ : α) (h₂ : β) : False := by
aesop (add safe forward h)
section Computation
-- Stateful forward reasoning sees through `reducible` definitions...
abbrev rid (x : α) : α := x
example {P Q : α → Prop} (h₁ : ∀ a, P a → Q a → X) (h₂ : P (rid a)) (h₃ : Q a) : X := by
saturate [h₁]
exact fwd
-- ... but not through semireducible ones.
/--
error: unsolved goals
α : Sort _
X : Sort _
a : α
P Q : α → Prop
h₁ : (a : α) → P a → Q a → X
h₂ : P (id a)
h₃ : Q a
⊢ X
-/
#guard_msgs in
example {P Q : α → Prop} (h₁ : ∀ a, P a → Q a → X) (h₂ : P (id a)) (h₃ : Q a) : X := by
saturate [h₁]
end Computation
namespace Immediate
axiom α : Type
axiom P : α → Prop
axiom Q : α → Prop
axiom R : α → Prop
@[aesop safe forward (immediate := [h₂])]
axiom foo : ∀ a (h₁ : P a) (h₂ : Q a), R a
/--
error: unsolved goals
a : α
h : Q a
fwd : P a → R a
⊢ False
-/
#guard_msgs in
example (h : Q a) : False := by
saturate
end Immediate
namespace Instance
class Foo (α : Type) : Prop
axiom β : Type
@[aesop safe forward]
axiom foo : ∀ (α : Type) (a : α) [Foo α], β
/--
error: unsolved goals
α : Type
inst✝ : Foo α
a : α
fwd : β
⊢ False
-/
#guard_msgs in
example [Foo α] (a : α) : False := by
saturate
axiom γ : Type
instance : Foo γ where
/--
error: unsolved goals
c : γ
fwd : β
⊢ False
-/
#guard_msgs in
example (c : γ) : False := by
saturate
@[aesop safe forward (immediate := [a])]
axiom bar : ∀ α β (a : α) (b : β) [Foo β], γ
/--
error: unsolved goals
α : Sort u_1
a : α
⊢ False
-/
#guard_msgs in
example (a : α) : False := by
saturate
/--
error: unsolved goals
c : γ
fwd : β
⊢ False
-/
#guard_msgs in
example (c : γ) : False := by
saturate
end Instance
namespace ConstForwardRule
axiom α : Type
@[local aesop safe forward]
axiom a : α
noncomputable example : α := by
aesop
/--
error: unsolved goals
fwd : α
⊢ α
-/
#guard_msgs in
noncomputable example : α := by
saturate
end ConstForwardRule
section MultipleUniverses
-- Here we test the handling of rules with multiple universe parameters.
axiom α.{u} : Type u
axiom β.{v} : Type v
axiom γ.{w} : Type w
axiom P.{u, v, w} : α.{u} → β.{v} → γ.{w} → Prop
axiom Q.{u, v, w} : β.{v} → α.{u} → γ.{w} → Prop
@[local aesop safe forward]
axiom foo {a b c} : P a b c → Q b a c
example (h : P a b c) : Q b a c := by
saturate
assumption
end MultipleUniverses |
.lake/packages/aesop/AesopTest/Metas.lean | import Aesop
set_option aesop.check.all true
example (P : α → Prop) (a : α) (h : P a) : ∃ a, P a := by
aesop
example (P : α → β → Prop) (a : α) (b : β) (h : P a b) : ∃ a b, P a b := by
aesop
example (P : α → Type) (a : α) (h : P a) : Σ a, P a := by
aesop
example (P : α → β → Type) (a : α) (b : β) (h : P a b) : Σ a b, P a b := by
aesop
example (P Q : α → Prop) (hPQ : ∀ a, P a → Q a) (a : α) (h : P a) : ∃ a, Q a := by
aesop
example (P Q Dead R : α → Prop)
(hPQ : ∀ a, P a → Q a)
(hDeadR : ∀ a, Dead a → R a)
(hQR : ∀ a, Q a → R a)
(a : α) (h : P a) :
∃ a, R a := by
aesop
example (R : α → α → Prop) (R_trans : ∀ x y z, R x y → R y z → R x z) (a b c d)
(hab : R a b) (hbc : R b c) (hcd : R c d) : R a d := by
aesop |
.lake/packages/aesop/AesopTest/BigStep.lean | import Aesop
set_option aesop.check.all true
abbrev Variable := String
def State := Variable → Nat
inductive Stmt : Type where
| skip : Stmt
| assign : Variable → (State → Nat) → Stmt
| seq : Stmt → Stmt → Stmt
| ifThenElse : (State → Prop) → Stmt → Stmt → Stmt
| whileDo : (State → Prop) → Stmt → Stmt
infix:60 ";; " => Stmt.seq
export Stmt (skip assign seq ifThenElse whileDo)
set_option quotPrecheck false in
notation s:70 "[" x:70 "↦" n:70 "]" => (fun v ↦ if v = x then n else s v)
inductive BigStep : Stmt → State → State → Prop where
| protected skip (s : State) : BigStep skip s s
| protected assign (x : Variable) (a : State → Nat) (s : State) : BigStep (assign x a) s (s[x ↦ a s])
| protected seq {S T : Stmt} {s t u : State} (hS : BigStep S s t) (hT : BigStep T t u) :
BigStep (S;; T) s u
| protected if_true {B : State → Prop} {s t : State} (hcond : B s) (S T : Stmt) (hbody : BigStep S s t) :
BigStep (ifThenElse B S T) s t
| protected if_false {B : State → Prop} {s t : State} (hcond : ¬ B s) (S T : Stmt) (hbody : BigStep T s t) :
BigStep (ifThenElse B S T) s t
| while_true {B S s t u} (hcond : B s) (hbody : BigStep S s t) (hrest : BigStep (whileDo B S) t u) :
BigStep (whileDo B S) s u
| while_false {B S s} (hcond : ¬ B s) : BigStep (whileDo B S) s s
notation:55 "(" S:55 "," s:55 ")" " ==> " t:55 => BigStep S s t
add_aesop_rules safe [BigStep.skip, BigStep.assign, BigStep.seq, BigStep.while_false]
add_aesop_rules 50% [apply BigStep.while_true]
add_aesop_rules safe [
(by apply BigStep.if_true (hcond := by assumption) (hbody := by assumption)),
(by apply BigStep.if_false (hcond := by assumption) (hbody := by assumption))
]
namespace BigStep
@[aesop safe destruct]
theorem cases_if_of_true {B S T s t} (hcond : B s) : (ifThenElse B S T, s) ==> t → (S, s) ==> t := by
intro h; cases h <;> aesop
@[aesop safe destruct]
theorem cases_if_of_false {B S T s t} (hcond : ¬ B s) : (ifThenElse B S T, s) ==> t → (T, s) ==> t := by
intro h; cases h <;> aesop
@[aesop 30%]
theorem and_excluded {P Q R : Prop} (hQ : P → Q) (hR : ¬ P → R) : (P ∧ Q ∨ ¬ P ∧ R) := by
by_cases h : P <;> aesop
theorem if_iff {B S T s t} : (ifThenElse B S T, s) ==> t ↔
(B s ∧ (S, s) ==> t) ∨ (¬ B s ∧ (T, s) ==> t) := by
aesop
end BigStep |
.lake/packages/aesop/AesopTest/EnableUnfold.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop norm unfold]
def T := True
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : T := by
aesop (config := { enableUnfold := false, terminal := true })
example : T := by
aesop |
.lake/packages/aesop/AesopTest/Subst.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
-- These test cases test the builtin subst tactic.
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h₁ : x = 5) (h₂ : y = 5) : x = y := by
aesop (erase Aesop.BuiltinRules.subst)
(config := { useSimpAll := false, terminal := true })
example (h₁ : x = 5) (h₂ : y = 5) : x = y := by
aesop (config := { useSimpAll := false })
variable {α : Type}
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example {x y z : α} (h₁ : x = y) (h₂ : y = z) : x = z := by
aesop (erase Aesop.BuiltinRules.subst)
(config := { useSimpAll := false, terminal := true })
example {x y z : α} (h₁ : x = y) (h₂ : y = z) : x = z := by
aesop (config := { useSimpAll := false })
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example {x y : α }(P : ∀ x y, x = y → Prop) (h₁ : x = y) (h₂ : P x y h₁) :
x = y := by
aesop
(erase Aesop.BuiltinRules.subst, Aesop.BuiltinRules.assumption,
Aesop.BuiltinRules.applyHyps)
(config := { useSimpAll := false, terminal := true })
example {x y : α }(P : ∀ x y, x = y → Prop) (h₁ : x = y) (h₂ : P x y h₁) :
x = y := by
aesop
(erase Aesop.BuiltinRules.assumption,
Aesop.BuiltinRules.applyHyps)
(config := { useSimpAll := false })
-- Subst also works for bi-implications.
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example (h₁ : P ↔ Q) (h₂ : Q ↔ R) (h₃ : P) : R := by
aesop (erase Aesop.BuiltinRules.subst)
(config := { useSimpAll := false, terminal := true })
example (h₁ : P ↔ Q) (h₂ : Q ↔ R) (h₃ : P) : R := by
aesop (config := { useSimpAll := false })
-- Subst also works for morally-homogeneous heterogeneous equalities (using a
-- builtin simp rule which turns these into actual homogeneous equalities).
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example {P : α → Prop} {x y z : α} (h₁ : x ≍ y) (h₂ : y ≍ z) (h₃ : P x) :
P z := by
aesop (erase Aesop.BuiltinRules.subst)
(config := { useSimpAll := false, terminal := true })
example {P : α → Prop} {x y z : α} (h₁ : x ≍ y) (h₂ : y ≍ z) (h₃ : P x) :
P z := by
aesop (config := { useSimpAll := false }) |
.lake/packages/aesop/AesopTest/Persistence1.lean | import AesopTest.Persistence0
set_option aesop.check.all true
namespace Aesop
@[aesop 50% constructors (rule_sets := [test_persistence1])]
inductive NatOrBool where
| ofNat (n : Nat)
| ofBool (b : Bool)
example (b : Bool) : NatOrBool := by
aesop (rule_sets := [test_persistence1])
end Aesop |
.lake/packages/aesop/AesopTest/26.lean | import Aesop
set_option aesop.check.all true
attribute [-simp] List.all_cons List.all_nil List.all_eq_true
/--
warning: aesop: failed to prove the goal after exhaustive search.
---
error: unsolved goals
case left
α : Type u_1
P : α → Bool
x : α
xs : List α
h : (x :: xs).all P = true
⊢ P x = true
case right
α : Type u_1
P : α → Bool
x : α
xs : List α
h : (x :: xs).all P = true
⊢ xs.all P = true
-/
#guard_msgs in
theorem all_cons (P : α → Bool) (x : α) (xs : List α) (h : (x :: xs).all P)
: P x ∧ xs.all P := by
aesop |
.lake/packages/aesop/AesopTest/LegacyForward.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
set_option pp.mvars false
-- This file contains regression tests for the old, stateless forward reasoning.
set_option aesop.dev.statefulForward false
open Aesop Lean Lean.Meta Lean.Elab.Tactic
/-! # Unit tests for the MetaM tactic that implements forward rules -/
syntax (name := forward) "t_forward " ident (" [" ident* "]")? : tactic
syntax (name := elim) "t_elim " ident (" [" ident* "]")? : tactic
def forwardTac (goal : MVarId) (id : Ident) (immediate : Option (Array Syntax))
(clear : Bool) : MetaM (List MVarId) := do
let userName := id.getId
let ldecl ← getLocalDeclFromUserName userName
let immediate ← RuleBuilder.getImmediatePremises ldecl.type none
(immediate.map (·.map (·.getId)))
let ((goal, _), _) ←
RuleTac.applyForwardRule goal (mkFVar ldecl.fvarId) none immediate clear
(maxDepth? := none) ∅ |>.run.run
return [goal.mvarId]
@[tactic forward]
def evalForward : Tactic
| `(tactic| t_forward $t:ident $[[ $immediate:ident* ]]?) =>
liftMetaTactic (forwardTac · t immediate (clear := false))
| _ => unreachable!
@[tactic elim]
def evalElim : Tactic
| `(tactic| t_elim $t:ident $[[ $immediate:ident* ]]?) =>
liftMetaTactic (forwardTac · t immediate (clear := true))
| _ => unreachable!
example (rule : (a : α) → (b : β) → γ) (h₁ : α) (h₂ : β) : γ := by
t_forward rule [a b]
assumption
example {P Q R : α → Type} (rule : ∀ a (p : P a) (q : Q a), R a)
(h₁ : P a) (h₁' : P a) (h₂ : Q a) (h₃ : P b) (h₄ : Q c) : R a := by
t_forward rule [p q]
assumption
example {P Q R : α → Type} (rule : ∀ a (p : P a) (q : Q a), R a)
(h₁ : P a) (h₁' : P a) (h₂ : Q a) (h₃ : P b) (h₄ : Q c) : R a := by
t_forward rule
assumption
example {P Q R : α → Type} (rule : ∀ a (p : P a) (q : Q a), R a)
(h₁ : P a) (h₂ : P b) : (Q a → R a) × (Q b → R b) := by
t_forward rule [p]
exact (by assumption, by assumption)
example (rule : ∀ α β, α ∧ β → α) (h : P ∧ Q ∧ R) : P := by
t_elim rule
assumption
/-! # Tests for the `forward` and `saturate` tactics -/
/--
info: Try this:
[apply] have fwd : P := rule P (Q ∧ R) h
-/
#guard_msgs in
example (rule : ∀ α β, α ∧ β → α) (h : P ∧ Q ∧ R) : P := by
forward? [*]
guard_hyp fwd : P
assumption
/--
info: Try this:
[apply] have fwd : γ₁ ∧ γ₂ := r₁ a b
have fwd_1 : δ₁ ∧ δ₂ := r₂ a
-/
#guard_msgs in
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
saturate? [*]
guard_hyp fwd : γ₁ ∧ γ₂
guard_hyp fwd_1 : δ₁ ∧ δ₂
aesop
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
have fwd_1 : γ := h₂ fwd
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
saturate? [*]
guard_hyp fwd : β
guard_hyp fwd_1 : γ
assumption
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
---
error: unsolved goals
α β γ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : α
fwd : β
⊢ γ
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
forward? [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₃
---
error: unsolved goals
α β γ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : α
fwd : β
⊢ γ
-/
#guard_msgs in
example {α β γ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : α) : γ := by
saturate? 1 [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₄
have fwd_1 : γ := h₂ fwd
---
error: unsolved goals
α β γ δ : Prop
h₁ : α → β
h₂ : β → γ
h₃ : γ → δ
h₄ : α
fwd : β
fwd_1 : γ
⊢ δ
-/
#guard_msgs in
example {α β γ δ : Prop} (h₁ : α → β) (h₂ : β → γ) (h₃ : γ → δ) (h₄ : α) : δ := by
saturate? 2 [*]
/--
info: Try this:
[apply] have fwd : β := h₁ h₄
have fwd_1 : γ := h₂ h₄
---
error: unsolved goals
α β γ δ : Prop
h₁ : α → β
h₂ : α → γ
h₃ : β → γ → δ
h₄ : α
fwd : β
fwd_1 : γ
⊢ δ
-/
#guard_msgs in
example {α β γ δ : Prop} (h₁ : α → β) (h₂ : α → γ) (h₃ : β → γ → δ) (h₄ : α) : δ := by
saturate? 1 [*]
axiom A : Type
axiom B : Type
axiom C : Type
@[aesop safe forward]
axiom ab : A → B
@[aesop norm forward]
axiom bc : B → C
/--
info: Try this:
[apply] have fwd : B := ab a
have fwd_1 : C := bc fwd
-/
#guard_msgs in
noncomputable example : A → C := by
intro a
saturate?
guard_hyp fwd : B
guard_hyp fwd_1 : C
exact fwd_1
/-! # Tests for Aesop's forward rules -/
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop (add safe [forward r₁, forward (immediate := [a]) r₂])
/--
info: Try this:
[apply] have fwd : γ₁ ∧ γ₂ := r₁ a b
simp_all only [and_self, implies_true, true_and]
obtain ⟨left, right⟩ := fwd
have fwd : δ₁ ∧ δ₂ := r₂ a
simp_all only [and_self, implies_true]
-/
#guard_msgs in
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop? (add safe [forward r₁, forward (immediate := [a]) r₂])
-- `destruct` rules only clear propositional hypotheses. So this succeeds:
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ)
(r₂ : (a : α) → δ) : γ ∧ δ := by
aesop (add 1% [destruct r₁, destruct (immediate := [a]) r₂])
(config := { enableSimp := false, terminal := true })
-- ... but this fails:
/-- error: tactic 'aesop' failed, failed to prove the goal after exhaustive search. -/
#guard_msgs in
example {α : Prop} (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ)
(r₂ : (a : α) → δ) : γ ∧ δ := by
aesop (add safe [destruct r₁, destruct (immediate := [a]) r₂])
(config := { enableSimp := false, terminal := true })
example (a : α) (b : β) (r₁ : (a : α) → (b : β) → γ₁ ∧ γ₂)
(r₂ : (a : α) → δ₁ ∧ δ₂) : γ₁ ∧ γ₂ ∧ δ₁ ∧ δ₂ := by
aesop (add safe [forward r₁], 90% destruct r₂) |
.lake/packages/aesop/AesopTest/Erase.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[aesop [10% cases, safe constructors]]
inductive Even : Nat → Prop
| zero : Even 0
| plus_two : Even n → Even (n + 2)
example : Even 2 := by
aesop
-- Removing the Aesop attribute erases all rules associated with the identifier
-- from all rule sets.
attribute [-aesop] Even
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : Even 2 := by
aesop (config := { terminal := true })
example : Even 2 := by
aesop (add safe Even)
-- We can also selectively remove rules in a certain phase or with a certain
-- builder.
attribute [aesop [unsafe 10% cases, safe constructors]] Even
erase_aesop_rules [ unsafe Even ]
example : Even 2 := by
aesop
erase_aesop_rules [ constructors Even ]
/--
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
-/
#guard_msgs in
example : Even 2 := by
aesop (config := { terminal := true })
example : Even 2 := by
aesop (add safe constructors Even) |
.lake/packages/aesop/AesopTest/27.lean | -- This test checks whether the output of trace.aesop.proof is
-- copy-and-pastable. When the test breaks because Aesop's output has changed,
-- please copy-and-paste the output to All.split_cons₂ and check whether it
-- still works.
import Aesop
set_option aesop.check.all true
@[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)
/--
trace: [aesop.proof] Final proof:
(fun (h_1 : All P (x :: xs)) =>
((fun (h_2 : All P (x :: xs)) =>
(casesOn (P := P) (motive := fun a x_1 => x :: xs = a → h ≍ x_1 → P x ∧ All P xs) h_2
(fun h_3 => False.elim (noConfusion_of_Nat List.ctorIdx h_3)) fun {x_1} {xs_1} a a_1 h_3 =>
List.cons.noConfusion (h ≍ cons (P := P) a a_1 → P x ∧ All P xs) x xs x_1 xs_1 h_3 fun head_eq =>
Eq.ndrec (motive := fun {x_1} =>
∀ (a : P x_1), xs = xs_1 → h ≍ cons (P := P) a a_1 → P x ∧ All P xs)
(fun a tail_eq =>
Eq.ndrec (motive := fun {xs_1} =>
∀ (a_1 : All P xs_1), h ≍ cons (P := P) a a_1 → P x ∧ All P xs)
(fun a_1 h =>
of_eq_true (Eq.trans (congr (congrArg And (eq_true a)) (eq_true a_1)) (and_self True)))
tail_eq a_1)
head_eq a :
x :: xs = x :: xs → h ≍ h_2 → P x ∧ All P xs))
h_1 :
x :: xs = x :: xs → h ≍ h_1 → P x ∧ All P xs))
h (Eq.refl (x :: xs)) (HEq.refl h)
-/
#guard_msgs in
theorem All.split_cons (P : α → Prop) (x : α) (xs : List α) (h : All P (x :: xs))
: P x ∧ All P xs := by
set_option trace.aesop.proof true in
aesop
theorem All.split_cons₂ (P : α → Prop) (x : α) (xs : List α) (h : All P (x :: xs))
: P x ∧ All P xs :=
(fun (h_1 : All P (x :: xs)) =>
((fun (h_2 : All P (x :: xs)) =>
(All.casesOn (P := P) (motive := fun a x_1 => x :: xs = a → h ≍ x_1 → P x ∧ All P xs) h_2
(fun h_1 => List.noConfusion h_1) fun {x_1} {xs_1} a a_1 h_1 =>
List.noConfusion h_1 fun head_eq =>
Eq.ndrec (motive := fun {x_1} =>
∀ (a : P x_1), xs = xs_1 → h ≍ All.cons (P := P) a a_1 → P x ∧ All P xs)
(fun a tail_eq =>
Eq.ndrec (motive := fun {xs_1} =>
∀ (a_1 : All P xs_1), h ≍ All.cons (P := P) a a_1 → P x ∧ All P xs)
(fun a_1 h_1 =>
Eq.ndrec (motive := fun h => P x ∧ All P xs)
(of_eq_true (Eq.trans (congr (congrArg And (eq_true a)) (eq_true a_1)) (and_self True)))
(Eq.symm (eq_of_heq h_1)))
tail_eq a_1)
head_eq a :
x :: xs = x :: xs → h ≍ h_2 → P x ∧ All P xs))
h_1 :
x :: xs = x :: xs → h ≍ h_1 → P x ∧ All P xs))
h (Eq.refl (x :: xs)) (HEq.refl h) |
.lake/packages/aesop/AesopTest/Persistence0.lean | import Aesop
set_option aesop.check.all true
declare_aesop_rule_sets [test_persistence1] |
.lake/packages/aesop/AesopTest/EqualUpToIds.lean | import Aesop.Util.Basic
import Aesop.Util.EqualUpToIds
import Aesop.Tree.RunMetaM
-- Some simple test cases for the EqualUpToIds module. The module is mostly
-- tested by using it in script validation, which is run on almost all Aesop
-- calls in the test suite.
open Aesop Lean Lean.Elab.Tactic
def assertEqualTactics (t₁ t₂ : TacticM Unit) : TacticM Unit := do
let commonMCtx ← getMCtx
let preState ← show MetaM _ from saveState
let preGoals ← getGoals
let (state₁, goals₁) ← runTacticMCapturingPostState t₁ preState preGoals
let (state₂, goals₂) ← runTacticMCapturingPostState t₂ preState preGoals
let eq ←
tacticStatesEqualUpToIds commonMCtx state₁.meta.mctx state₂.meta.mctx
goals₁.toArray goals₂.toArray
if ! eq then
throwError "Tactics produced different tactic states.\nTactic 1:{indentD $ ← ppTacticState state₁ goals₁}\nTactic 2:{indentD $ ← ppTacticState state₂ goals₂}\n"
where
ppTacticState (state : Meta.SavedState) (goals : List MVarId) :
MetaM MessageData :=
state.runMetaM' do
addMessageContext $ .joinSep (goals.map toMessageData) "\n"
open Lean.Elab.Tactic in
elab &"assert_equal_tactics "
" { " ts₁:tacticSeq " } " " { " ts₂:tacticSeq " } " : tactic => do
assertEqualTactics (evalTactic ts₁) (evalTactic ts₂)
example : True := by
assert_equal_tactics { trivial } { trivial }
trivial
example : True := by
assert_equal_tactics { open Classical in trivial } { trivial }
trivial
/--
error: Tactics produced different tactic states.
Tactic 1:
case zero
m : Nat
⊢ True
case succ
m n✝ : Nat
⊢ True
Tactic 2:
case zero
n : Nat
⊢ True
case succ
n n✝ : Nat
⊢ True
-/
#guard_msgs in
example (n m : Nat) : True := by
assert_equal_tactics { cases n } { cases m }
trivial
example : 0 < 3 := by
apply Nat.lt_trans
assert_equal_tactics { exact Nat.lt_succ_self 0 } { exact Nat.lt_succ_self 0 }
(case m => exact 1); all_goals decide
example : 0 < 3 := by
apply Nat.lt_trans
assert_equal_tactics { apply Nat.lt_trans } { apply Nat.lt_trans }
(case m => exact 1); all_goals decide |
.lake/packages/aesop/AesopTest/ElabConfig.lean | import Aesop
set_option aesop.check.all true
/-- error: `noSuchOption` is not a field of structure `Aesop.Options` -/
#guard_msgs in
example : True := by
aesop (config := { noSuchOption := true })
/-- error: `noSuchOption` is not a field of structure `Lean.Meta.Simp.ConfigCtx` -/
#guard_msgs in
example : True := by
aesop (simp_config := { noSuchOption := true }) |
.lake/packages/aesop/AesopTest/IntrosAllTransparency.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
@[irreducible] def T := False → 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 (config := { introsTransparency? := some .all }) |
.lake/packages/aesop/AesopTest/PostponeSafeRules.lean | import Aesop
set_option aesop.check.all true
-- This is a test case for postponed safe rules. When a safe rule assigns mvars,
-- it is not applied but instead postponed. Then we later try it again as an
-- unsafe rule.
--
-- It's hard to test this feature completely because we can't really tell from
-- the outside when a rule has been applied. But we can at least look at the
-- traces of the following test cases.
axiom T : Nat → Prop
@[aesop safe]
axiom t : T 0
example : ∃ (i : Nat), T i := by
aesop
axiom U : Nat → Prop
@[aesop safe 0]
axiom u₁ : U 0
@[aesop safe 1]
axiom u₂ : U 1
example : ∃ i, U i ∧ i = 1 := by
aesop |
.lake/packages/aesop/AesopTest/NoImportClash.lean | /-
This test case ensures that Aesop does not define anything that already exists
in our dependencies.
-/
import Aesop
import Lean
import Batteries |
.lake/packages/aesop/AesopTest/13_2.lean | import Aesop
set_option aesop.check.all true
set_option aesop.smallErrorMessages true
inductive Perm : (xs ys : List α) → Type where
| prep {xs} x : Perm (x :: xs) (x :: xs)
inductive Proof : (Γ Δ : List Φ) → Prop where
| basic (Γ Δ n) : Proof (n :: Γ) (n :: Δ)
| per_l (Γ Γ' Δ) : Proof Γ Δ → Perm Γ' Γ → Proof Γ' Δ
/--
error: tactic 'aesop' failed, maximum number of rule applications (50) reached. Set the 'maxRuleApplications' option to increase the limit.
-/
#guard_msgs in
theorem weaken (Γ Δ : List Φ) (prf : Proof Γ Δ) (δ : Φ) : Proof Γ (δ :: Δ) := by
induction prf
case basic Γ Δ n =>
aesop (add unsafe [constructors Proof, constructors Perm])
(config := { maxRuleApplications := 50, terminal := true })
case per_l Γ Γ' Δ _ perm ih =>
apply Proof.per_l Γ Γ' (δ :: Δ) ih perm |
.lake/packages/aesop/Aesop/Tracing.lean | module
public import Lean.Meta.Tactic.Simp.SimpTheorems
import Aesop.Util.Basic
public meta import Lean.Parser.Do
public section
open Lean Lean.Meta
namespace Aesop
structure TraceOption where
traceClass : Name
option : Lean.Option Bool
deriving Inhabited
def registerTraceOption (traceName : Name) (descr : String) :
IO TraceOption := do
let option ← Option.register (`trace.aesop ++ traceName) {
defValue := false
group := "trace"
descr
}
return { traceClass := `aesop ++ traceName, option }
namespace TraceOption
def isEnabled [Monad m] [MonadOptions m] (opt : TraceOption) : m Bool :=
return opt.option.get (← getOptions)
def withEnabled [MonadWithOptions m] (opt : TraceOption) (k : m α) : m α :=
withOptions (λ opts => opt.option.set opts true) k
initialize steps : TraceOption ←
registerTraceOption .anonymous
"(aesop) Print actions taken by Aesop during the proof search."
initialize ruleSet : TraceOption ←
registerTraceOption `ruleSet
"(aesop) Print the rule set before starting the search."
initialize proof : TraceOption ←
registerTraceOption `proof
"(aesop) If the search is successful, print the produced proof term."
initialize tree : TraceOption ←
registerTraceOption `tree
"(aesop) Once the search has concluded (successfully or unsuccessfully), print the final search tree."
initialize extraction : TraceOption ←
registerTraceOption `extraction
"(aesop) Print a trace of the proof extraction procedure."
initialize stats : TraceOption ←
registerTraceOption `stats
"(aesop) If the search is successful, print some statistics."
initialize debug : TraceOption ←
registerTraceOption `debug
"(aesop) Print various debugging information."
initialize script : TraceOption ←
registerTraceOption `script
"(aesop) Print a trace of script generation."
initialize forward : TraceOption ←
registerTraceOption `forward
"(aesop) Trace forward reasoning."
initialize forwardDebug : TraceOption ←
registerTraceOption `forward.debug
"(aesop) Trace more information about forward reasoning. Mostly intended for performance analysis."
initialize rpinf : TraceOption ←
registerTraceOption `rpinf
"(aesop) Trace RPINF calculations."
end TraceOption
section
open Lean.Elab Lean.Elab.Term
private meta def isFullyQualifiedGlobalName (n : Name) : MacroM Bool :=
return (← Macro.resolveGlobalName n).any (·.fst == n)
meta def resolveTraceOption (stx : Ident) : MacroM Name :=
withRef stx do
let n := stx.getId
let fqn := ``TraceOption ++ n
if ← isFullyQualifiedGlobalName fqn then
return fqn
else
return n
macro "aesop_trace![" opt:ident "] " msg:(interpolatedStr(term) <|> term) :
doElem => do
let opt ← mkIdent <$> resolveTraceOption opt
let msg := msg.raw
let msg ← if msg.getKind == interpolatedStrKind then
`(m! $(⟨msg⟩):interpolatedStr)
else
`(toMessageData ($(⟨msg⟩)))
`(doElem| Lean.addTrace (Aesop.TraceOption.traceClass $opt) $msg)
macro "aesop_trace[" opt:ident "] "
msg:(interpolatedStr(term) <|> Parser.Term.do <|> term) : doElem => do
let msg := msg.raw
let opt ← mkIdent <$> resolveTraceOption opt
match msg with
| `(do $action) =>
`(doElem| do
if ← Aesop.TraceOption.isEnabled $opt then
$action)
| _ =>
`(doElem| do
if ← Aesop.TraceOption.isEnabled $opt then
aesop_trace![$opt] $(⟨msg⟩))
end
def ruleSuccessEmoji := checkEmoji
def ruleFailureEmoji := crossEmoji
def ruleProvedEmoji := "🏁"
def ruleErrorEmoji := bombEmoji
def rulePostponedEmoji := "⏳️"
def ruleSkippedEmoji := "⏩️"
def nodeUnknownEmoji := "❓️"
def nodeProvedEmoji := ruleProvedEmoji
def nodeUnprovableEmoji := ruleFailureEmoji
def newNodeEmoji := "🆕"
def exceptRuleResultToEmoji (toEmoji : α → String) : Except ε α → String
| .error _ => ruleFailureEmoji
| .ok r => toEmoji r
section
variable [Monad m] [MonadTrace m] [MonadLiftT BaseIO m] [MonadLiftT IO m]
[MonadRef m] [AddMessageContext m] [MonadOptions m] [MonadAlwaysExcept ε m]
@[inline, always_inline]
def withAesopTraceNode (opt : TraceOption)
(msg : Except ε α → m MessageData) (k : m α) (collapsed := true) : m α :=
withTraceNode opt.traceClass msg k collapsed
@[inline, always_inline]
def withAesopTraceNodeBefore [ExceptToEmoji ε α] (opt : TraceOption)
(msg : m MessageData) (k : m α) (collapsed := true) : m α :=
withTraceNodeBefore opt.traceClass msg k collapsed
@[inline, always_inline]
def withConstAesopTraceNode (opt : TraceOption) (msg : m MessageData) (k : m α)
(collapsed := true) : m α :=
withAesopTraceNode opt (λ _ => msg) k collapsed
end
def traceSimpTheoremTreeContents (t : SimpTheoremTree) (opt : TraceOption) :
CoreM Unit := do
if ! (← opt.isEnabled) then
return
for e in t.values.map (toString ·.origin.key) |>.qsortOrd do
aesop_trace![opt] e
def traceSimpTheorems (s : SimpTheorems) (opt : TraceOption) : CoreM Unit := do
if ! (← opt.isEnabled) then
return
withConstAesopTraceNode opt (return "Erased entries") do
aesop_trace![opt] "(Note: even if these entries appear in the sections below, they will not be used by simp.)"
for e in PersistentHashSet.toArray s.erased |>.map (toString ·.key) |>.qsortOrd do
aesop_trace![opt] e
withConstAesopTraceNode opt (return "Pre lemmas") do
traceSimpTheoremTreeContents s.pre opt
withConstAesopTraceNode opt (return "Post lemmas") do
traceSimpTheoremTreeContents s.post opt
withConstAesopTraceNode opt (return "Constants to unfold") do
for e in PersistentHashSet.toArray s.toUnfold |>.map toString |>.qsortOrd do
aesop_trace![opt] e
end Aesop |
.lake/packages/aesop/Aesop/Percent.lean | module
public section
namespace Aesop
open Lean
open Std
/-
Invariant: between 0 and 1.0
-/
structure Percent where
toFloat : Float
deriving Inhabited
namespace Percent
protected def ofFloat (f : Float) : Option Percent :=
if 0 <= f && f <= 1.0 then some ⟨f⟩ else none
instance : Mul Percent where
mul p q := ⟨p.toFloat * q.toFloat⟩
@[inline]
def δ : Percent :=
⟨0.00001⟩
instance : BEq Percent where
beq | ⟨p⟩, ⟨q⟩ => if p > q then p - q < δ.toFloat else q - p < δ.toFloat
instance : Ord Percent where
compare p q :=
if p == q then Ordering.eq
else if p.toFloat < q.toFloat then Ordering.lt
else Ordering.gt
-- NOTE: This is not the same as
--
-- p < q := p.toFloat < q.toFloat
--
-- That definition would not agree with the Ord instance.
instance : LT Percent :=
ltOfOrd
instance : LE Percent :=
leOfOrd
instance : ToString Percent where
toString p := toString p.toFloat
instance : HPow Percent Nat Percent where
hPow | ⟨p⟩, n => ⟨p ^ n.toFloat⟩
def hundred : Percent :=
⟨1⟩
def fifty : Percent :=
⟨0.5⟩
def toHumanString (p : Percent) : String :=
let str := toString (p.toFloat * 100)
match str.splitToList λ c => c == '.' with
| [beforePoint] => beforePoint ++ "%"
| [beforePoint, afterPoint] =>
beforePoint ++ "." ++ afterPoint.take 4 ++ "%"
| _ => unreachable!
protected def ofNat (n : Nat) : Option Percent :=
Percent.ofFloat $ n.toFloat / 100
end Aesop.Percent |
.lake/packages/aesop/Aesop/Check.lean | module
public import Lean.Data.Options
public section
open Lean
namespace Aesop
initialize Check.all : Lean.Option Bool ←
Option.register `aesop.check.all
{ defValue := false
descr := "(aesop) Enable all runtime checks. Individual checks can still be disabled."
group := "tactic" }
structure Check where
toOption : Lean.Option Bool
namespace Check
def get (opts : Options) (opt : Check) : Bool :=
if let some val := opt.toOption.get? opts then
val
else
Check.all.get opts
def isEnabled [Monad m] [MonadOptions m] (opt : Check) : m Bool :=
return opt.get (← getOptions)
def name (opt : Check) : Name :=
opt.toOption.name
end Check
-- Inspired by `Lean.Data.Options`.
local macro "register_aesop_check_option" optName:ident descr:str : command =>
`(initialize option : Lean.Option Bool ←
Lean.Option.register $(quote $ `aesop.check ++ optName.getId)
{ defValue := false, descr := $descr, group := "tactic" }
def $(mkIdent $ `Check ++ optName.getId) : Aesop.Check := ⟨option⟩)
register_aesop_check_option proofReconstruction
"(aesop) Typecheck partial proof terms during proof reconstruction."
register_aesop_check_option tree
"(aesop) Check search tree invariants after every iteration of the search loop. Quite expensive."
register_aesop_check_option rules
"(aesop) Check that information reported by rules is correct."
register_aesop_check_option script
"(aesop) Check that the tactic script generated by Aesop proves the goal. When this check is active, Aesop generates a tactic script even if the user did not request one."
register_aesop_check_option script.steps
"(aesop) Check each step of the tactic script generated by Aesop. When this check is active, Aesop generates a tactic script even if the user did not request one."
end Aesop |
.lake/packages/aesop/Aesop/Saturate.lean | module
public import Batteries.Data.BinomialHeap.Basic
public import Aesop.RuleSet
public import Aesop.Script.ScriptM
import Aesop.RPINF
import Aesop.RuleTac
import Aesop.Script.Check
import Aesop.Forward.State.ApplyGoalDiff
import Aesop.Forward.State.Initial
import Aesop.Search.Expansion.Basic
public section
open Lean Lean.Meta
open Batteries (BinomialHeap)
namespace Aesop
def isForwardOrDestructRuleName (n : RuleName) : Bool :=
n.builder == .forward || n.builder == .destruct
structure SaturateM.Context where
options : Aesop.Options'
deriving Inhabited
structure SaturateM.State where
rulePatternCache : RulePatternCache := {}
rpinfCache : RPINFCache := ∅
deriving Inhabited
abbrev SaturateM :=
ReaderT SaturateM.Context $ StateRefT SaturateM.State $ ScriptT BaseM
namespace SaturateM
def run (options : Aesop.Options') (x : SaturateM α) :
MetaM (α × Array Script.LazyStep) :=
(·.fst) <$> (ReaderT.run x { options } |>.run' {} |>.run.run)
end SaturateM
def getSingleGoal [Monad m] [MonadError m] (o : RuleTacOutput) :
m (GoalDiff × Meta.SavedState × Option (Array Script.LazyStep)) := do
let #[app] := o.applications
| throwError "rule produced more than one rule application"
let #[goal] := app.goals
| throwError "rule did not produce exactly one subgoal"
return (goal.diff, app.postState, app.scriptSteps?)
initialize
registerTraceClass `saturate
partial def saturateCore (rs : LocalRuleSet) (goal : MVarId) : SaturateM MVarId :=
withExceptionPrefix "saturate: internal error: " do
goal.checkNotAssigned `saturate
-- We use the forward state only to track the hypotheses present in the goal.
let (fs, _) ← rs.mkInitialForwardState goal
go goal fs
where
go (goal : MVarId) (fs : ForwardState) : SaturateM MVarId :=
withIncRecDepth do
trace[saturate] "goal {goal.name}:{indentD goal}"
let mvars := UnorderedArraySet.ofHashSet $ ← goal.getMVarDependencies
let preState ← show MetaM _ from saveState
if let some diff ← tryNormRules goal mvars preState fs.hypTypes then
let (fs, _) ← fs.applyGoalDiff rs diff
return ← go diff.newGoal fs
else if let some diff ← trySafeRules goal mvars preState fs.hypTypes then
let (fs, _) ← fs.applyGoalDiff rs diff
return ← go diff.newGoal fs
else
clearForwardImplDetailHyps goal
tryNormRules (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(preState : Meta.SavedState) (hypTypes : PHashSet RPINF) :
SaturateM (Option GoalDiff) :=
withTraceNode `saturate (λ res => return m!"{exceptOptionEmoji res} trying normalisation rules") do
let matchResults ←
withTraceNode `saturate (λ res => return m!"{exceptEmoji res} selecting normalisation rules") do
rs.applicableNormalizationRulesWith ∅ goal
(include? := (isForwardOrDestructRuleName ·.name))
runFirstRule goal mvars preState matchResults hypTypes
trySafeRules (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(preState : Meta.SavedState) (hypTypes : PHashSet RPINF) :
SaturateM (Option GoalDiff) :=
withTraceNode `saturate (λ res => return m!"{exceptOptionEmoji res} trying safe rules") do
let matchResults ←
withTraceNode `saturate (λ res => return m!"{exceptEmoji res} selecting safe rules") do
rs.applicableSafeRulesWith ∅ goal
(include? := (isForwardOrDestructRuleName ·.name))
runFirstRule goal mvars preState matchResults hypTypes
runRule {α} (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(preState : Meta.SavedState) (matchResult : IndexMatchResult (Rule α))
(hypTypes : PHashSet RPINF) :
SaturateM (Option (GoalDiff × Option (Array Script.LazyStep))) := do
withTraceNode `saturate (λ res => return m!"{exceptOptionEmoji res} running rule {matchResult.rule.name}") do
let input := {
indexMatchLocations := matchResult.locations
patternSubsts? := matchResult.patternSubsts?
options := (← read).options
hypTypes, goal, mvars
}
let tacResult ←
runRuleTac matchResult.rule.tac.run matchResult.rule.name preState input
match tacResult with
| .error exc =>
trace[saturate] exc.toMessageData
return none
| .ok output =>
let (diff, postState, scriptSteps?) ← getSingleGoal output
postState.restore
return (diff, scriptSteps?)
runFirstRule {α} (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(preState : Meta.SavedState)
(matchResults : Array (IndexMatchResult (Rule α)))
(hypTypes : PHashSet RPINF) : SaturateM (Option GoalDiff) := do
for matchResult in matchResults do
let ruleResult? ← runRule goal mvars preState matchResult hypTypes
if let some (diff, scriptSteps?) := ruleResult? then
if (← read).options.generateScript then
let some scriptSteps := scriptSteps?
| throwError "rule '{matchResult.rule.name}' does not support script generation (saturate?)"
recordScriptSteps scriptSteps
return some diff
return none
namespace Stateful
abbrev Queue := BinomialHeap ForwardRuleMatch ForwardRuleMatch.le
partial def saturateCore (rs : LocalRuleSet) (goal : MVarId)
(options : Options') : SaturateM MVarId :=
withExceptionPrefix "saturate: internal error: " do
goal.withContext do
goal.checkNotAssigned `saturate
let (fs, ruleMatches) ← rs.mkInitialForwardState goal
let queue := ruleMatches.foldl (init := ∅) λ queue m => queue.insert m
go ∅ fs queue ∅ goal
where
go (hypDepths : Std.HashMap FVarId Nat) (fs : ForwardState) (queue : Queue)
(erasedHyps : Std.HashSet FVarId) (goal : MVarId) : SaturateM MVarId := do
withIncRecDepth do
goal.withContext do
if let some (m, queue) := queue.deleteMin then
if m.rule.name.phase == .unsafe || m.anyHyp erasedHyps.contains then
return ← go hypDepths fs queue erasedHyps goal
trace[saturate] "goal:{indentD goal}"
let oldGoal := goal
let some (goal, hyp, removedHyps) ←
m.apply goal (skip? := some (fs.hypTypes.contains ·))
| return ← go hypDepths fs queue erasedHyps goal
goal.withContext do
-- TODO use applyGoalDiff
let fs ← removedHyps.foldlM (init := fs) λ fs h => do
let type ← oldGoal.withContext do rpinf (← h.getType)
return fs.eraseHyp h type
let type ← hyp.getType
let erasedHyps := erasedHyps.insertMany removedHyps
let mut depth := 0
let mut hypDepths := hypDepths
let maxDepth? := options.forwardMaxDepth?
if maxDepth?.isSome then
depth := 1 + m.foldHyps (init := 0) λ depth h =>
max depth (hypDepths[h]?.getD 0)
hypDepths := hypDepths.insert hyp depth
trace[saturate] "added hyp (depth {depth}) {Expr.fvar hyp} : {type}"
if maxDepth?.isSome && depth ≥ maxDepth?.get! then
go hypDepths fs queue erasedHyps goal
else
let rules ← rs.applicableForwardRules type
let patInsts ←
rs.forwardRulePatternSubstsInLocalDecl (← hyp.getDecl)
let (fs, ruleMatches) ←
fs.addHypWithPatSubsts goal hyp rules patInsts
let queue :=
ruleMatches.foldl (init := queue) λ queue m => queue.insert m
go hypDepths fs queue erasedHyps goal
else
return goal
end Stateful
def saturateMain (rs : LocalRuleSet) (goal : MVarId) (options : Aesop.Options') :
MetaM (MVarId × Array Script.LazyStep) := do
let doSaturate :=
if aesop.dev.statefulForward.get (← getOptions) then
Stateful.saturateCore rs goal options
else
saturateCore rs goal
doSaturate.run options
def saturate (rs : LocalRuleSet) (goal : MVarId) (options : Aesop.Options') :
MetaM MVarId := do
if ! options.generateScript then
(·.fst) <$> saturateMain rs goal options
else
let preState ← saveState
let tacticState ← Script.TacticState.mkInitial goal
let preGoal := goal
let (goal, steps) ← saturateMain rs goal options
let options ← options.toOptions'
if options.generateScript then
let uscript : Script.UScript ← steps.mapM (·.toStep)
let tacticSeq ← `(tacticSeq| $(← uscript.render tacticState):tactic*)
checkRenderedScriptIfEnabled tacticSeq preState preGoal
(expectCompleteProof := false)
if options.traceScript then
addTryThisTacticSeqSuggestion (← getRef) tacticSeq
return goal
end Aesop |
.lake/packages/aesop/Aesop/Builder.lean | import Aesop.Builder.Apply
import Aesop.Builder.Basic
import Aesop.Builder.Cases
import Aesop.Builder.Constructors
import Aesop.Builder.Default
import Aesop.Builder.Forward
import Aesop.Builder.NormSimp
import Aesop.Builder.Tactic
import Aesop.Builder.Unfold |
.lake/packages/aesop/Aesop/Exception.lean | module
import Lean.Exception
public section
open Lean
namespace Aesop
scoped macro "declare_aesop_exception"
excName:ident idName:ident testName:ident : command =>
`(initialize $idName : InternalExceptionId ←
Lean.registerInternalExceptionId $(quote $ `Aesop ++ excName.getId)
def $excName : Exception :=
.internal $idName
def $testName : Exception → Bool
| .internal id _ => id == $idName
| _ => false)
end Aesop |
.lake/packages/aesop/Aesop/Index.lean | module
public import Aesop.Index.Basic
public import Aesop.Index.RulePattern
public import Batteries.Lean.Meta.InstantiateMVars
public import Aesop.Index.DiscrTreeConfig
public import Aesop.Rule.Basic
import Batteries.Lean.PersistentHashSet
import Batteries.Lean.Meta.DiscrTree
public section
open Lean
open Lean.Meta
namespace Aesop
structure Index (α : Type) where
byTarget : DiscrTree (Rule α)
byHyp : DiscrTree (Rule α)
unindexed : PHashSet (Rule α)
deriving Inhabited
namespace Index
variable [BEq α] [Ord α] [Hashable α]
def trace [ToString (Rule α)] (ri : Index α) (traceOpt : TraceOption) :
CoreM Unit := do
if ! (← traceOpt.isEnabled) then
return
withConstAesopTraceNode traceOpt (return "Indexed by target") do
traceArray ri.byTarget.values
withConstAesopTraceNode traceOpt (return "Indexed by hypotheses") do
traceArray ri.byHyp.values
withConstAesopTraceNode traceOpt (return "Unindexed") do
traceArray $ PersistentHashSet.toArray ri.unindexed
where
traceArray (as : Array (Rule α)) : CoreM Unit :=
as.map toString |>.qsortOrd.forM λ r => do aesop_trace![traceOpt] r
instance : EmptyCollection (Index α) where
emptyCollection := {
byTarget := {}
byHyp := {}
unindexed := {}
}
def merge (ri₁ ri₂ : Index α) : Index α where
byTarget := ri₁.byTarget.mergePreservingDuplicates ri₂.byTarget
byHyp := ri₁.byHyp.mergePreservingDuplicates ri₂.byHyp
unindexed := ri₁.unindexed.merge ri₂.unindexed
@[specialize]
partial def add (r : Rule α) (imode : IndexingMode) (ri : Index α) :
Index α :=
match imode with
| IndexingMode.unindexed =>
{ ri with unindexed := ri.unindexed.insert r }
| IndexingMode.target keys =>
{ ri with byTarget := ri.byTarget.insertCore keys r }
| IndexingMode.hyps keys =>
{ ri with byHyp := ri.byHyp.insertCore keys r }
| IndexingMode.or imodes =>
imodes.foldl (init := ri) λ ri imode =>
ri.add r imode
def unindex (ri : Index α) (p : Rule α → Bool) : Index α :=
let (byTarget, unindexed) := filterDiscrTree' ri.unindexed ri.byTarget
let (byHyp, unindexed) := filterDiscrTree' unindexed ri.byHyp
{ byTarget, byHyp, unindexed }
where
@[inline, always_inline]
filterDiscrTree' (unindexed : PHashSet (Rule α)) (t : DiscrTree (Rule α)) :
DiscrTree (Rule α) × PHashSet (Rule α) :=
filterDiscrTree (not ∘ p) (λ unindexed v => unindexed.insert v) unindexed
t
def foldM [Monad m] (ri : Index α) (f : σ → Rule α → m σ) (init : σ) : m σ :=
match ri with
| { byHyp, byTarget, unindexed} => do
let mut s := init
s ← byHyp.foldValuesM (init := s) f
s ← byTarget.foldValuesM (init := s) f
unindexed.foldM (init := s) f
@[inline]
def fold (ri : Index α) (f : σ → Rule α → σ) (init : σ) : σ :=
Id.run $ ri.foldM (init := init) f
-- May return duplicate `IndexMatchLocation`s.
@[inline]
private def applicableByTargetRules (ri : Index α) (goal : MVarId)
(include? : Rule α → Bool) :
MetaM (Array (Rule α × Array IndexMatchLocation)) :=
goal.withContext do
let rules ← getUnify ri.byTarget (← goal.getType)
let mut rs := Array.mkEmpty rules.size
-- Assumption: include? is true for most rules.
for r in rules do
if include? r then
rs := rs.push (r, #[.target])
return rs
-- May return duplicate `IndexMatchLocation`s.
@[inline]
private def applicableByHypRules (ri : Index α) (goal : MVarId)
(include? : Rule α → Bool) :
MetaM (Array (Rule α × Array IndexMatchLocation)) :=
goal.withContext do
let mut rs := #[]
for localDecl in ← getLCtx do
if localDecl.isImplementationDetail then
continue
let rules ← getUnify ri.byHyp localDecl.type
for r in rules do
if include? r then
rs := rs.push (r, #[.hyp localDecl])
return rs
-- May return duplicate `IndexMatchLocation`s.
@[inline]
private def applicableUnindexedRules (ri : Index α) (include? : Rule α → Bool) :
Array (Rule α × Array IndexMatchLocation) :=
ri.unindexed.fold (init := #[]) λ acc r =>
if include? r then
acc.push (r, #[.none])
else
acc
-- Returns the rules in the order given by the `Ord α` instance.
@[specialize]
def applicableRules (ri : Index α) (goal : MVarId)
(patSubstMap : RulePatternSubstMap)
(additionalRules : Array (IndexMatchResult (Rule α)))
(include? : Rule α → Bool) :
MetaM (Array (IndexMatchResult (Rule α))) := do
withConstAesopTraceNode .debug (return "rule selection") do
goal.instantiateMVars
let result ← addRules additionalRules #[
(← applicableByTargetRules ri goal include?),
(← applicableByHypRules ri goal include?),
(applicableUnindexedRules ri include?)
]
let result := result.qsort λ x y => x.rule.compareByPriorityThenName y.rule |>.isLT
aesop_trace[debug] "selected rules:{.joinSep (result.map (m!"{·.rule.name}") |>.toList) "\n"}"
return result
where
addRules (acc : Array (IndexMatchResult (Rule α)))
(ruless : Array (Array (Rule α × Array IndexMatchLocation))) :
MetaM (Array (IndexMatchResult (Rule α))) := do
let mut locMap : Std.HashMap (Rule α) (Array IndexMatchLocation) := ∅
for rules in ruless do
for (rule, locs) in rules do
if let some locs' := locMap[rule]? then
locMap := locMap.insert rule (locs' ++ locs)
else
locMap := locMap.insert rule locs
let mut result := acc
for (rule, locations) in locMap do
if rule.pattern?.isSome then
if let some patternSubsts := patSubstMap[rule.name]? then
result := result.push {
locations := locations.qsortOrd |>.dedupSorted
patternSubsts? := some <| patternSubsts.toArray
rule
}
else
result := result.push {
locations := locations.qsortOrd |>.dedupSorted
patternSubsts? := none
rule
}
return result
end Aesop.Index |
.lake/packages/aesop/Aesop/BuiltinRules.lean | -- The Aesop.BuiltinRules.* imports are needed to ensure that the tactics from
-- these files are registered.
module
public import Aesop.BuiltinRules.Assumption
public import Aesop.BuiltinRules.ApplyHyps
public import Aesop.BuiltinRules.DestructProducts
public import Aesop.BuiltinRules.Ext
public import Aesop.BuiltinRules.Intros
public import Aesop.BuiltinRules.Rfl
public import Aesop.BuiltinRules.Split
public import Aesop.BuiltinRules.Subst
import Aesop.Frontend.Attribute
public section
namespace Aesop.BuiltinRules
attribute [aesop (rule_sets := [builtin]) safe 0 apply] PUnit.unit
-- Hypotheses of product type are split by a separate builtin rule because the
-- `cases` builder currently cannot be used for norm rules.
attribute [aesop (rule_sets := [builtin]) safe 101 constructors]
And Prod PProd MProd
attribute [aesop (rule_sets := [builtin]) unsafe 30% constructors]
Exists Subtype Sigma PSigma
-- Sums are split and introduced lazily.
attribute [aesop (rule_sets := [builtin]) [safe 100 cases, 50% constructors]]
Or Sum PSum
-- A goal ⊢ P ↔ Q is split into ⊢ P → Q and ⊢ Q → P. Hypotheses of type `P ↔ Q`
-- are treated as equations `P = Q` by the simplifier and by our builtin subst
-- rule.
attribute [aesop (rule_sets := [builtin]) safe 100 constructors] Iff
-- A negated goal Γ ⊢ ¬ P is transformed into Γ, P ⊢ ⊥. A goal with a
-- negated hypothesis Γ, h : ¬ P ⊢ Q is transformed into Γ[P := ⊥] ⊢ Q[P := ⊥]
-- by the simplifier. Quantified negated hypotheses h : ∀ x : T, ¬ P x are also
-- supported by the simplifier if the premises x can be discharged.
@[aesop (rule_sets := [builtin]) safe 0]
theorem not_intro (h : P → False) : ¬ P := h
@[aesop (rule_sets := [builtin]) norm destruct]
theorem empty_false (h : Empty) : False := nomatch h
@[aesop (rule_sets := [builtin]) norm destruct]
theorem pEmpty_false (h : PEmpty) : False := nomatch h
attribute [aesop (rule_sets := [builtin]) norm constructors] ULift
attribute [aesop (rule_sets := [builtin]) norm 0 destruct] ULift.down
@[aesop (rule_sets := [builtin]) norm simp]
theorem heq_iff_eq (x y : α) : x ≍ y ↔ x = y :=
⟨eq_of_heq, heq_of_eq⟩
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BaseM.lean | module
public import Aesop.Stats.Basic
public import Aesop.RulePattern.Cache
public section
set_option linter.missingDocs true
open Lean
namespace Aesop
/-- State of the `BaseM` monad. -/
structure BaseM.State where
/-- The rule pattern cache. -/
rulePatternCache : RulePatternCache
/-- The RPINF cache. -/
rpinfCache : RPINFCache
/-- Stats collected during an Aesop call. -/
stats : Stats
deriving Inhabited
instance : EmptyCollection BaseM.State :=
⟨by refine' { .. } <;> exact ∅⟩
/-- Aesop's base monad. Contains no interesting data, only various caches and
stats. -/
abbrev BaseM := StateRefT BaseM.State MetaM
namespace BaseM
/-- Run a `BaseM` action. -/
protected def run (x : BaseM α) (stats : Stats := ∅) : MetaM (α × Stats) := do
let (a, s) ← StateRefT'.run x { stats, rulePatternCache := ∅, rpinfCache := ∅ }
return (a, s.stats)
instance : MonadHashMapCacheAdapter Expr RulePatternCache.Entry BaseM where
getCache := return (← get).rulePatternCache.map
modifyCache f := modify λ s =>
{ s with rulePatternCache.map := f s.rulePatternCache.map }
instance : MonadHashMapCacheAdapter Expr RPINFRaw BaseM where
getCache := return (← get).rpinfCache.map
modifyCache f := modify λ s => { s with rpinfCache.map := f s.rpinfCache.map }
instance : MonadStats BaseM where
modifyGetStats f := modifyGet λ s =>
let (a, stats) := f s.stats
(a, { s with stats })
getStats := return (← get).stats
modifyStats f := modify λ s => { s with stats := f s.stats }
instance : MonadBacktrack Meta.SavedState BaseM where
saveState := Meta.saveState
restoreState := (·.restore)
end Aesop.BaseM |
.lake/packages/aesop/Aesop/RulePattern.lean | module
public import Aesop.BaseM
import Aesop.RPINF
import Aesop.Index.DiscrTreeConfig
public section
open Lean Lean.Meta
namespace Aesop
/--
A rule pattern. For a rule of type `∀ (x₀ : T₀) ... (xₙ : Tₙ), U`, a valid rule
pattern is an expression `p` such that `x₀ : T₁, ..., xₙ : Tₙ ⊢ p : P`. Let
`y₀, ..., yₖ` be those variables `xᵢ` on which `p` depends. When `p` matches an
expression `e`, this means that `e` is defeq to `p` (where each `yᵢ` is replaced
with a metavariable) and we obtain a substitution
{y₀ ↦ t₀ : T₀, y₁ ↦ t₁ : T₁[x₀ := t₀], ...}
Now suppose we want to match the above rule type against a type `V` (where `V`
is the target for an `apply`-like rule and a hypothesis type for a
`forward`-like rule). To that end, we take `U` and replace each `xᵢ` where
`xᵢ = yⱼ` with `tⱼ` and each `xᵢ` with `xᵢ ≠ yⱼ ∀ j` with a metavariable. The
resulting expression `U'` is then matched against `V`.
-/
structure RulePattern where
/--
An expression of the form `λ y₀ ... yₖ, p` representing the
pattern.
-/
pattern : AbstractMVarsResult
/--
A partial map from the index set `{0, ..., n-1}` into `{0, ..., k-1}`. If
`argMap[i] = j`, this indicates that when matching against the rule type, the
instantiation `tⱼ` of `yⱼ` should be substituted for `xᵢ`.
-/
argMap : Array (Option Nat)
/--
A partial map from the level metavariables occurring in the rule to the
pattern's level params.
-/
levelArgMap : Array (Option Nat)
/--
Discrimination tree keys for `p`.
-/
discrTreeKeys : Array DiscrTree.Key
deriving Inhabited
namespace RulePattern
def boundPremises (pat : RulePattern) : Array Nat := Id.run do
let mut result := Array.mkEmpty pat.argMap.size
for h : i in [:pat.argMap.size] do
if pat.argMap[i].isSome then
result := result.push i
return result
-- Largely copy-paste from openAbstractMVarsResult
def «open» (pat : RulePattern) :
MetaM (Array MVarId × Array LMVarId × Expr) := do
let a := pat.pattern
let us ← a.paramNames.mapM fun _ => mkFreshLevelMVar
let e := a.expr.instantiateLevelParamsArray a.paramNames us
let (mvars, _, e) ← lambdaMetaTelescope e (some a.numMVars)
return (mvars.map (·.mvarId!), us.map (·.mvarId!) , e)
def «match» (e : Expr) (pat : RulePattern) : BaseM (Option Substitution) :=
withNewMCtxDepth do
let (mvarIds, lmvarIds, p) ← pat.open
if ! (← isDefEq e p) then
return none
let mut subst := .empty pat.argMap.size pat.levelArgMap.size
for h : i in [:pat.argMap.size] do
if let some j := pat.argMap[i] then
let mvarId := mvarIds[j]!
let mvar := .mvar mvarId
let inst ← instantiateMVars mvar
if inst == mvar then
throwError "RulePattern.match: while matching pattern '{p}' against expression '{e}': expected metavariable ?{(← mvarId.getDecl).userName} ({mvarId.name}) to be assigned"
subst := subst.insert ⟨i⟩ (← rpinf inst)
for h : i in [:pat.levelArgMap.size] do
if let some j := pat.levelArgMap[i] then
let mvar := .mvar lmvarIds[j]!
let inst ← instantiateLevelMVars mvar
if inst != mvar then
subst := subst.insertLevel ⟨i⟩ inst
return some subst
open Lean.Elab Lean.Elab.Term in
def «elab» (stx : Term) (rule : Expr) : TermElabM RulePattern :=
withConstAesopTraceNode .debug (return m!"elaborating rule pattern") do
-- TODO withNewMCtxDepth produces an error, but I don't understand why
withLCtx {} {} $ withoutModifyingState do
aesop_trace[debug] "rule: {rule}"
aesop_trace[debug] "pattern: {stx}"
let lmvarIds := collectLevelMVars {} (← instantiateMVars rule) |>.result
aesop_trace[debug] "level metavariables in rule: {lmvarIds.map Level.mvar}"
forallTelescope (← inferType rule) λ fvars _ => do
let pat := (← elabPattern stx).consumeMData
let (pat, mvarIds) ← fvarsToMVars fvars pat
let discrTreeKeys ← mkDiscrTreePath pat
let (pat, mvarIdToPatternPos, lmvarIdToPatternPos) ← abstractMVars' pat
let argMap := mvarIds.map (mvarIdToPatternPos[·]?)
let levelArgMap := lmvarIds.map (lmvarIdToPatternPos[·]?)
aesop_trace[debug] "result: '{pat.expr}' with arg map{indentD $ toMessageData argMap}\nand level arg map{indentD $ toMessageData levelArgMap}"
return { pattern := pat, argMap, levelArgMap, discrTreeKeys }
where
fvarsToMVars (fvars : Array Expr) (e : Expr) :
MetaM (Expr × Array MVarId) := do
let e ← mkLambdaFVars fvars (← instantiateMVars e)
let (mvars, _, e) ← lambdaMetaTelescope e (maxMVars? := some fvars.size)
return (e, mvars.map (·.mvarId!))
-- Largely copy-pasta of `abstractMVars`.
abstractMVars' (e : Expr) :
MetaM (AbstractMVarsResult × Std.HashMap MVarId Nat × Std.HashMap LMVarId Nat) := do
let e ← instantiateMVars e
let (e, s) := AbstractMVars.abstractExprMVars e
{ mctx := (← getMCtx)
lctx := (← getLCtx)
ngen := (← getNGen)
abstractLevels := true }
setNGen s.ngen
setMCtx s.mctx
let e := s.lctx.mkLambda s.fvars e
let mut fvarIdToMVarId : Std.HashMap FVarId MVarId := ∅
for (mvarId, e) in s.emap do
if let .fvar fvarId := e then
fvarIdToMVarId := fvarIdToMVarId.insert fvarId mvarId
let mut mvarIdToPos := ∅
for h : i in [:s.fvars.size] do
mvarIdToPos := mvarIdToPos.insert fvarIdToMVarId[s.fvars[i].fvarId!]! i
let mut paramToLMVarId : Std.HashMap Name LMVarId := ∅
for (lmvarId, l) in s.lmap do
if let .param n := l then
paramToLMVarId := paramToLMVarId.insert n lmvarId
let mut lmvarIdToPos := ∅
for h : i in [:s.paramNames.size] do
lmvarIdToPos := lmvarIdToPos.insert paramToLMVarId[s.paramNames[i]]! i
let result :=
{ paramNames := s.paramNames, mvars := s.mvars, expr := e }
return (result, mvarIdToPos, lmvarIdToPos)
end Aesop.RulePattern |
.lake/packages/aesop/Aesop/Nanos.lean | module
public section
namespace Aesop
structure Nanos where
nanos : Nat
deriving Inhabited, BEq, Ord
namespace Nanos
instance : OfNat Nanos n where
ofNat := ⟨n⟩
instance : LT Nanos where
lt | ⟨n₁⟩, ⟨n₂⟩ => n₁ < n₂
instance : DecidableRel (α := Nanos) (· < ·) :=
λ ⟨n₁⟩ ⟨n₂⟩ => inferInstanceAs (Decidable (n₁ < n₂))
instance : LE Nanos where
le | ⟨n₁⟩, ⟨n₂⟩ => n₁ ≤ n₂
instance : DecidableRel (α := Nanos) (· ≤ ·) :=
λ ⟨n₁⟩ ⟨n₂⟩ => inferInstanceAs (Decidable (n₁ ≤ n₂))
instance : Add Nanos where
add n m := ⟨n.nanos + m.nanos⟩
instance : HDiv Nanos Nat Nanos where
hDiv n m := ⟨n.nanos / m⟩
def printAsMillis (n : Nanos) : String :=
let str := toString (n.nanos.toFloat / 1000000)
match str.splitToList λ c => c == '.' with
| [beforePoint] => beforePoint ++ "ms"
| [beforePoint, afterPoint] => beforePoint ++ "." ++ afterPoint.take 1 ++ "ms"
| _ => unreachable!
end Aesop.Nanos |
.lake/packages/aesop/Aesop/Tree.lean | module
public import Aesop.Tree.AddRapp
public import Aesop.Tree.Check
public import Aesop.Tree.Data
public import Aesop.Tree.ExtractProof
public import Aesop.Tree.ExtractScript
public import Aesop.Tree.Free
public import Aesop.Tree.RunMetaM
public import Aesop.Tree.State
public import Aesop.Tree.Tracing
public import Aesop.Tree.Traversal
public import Aesop.Tree.TreeM
public import Aesop.Tree.UnsafeQueue |
.lake/packages/aesop/Aesop/Rule.lean | module
public import Aesop.Rule.Basic
public section
namespace Aesop
open Lean
open Lean.Meta
/-! ### Normalisation Rules -/
structure NormRuleInfo where
penalty : Int
deriving Inhabited
instance : Ord NormRuleInfo where
compare i j := compare i.penalty j.penalty
instance : LT NormRuleInfo :=
ltOfOrd
instance : LE NormRuleInfo :=
leOfOrd
abbrev NormRule := Rule NormRuleInfo
instance : ToString NormRule where
toString r := s!"[{r.extra.penalty}] {r.name}"
def defaultNormPenalty : Int := 1
def defaultSimpRulePriority : Int := eval_prio default
/-! ### Safe and Almost Safe Rules -/
inductive Safety
| safe
| almostSafe
deriving Inhabited
namespace Safety
instance : ToString Safety where
toString
| safe => "safe"
| almostSafe => "almostSafe"
end Safety
structure SafeRuleInfo where
penalty : Int
safety : Safety
deriving Inhabited
instance : Ord SafeRuleInfo where
compare i j := compare i.penalty j.penalty
instance : LT SafeRuleInfo :=
ltOfOrd
instance : LE SafeRuleInfo :=
leOfOrd
abbrev SafeRule := Rule SafeRuleInfo
instance : ToString SafeRule where
toString r := s!"[{r.extra.penalty}/{r.extra.safety}] {r.name}"
def defaultSafePenalty : Int := 1
/-! ### Unsafe Rules -/
structure UnsafeRuleInfo where
successProbability : Percent
deriving Inhabited
instance : Ord UnsafeRuleInfo where
compare i j := compare j.successProbability i.successProbability
-- NOTE: Rule with greater success probabilities are considered smaller.
-- This is because we take 'small' to mean 'high priority'.
instance : LT UnsafeRuleInfo :=
ltOfOrd
instance : LE UnsafeRuleInfo :=
leOfOrd
abbrev UnsafeRule := Rule UnsafeRuleInfo
instance : ToString UnsafeRule where
toString r := s!"[{r.extra.successProbability.toHumanString}] {r.name}"
def defaultSuccessProbability : Percent := .fifty
/-! ### Regular Rules -/
inductive RegularRule
| safe (r : SafeRule)
| «unsafe» (r : UnsafeRule)
deriving Inhabited, BEq
namespace RegularRule
instance : ToFormat RegularRule where
format
| safe r => format r
| «unsafe» r => format r
def successProbability : RegularRule → Percent
| safe _ => Percent.hundred
| «unsafe» r => r.extra.successProbability
def isSafe : RegularRule → Bool
| safe _ => true
| «unsafe» _ => false
def isUnsafe : RegularRule → Bool
| safe _ => false
| «unsafe» _ => true
@[inline]
def withRule (f : ∀ {α}, Rule α → β) : RegularRule → β
| safe r => f r
| «unsafe» r => f r
def name (r : RegularRule) : RuleName :=
r.withRule (·.name)
def indexingMode (r : RegularRule) : IndexingMode :=
r.withRule (·.indexingMode)
def tac (r : RegularRule) : RuleTacDescr :=
r.withRule (·.tac)
end RegularRule
/-! ### Normalisation Simp Rules -/
/--
A global rule for the norm simplifier. Each `SimpEntry` represents a member
of the simp set, e.g. a declaration whose type is an equality or a smart
unfolding theorem for a declaration.
-/
structure NormSimpRule where
name : RuleName
entries : Array SimpEntry
deriving Inhabited
namespace NormSimpRule
instance : BEq NormSimpRule where
beq r s := r.name == s.name
instance : Hashable NormSimpRule where
hash r := hash r.name
end NormSimpRule
/--
A local rule for the norm simplifier.
-/
structure LocalNormSimpRule where
id : Name
simpTheorem : Term
deriving Inhabited
namespace LocalNormSimpRule
instance : BEq LocalNormSimpRule where
beq r₁ r₂ := r₁.id == r₂.id
instance : Hashable LocalNormSimpRule where
hash r := hash r.id
def name (r : LocalNormSimpRule) : RuleName :=
{ name := r.id, scope := .local, builder := .simp, phase := .norm }
end LocalNormSimpRule
structure UnfoldRule where
decl : Name
unfoldThm? : Option Name
deriving Inhabited
namespace UnfoldRule
instance : BEq UnfoldRule where
beq r s := r.decl == s.decl
instance : Hashable UnfoldRule where
hash r := hash r.decl
def name (r : UnfoldRule) : RuleName :=
{ name := r.decl, builder := .unfold, phase := .norm, scope := .global }
end Aesop.UnfoldRule |
.lake/packages/aesop/Aesop/RuleSet.lean | module
public import Aesop.Index
public import Aesop.Index.Forward
public import Aesop.RuleSet.Filter
public import Aesop.RuleSet.Member
public import Aesop.Tree.Data.ForwardRuleMatches
public import Lean.Meta.Tactic.Simp.Types
import Batteries.Lean.PersistentHashMap
import Batteries.Lean.PersistentHashSet
import Lean.Meta.Tactic.Simp.Attr
public section
open Lean Lean.Meta
namespace Aesop
section Types
set_option linter.missingDocs true
/--
The Aesop-specific parts of an Aesop rule set. A `BaseRuleSet` stores global
Aesop rules, e.g. safe and unsafe rules. It does not store simp theorems for
the builtin norm simp rule; these are instead stored in a simp extension.
-/
structure BaseRuleSet where
/--
Normalisation rules registered in this rule set.
-/
normRules : Index NormRuleInfo
/--
Unsafe rules registered in this rule set.
-/
unsafeRules : Index UnsafeRuleInfo
/--
Safe rules registered in this rule set.
-/
safeRules : Index SafeRuleInfo
/--
Rules for the builtin unfold rule. A pair `(decl, unfoldThm?)` in this map
represents a declaration `decl` which should be unfolded. `unfoldThm?` should
be the output of `getUnfoldEqnFor? decl` and is cached here for efficiency.
-/
-- TODO Don't cache equation name; this may lead to bugs and the performance
-- cost is negligible.
unfoldRules : PHashMap Name (Option Name)
/--
Forward rules. There's a special procedure for applying forward rules, so we
don't store them in the regular indices.
-/
forwardRules : ForwardIndex
/-- The names of all rules in `forwardRules`. -/
-- HACK to be removed once we switch fully to stateful forward reasoning.
forwardRuleNames : PHashSet RuleName
/--
An index for the rule patterns associated with rules contained in this rule
set. When rules are removed from the rule set, their patterns are not removed
from this index.
-/
rulePatterns : RulePatternIndex
/--
The set of rules that were erased from `normRules`, `unsafeRules`, `safeRules`
and `forwardRules`. When we erase a rule which is present in any of these four
indices, the rule is not removed from the indices but just added to this set.
By contrast, when we erase a rule from `unfoldRules`, we actually delete it.
-/
erased : PHashSet RuleName
/--
A cache of the names of all rules registered in this rule set. Invariant:
`ruleNames` contains exactly the names of the rules present in `normRules`,
`unsafeRules`, `safeRules`, `forwardRules` and `unfoldRules` and not present
in `erased`. We use this cache (a) to quickly determine whether a rule is
present in the rule set and (b) to find the full rule names associated with
the fvar or const identified by a name.
-/
ruleNames : PHashMap Name (UnorderedArraySet RuleName)
deriving Inhabited
/--
A global Aesop rule set. When we tag a declaration with `@[aesop]`, it is stored
in one or more of these rule sets. Internally, a `GlobalRuleSet` is composed of
a `BaseRuleSet` (stored in an Aesop rule set extension) plus a set of simp
theorems (stored in a `SimpExtension`).
-/
structure GlobalRuleSet extends BaseRuleSet where
/--
The simp theorems stored in this rule set.
-/
simpTheorems : SimpTheorems
/--
The simprocs stored in this rule set.
-/
simprocs : Simprocs
deriving Inhabited
/--
The rule set used by an Aesop tactic call. A local rule set is produced by
combining several global rule sets and possibly adding or erasing some
individual rules.
-/
structure LocalRuleSet extends BaseRuleSet where
/--
The simp theorems used by the builtin norm simp rule.
-/
simpTheoremsArray : Array (Name × SimpTheorems)
/--
The simp theorems array must contain at least one `SimpTheorems` structure.
When a simp theorem is added to a `LocalRuleSet`, it is stored in this first
`SimpTheorems` structure.
-/
simpTheoremsArrayNonempty : 0 < simpTheoremsArray.size
/--
The simprocs used by the builtin norm simp rule.
-/
simprocsArray : Array (Name × Simprocs)
/--
The simprocs array must contain at least one `Simprocs` structure, for the
same reason as above.
-/
simprocsArrayNonempty : 0 < simprocsArray.size
/--
FVars that were explicitly added as simp rules.
-/
localNormSimpRules : Array LocalNormSimpRule
end Types
namespace GlobalRuleSet
@[inline, always_inline]
def onBaseM [Monad m] (f : BaseRuleSet → m (BaseRuleSet × α))
(rs : GlobalRuleSet) : m (GlobalRuleSet × α) := do
let (toBaseRuleSet, a) ← f rs.toBaseRuleSet
let rs := { rs with toBaseRuleSet }
return (rs, a)
@[inline, always_inline]
def onBase (f : BaseRuleSet → BaseRuleSet × α) (rs : GlobalRuleSet) :
GlobalRuleSet × α :=
rs.onBaseM (m := Id) f
@[inline, always_inline]
def modifyBaseM [Monad m] (f : BaseRuleSet → m BaseRuleSet)
(rs : GlobalRuleSet) : m GlobalRuleSet :=
(·.fst) <$> rs.onBaseM (λ rs => return (← f rs, ()))
@[inline, always_inline]
def modifyBase (f : BaseRuleSet → BaseRuleSet) (rs : GlobalRuleSet) :
GlobalRuleSet :=
rs.modifyBaseM (m := Id) f
end GlobalRuleSet
namespace LocalRuleSet
@[inline, always_inline]
def onBaseM [Monad m] (f : BaseRuleSet → m (BaseRuleSet × α))
(rs : LocalRuleSet) : m (LocalRuleSet × α) := do
let (toBaseRuleSet, a) ← f rs.toBaseRuleSet
return ({ rs with toBaseRuleSet }, a)
@[inline, always_inline]
def onBase (f : BaseRuleSet → (BaseRuleSet × α)) (rs : LocalRuleSet) :
LocalRuleSet × α :=
rs.onBaseM (m := Id) f
def modifyBaseM [Monad m] (f : BaseRuleSet → m BaseRuleSet) (rs : LocalRuleSet) :
m LocalRuleSet :=
(·.fst) <$> rs.onBaseM (λ rs => return (← f rs, ()))
def modifyBase (f : BaseRuleSet → BaseRuleSet) (rs : LocalRuleSet) :
LocalRuleSet :=
rs.modifyBaseM (m := Id) f
end LocalRuleSet
def BaseRuleSet.trace (rs : BaseRuleSet) (traceOpt : TraceOption) :
CoreM Unit := do
if ! (← traceOpt.isEnabled) then
return
withConstAesopTraceNode traceOpt (return "Erased rules") do
aesop_trace![traceOpt] "(Note: even if these rules appear in the sections below, they will not be applied by Aesop.)"
let erased := rs.erased.fold (init := #[])
λ ary r => ary.push r
for r in erased.qsortOrd do
aesop_trace![traceOpt] r
withConstAesopTraceNode traceOpt (return "Unsafe rules") do
rs.unsafeRules.trace traceOpt
withConstAesopTraceNode traceOpt (return "Safe rules") do
rs.safeRules.trace traceOpt
withConstAesopTraceNode traceOpt (return "Forward rules") do
rs.forwardRules.trace traceOpt
withConstAesopTraceNode traceOpt (return "Normalisation rules") do
rs.normRules.trace traceOpt
withConstAesopTraceNode traceOpt (return "Constants to unfold") do
for r in rs.unfoldRules.toArray.map (·.fst.toString) |>.qsortOrd do
aesop_trace![traceOpt] r
def GlobalRuleSet.trace (rs : GlobalRuleSet) (traceOpt : TraceOption) :
CoreM Unit := do
if ! (← traceOpt.isEnabled) then
return
rs.toBaseRuleSet.trace traceOpt
withConstAesopTraceNode traceOpt (return "Normalisation simp theorems:") do
traceSimpTheorems rs.simpTheorems traceOpt
-- TODO trace simprocs
def LocalRuleSet.trace (rs : LocalRuleSet) (traceOpt : TraceOption) :
CoreM Unit := do
if ! (← traceOpt.isEnabled) then
return
rs.toBaseRuleSet.trace traceOpt
withConstAesopTraceNode traceOpt (return "Simp sets used by normalisation simp:") do
rs.simpTheoremsArray.map (printSimpSetName ·.fst) |>.qsortOrd.forM λ s => do
aesop_trace![traceOpt] s
withConstAesopTraceNode traceOpt (return "Local normalisation simp theorems") do
for r in rs.localNormSimpRules.map (·.simpTheorem) do
aesop_trace![traceOpt] r
where
printSimpSetName : Name → String
| `_ => "<default>"
| n => toString n
def BaseRuleSet.empty : BaseRuleSet := by
refine' {..} <;> exact {}
instance : EmptyCollection BaseRuleSet :=
⟨.empty⟩
def GlobalRuleSet.empty : GlobalRuleSet := by
refine' {..} <;> exact {}
instance : EmptyCollection GlobalRuleSet :=
⟨.empty⟩
def LocalRuleSet.empty : LocalRuleSet where
toBaseRuleSet := .empty
simpTheoremsArray := #[(`_, {})]
simpTheoremsArrayNonempty := by decide
simprocsArray := #[(`_, {})]
simprocsArrayNonempty := by decide
localNormSimpRules := ∅
instance : EmptyCollection LocalRuleSet :=
⟨.empty⟩
instance : Inhabited LocalRuleSet :=
⟨∅⟩
private def BaseRuleSet.isErased (rs : BaseRuleSet) (n : RuleName) : Bool :=
rs.erased.contains n
def BaseRuleSet.contains (rs : BaseRuleSet) (n : RuleName) : Bool :=
! rs.isErased n &&
if let some ns := rs.ruleNames.find? n.name then
ns.contains n
else
false
def GlobalRuleSet.contains (rs : GlobalRuleSet) (n : RuleName) : Bool :=
rs.toBaseRuleSet.contains n ||
(n.builder == .simp && n.scope == .global &&
SimpTheorems.containsDecl rs.simpTheorems n.name)
def LocalRuleSet.containsGlobalSimpTheorem (rs : LocalRuleSet) (decl : Name) :
Bool :=
rs.simpTheoremsArray.any λ (_, simpTheorems) =>
SimpTheorems.containsDecl simpTheorems decl
def LocalRuleSet.contains (rs : LocalRuleSet) (n : RuleName) : Bool :=
rs.toBaseRuleSet.contains n ||
(n.builder == .simp &&
match n.scope with
| .global => rs.containsGlobalSimpTheorem n.name
| .local => rs.localNormSimpRules.any (·.id == n.name))
def BaseRuleSet.merge (rs₁ rs₂ : BaseRuleSet) : BaseRuleSet where
normRules := rs₁.normRules.merge rs₂.normRules
unsafeRules := rs₁.unsafeRules.merge rs₂.unsafeRules
safeRules := rs₁.safeRules.merge rs₂.safeRules
forwardRules := rs₁.forwardRules.merge rs₂.forwardRules
forwardRuleNames := rs₁.forwardRuleNames.merge rs₂.forwardRuleNames
rulePatterns := rs₁.rulePatterns.merge rs₂.rulePatterns
unfoldRules := rs₁.unfoldRules.mergeWith rs₂.unfoldRules
λ _ unfoldThm?₁ _ => unfoldThm?₁
ruleNames :=
rs₁.ruleNames.mergeWith rs₂.ruleNames λ _ ns₁ ns₂ =>
ns₁ ++ ns₂
erased :=
-- Add the erased rules from `rs₁` to `init`, except those rules which are
-- present (and not erased) in `rs₂`.
let go (rs₁ rs₂ : BaseRuleSet) (init : PHashSet RuleName) :
PHashSet RuleName :=
rs₁.erased.fold (init := init) λ x n =>
match rs₂.ruleNames.find? n.name with
| none => x.insert n
| some ns =>
if ns.contains n then x else x.insert n
go rs₂ rs₁ $ go rs₁ rs₂ {}
def BaseRuleSet.add (rs : BaseRuleSet) (r : BaseRuleSetMember) :
BaseRuleSet :=
let erased := rs.erased.erase r.name
let name := r.name.name
let ruleNames :=
match rs.ruleNames.find? name with
| none => rs.ruleNames.insert name $ .singleton r.name
| some ns => rs.ruleNames.insert name $ ns.insert r.name
let rs := { rs with erased, ruleNames }
match r with
| .normRule r =>
let rs := { rs with normRules := rs.normRules.add r r.indexingMode }
addRulePattern r.name r.pattern? rs
| .unsafeRule r =>
let rs := { rs with unsafeRules := rs.unsafeRules.add r r.indexingMode }
addRulePattern r.name r.pattern? rs
| .safeRule r =>
let rs := { rs with safeRules := rs.safeRules.add r r.indexingMode }
addRulePattern r.name r.pattern? rs
| .unfoldRule r =>
{ rs with unfoldRules := rs.unfoldRules.insert r.decl r.unfoldThm? }
| .normForwardRule r₁ r₂ =>
let rs := {
rs with
forwardRules := rs.forwardRules.insert r₁
forwardRuleNames := rs.forwardRuleNames.insert r₁.name
normRules := rs.normRules.add r₂ r₂.indexingMode
}
addRulePattern r₂.name r₂.pattern? rs
| .unsafeForwardRule r₁ r₂ =>
let rs := {
rs with
forwardRules := rs.forwardRules.insert r₁
forwardRuleNames := rs.forwardRuleNames.insert r₁.name
unsafeRules := rs.unsafeRules.add r₂ r₂.indexingMode
}
addRulePattern r₂.name r₂.pattern? rs
| .safeForwardRule r₁ r₂ =>
let rs := {
rs with
forwardRules := rs.forwardRules.insert r₁
forwardRuleNames := rs.forwardRuleNames.insert r₁.name
safeRules := rs.safeRules.add r₂ r₂.indexingMode
}
addRulePattern r₂.name r₂.pattern? rs
where
addRulePattern (n : RuleName) (pat? : Option RulePattern)
(rs : BaseRuleSet) : BaseRuleSet :=
match pat? with
| none => rs
| some pat => { rs with rulePatterns := rs.rulePatterns.add n pat }
def LocalRuleSet.add (rs : LocalRuleSet) :
LocalRuleSetMember → LocalRuleSet
| .global (.base m) => rs.modifyBase (·.add m)
| .global (.normSimpRule r) =>
let simpTheoremsArray :=
rs.simpTheoremsArray.modify 0 λ (name, simpTheorems) =>
let simpTheorems :=
r.entries.foldl (init := simpTheorems) SimpTheorems.addSimpEntry
(name, simpTheorems)
let simpTheoremsArrayNonempty : 0 < simpTheoremsArray.size := by
simp [simpTheoremsArray, Array.size_modify, rs.simpTheoremsArrayNonempty]
{ rs with simpTheoremsArray, simpTheoremsArrayNonempty }
| .localNormSimpRule r =>
{ rs with localNormSimpRules := rs.localNormSimpRules.push r }
def BaseRuleSet.erase (rs : BaseRuleSet) (f : RuleFilter) :
BaseRuleSet × Bool := Id.run do
let some ns := rs.ruleNames.find? f.name
| return (rs, false)
let (toErase, toKeep) := ns.partition f.matches
if toErase.isEmpty then
return (rs, false)
let ruleNames :=
if toKeep.isEmpty then
rs.ruleNames.erase f.name
else
rs.ruleNames.insert f.name toKeep
let mut erased := rs.erased
let mut unfoldRules := rs.unfoldRules
for r in toErase do
match r.builder with
| .unfold => unfoldRules := unfoldRules.erase r.name
| .tactic | .forward | .destruct | .constructors | .cases | .apply =>
erased := erased.insert r
| .simp => continue
let res := { rs with ruleNames, erased, unfoldRules }
return (res, true)
def GlobalRuleSet.erase (rs : GlobalRuleSet) (f : RuleFilter) :
GlobalRuleSet × Bool := Id.run do
let (rs, anyErased) := rs.onBase (·.erase f)
if let some decl := f.matchesSimpTheorem? then
if SimpTheorems.containsDecl rs.simpTheorems decl then
let simpTheorems := rs.simpTheorems.eraseCore (.decl decl (inv := false))
return ({ rs with simpTheorems := simpTheorems }, true)
return (rs, anyErased)
def LocalRuleSet.erase (rs : LocalRuleSet) (f : RuleFilter) :
LocalRuleSet × Bool := Id.run do
let (rs, anyErased) := rs.onBase (·.erase f)
let mut anyErased := anyErased
let mut localNormSimpRules := rs.localNormSimpRules
let mut simpTheoremsArray' :
Σ' a : Array (Name × SimpTheorems), a.size = rs.simpTheoremsArray.size :=
⟨rs.simpTheoremsArray, rfl⟩
if let some id := f.matchesLocalNormSimpRule? then
if let some idx := localNormSimpRules.findFinIdx? (·.id == id) then
localNormSimpRules := localNormSimpRules.eraseIdx idx
if let some decl := f.matchesSimpTheorem? then
for h : i in [:rs.simpTheoremsArray.size] do
have i_valid : i < simpTheoremsArray'.fst.size := by
simp_all +zetaDelta [Membership.mem, simpTheoremsArray'.snd]
let (name, simpTheorems) := simpTheoremsArray'.fst[i]
if SimpTheorems.containsDecl simpTheorems decl then
let origin := .decl decl (inv := false)
simpTheoremsArray' :=
⟨simpTheoremsArray'.fst.set i
(name, simpTheorems.eraseCore origin),
by simp [simpTheoremsArray'.snd, Array.size_set]⟩
anyErased := true
let simpTheoremsArray := simpTheoremsArray'.fst
let simpTheoremsArrayNonempty : 0 < simpTheoremsArray.size := by
simp [simpTheoremsArray, simpTheoremsArray'.snd, rs.simpTheoremsArrayNonempty]
let rs := { rs with
localNormSimpRules, simpTheoremsArray, simpTheoremsArrayNonempty
}
return (rs, anyErased)
namespace LocalRuleSet
@[inline, always_inline]
private def fwdRulePredicate (opts : Lean.Options) (rs : LocalRuleSet)
(include? : Rule α → Bool) (r : Rule α) : Bool :=
aesop.dev.statefulForward.get opts && include? r && ! rs.isErased r.name
@[inline, always_inline]
private def rulePredicate (opts : Lean.Options) (rs : LocalRuleSet)
(include? : Rule α → Bool) : Rule α → Bool :=
-- HACK When stateful forward reasoning is active, we exclude rules which are
-- already covered by equivalent `ForwardRule`s.
if aesop.dev.statefulForward.get opts then
λ r => include? r && ! rs.isErased r.name &&
! rs.forwardRuleNames.contains r.name
else
λ r => include? r && ! rs.isErased r.name
private def postprocessForwardMatchRules (opts : Lean.Options) (rs : LocalRuleSet)
(include? : Rule α → Bool) (rules : Array (Rule α)) :
Array (IndexMatchResult (Rule α)) :=
rules.filter (fwdRulePredicate opts rs include?) |>.map λ rule =>
{ rule, locations := ∅, patternSubsts? := none }
def applicableNormalizationRulesWith (rs : LocalRuleSet)
(fms : ForwardRuleMatches) (goal : MVarId)
(include? : NormRule → Bool) : BaseM (Array (IndexMatchResult NormRule)) := do
let opts ← getOptions
let normFwdRules := postprocessForwardMatchRules opts rs include? fms.normRules
let patInstMap ← rs.rulePatterns.getInGoal goal
rs.normRules.applicableRules goal patInstMap normFwdRules
(rulePredicate opts rs include?)
@[inline, always_inline]
def applicableNormalizationRules (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) : BaseM (Array (IndexMatchResult NormRule)) :=
rs.applicableNormalizationRulesWith fms goal (include? := λ _ => true)
def applicableUnsafeRulesWith (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) (include? : UnsafeRule → Bool) :
BaseM (Array (IndexMatchResult UnsafeRule)) := do
let opts ← getOptions
let unsafeFwdRules := postprocessForwardMatchRules opts rs include? fms.unsafeRules
let patInstMap ← rs.rulePatterns.getInGoal goal
rs.unsafeRules.applicableRules goal patInstMap unsafeFwdRules
(rulePredicate opts rs include?)
@[inline, always_inline]
def applicableUnsafeRules (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) : BaseM (Array (IndexMatchResult UnsafeRule)) :=
rs.applicableUnsafeRulesWith fms goal (include? := λ _ => true)
def applicableSafeRulesWith (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) (include? : SafeRule → Bool) :
BaseM (Array (IndexMatchResult SafeRule)) := do
let opts ← getOptions
let safeFwdRules := postprocessForwardMatchRules opts rs include? fms.safeRules
let patInstMap ← rs.rulePatterns.getInGoal goal
rs.safeRules.applicableRules goal patInstMap safeFwdRules
(rulePredicate opts rs include?)
@[inline, always_inline]
def applicableSafeRules (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) : BaseM (Array (IndexMatchResult SafeRule)) :=
rs.applicableSafeRulesWith fms goal (include? := λ _ => true)
def applicableForwardRulesWith (rs : LocalRuleSet) (e : Expr)
(include? : ForwardRule → Bool) :
MetaM (Array (ForwardRule × PremiseIndex)) :=
withConstAesopTraceNode .forward (return m!"selected forward rules:") do
let rules ← rs.forwardRules.get e
let rules := rules.filter λ (rule, _) =>
include? rule && !rs.isErased rule.name
aesop_trace[forward] do
for (r, i) in rules do
aesop_trace![forward] mkMsg r i
return rules
where
mkMsg r i := m!"{r}, premise {i}" -- Inlining this triggers a Lean bug.
@[inline, always_inline]
def applicableForwardRules (rs : LocalRuleSet) (e : Expr) :
MetaM (Array (ForwardRule × PremiseIndex)) :=
rs.applicableForwardRulesWith e (include? := λ _ => true)
def constForwardRuleMatches (rs : LocalRuleSet) : Array ForwardRuleMatch :=
rs.forwardRules.getConstRuleMatches
section ForwardRulePattern
private def postprocessPatSubstMap (rs : LocalRuleSet)
(m : RulePatternSubstMap) : Array (ForwardRule × Substitution) :=
m.toFlatArray.filterMap λ (n, patSubst) =>
rs.forwardRules.getRuleWithName? n |>.map (·, patSubst)
def forwardRulePatternSubstsInExpr (rs : LocalRuleSet) (e : Expr) :
BaseM (Array (ForwardRule × Substitution)) := do
withConstAesopTraceNode .forward (return m!"rule patterns in expr {e}:") do
let ms ← rs.rulePatterns.get e
let ms := postprocessPatSubstMap rs ms
aesop_trace[forward] do
for (r, inst) in ms do
aesop_trace![forward] m!"{r}, {inst}"
return ms
def forwardRulePatternSubstsInLocalDecl (rs : LocalRuleSet) (ldecl : LocalDecl) :
BaseM (Array (ForwardRule × Substitution)) := do
withConstAesopTraceNode .forward (return m!"rule patterns in hyp {ldecl.userName}:") do
let ms ← rs.rulePatterns.getInLocalDecl ldecl
let ms := postprocessPatSubstMap rs ms
aesop_trace[forward] do
for (r, inst) in ms do
aesop_trace![forward] m!"{r}, {inst}"
return ms
end ForwardRulePattern
-- NOTE: only non-forward norm/safe/unsafe rules can be unindexed.
def unindex (rs : LocalRuleSet) (p : RuleName → Bool) : LocalRuleSet := {
rs with
normRules := rs.normRules.unindex (p ·.name)
unsafeRules := rs.unsafeRules.unindex (p ·.name)
safeRules := rs.safeRules.unindex (p ·.name)
}
end LocalRuleSet
@[inline, always_inline]
def unindexPredicate? (options : Options') : Option (RuleName → Bool) :=
if options.destructProductsTransparency == .reducible then
none
else
some λ n => n.name == `Aesop.BuiltinRules.destructProducts
def mkLocalRuleSet (rss : Array (GlobalRuleSet × Name × Name))
(options : Options') : CoreM LocalRuleSet := do
let mut result := ∅
let simpTheorems ← getSimpTheorems
let simprocs ← Simp.getSimprocs
result := {
toBaseRuleSet := ∅
simpTheoremsArray :=
if options.useDefaultSimpSet then
Array.mkEmpty (rss.size + 1) |>.push (`_, simpTheorems)
else
Array.mkEmpty (rss.size + 1) |>.push (`_, {})
simprocsArray :=
if options.useDefaultSimpSet then
Array.mkEmpty (rss.size + 1) |>.push (`_, simprocs)
else
Array.mkEmpty (rss.size + 1) |>.push ((`_, {}))
simpTheoremsArrayNonempty := by split <;> simp
simprocsArrayNonempty := by split <;> simp
localNormSimpRules := ∅
}
for (rs, simpExtName, simprocExtName) in rss do
result := { result with
toBaseRuleSet := result.toBaseRuleSet.merge rs.toBaseRuleSet
simpTheoremsArray :=
result.simpTheoremsArray.push (simpExtName, rs.simpTheorems)
simpTheoremsArrayNonempty := by simp
simprocsArray :=
result.simprocsArray.push (simprocExtName, rs.simprocs)
simprocsArrayNonempty := by simp
}
if let some p := unindexPredicate? options then
return result.unindex p
else
return result
end Aesop |
.lake/packages/aesop/Aesop/Constants.lean | module
public import Aesop.Percent
public section
namespace Aesop
def unificationGoalPenalty : Percent :=
⟨0.8⟩
def postponedSafeRuleSuccessProbability : Percent :=
⟨0.9⟩
end Aesop |
.lake/packages/aesop/Aesop/RPINF.lean | module
public import Aesop.BaseM
import Batteries.Lean.Expr
public section
open Lean Lean.Meta
namespace Aesop
local instance : MonadCache Expr Expr BaseM where
findCached? e :=
return (← MonadCache.findCached? e : Option RPINFRaw).map (·.toExpr)
cache k v := MonadCache.cache k (⟨v⟩ : RPINFRaw)
@[specialize]
partial def rpinfRaw (e : Expr) : BaseM RPINFRaw :=
withReducible do return ⟨← go e⟩
where
go (e : Expr) : BaseM Expr :=
withIncRecDepth do
checkCache e λ _ => do
if ← isProof e then
return .mdata (mdataSetIsProof {}) e
let e ← whnf e
match e with
| .app .. =>
let f ← go e.getAppFn'
let mut args := e.getAppArgs'
for i in [:args.size] do
let arg := args[i]!
args := args.set! i default -- prevent nonlinear access to args[i]
let arg ← go arg
args := args.set! i arg
if f.isConstOf ``Nat.succ && args.size == 1 && args[0]!.isRawNatLit then
return mkRawNatLit (args[0]!.rawNatLit?.get! + 1)
else
return mkAppN f args
| .lam .. =>
-- TODO disable cache?
lambdaTelescope e λ xs e => withNewFVars xs do
mkLambdaFVars xs (← go e)
| .forallE .. =>
-- TODO disable cache?
forallTelescope e λ xs e => withNewFVars xs do
mkForallFVars xs (← go e)
| .proj t i e =>
return .proj t i (← go e)
| .sort u => return .sort <| ← normalizeLevel u
| .const n us => return .const n <| ← us.mapM fun u => normalizeLevel u
| .mvar .. | .lit .. | .fvar .. =>
return e
| .letE .. | .mdata .. | .bvar .. => unreachable!
withNewFVars {α} (fvars : Array Expr) (k : BaseM α) : BaseM α := do
let mut lctx ← (getLCtx : MetaM _)
for fvar in fvars do
let fvarId := fvar.fvarId!
let ldecl ← fvarId.getDecl
let ldecl := ldecl.setType $ ← go ldecl.type
lctx := lctx.modifyLocalDecl fvarId λ _ => ldecl
withLCtx lctx (← getLocalInstances) k
def rpinf (e : Expr) : BaseM RPINF :=
withConstAesopTraceNode .rpinf (return m!"rpinf") do
aesop_trace[rpinf] "input:{indentExpr e}"
let e ← rpinfRaw e
let hash := pinfHash e.toExpr
aesop_trace[rpinf] "result hash: {hash}"
aesop_trace[rpinf] "resut:{indentExpr e.toExpr}"
return { e with hash }
end Aesop |
.lake/packages/aesop/Aesop/Options.lean | module
public import Aesop.Options.Internal
public import Aesop.Options.Public |
.lake/packages/aesop/Aesop/RuleTac.lean | module
public import Aesop.RuleTac.Apply
public import Aesop.RuleTac.Basic
public import Aesop.RuleTac.Cases
public import Aesop.RuleTac.Forward
public import Aesop.RuleTac.Preprocess
public import Aesop.RuleTac.Tactic
public import Aesop.RuleTac.Descr
public section
open Lean
namespace Aesop.RuleTacDescr
protected def run : RuleTacDescr → RuleTac
| apply t md => RuleTac.apply t md
| constructors cs md => RuleTac.applyConsts cs md
| forward t immediate clear => RuleTac.forward t immediate clear
| cases target md isRecursiveType ctorNames =>
RuleTac.cases target md isRecursiveType ctorNames
| tacticM decl => RuleTac.tacticM decl
| singleRuleTac decl => RuleTac.singleRuleTac decl
| ruleTac decl => RuleTac.ruleTac decl
| tacticStx stx => RuleTac.tacticStx stx
| tacGen decl => RuleTac.tacGen decl
| preprocess => RuleTac.preprocess
| forwardMatches m => RuleTac.forwardMatches m
end RuleTacDescr |
.lake/packages/aesop/Aesop/Frontend.lean | import Aesop.Frontend.Attribute
import Aesop.Frontend.Command
import Aesop.Frontend.RuleExpr
import Aesop.Frontend.Tactic |
.lake/packages/aesop/Aesop/ElabM.lean | module
public import Lean.Elab.Term.TermElabM
public section
open Lean Lean.Meta Lean.Elab
namespace Aesop.ElabM
structure Context where
parsePriorities : Bool
goal : MVarId
namespace Context
def forAdditionalRules (goal : MVarId) : Context where
parsePriorities := true
goal := goal
-- HACK: Some of the elaboration functions require that we pass in the current
-- goal. The goal is used exclusively to look up fvars in the lctx, so when
-- we operate outside a goal, we pass in a dummy mvar with empty lctx.
def forAdditionalGlobalRules : MetaM Context := do
let mvarId := (← mkFreshExprMVarAt {} {} (.const ``True [])).mvarId!
return .forAdditionalRules mvarId
def forErasing (goal : MVarId) : Context where
parsePriorities := false
goal := goal
-- HACK: See `forAdditionalGlobalRules`
def forGlobalErasing : MetaM Context := do
let mvarId := (← mkFreshExprMVarAt {} {} (.const ``True [])).mvarId!
return .forErasing mvarId
end ElabM.Context
abbrev ElabM := ReaderT ElabM.Context $ Term.TermElabM
-- Generate specialized pure/bind implementations so we don't need to optimise
-- them on the fly at each use site.
instance : Monad ElabM :=
{ inferInstanceAs (Monad ElabM) with }
protected def ElabM.run (ctx : Context) (x : ElabM α) : Term.TermElabM α := do
ReaderT.run x ctx
def shouldParsePriorities : ElabM Bool :=
return (← read).parsePriorities
def getGoal : ElabM MVarId :=
return (← read).goal
end Aesop |
.lake/packages/aesop/Aesop/Main.lean | module
public meta import Aesop.Stats.Extension
public import Aesop.Frontend.Tactic
meta import Aesop.Frontend.Tactic
public meta import Aesop.Search.Main
import Aesop.Stats.Basic
public section
open Lean
open Lean.Elab.Tactic
namespace Aesop
@[tactic Frontend.Parser.aesopTactic, tactic Frontend.Parser.aesopTactic?]
meta def evalAesop : Tactic := λ stx => do
profileitM Exception "aesop" (← getOptions) do
let goal ← getMainGoal
goal.withContext do
let (_, stats) ← go stx goal |>.run ∅
recordStatsForCurrentFileIfEnabled stx stats
stats.trace .stats
where
go (stx : Syntax) (goal : MVarId) : StateRefT Stats TacticM Unit :=
profiling (λ s _ t => { s with total := t }) do
let config ← profiling (λ s _ t => { s with configParsing := t }) do
Frontend.TacticConfig.parse stx goal
let ruleSet ←
profiling (λ s _ t => { s with ruleSetConstruction := t }) do
config.getRuleSet goal
withConstAesopTraceNode .ruleSet (return "Rule set") do
ruleSet.trace .ruleSet
profiling (λ s _ t => { s with search := t }) do
let (goals, stats) ←
search goal ruleSet config.options config.simpConfig
config.simpConfigSyntax? (← getStats)
replaceMainGoal goals.toList
modifyStats λ _ => stats
end Aesop |
.lake/packages/aesop/Aesop/Tree/Tracing.lean | module
public import Aesop.Tree.RunMetaM
import Batteries.Data.Array.Basic
import Batteries.Lean.Meta.SavedState
public section
open Lean
open MessageData
namespace Aesop
private def toYesNo : Bool → String
| true => "yes"
| false => "no"
def Goal.withHeadlineTraceNode (g : Goal) (traceOpt : TraceOption) (k : MetaM α)
(collapsed := true) (transform : MessageData → MetaM MessageData := pure) :
MetaM α := do
withConstAesopTraceNode traceOpt fmt k collapsed
where
fmt : MetaM MessageData := do
g.runMetaMInParentState' do
g.preNormGoal.withContext do
addMessageContext $ ← transform
m!"{g.state.toEmoji} G{g.id} [{g.priority.toHumanString}] ⋯ ⊢ {← g.preNormGoal.getType}"
def Goal.traceMetadata (g : Goal) (traceOpt : TraceOption) : MetaM Unit := do
if ! (← traceOpt.isEnabled) then
return
trc m!"ID: {g.id}"
trcNode m!"Pre-normalisation goal ({g.preNormGoal.name}):" do
g.runMetaMInParentState' do
trc m!"{g.preNormGoal}"
match g.postNormGoalAndMetaState? with
| none =>
trc m!"Post-normalisation goal: <goal not normalised>"
| some (goal, state) =>
state.runMetaM' do
trcNode m!"Post-normalisation goal ({goal.name}):" do
trc m!"{goal}"
trc m!"Metavariables: {g.mvars.toArray.map (·.name)}"
trc m!"Parent rapp: {← (← g.parentRapp?).mapM λ rref => (·.id) <$> rref.get}"
trc m!"Child rapps: {← g.children.mapM λ rref => (·.id) <$> rref.get}"
trc m!"Origin: {g.origin.toString}"
trc m!"Depth: {g.depth}"
trc m!"State: {g.state.toEmoji} {g.state}"
trc m!"Forward rule matches: {g.forwardRuleMatches.size}"
trc m!"Irrelevant: {toYesNo g.isIrrelevant}"
trc m!"Forced unprovable: {toYesNo g.isForcedUnprovable}"
trc m!"Added in iteration: {g.addedInIteration}"
trc m!"Last expanded in iteration: {if g.lastExpandedInIteration == .none then "never" else toString $ g.lastExpandedInIteration}"
trcNode m!"Forward state" do
match g.postNormGoalAndMetaState? with
| some (mvarId, metaState) =>
metaState.runMetaM' do mvarId.withContext do
trc $ toMessageData g.forwardState
| none =>
g.runMetaMInParentState' do g.preNormGoal.withContext do
trc $ toMessageData g.forwardState
if g.unsafeRulesSelected then
if g.unsafeQueue.isEmpty then
trc m!"Unsafe rule queue: <empty>"
else
trcNode m!"Unsafe rule queue:" do
for r in g.unsafeQueue.toArray do
trc m!"[{r.successProbability.toHumanString}] {r.name}"
else
trc m!"Unsafe rule queue: <not selected>"
if g.failedRapps.isEmpty then
trc m!"Failed rules: <none>"
else
trcNode m!"Failed rules:" do
for r in g.failedRapps do
trc m!"[{r.successProbability.toHumanString}] {r.name}"
where
trc msg : MetaM Unit := do aesop_trace![traceOpt] msg
trcNode msg (k : MetaM Unit) : MetaM Unit :=
withConstAesopTraceNode traceOpt (return msg) k
def Rapp.withHeadlineTraceNode (r : Rapp) (traceOpt : TraceOption) (k : MetaM α)
(collapsed := true) (transform : MessageData → MetaM MessageData := pure) :
MetaM α :=
withConstAesopTraceNode traceOpt
(transform m!"{r.state.toEmoji} R{r.id} [{r.successProbability.toHumanString}] {r.appliedRule.name}")
k collapsed
def Rapp.traceMetadata (r : Rapp) (traceOpt : TraceOption) : MetaM Unit := do
if ! (← traceOpt.isEnabled) then
return
trc m!"ID: {r.id}"
trc m!"Rule: {r.appliedRule}"
trc m!"Success probability: {r.successProbability.toHumanString}"
trc m!"Parent goal: {(← r.parent.get).id}"
trc m!"Child goals: {← (← r.subgoals).mapM λ gref => (·.id) <$> gref.get}"
trc m!"State: {r.state}"
trc m!"Irrelevant: {r.isIrrelevant}"
trc m!"Introduced metavariables: {r.introducedMVars.toArray.map (·.name)}"
trc m!"Assigned metavariables: {r.assignedMVars.toArray.map (·.name)}"
where
trc m : MetaM Unit := do aesop_trace![traceOpt] m
mutual
partial def Goal.traceTreeCore (g : Goal) (traceOpt : TraceOption) :
MetaM Unit :=
g.withHeadlineTraceNode traceOpt (collapsed := false) do
g.runMetaMInParentState' do
aesop_trace![traceOpt] g.preNormGoal
withConstAesopTraceNode traceOpt (return "Metadata") do
g.traceMetadata traceOpt
for rref in g.children do
(← rref.get).traceTreeCore traceOpt
partial def Rapp.traceTreeCore (r : Rapp) (traceOpt : TraceOption) :
MetaM Unit := do
r.withHeadlineTraceNode traceOpt (collapsed := false) do
withConstAesopTraceNode traceOpt (return "Metadata") do
r.traceMetadata traceOpt
r.forSubgoalsM λ gref => do
(← gref.get).traceTreeCore traceOpt
end
def Goal.traceTree (g : Goal) (traceOpt : TraceOption) : MetaM Unit := do
if ← traceOpt.isEnabled then
g.traceTreeCore traceOpt
def Rapp.traceTree (r : Rapp) (traceOpt : TraceOption) : MetaM Unit := do
if ← traceOpt.isEnabled then
r.traceTreeCore traceOpt
end Aesop |
.lake/packages/aesop/Aesop/Tree/Check.lean | module
public import Aesop.Tree.TreeM
import Aesop.Tree.RunMetaM
import Aesop.Tree.State
import Batteries.Lean.HashSet
import Batteries.Data.Array.Basic
import Batteries.Lean.Meta.SavedState
public section
open Lean
open Lean.Meta
namespace Aesop.MVarClusterRef
def checkIds (root : MVarClusterRef) : CoreM Unit := do
let visitedGoalIds : IO.Ref (Std.HashSet GoalId) ← IO.mkRef {}
let visitedRappIds : IO.Ref (Std.HashSet RappId) ← IO.mkRef {}
preTraverseDown
(λ gref => do
let id := (← gref.get).id
if (← visitedGoalIds.get).contains id then
throwError "{Check.tree.name}: duplicate goal id: {id}"
visitedGoalIds.modify λ s => s.insert id
return true)
(λ rref => do
let id := (← rref.get).id
if (← visitedRappIds.get).contains id then
throwError "{Check.tree.name}: duplicate rapp id: {id}"
visitedRappIds.modify λ s => s.insert id
return true)
(λ _ => return true)
(TreeRef.mvarCluster root)
def checkAcyclic (root : MVarClusterRef) : CoreM Unit := do
-- We use arrays to store the visited nodes (rather than some data structure
-- with asymptotically faster lookup) because STRefs only have pointer
-- equality, not pointer comparison. Besides, this is probably faster anyway
-- for small to medium trees.
let visitedGoalRefs : IO.Ref (Array GoalRef) ← ST.mkRef #[]
let visitedRappRefs : IO.Ref (Array RappRef) ← ST.mkRef #[]
let visitedMVarClusterRefs : IO.Ref (Array MVarClusterRef) ← ST.mkRef #[]
preTraverseDown
(λ gref => go visitedGoalRefs gref)
(λ rref => go visitedRappRefs rref)
(λ cref => go visitedMVarClusterRefs cref)
(TreeRef.mvarCluster root)
where
go {α} (visited : IO.Ref (Array (IO.Ref α))) (current : IO.Ref α) :
CoreM Bool := do
if ← (← visited.get).anyM (current.ptrEq ·) then throwError
"{Check.tree.name}: search tree contains a cycle."
visited.modify (·.push current)
return true
def checkConsistentParentChildLinks (root : MVarClusterRef) : CoreM Unit :=
preTraverseDown
(λ gref => do
for c in (← gref.get).children do
if ← notM $ (← c.get).parent.ptrEq gref then err
return true)
(λ rref => do
for c in (← rref.get).children do
match (← c.get).parent? with
| some parent =>
if ← notM $ parent.ptrEq rref then err
| none =>
err
return true)
(λ cref => do
for c in (← cref.get).goals do
if ← notM $ (← c.get).parent.ptrEq cref then err
return true)
(TreeRef.mvarCluster root)
where
err := throwError "{Check.tree.name}: search tree is not properly linked."
private def mvarClusterId (c : MVarCluster) : BaseIO String :=
match c.parent? with
| some parentRef => return s!"mvar cluster of rapp {(← parentRef.get).id}"
| none => return s!"root mvar cluster"
def checkState (root : MVarClusterRef) : CoreM Unit :=
postTraverseDown
(λ gref => do
let g ← gref.get
go s!"goal {g.id}" (← g.stateNoCache) g.state)
(λ rref => do
let r ← rref.get
go s!"rapp {r.id}" (← r.stateNoCache) r.state)
(λ cref => do
let c ← cref.get
go (← mvarClusterId c) (← c.stateNoCache) c.state)
(TreeRef.mvarCluster root)
where
@[inline]
go {σ} [BEq σ] [ToString σ] (id : String) (expected actual : σ) :
CoreM Unit := do
if expected != actual then throwError
"{Check.tree.name}: {id} has wrong state: marked as '{actual}' but should be '{expected}'."
def checkIrrelevance (root : MVarClusterRef) : CoreM Unit :=
preTraverseDown
(λ gref => do
let g ← gref.get
go s!"goal {g.id}" (← g.isIrrelevantNoCache) g.isIrrelevant)
(λ rref => do
let r ← rref.get
go s!"rapp {r.id}" (← r.isIrrelevantNoCache) r.isIrrelevant)
(λ cref => do
let c ← cref.get
go (← mvarClusterId c) (← c.isIrrelevantNoCache) c.isIrrelevant)
(TreeRef.mvarCluster root)
where
@[inline]
go (id : String) (expected actual : Bool) : CoreM Bool := do
match actual, expected with
| true, false => throwError
"{Check.tree.name}: {id} is marked as irrelevant, but is not irrelevant."
| false, true => throwError
"{Check.tree.name}: {id} is marked as not irrelevant, but is irrelevant."
| _, _ => return true
def checkMVars (root : MVarClusterRef) (rootMetaState : Meta.SavedState) :
MetaM Unit :=
preTraverseDown
(λ gref => do
let g ← gref.get
checkGoalMVars g
return true)
(λ rref => do
let r ← rref.get
checkAssignedMVars r
checkDroppedMVars r
return true)
(λ _ => return true)
(TreeRef.mvarCluster root)
where
getParentInfo (r : Rapp) : CoreM (MVarId × Meta.SavedState) := do
let some res := (← r.parent.get).postNormGoalAndMetaState? | throwError
"{Check.tree.name}: expected parent goal of rapp {r.id} to be normalised (but not proven by normalisation)."
return res
checkAssignedMVars (r : Rapp) : MetaM Unit := do
let (parentPostNormGoal, parentPostNormState) ← getParentInfo r
let actualAssigned :=
(← getAssignedExprMVars parentPostNormState r.metaState).erase
parentPostNormGoal
unless actualAssigned.equalSet r.assignedMVars.toArray do throwError
"{Check.tree.name}: rapp {r.id} reports incorrect assigned mvars.\n reported: {r.assignedMVars.toArray.map (·.name)}\n actual: {actualAssigned.map (·.name)}"
checkDroppedMVars (r : Rapp) : MetaM Unit := do
let droppableMVars :=
(← r.parent.get).mvars ++ r.introducedMVars |>.toArray
let mut nonDroppedMVars := Std.HashSet.ofArray r.assignedMVars.toArray
for cref in r.children do
for gref in (← cref.get).goals do
let g ← gref.get
nonDroppedMVars := nonDroppedMVars.insert g.preNormGoal
nonDroppedMVars := nonDroppedMVars.insertMany g.mvars
if droppableMVars.any (! nonDroppedMVars.contains ·) then throwError
"{Check.tree.name}: rapp {r.id} dropped mvars.\n mvars introduced or present in parent: {droppableMVars.map (·.name)}\n mvars assigned or present in subgoals:\n {nonDroppedMVars.toArray.map (·.name)}"
checkGoalMVars (g : Goal) : MetaM Unit := do
checkNormMVars g
let actualPreNormMVars ← g.runMetaMInParentState'
g.preNormGoal.getMVarDependencies
let expectedMVars := Std.HashSet.ofArray g.mvars.toArray
unless actualPreNormMVars == expectedMVars do throwError
"{Check.tree.name}: goal {g.id} reports incorrect unassigned mvars.\n reported: {g.mvars.toArray.map (·.name)}\n actual: {actualPreNormMVars.toArray.map (·.name)}"
checkNormMVars (g : Goal) : MetaM Unit := do
let go (parentMetaState postMetaState : Meta.SavedState)
(introduced : Array MVarId) : MetaM Unit := do
unless introduced.isEmpty do throwError
"{Check.tree.name}: normalisation of goal {g.id} introduced additional metavariables:{indentD $ toMessageData $ introduced.map (·.name)}"
let assigned :=
(← getAssignedExprMVars parentMetaState postMetaState).erase
g.preNormGoal
unless assigned.isEmpty do throwError
"{Check.tree.name}: normalisation of goal {g.id} assigned metavariables:{indentD $ toMessageData $ assigned.map (·.name)}"
match g.normalizationState with
| .notNormal => return
| .provenByNormalization postMetaState .. =>
let parentMetaState ← g.parentMetaState rootMetaState
let introduced ← getIntroducedExprMVars parentMetaState postMetaState
go parentMetaState postMetaState introduced
| .normal postGoal postMetaState .. =>
let parentMetaState ← g.parentMetaState rootMetaState
let introduced :=
(← getIntroducedExprMVars parentMetaState postMetaState).erase
postGoal
go parentMetaState postMetaState introduced
-- Check that each mvar ocurring in a goal is either present in the root meta
-- state or has an introducing rapp.
def checkIntroducedMVars (root : MVarClusterRef)
(rootMetaState : Meta.SavedState) : MetaM Unit := do
let declaredAtRoot : Std.HashSet MVarId :=
rootMetaState.meta.mctx.decls.foldl (init := ∅) λ acc mvarId _ =>
acc.insert mvarId
let introducedMVarsRef ← IO.mkRef declaredAtRoot
preTraverseDown
(λ gref => do
for mvarId in (← gref.get).mvars do
unless (← introducedMVarsRef.get).contains mvarId do
throwError "{Check.tree.name}: at goal {(← gref.get).id}: no introducing rapp found for mvarId {mvarId.name}"
return true)
(λ rref => do
let introduced := (← rref.get).introducedMVars
introducedMVarsRef.modify λ mvars => mvars.insertMany introduced
return true)
(λ _ => return true)
(.mvarCluster root)
def checkInvariants (root : MVarClusterRef) (rootMetaState : Meta.SavedState) :
MetaM Unit := do
root.checkAcyclic
root.checkConsistentParentChildLinks
root.checkIds
root.checkState
root.checkIrrelevance
root.checkMVars rootMetaState
root.checkIntroducedMVars rootMetaState
def checkInvariantsIfEnabled (root : MVarClusterRef)
(rootMetaState : Meta.SavedState) : MetaM Unit := do
if ← Check.tree.isEnabled then
root.checkInvariants rootMetaState
end MVarClusterRef
def checkInvariantsIfEnabled : TreeM Unit := do
(← getRootMVarCluster).checkInvariantsIfEnabled (← getRootMetaState)
end Aesop |
.lake/packages/aesop/Aesop/Tree/Data.lean | module
public import Aesop.Tree.Data.ForwardRuleMatches
public import Aesop.Tree.UnsafeQueue
public import Aesop.Forward.State
import Aesop.Constants
import Batteries.Data.Array.Basic
public section
open Lean
open Lean.Meta
open Std
private def Bool.toYesNo : Bool → Format
| true => "yes"
| false => "no "
namespace Aesop
/-! ## Node IDs -/
-- TODO Change to USize?
structure GoalId where
toNat : Nat
deriving Inhabited, DecidableEq
namespace GoalId
protected def zero : GoalId :=
⟨0⟩
protected def one : GoalId :=
⟨1⟩
protected def succ : GoalId → GoalId
| ⟨n⟩ => ⟨n + 1⟩
def dummy : GoalId :=
⟨1000000000000000⟩
instance : LT GoalId where
lt n m := n.toNat < m.toNat
instance : DecidableRel (α := GoalId) (· < ·) :=
λ n m => inferInstanceAs (Decidable (n.toNat < m.toNat))
instance : ToString GoalId where
toString n := toString n.toNat
instance : Hashable GoalId where
hash n := hash n.toNat
end GoalId
/-! ## Rule Application IDs -/
structure RappId where
toNat : Nat
deriving Inhabited, DecidableEq
namespace RappId
protected def zero : RappId :=
⟨0⟩
protected def succ : RappId → RappId
| ⟨n⟩ => ⟨n + 1⟩
protected def one : RappId :=
⟨1⟩
def dummy : RappId :=
⟨1000000000000000⟩
instance : LT RappId where
lt n m := n.toNat < m.toNat
instance : DecidableRel (α := RappId) (· < ·) :=
λ n m => inferInstanceAs $ Decidable (n.toNat < m.toNat)
instance : ToString RappId where
toString n := toString n.toNat
instance : Hashable RappId where
hash n := hash n.toNat
end RappId
/-! ## Iterations -/
@[expose] def Iteration := Nat
deriving Inhabited
namespace Iteration
@[inline]
private def toNat : Iteration → Nat :=
id
@[inline]
private def ofNat : Nat → Iteration :=
id
@[inline]
protected def one : Iteration :=
ofNat 1
@[inline]
protected def succ (i : Iteration) : Iteration :=
ofNat $ i.toNat + 1
protected def none : Iteration :=
ofNat 0
instance : DecidableEq Iteration :=
inferInstanceAs $ DecidableEq Nat
instance : ToString Iteration :=
inferInstanceAs $ ToString Nat
instance : LT Iteration :=
inferInstanceAs $ LT Nat
instance : LE Iteration :=
inferInstanceAs $ LE Nat
instance : DecidableRel (α := Iteration) (· < ·) :=
inferInstanceAs $ DecidableRel (α := Nat) (· < ·)
instance : DecidableRel (α := Iteration) (· ≤ ·) :=
inferInstanceAs $ DecidableRel (α := Nat) (· ≤ ·)
end Iteration
/-! ## The Tree -/
/--
At each point during the search, every node of the tree (goal, rapp or mvar
cluster) is in one of these states:
- `proven`: the node is proven.
- `unprovable`: the node is unprovable, i.e. it will never be proven regardless
of any future expansions that might be performed.
- `unknown`: neither of the above.
Every node starts in the `unknown` state and may later become either `proven` or
`unprovable`. After this, the state does not change any more.
-/
inductive NodeState
| unknown
| proven
| unprovable
deriving Inhabited, BEq
namespace NodeState
instance : ToString NodeState where
toString
| unknown => "unknown"
| proven => "proven"
| unprovable => "unprovable"
def isUnknown : NodeState → Bool
| unknown => true
| _ => false
def isProven : NodeState → Bool
| proven => true
| _ => false
def isUnprovable : NodeState → Bool
| unprovable => true
| _ => false
def isIrrelevant : NodeState → Bool
| proven => true
| unprovable => true
| unknown => false
def toEmoji : NodeState → String
| proven => nodeProvedEmoji
| unprovable => nodeUnprovableEmoji
| unknown => nodeUnknownEmoji
end NodeState
/--
A refinement of the `NodeState`, distinguishing between goals proven during
normalisation and goals proven by a child rule application.
-/
inductive GoalState
| unknown
| provenByRuleApplication
| provenByNormalization
| unprovable
deriving Inhabited, BEq
namespace GoalState
instance : ToString GoalState where
toString
| unknown => "unknown"
| provenByRuleApplication => "provenByRuleApplication"
| provenByNormalization => "provenByNormalization"
| unprovable => "unprovable"
def isProvenByRuleApplication : GoalState → Bool
| provenByRuleApplication => true
| _ => false
def isProvenByNormalization : GoalState → Bool
| provenByNormalization => true
| _ => false
def isProven : GoalState → Bool
| provenByRuleApplication => true
| provenByNormalization => true
| _ => false
def isUnprovable : GoalState → Bool
| unprovable => true
| _ => false
def isUnknown : GoalState → Bool
| unknown => true
| _ => false
def toNodeState : GoalState → NodeState
| unknown => NodeState.unknown
| provenByRuleApplication => NodeState.proven
| provenByNormalization => NodeState.proven
| unprovable => NodeState.unprovable
def isIrrelevant (s : GoalState) : Bool :=
s.toNodeState.isIrrelevant
def toEmoji : GoalState → String
| unknown => nodeUnknownEmoji
| provenByRuleApplication | provenByNormalization => nodeProvedEmoji
| unprovable => nodeUnprovableEmoji
end GoalState
inductive NormalizationState
| notNormal
| normal (postGoal : MVarId) (postState : Meta.SavedState)
(script : Array (DisplayRuleName × Option (Array Script.LazyStep)))
| provenByNormalization (postState : Meta.SavedState)
(script : Array (DisplayRuleName × Option (Array Script.LazyStep)))
deriving Inhabited
namespace NormalizationState
def isNormal : NormalizationState → Bool
| notNormal => false
| normal .. => true
| provenByNormalization .. => true
def isProvenByNormalization : NormalizationState → Bool
| notNormal .. => false
| normal .. => false
| provenByNormalization .. => true
def normalizedGoal? : NormalizationState → Option MVarId
| notNormal .. | provenByNormalization .. => none
| normal (postGoal := g) .. => g
end NormalizationState
/--
A goal `G` can be added to the tree for three reasons:
1. `G` was produced by its parent rule as a subgoal. This is the most common
reason.
2. `G` was copied because it contains some metavariables which were assigned by
its parent rule. In this case, we record goal of which `G` is a copy. We also
record the representative of the equivalence class of goals which are copies
of each other. E.g. if goal `1` is copied to goal `2` and goal `2` is copied
to goal `3`, they are all part of the equivalence class with representative
`1`.
-/
inductive GoalOrigin
| subgoal
| copied («from» : GoalId) (rep : GoalId)
| droppedMVar
deriving Inhabited
namespace GoalOrigin
def originalGoalId? : GoalOrigin → Option GoalId
| copied _ rep => some rep
| _ => none
protected def toString : GoalOrigin → String
| subgoal => "subgoal"
| copied «from» rep => s!"copy of {«from»}, originally {«rep»}"
| droppedMVar => "dropped mvar"
end GoalOrigin
-- TODO docs
structure GoalData (Rapp MVarCluster : Type) : Type where
id : GoalId
parent : IO.Ref MVarCluster
children : Array (IO.Ref Rapp)
origin : GoalOrigin
depth : Nat
state : GoalState
isIrrelevant : Bool
isForcedUnprovable : Bool
-- True if the goal was designated unprovable 'by force'. This happens when
-- we reach the search depth limit. Any goal beyond this limit becomes
-- irrelevant and therefore unprovable.
preNormGoal : MVarId
-- The goal before normalisation. The goal after normalisation (if any) is
-- contained in the `normalizationState`.
normalizationState : NormalizationState
mvars : UnorderedArraySet MVarId
-- Unassigned expression metavariables that appear in the goal, i.e. that
-- appear in the target or hypotheses of `goal` when interpreted in the
-- metavar context of `parent?` (or in the global metavar context if
-- `parent? = none`).
/-- The forward state reflects the local context of the current goal. Before
normalisation, this is the local context of `preNormGoal`; after normalisation,
it is the local context of the post-normalisation goal (unless normalisation
solved the goal, in which case the forward state is undetermined). -/
forwardState : ForwardState
/-- Complete matches of forward rules for the current goal (in the same sense
as above). -/
forwardRuleMatches : ForwardRuleMatches
successProbability : Percent
addedInIteration : Iteration
lastExpandedInIteration : Iteration
-- Iteration 0 means the node has never been expanded.
unsafeRulesSelected : Bool
unsafeQueue : UnsafeQueue
failedRapps : Array RegularRule
deriving Nonempty
structure MVarClusterData (Goal Rapp : Type) : Type where
parent? : Option (IO.Ref Rapp)
goals : Array (IO.Ref Goal)
isIrrelevant : Bool
state : NodeState
deriving Inhabited
structure RappData (Goal MVarCluster : Type) : Type where
id : RappId
parent : IO.Ref Goal
children : Array (IO.Ref MVarCluster)
state : NodeState
isIrrelevant : Bool
appliedRule : RegularRule
scriptSteps? : Option (Array Script.LazyStep)
originalSubgoals : Array MVarId
successProbability : Percent
metaState : Meta.SavedState
-- This is the state *after* the rule was successfully applied, so the goal
-- mvar is assigned in this state.
introducedMVars : UnorderedArraySet MVarId
-- Unassigned expression mvars introduced by this rapp. These are exactly
-- the unassigned expr mvars that are declared in `metaState`, but not in
-- the meta state of the parent rapp of `parent`.
assignedMVars : UnorderedArraySet MVarId
-- Expression mvars that were previously unassigned but were assigned by
-- this rapp. These are exactly the expr mvars that (a) are declared and
-- unassigned in the meta state of the parent rapp of `parent` and (b) are
-- assigned in `metaState`.
deriving Nonempty
mutual
unsafe inductive GoalUnsafe
| mk (d : GoalData RappUnsafe MVarClusterUnsafe)
unsafe inductive MVarClusterUnsafe
| mk (d : MVarClusterData GoalUnsafe RappUnsafe)
unsafe inductive RappUnsafe
| mk (d : RappData GoalUnsafe MVarClusterUnsafe)
end
structure TreeSpec where
Goal : Type
Rapp : Type
MVarCluster : Type
introGoal : GoalData Rapp MVarCluster → Goal
elimGoal : Goal → GoalData Rapp MVarCluster
introRapp : RappData Goal MVarCluster → Rapp
elimRapp : Rapp → RappData Goal MVarCluster
introMVarCluster : MVarClusterData Goal Rapp → MVarCluster
elimMVarCluster : MVarCluster → MVarClusterData Goal Rapp
instance : Nonempty TreeSpec := by
refine' ⟨{ Goal := Unit, Rapp := Unit, MVarCluster := Unit, .. }⟩
<;> exact Classical.ofNonempty
unsafe def treeImpl : TreeSpec where
Goal := GoalUnsafe
Rapp := RappUnsafe
MVarCluster := MVarClusterUnsafe
introGoal := GoalUnsafe.mk
elimGoal | GoalUnsafe.mk x => x
introRapp := RappUnsafe.mk
elimRapp | RappUnsafe.mk x => x
introMVarCluster := MVarClusterUnsafe.mk
elimMVarCluster | MVarClusterUnsafe.mk x => x
@[implemented_by treeImpl]
opaque tree : TreeSpec
def Goal := tree.Goal
def Rapp := tree.Rapp
def MVarCluster := tree.MVarCluster
abbrev GoalRef := IO.Ref Goal
abbrev RappRef := IO.Ref Rapp
abbrev MVarClusterRef := IO.Ref MVarCluster
namespace MVarCluster
@[inline]
protected def mk : MVarClusterData Goal Rapp → MVarCluster :=
tree.introMVarCluster
instance : Nonempty MVarCluster :=
⟨MVarCluster.mk Classical.ofNonempty⟩
@[inline]
protected def elim : MVarCluster → MVarClusterData Goal Rapp :=
tree.elimMVarCluster
@[inline]
protected def modify (f : MVarClusterData Goal Rapp → MVarClusterData Goal Rapp)
(c : MVarCluster) : MVarCluster :=
MVarCluster.mk $ f $ c.elim
@[inline]
def parent? (c : MVarCluster) : Option RappRef :=
c.elim.parent?
@[inline]
def setParent (parent? : Option RappRef) (c : MVarCluster) : MVarCluster :=
c.modify λ c => { c with parent? }
@[inline]
def goals (c : MVarCluster) : Array GoalRef :=
c.elim.goals
@[inline]
def setGoals (goals : Array GoalRef) (c : MVarCluster) : MVarCluster :=
c.modify λ c => { c with goals }
@[inline]
def isIrrelevant (c : MVarCluster) : Bool :=
c.elim.isIrrelevant
@[inline]
def setIsIrrelevant (isIrrelevant : Bool) (c : MVarCluster) : MVarCluster :=
c.modify λ c => { c with isIrrelevant }
@[inline]
def state (c : MVarCluster) : NodeState :=
c.elim.state
@[inline]
def setState (state : NodeState) (c : MVarCluster) : MVarCluster :=
c.modify λ c => { c with state }
end MVarCluster
namespace Goal
@[inline]
protected def mk : GoalData Rapp MVarCluster → Goal :=
tree.introGoal
@[inline]
protected def elim : Goal → GoalData Rapp MVarCluster :=
tree.elimGoal
@[inline]
protected def modify (f : GoalData Rapp MVarCluster → GoalData Rapp MVarCluster)
(g : Goal) : Goal :=
Goal.mk $ f $ g.elim
@[inline]
def id (g : Goal) : GoalId :=
g.elim.id
@[inline]
def parent (g : Goal) : MVarClusterRef :=
g.elim.parent
@[inline]
def children (g : Goal) : Array RappRef :=
g.elim.children
@[inline]
def origin (g : Goal) : GoalOrigin :=
g.elim.origin
@[inline]
def depth (g : Goal) : Nat :=
g.elim.depth
@[inline]
def state (g : Goal) : GoalState :=
g.elim.state
@[inline]
def isIrrelevant (g : Goal) : Bool :=
g.elim.isIrrelevant
@[inline]
def isForcedUnprovable (g : Goal) : Bool :=
g.elim.isForcedUnprovable
@[inline]
def preNormGoal (g : Goal) : MVarId :=
g.elim.preNormGoal
@[inline]
def normalizationState (g : Goal) : NormalizationState :=
g.elim.normalizationState
@[inline]
def mvars (g : Goal) : UnorderedArraySet MVarId :=
g.elim.mvars
@[inline]
def forwardState (g : Goal) : ForwardState :=
g.elim.forwardState
@[inline]
def forwardRuleMatches (g : Goal) : ForwardRuleMatches :=
g.elim.forwardRuleMatches
@[inline]
def successProbability (g : Goal) : Percent :=
g.elim.successProbability
@[inline]
def addedInIteration (g : Goal) : Iteration :=
g.elim.addedInIteration
@[inline]
def lastExpandedInIteration (g : Goal) : Iteration :=
g.elim.lastExpandedInIteration
@[inline]
def failedRapps (g : Goal) : Array RegularRule :=
g.elim.failedRapps
@[inline]
def unsafeRulesSelected (g : Goal) : Bool :=
g.elim.unsafeRulesSelected
@[inline]
def unsafeQueue (g : Goal) : UnsafeQueue :=
g.elim.unsafeQueue
@[inline]
def unsafeQueue? (g : Goal) : Option UnsafeQueue :=
if g.unsafeRulesSelected then some g.unsafeQueue else none
@[inline]
def setId (id : GoalId) (g : Goal) : Goal :=
g.modify λ g => { g with id }
@[inline]
def setParent (parent : MVarClusterRef) (g : Goal) : Goal :=
g.modify λ g => { g with parent }
@[inline]
def setChildren (children : Array RappRef) (g : Goal) : Goal :=
g.modify λ g => { g with children }
@[inline]
def setOrigin (origin : GoalOrigin) (g : Goal) : Goal :=
g.modify λ g => { g with origin }
@[inline]
def setDepth (depth : Nat) (g : Goal) : Goal :=
g.modify λ g => { g with depth }
@[inline]
def setIsIrrelevant (isIrrelevant : Bool) (g : Goal) : Goal :=
g.modify λ g => { g with isIrrelevant }
@[inline]
def setIsForcedUnprovable (isForcedUnprovable : Bool) (g : Goal) : Goal :=
g.modify λ g => { g with isForcedUnprovable }
@[inline]
def setPreNormGoal (preNormGoal : MVarId) (g : Goal) : Goal :=
g.modify λ g => { g with preNormGoal }
@[inline]
def setNormalizationState (normalizationState : NormalizationState) (g : Goal) :
Goal :=
g.modify λ g => { g with normalizationState }
@[inline]
def setMVars (mvars : UnorderedArraySet MVarId) (g : Goal) : Goal :=
g.modify λ g => { g with mvars }
@[inline]
def setForwardState (forwardState : ForwardState) (g : Goal) : Goal :=
g.modify λ g => { g with forwardState }
@[inline]
def setForwardRuleMatches (forwardRuleMatches : ForwardRuleMatches) (g : Goal) :
Goal :=
g.modify λ g => { g with forwardRuleMatches }
@[inline]
def setSuccessProbability (successProbability : Percent) (g : Goal) : Goal :=
g.modify λ g => { g with successProbability }
@[inline]
def setAddedInIteration (addedInIteration : Iteration) (g : Goal) : Goal :=
g.modify λ g => { g with addedInIteration }
@[inline]
def setLastExpandedInIteration (lastExpandedInIteration : Iteration) (g : Goal) :
Goal :=
g.modify λ g => { g with lastExpandedInIteration }
@[inline]
def setUnsafeRulesSelected (unsafeRulesSelected : Bool) (g : Goal) : Goal :=
g.modify λ g => { g with unsafeRulesSelected }
@[inline]
def setUnsafeQueue (unsafeQueue : UnsafeQueue) (g : Goal) : Goal :=
g.modify λ g => { g with unsafeQueue }
@[inline]
def setState (state : GoalState) (g : Goal) : Goal :=
g.modify λ g => { g with state }
@[inline]
def setFailedRapps (failedRapps : Array RegularRule) (g : Goal) : Goal :=
g.modify λ g => { g with failedRapps }
instance : Nonempty Goal :=
⟨Goal.mk Classical.ofNonempty⟩
instance : BEq Goal where
beq g₁ g₂ := g₁.id == g₂.id
instance : Hashable Goal where
hash g := hash g.id
end Goal
namespace Rapp
@[inline]
protected def mk : RappData Goal MVarCluster → Rapp :=
tree.introRapp
@[inline]
protected def elim : Rapp → RappData Goal MVarCluster :=
tree.elimRapp
@[inline]
protected def modify (f : RappData Goal MVarCluster → RappData Goal MVarCluster)
(r : Rapp) : Rapp :=
Rapp.mk $ f $ r.elim
@[inline]
def id (r : Rapp) : RappId :=
r.elim.id
@[inline]
def parent (r : Rapp) : GoalRef :=
r.elim.parent
@[inline]
def children (r : Rapp) : Array MVarClusterRef :=
r.elim.children
@[inline]
def state (r : Rapp) : NodeState :=
r.elim.state
@[inline]
def isIrrelevant (r : Rapp) : Bool :=
r.elim.isIrrelevant
@[inline]
def appliedRule (r : Rapp) : RegularRule :=
r.elim.appliedRule
@[inline]
def scriptSteps? (r : Rapp) : Option (Array Script.LazyStep) :=
r.elim.scriptSteps?
@[inline]
def originalSubgoals (r : Rapp) : Array MVarId :=
r.elim.originalSubgoals
@[inline]
def successProbability (r : Rapp) : Percent :=
r.elim.successProbability
@[inline]
def metaState (r : Rapp) : Meta.SavedState :=
r.elim.metaState
@[inline]
def introducedMVars (r : Rapp) : UnorderedArraySet MVarId :=
r.elim.introducedMVars
@[inline]
def assignedMVars (r : Rapp) : UnorderedArraySet MVarId :=
r.elim.assignedMVars
@[inline]
def setId (id : RappId) (r : Rapp) : Rapp :=
r.modify λ r => { r with id }
@[inline]
def setParent (parent : GoalRef) (r : Rapp) : Rapp :=
r.modify λ r => { r with parent }
@[inline]
def setChildren (children : Array MVarClusterRef) (r : Rapp) : Rapp :=
r.modify λ r => { r with children }
@[inline]
def setState (state : NodeState) (r : Rapp) : Rapp :=
r.modify λ r => { r with state }
@[inline]
def setIsIrrelevant (isIrrelevant : Bool) (r : Rapp) : Rapp :=
r.modify λ r => { r with isIrrelevant }
@[inline]
def setAppliedRule (appliedRule : RegularRule) (r : Rapp) : Rapp :=
r.modify λ r => { r with appliedRule }
@[inline]
def setScriptSteps? (scriptSteps? : Option (Array Script.LazyStep)) (r : Rapp) :
Rapp :=
r.modify λ r => { r with scriptSteps? }
@[inline]
def setOriginalSubgoals (originalSubgoals : Array MVarId)
(r : Rapp) : Rapp :=
r.modify λ r => { r with originalSubgoals }
@[inline]
def setSuccessProbability (successProbability : Percent) (r : Rapp) : Rapp :=
r.modify λ r => { r with successProbability }
@[inline]
def setMetaState (metaState : Meta.SavedState) (r : Rapp) : Rapp :=
r.modify λ r => { r with metaState }
@[inline]
def setIntroducedMVars (introducedMVars : UnorderedArraySet MVarId)
(r : Rapp) : Rapp :=
r.modify λ r => { r with introducedMVars }
@[inline]
def setAssignedMVars (assignedMVars : UnorderedArraySet MVarId) (r : Rapp) :
Rapp :=
r.modify λ r => { r with assignedMVars }
instance : Nonempty Rapp :=
⟨Rapp.mk Classical.ofNonempty⟩
instance : BEq Rapp where
beq r₁ r₂ := r₁.id == r₂.id
instance : Hashable Rapp where
hash r := hash r.id
end Rapp
/-! ## Miscellaneous Queries -/
def Rapp.isSafe (r : Rapp) : Bool :=
r.appliedRule.isSafe && r.assignedMVars.isEmpty
-- During expansion, we postpone safe rules that assign metavariables and
-- treat them as unsafe.
namespace Goal
@[inline]
def postNormGoalAndMetaState? (g : Goal) : Option (MVarId × Meta.SavedState) :=
match g.normalizationState with
| .normal postGoal postState _ => some (postGoal, postState)
| _ => none
def postNormGoal? (g : Goal) : Option MVarId :=
g.postNormGoalAndMetaState?.map (·.fst)
def currentGoal (g : Goal) : MVarId :=
g.postNormGoal?.getD g.preNormGoal
def parentRapp? (g : Goal) : BaseIO (Option RappRef) :=
return (← g.parent.get).parent?
def parentMetaState (g : Goal) (rootMetaState : Meta.SavedState) :
BaseIO Meta.SavedState := do
match ← g.parentRapp? with
| none => return rootMetaState
| some parent => return (← parent.get).metaState
def currentGoalAndMetaState (g : Goal) (rootMetaState : Meta.SavedState) :
MetaM (MVarId × Meta.SavedState) :=
match g.postNormGoalAndMetaState? with
| some x => return x
| none => return (g.preNormGoal, ← g.parentMetaState rootMetaState)
def safeRapps (g : Goal) : BaseIO (Array RappRef) :=
g.children.filterM λ rref => return (← rref.get).isSafe
def hasSafeRapp (g : Goal) : BaseIO Bool :=
g.children.anyM λ rref => return (← rref.get).isSafe
def isUnsafeExhausted (g : Goal) : Bool :=
g.unsafeRulesSelected && g.unsafeQueue.isEmpty
def isExhausted (g : Goal) : BaseIO Bool :=
pure g.isUnsafeExhausted <||> g.hasSafeRapp
def isActive (g : Goal) : BaseIO Bool :=
return ! (← pure g.isIrrelevant <||> g.isExhausted)
def hasProvableRapp (g : Goal) : BaseIO Bool :=
g.children.anyM λ r => return ! (← r.get).state.isUnprovable
def firstProvenRapp? (g : Goal) : BaseIO (Option RappRef) :=
g.children.findSomeM? λ rref =>
return if (← rref.get).state.isProven then some rref else none
def hasMVar (g : Goal) : Bool :=
! g.mvars.isEmpty
def priority (g : Goal) : Percent :=
g.successProbability * unificationGoalPenalty ^ g.mvars.size
def isNormal (g : Goal) : Bool :=
g.normalizationState.isNormal
def originalGoalId (g : Goal) : GoalId :=
g.origin.originalGoalId?.getD g.id
def isRoot (g : Goal) : BaseIO Bool :=
return (← g.parentRapp?).isNone
end Goal
namespace Rapp
def introducesMVar (r : Rapp) : Bool :=
! r.introducedMVars.isEmpty
def parentPostNormMetaState (r : Rapp) (rootMetaState : Meta.SavedState) :
BaseIO Meta.SavedState := do
(← r.parent.get).parentMetaState rootMetaState
def foldSubgoalsM [Monad m] [MonadLiftT (ST IO.RealWorld) m] (init : σ)
(f : σ → GoalRef → m σ) (r : Rapp) : m σ :=
r.children.foldlM (init := init) λ s cref => do
(← cref.get).goals.foldlM (init := s) f
def forSubgoalsM [Monad m] [MonadLiftT (ST IO.RealWorld) m]
(f : GoalRef → m Unit) (r : Rapp) : m Unit :=
r.children.forM λ cref => do (← cref.get).goals.forM f
def subgoals [Monad m] [MonadLiftT (ST IO.RealWorld) m] (r : Rapp) :
m (Array GoalRef) :=
r.foldSubgoalsM (init := #[]) λ subgoals gref => return subgoals.push gref
def depth (r : Rapp) : BaseIO Nat :=
return (← r.parent.get).depth
end Rapp
namespace MVarCluster
def provenGoal? (c : MVarCluster) : BaseIO (Option GoalRef) :=
c.goals.findM? λ gref => return (← gref.get).state.isProven
end MVarCluster
namespace RappRef
/-- Get a `DeclNameGenerator` for auxiliary declarations that can be used by
children of this rapp. Successive calls to this function return
`DeclNameGenerators` that are guaranteed to generate distinct names. -/
def getChildAuxDeclNameGenerator (r : RappRef) : BaseIO DeclNameGenerator := do
r.modifyGet λ r =>
let (child, parent) := r.metaState.core.auxDeclNGen.mkChild
let r := r.setMetaState $ { r.metaState with core.auxDeclNGen := parent }
(child, r)
end RappRef |
.lake/packages/aesop/Aesop/Tree/ExtractProof.lean | module
public import Aesop.Tree.TreeM
import Batteries.Lean.Meta.SavedState
public section
open Lean
open Lean.Meta
/-
To extract a proof, we start in the `MetaM` state in which Aesop was called.
Then we iterate through the proven part of the tree, top to bottom, 'replaying'
the mvar assignments that were performed during the search. This means:
- For each goal `g`, we assign `g`'s pre-norm mvar to the term generated by
normalisation. If `g` was proved by normalisation, we are done. Otherwise,
we find the proving child rapp of `g` and descend into it.
- For each rapp `r`, we assign the post-norm mvar of `r`'s parent goal to the
term generated by `r`. Additionally, we assign each mvar assigned by `r`.
Then we descend into `r`'s children.
- For each mvar cluster `c`, we find the proven goal of `c` and descend into it.
When we assign a metavariable `m`, we must take some care:
- We must first declare `m` if it is not already declared.
- We must assign (and declare) any metavariables on which the assignment of `m`
depends. We cannot assume that these assignments are meta-free, since they may
contain metavariables that were only assigned later during the search. We
also cannot assume that these are the *only* metavariables occurring in the
assignments, since they may additionally contain delayed-assigned
metavariables which depend on the unassigned metavariables.
We also replay environment modifications -- e.g., auxiliary declarations added
by a tactic -- in a similar fashion. To do this, we use
`Environment.replayConsts`, so newly added constants are sent to the kernel
again and environment extensions get a chance to replay their changes with
`replay?`.
If the root goal is not proven, we extract the goals after safe rule
applications. This means we proceed as above, but stop as soon as we reach the
first non-safe rule application. If a goal has multiple safe rule applications,
we arbitrarily choose the first one. (This should happen rarely in practice.)
-/
namespace Aesop
local macro "throwPRError " s:interpolatedStr(term) : term =>
`(throwError m!"aesop: internal error during proof reconstruction: " ++ m!$s)
-- ## Copying Declarations
private def copyEnvModifications (oldEnv newEnv : Environment) : CoreM Unit := do
setEnv $ ← (← getEnv).replayConsts oldEnv newEnv (skipExisting := true)
-- ## Copying Metavariables
private partial def copyExprMVar (s : Meta.SavedState) (mvarId : MVarId) :
MetaM Unit := do
if ← mvarId.isAssignedOrDelayedAssigned then
return
unless ← mvarId.isDeclared do
let (decl, depMVarIds) ← s.runMetaM' $ do
mvarId.instantiateMVars
let decl ← mvarId.getDecl
let depMVarIds ← mvarId.getMVarDependencies (includeDelayed := true)
aesop_trace[extraction] "declare ?{mvarId.name}:{indentD $ toMessageData mvarId}"
pure (decl, depMVarIds)
modifyMCtx λ mctx => { mctx with decls := mctx.decls.insert mvarId decl }
for depMVarId in depMVarIds do
copyExprMVar s depMVarId
let assignment? ← s.runMetaM' do
if let (some e) ← getExprMVarAssignment? mvarId then
return some $ Sum.inl $ ← instantiateMVars e
else if let (some d) ← getDelayedMVarAssignment? mvarId then
return some $ Sum.inr d
else
return none
match assignment? with
| some (Sum.inl e) =>
for mvarId in ← getMVars e do
copyExprMVar s mvarId
aesop_trace[extraction] "assign ?{mvarId.name} := {toString e}"
mvarId.assign e
| some (Sum.inr d) =>
for mvarId in ← getMVars (mkMVar d.mvarIdPending) do
copyExprMVar s mvarId
aesop_trace[extraction] "dassign ?{mvarId.name} := {d.fvars} => {d.mvarIdPending.name}"
assignDelayedMVar mvarId d.fvars d.mvarIdPending
| none => return
-- ## Main Functions
private def visitGoal (parentEnv : Environment) (g : Goal) :
MetaM (Option (MVarId × Array RappRef × Environment)) := do
aesop_trace[extraction] "visiting G{g.id}"
match g.normalizationState with
| NormalizationState.notNormal => throwPRError
"goal {g.id} was not normalised."
| NormalizationState.normal postNormGoal postState _ =>
copyEnvModifications parentEnv postState.core.env
copyExprMVar postState g.preNormGoal
return (postNormGoal, g.children, postState.core.env)
| NormalizationState.provenByNormalization postState _ =>
copyEnvModifications parentEnv postState.core.env
copyExprMVar postState g.preNormGoal
return none
private def visitRapp (parentEnv : Environment) (parentGoal : MVarId) (r : Rapp) :
MetaM (Array MVarClusterRef × Environment) := do
aesop_trace[extraction] "visiting R{r.id}"
let newEnv := r.metaState.core.env
copyEnvModifications parentEnv newEnv
copyExprMVar r.metaState parentGoal
for m in r.assignedMVars do
copyExprMVar r.metaState m
return (r.children, newEnv)
mutual
private partial def extractProofGoal (parentEnv : Environment) (g : Goal) :
MetaM Unit := do
let (some (postNormGoal, children, postNormEnv)) ← visitGoal parentEnv g
| return
let rref? ← children.findM? λ rref => return (← rref.get).state.isProven
let (some rref) := rref? | throwPRError
"goal {g.id} does not have a proven rapp."
extractProofRapp postNormEnv postNormGoal (← rref.get)
private partial def extractProofRapp (parentEnv : Environment)
(parentGoal : MVarId) (r : Rapp) : MetaM Unit := do
let (children, newEnv) ← visitRapp parentEnv parentGoal r
children.forM λ cref => do extractProofMVarCluster newEnv (← cref.get)
private partial def extractProofMVarCluster (parentEnv : Environment)
(c : MVarCluster) : MetaM Unit := do
let gref? ← c.goals.findM? λ gref => return (← gref.get).state.isProven
let (some gref) := gref? | throwPRError
"an mvar cluster does not contain a proven goal (candidate goals: {← c.goals.mapM λ gref => return (← gref.get).id})."
extractProofGoal parentEnv (← gref.get)
end
private structure SafePrefixState where
goals : Array MVarId := #[]
private abbrev SafePrefixM := StateRefT SafePrefixState MetaM
mutual
private partial def extractSafePrefixGoal (parentEnv : Environment)
(g : Goal) : SafePrefixM Unit := do
let (some (postNormGoal, _, parentEnv)) ← visitGoal parentEnv g
| return
let safeRapps ← g.safeRapps
if safeRapps.size > 1 then
throwError "aesop: internal error: goal {g.id} has multiple safe rapps"
if h : 0 < safeRapps.size then
extractSafePrefixRapp parentEnv postNormGoal (← safeRapps[0].get)
else
modify λ s => { s with goals := s.goals.push postNormGoal }
private partial def extractSafePrefixRapp (parentEnv : Environment)
(parentGoal : MVarId) (r : Rapp) : SafePrefixM Unit := do
let (children, newEnv) ← visitRapp parentEnv parentGoal r
children.forM λ cref => do extractSafePrefixMVarCluster newEnv (← cref.get)
private partial def extractSafePrefixMVarCluster (parentEnv : Environment)
(c : MVarCluster) : SafePrefixM Unit :=
c.goals.forM λ gref => do extractSafePrefixGoal parentEnv (← gref.get)
end
def Goal.extractProof (root : Goal) : MetaM Unit := do
extractProofGoal (← getEnv) root
def extractProof : TreeM Unit := do
(← (← getRootGoal).get).extractProof
def Goal.extractSafePrefix (root : Goal) : MetaM (Array MVarId) := do
let (_, state) ← extractSafePrefixGoal (← getEnv) root |>.run {}
return state.goals
def extractSafePrefix : TreeM (Array MVarId) := do
(← (← getRootGoal).get).extractSafePrefix
end Aesop |
.lake/packages/aesop/Aesop/Tree/ExtractScript.lean | module
public import Aesop.Script.UScript
public import Aesop.Tree.TreeM
public section
open Lean
open Lean.Meta
open Lean.Parser.Tactic (tacticSeq)
namespace Aesop
open Script
structure ExtractScriptM.State where
script : UScript := #[]
proofHasMVar : Bool := false
abbrev ExtractScriptM := StateRefT ExtractScriptM.State TreeM
def ExtractScriptM.run (x : ExtractScriptM α) : TreeM (UScript × Bool) := do
let (_, r) ← StateRefT'.run x {}
return (r.script, r.proofHasMVar)
namespace ExtractScript
def lazyStepToStep (ruleName : DisplayRuleName) (lstep : LazyStep) :
MetaM Step :=
try
lstep.toStep
catch e =>
throwError "tactic script generation failed for rule {ruleName}:{indentD e.toMessageData}"
def lazyStepsToSteps (ruleName : DisplayRuleName) :
Option (Array LazyStep) → MetaM (Array Step)
| none => throwError "tactic script generation is not supported by rule {ruleName}"
| some lsteps => lsteps.mapM (lazyStepToStep ruleName)
def recordStep (step : Script.Step) : ExtractScriptM Unit := do
modify λ s => { s with script := s.script.push step }
def recordLazySteps (ruleName : DisplayRuleName)
(steps? : Option (Array Script.LazyStep)) : ExtractScriptM Unit := do
let steps ← lazyStepsToSteps ruleName steps?
modify λ s => { s with script := s.script ++ steps }
def visitGoal (g : Goal) : ExtractScriptM Unit := do
withConstAesopTraceNode .script (return m!"goal {g.id}") do
if ! g.mvars.isEmpty then
modify λ s => { s with proofHasMVar := true }
match g.normalizationState with
| .notNormal => throwError "expected goal {g.id} to be normalised"
| .normal (script := script) ..
| .provenByNormalization (script := script) .. =>
for (ruleName, script?) in script do
recordLazySteps ruleName script?
def visitRapp (r : Rapp) : ExtractScriptM Unit := do
withConstAesopTraceNode .script (return m!"rapp {r.id}") do
recordLazySteps r.appliedRule.name r.scriptSteps?
end ExtractScript
open ExtractScript
mutual
partial def MVarClusterRef.extractScriptCore (cref : MVarClusterRef) :
ExtractScriptM Unit := do
let c ← cref.get
let (some gref) ← c.provenGoal? | throwError
m!"the mvar cluster with goals {(← c.goals.mapM (·.get)).map (·.id)} does not contain a proven goal"
gref.extractScriptCore
partial def GoalRef.extractScriptCore (gref : GoalRef) : ExtractScriptM Unit := do
let g ← gref.get
visitGoal g
if ! g.normalizationState.isProvenByNormalization then
let (some rref) ← g.firstProvenRapp? | throwError
m!"goal {g.id} does not have a proven rapp"
rref.extractScriptCore
partial def RappRef.extractScriptCore (rref : RappRef) :
ExtractScriptM Unit := do
let r ← rref.get
visitRapp r
r.children.forM (·.extractScriptCore)
end
@[inline]
def extractScript : TreeM (UScript × Bool) :=
withAesopTraceNode .script (λ r => return m!"{exceptEmoji r} Extract script") do
(← getRootGoal).extractScriptCore.run
mutual
partial def MVarClusterRef.extractSafePrefixScriptCore
(mref : MVarClusterRef) : ExtractScriptM Unit := do
(← mref.get).goals.forM (·.extractSafePrefixScriptCore)
partial def GoalRef.extractSafePrefixScriptCore (gref : GoalRef) :
ExtractScriptM Unit := do
let g ← gref.get
visitGoal g
if ! g.normalizationState.isProvenByNormalization then
let safeRapps ← g.safeRapps
if safeRapps.size > 1 then
throwError "aesop: internal error: goal {g.id} has {safeRapps.size} safe rapps"
if let some rref := safeRapps[0]? then
rref.extractSafePrefixScriptCore
else
let some (postNormGoal, postNormState) := g.postNormGoalAndMetaState?
| throwError "aesop: internal error at extractSafePrefixScript: goal {g.id} is not normalised"
recordStep $ ← Step.mkSorry postNormGoal postNormState
partial def RappRef.extractSafePrefixScriptCore (rref : RappRef) :
ExtractScriptM Unit := do
let r ← rref.get
visitRapp r
-- The safe prefix can't assign mvars because any safe rule that assigns
-- mvars is downgraded to an unsafe rule. So we add `sorry` steps for all
-- introduced mvars.
for mvarId in r.introducedMVars do
recordStep $ ← Step.mkSorry mvarId r.metaState
r.forSubgoalsM (·.extractSafePrefixScriptCore)
end
def extractSafePrefixScript : TreeM (UScript × Bool) := do
withAesopTraceNode .script (λ r => return m!"{exceptEmoji r} Extract safe prefix script") do
(← getRootGoal).extractSafePrefixScriptCore.run
end Aesop |
.lake/packages/aesop/Aesop/Tree/TreeM.lean | module
public import Aesop.Tree.Data
public import Aesop.RuleSet
import Aesop.Forward.State.Initial
public section
open Lean
open Lean.Meta
namespace Aesop
structure Tree where
root : MVarClusterRef
rootMetaState : Meta.SavedState
numGoals : Nat
numRapps : Nat
nextGoalId : GoalId
nextRappId : RappId
/--
Union of the mvars introduced by all rapps.
-/
allIntroducedMVars : Std.HashSet MVarId
def mkInitialTree (goal : MVarId) (rs : LocalRuleSet) : BaseM Tree := do
let rootClusterRef ← IO.mkRef $ MVarCluster.mk {
parent? := none
goals := #[] -- patched up below
isIrrelevant := false
state := NodeState.unknown
}
let (forwardState, ms) ← withConstAesopTraceNode .forward (return m!"building initial forward state") do
rs.mkInitialForwardState goal
let rootGoalRef ← IO.mkRef $ Goal.mk {
id := GoalId.zero
parent := rootClusterRef
children := #[]
origin := .subgoal
depth := 0
state := GoalState.unknown
isIrrelevant := false
isForcedUnprovable := false
preNormGoal := goal
normalizationState := NormalizationState.notNormal
mvars := .ofHashSet (← goal.getMVarDependencies)
forwardState
forwardRuleMatches := .ofArray ms
successProbability := Percent.hundred
addedInIteration := Iteration.one
lastExpandedInIteration := Iteration.none
unsafeRulesSelected := false
unsafeQueue := {}
failedRapps := #[]
}
rootClusterRef.modify λ c => c.setGoals #[rootGoalRef]
return {
root := rootClusterRef
rootMetaState := ← saveState
numGoals := 1
numRapps := 0
nextGoalId := .one
nextRappId := .zero
allIntroducedMVars := ∅
}
structure TreeM.Context where
currentIteration : Iteration
ruleSet : LocalRuleSet
structure TreeM.State where
tree : Tree
abbrev TreeM := ReaderT TreeM.Context $ StateRefT TreeM.State BaseM
namespace TreeM
-- Generate specialized pure/bind implementations so we don't need to optimise
-- them on the fly at each use site.
instance : Monad TreeM :=
{ inferInstanceAs (Monad TreeM) with }
instance (priority := low) : MonadStateOf Tree TreeM where
get := return (← getThe State).tree
set tree := modifyThe State ({ · with tree })
modifyGet f := modifyGetThe State λ s =>
let (a, tree) := f s.tree
(a, { s with tree })
instance : Inhabited (TreeM α) where
default := failure
def run' (ctx : TreeM.Context) (tree : Tree) (x : TreeM α) :
BaseM (α × TreeM.State) :=
ReaderT.run x ctx |>.run { tree }
end TreeM
def getRootMVarCluster : TreeM MVarClusterRef :=
return (← getThe Tree).root
def getRootMetaState : TreeM Meta.SavedState :=
return (← getThe Tree).rootMetaState
def getRootGoal : TreeM GoalRef := do
let cref ← getRootMVarCluster
let grefs := (← cref.get).goals
if h : grefs.size = 1 then
return grefs[0]
else
throwError "aesop: internal error: unexpected number of goals in root mvar cluster: {grefs.size}"
def getRootMVarId : TreeM MVarId := do
let gref ← getRootGoal
return (← gref.get).preNormGoal
def incrementNumGoals (increment := 1) : TreeM Unit := do
modifyThe Tree λ s => { s with numGoals := s.numGoals + increment }
def incrementNumRapps (increment := 1) : TreeM Unit := do
modifyThe Tree λ s => { s with numRapps := s.numRapps + increment }
def getAllIntroducedMVars : TreeM (Std.HashSet MVarId) :=
return (← getThe Tree).allIntroducedMVars
def getAndIncrementNextGoalId : TreeM GoalId := do
modifyGetThe Tree λ t =>
let curr := t.nextGoalId
(curr, { t with nextGoalId := curr.succ })
def getAndIncrementNextRappId : TreeM RappId := do
modifyGetThe Tree λ t =>
let curr := t.nextRappId
(curr, { t with nextRappId := curr.succ })
end Aesop |
.lake/packages/aesop/Aesop/Tree/Traversal.lean | module
public import Aesop.Tree.Data
public section
namespace Aesop
inductive TreeRef
| goal (gref : GoalRef)
| rapp (rref : RappRef)
| mvarCluster (cref : MVarClusterRef)
section
open TreeRef
variable
{m} [Monad m] [MonadLiftT (ST IO.RealWorld) m]
(visitGoalPre : GoalRef → m Bool)
(visitGoalPost : GoalRef → m Unit)
(visitRappPre : RappRef → m Bool)
(visitRappPost : RappRef → m Unit)
(visitMVarClusterPre : MVarClusterRef → m Bool)
(visitMVarClusterPost : MVarClusterRef → m Unit)
@[specialize]
partial def traverseDown : TreeRef → m Unit
| goal gref => do
if ← visitGoalPre gref then
(← gref.get).children.forM (traverseDown ∘ rapp)
visitGoalPost gref
| rapp rref => do
if ← visitRappPre rref then
(← rref.get).children.forM (traverseDown ∘ mvarCluster)
visitRappPost rref
| mvarCluster cref => do
if ← visitMVarClusterPre cref then
(← cref.get).goals.forM (traverseDown ∘ goal)
visitMVarClusterPost cref
@[specialize]
partial def traverseUp : TreeRef → m Unit
| goal gref => do
if ← visitGoalPre gref then
traverseUp $ mvarCluster (← gref.get).parent
visitGoalPost gref
| rapp rref => do
if ← visitRappPre rref then
traverseUp $ goal (← rref.get).parent
visitRappPost rref
| mvarCluster cref => do
if ← visitMVarClusterPre cref then
if let (some parent) := (← cref.get).parent? then
traverseUp $ rapp parent
visitMVarClusterPost cref
end
variable [Monad m] [MonadLiftT (ST IO.RealWorld) m]
@[inline]
def preTraverseDown (visitGoal : GoalRef → m Bool)
(visitRapp : RappRef → m Bool) (visitMVarCluster : MVarClusterRef → m Bool) :
TreeRef → m Unit :=
traverseDown
visitGoal
(λ _ => pure ())
visitRapp
(λ _ => pure ())
visitMVarCluster
(λ _ => pure ())
@[inline]
def preTraverseUp (visitGoal : GoalRef → m Bool) (visitRapp : RappRef → m Bool)
(visitMVarCluster : MVarClusterRef → m Bool) : TreeRef → m Unit :=
traverseUp
visitGoal
(λ _ => pure ())
visitRapp
(λ _ => pure ())
visitMVarCluster
(λ _ => pure ())
@[inline]
def postTraverseDown (visitGoal : GoalRef → m Unit)
(visitRapp : RappRef → m Unit) (visitMVarCluster : MVarClusterRef → m Unit) :
TreeRef → m Unit :=
traverseDown
(λ _ => pure true)
visitGoal
(λ _ => pure true)
visitRapp
(λ _ => pure true)
visitMVarCluster
@[inline]
def postTraverseUp (visitGoal : GoalRef → m Unit) (visitRapp : RappRef → m Unit)
(visitMVarCluster : MVarClusterRef → m Unit) : TreeRef → m Unit :=
traverseUp
(λ _ => pure true)
visitGoal
(λ _ => pure true)
visitRapp
(λ _ => pure true)
visitMVarCluster
end Aesop |
.lake/packages/aesop/Aesop/Tree/RunMetaM.lean | module
public import Aesop.Tree.Data
public section
open Lean
open Lean.Meta
namespace Aesop
/-!
The following functions let us run MetaM actions in the context of a rapp or
goal. Rapps save the metavariable context in which they were run by storing a
`Meta.SavedState`. When we, for example, apply a rule to a goal, we run the
rule's action in the metavariable context of the goal (which is the
metavariable context of the goal's parent rapp). The resulting metavariable
context, in which the goal mvar is assigned to an expression generated by the
rule, then becomes the metavariable context of the rule's rapp.
To save and restore metavariable contexts, we use the `MonadBacktrack MetaM`
instance. This means that some elements of the state are persistent, notably
caches and trace messages. These become part of the global state.
The environment is not persistent. This means that modifications of the
environment made by a rule are not visible in the global state and are reset
once the tactic exits. As a result, rules which modify the environment are
likely to fail.
-/
variable [Monad m] [MonadLiftT MetaM m] [MonadFinally m]
local instance : MonadLiftT (ST IO.RealWorld) m where
monadLift x := (x : MetaM _)
@[inline, always_inline]
private def withSaveState (x : m α) : m (α × Meta.SavedState) := do
let r ← x
let s ← Meta.saveState
return (r, s)
def Rapp.runMetaM' (x : m α) (r : Rapp) : m α :=
runInMetaState r.metaState x
def Rapp.runMetaM (x : m α) (r : Rapp) : m (α × Meta.SavedState) :=
r.runMetaM' do withSaveState x
def Rapp.runMetaMModifying (x : m α) (r : Rapp) : m (α × Rapp) := do
let (result, finalState) ← r.runMetaM x
return (result, r |>.setMetaState finalState)
def RappRef.runMetaMModifying (x : m α) (rref : RappRef) : m α := do
let (result, r) ← (← rref.get).runMetaMModifying x
rref.set r
return result
def Goal.runMetaMInPostNormState' [MonadError m] (x : MVarId → m α) (g : Goal) :
m α := do
let some (postGoal, postState) := g.postNormGoalAndMetaState? | throwError
"aesop: internal error: expected goal {g.id} to be normalised (but not proven by normalisation)."
runInMetaState postState $ x postGoal
def Goal.runMetaMInPostNormState [MonadError m] (x : MVarId → m α) (g : Goal) :
m (α × Meta.SavedState) :=
g.runMetaMInPostNormState' λ g => withSaveState (x g)
def Goal.runMetaMInParentState' (x : m α) (g : Goal) : m α := do
match ← show MetaM _ from g.parentRapp? with
| none =>
let initialState ← Meta.saveState
try
x
finally
initialState.restore
| some rref => (← rref.get).runMetaM' x
def Goal.runMetaMInParentState (x : m α) (g : Goal) : m (α × Meta.SavedState) :=
g.runMetaMInParentState' do withSaveState x
def Goal.runMetaMModifyingParentState (x : m α) (g : Goal) : m α := do
match ← show MetaM _ from g.parentRapp? with
| none => x
| some rref => rref.runMetaMModifying x
def Rapp.runMetaMInParentState (x : m α) (r : Rapp) :
m (α × Meta.SavedState) := do
(← r.parent.get).runMetaMInParentState x
def Rapp.runMetaMInParentState' (x : m α) (r : Rapp) : m α := do
(← r.parent.get).runMetaMInParentState' x
def Rapp.runMetaMModifyingParentState (x : m α) (r : Rapp) : m α := do
(← r.parent.get).runMetaMModifyingParentState x
end Aesop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.