source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/aesop/Aesop/Tree/State.lean | module
public import Aesop.Tree.Traversal
public section
namespace Aesop
/-! ## Marking Nodes As Proven/Unprovable/Irrelevant -/
/-! ### Irrelevant -/
/-
Each of our node types (goal, rapp, mvar cluster) is irrelevant under the
same conditions:
1. the node is proven or unprovable *or*
2. the node's parent is irrelevant. (If the node has no parent, this condition
does not apply.)
-/
def Goal.isIrrelevantNoCache (g : Goal) : BaseIO Bool :=
(return g.state.isIrrelevant) <||>
(return (← g.parent.get).isIrrelevant)
def Rapp.isIrrelevantNoCache (r : Rapp) : BaseIO Bool :=
(return r.state.isIrrelevant) <||>
(return (← r.parent.get).isIrrelevant)
def MVarCluster.isIrrelevantNoCache (c : MVarCluster) : BaseIO Bool := do
(return c.state.isIrrelevant) <||> do
match c.parent? with
| none => return false
| some parentRef => return (← parentRef.get).isIrrelevant
def TreeRef.markSubtreeIrrelevant : TreeRef → BaseIO Unit :=
preTraverseDown
(λ gref => do
if (← gref.get).isIrrelevant then
return false -- Subtree is already irrelevant.
gref.modify λ g => g.setIsIrrelevant true
return true)
(λ rref => do
if (← rref.get).isIrrelevant then
return false -- Subtree is already irrelevant.
rref.modify λ r => r.setIsIrrelevant true
return true)
(λ cref => do
if (← cref.get).isIrrelevant then
return false -- Subtree is already irrelevant.
cref.modify λ c => c.setIsIrrelevant true
return true)
def GoalRef.markSubtreeIrrelevant (gref : GoalRef) : BaseIO Unit :=
(TreeRef.goal gref).markSubtreeIrrelevant
def RappRef.markSubtreeIrrelevant (rref : RappRef) : BaseIO Unit :=
(TreeRef.rapp rref).markSubtreeIrrelevant
def MVarClusterRef.markSubtreeIrrelevant (cref : MVarClusterRef) : BaseIO Unit :=
(TreeRef.mvarCluster cref).markSubtreeIrrelevant
/-! ### Proven -/
-- A goal is proven if any of its child rapps are proven, or if the goal was
-- proven by normalisation.
def Goal.isProvenByNormalizationNoCache (g : Goal) : Bool :=
g.normalizationState.isProvenByNormalization
def Goal.isProvenByRuleApplicationNoCache (g : Goal) : BaseIO Bool :=
g.children.anyM λ rref => return (← rref.get).state.isProven
def Goal.isProvenNoCache (g : Goal) : BaseIO Bool :=
(return g.isProvenByNormalizationNoCache) <||>
g.isProvenByRuleApplicationNoCache
-- A rapp is proven if each of its child mvar clusters is proven.
def Rapp.isProvenNoCache (r : Rapp) : BaseIO Bool :=
r.children.allM λ cref => return (← cref.get).state.isProven
-- An mvar cluster is proven if any of its goals is proven.
def MVarCluster.isProvenNoCache (c : MVarCluster) : BaseIO Bool :=
c.goals.anyM λ cref => return (← cref.get).state.isProven
private def markProvenCore (root : TreeRef) : BaseIO Unit := do
/-
We iterate up the tree, marking nodes as proven according to the rules
of provenness:
- A goal is proven if any of its child rapps is proven. Since we're
iterating up from a proven child rapp, we mark goals as proven
unconditionally. As a result, all child rapps of the goal become
irrelevant.
- A rapp is proven if all its child mvar clusters are proven. We must check
whether this is the case. If so, the rapp is marked as proven and
irrelevant. (Its children, being proven, are already marked as
irrelevant.)
- An mvar cluster is proven if any of its goals is proven. Since we're
iterating up from a proven goal, we mark mvar clusters as proven
unconditionally. As a result, all goals in the mvar cluster become
irrelevant.
-/
preTraverseUp
(λ gref => do
let g ← gref.get
gref.set $
g.setState GoalState.provenByRuleApplication |>.setIsIrrelevant true
g.children.forM λ rref => rref.markSubtreeIrrelevant
return true)
(λ rref => do
let r ← rref.get
if ! (← r.isProvenNoCache) then
return false
rref.set $ r.setState NodeState.proven |>.setIsIrrelevant true
return true)
(λ cref => do
let c ← cref.get
cref.set $ c.setState NodeState.proven |>.setIsIrrelevant true
c.goals.forM λ gref => gref.markSubtreeIrrelevant
return true)
root
def GoalRef.markProvenByNormalization (gref : GoalRef) : BaseIO Unit := do
let g ← gref.get
gref.set $ g.setState GoalState.provenByNormalization |>.setIsIrrelevant true
g.children.forM λ rref => rref.markSubtreeIrrelevant
-- `g` should not have any children, but better safe than sorry.
markProvenCore (TreeRef.mvarCluster g.parent)
def RappRef.markProven (rref : RappRef) : BaseIO Unit :=
markProvenCore (TreeRef.rapp rref)
/-! ### Unprovable -/
-- A goal is unrovable if it is exhausted (i.e. we've applied all applicable
-- rules) and all resulting rule applications are unprovable.
def Goal.isUnprovableNoCache (g : Goal) : BaseIO Bool :=
pure g.isForcedUnprovable <||> (
g.isExhausted <&&>
g.children.allM λ rref => return (← rref.get).state.isUnprovable)
-- A rapp is unprovable if any of its child mvar clusters are unprovable.
def Rapp.isUnprovableNoCache (r : Rapp) : BaseIO Bool :=
r.children.anyM λ cref => return (← cref.get).state.isUnprovable
-- An mvar cluster is unprovable if all its goals are unprovable.
def MVarCluster.isUnprovableNoCache (c : MVarCluster) : BaseIO Bool := do
c.goals.allM λ cref => return (← cref.get).state.isUnprovable
private def markUnprovableCore : TreeRef → BaseIO Unit :=
/-
We iterate up the tree, marking nodes as unprovable according to the rules
of unprovability:
- A goal is unprovable if it is exhausted and all its child rapps are
unprovable. We must check whether this is the case. If so, the goal
is marked as unprovable and irrelevant. (Its children, being unprovable,
are already marked as irrelevant.)
- A rapp is unprovable if any of its child mvar clusters is unprovable.
Since we iterate up from an unprovable mvar cluster, we mark rapps as
unprovable unconditionally. As a result, all mvar clusters of the rapp
become irrelevant.
- An mvar cluster is unprovable if all its goals are unprovable. We must
check whether this is the case. If so, the cluster is marked as unprovable
and irrelevant. (Its children, being unprovable, are already marked as
irrelevant.)
-/
preTraverseUp
(λ gref => do
let g ← gref.get
if ! (← g.isUnprovableNoCache) then
return false
gref.set $ g.setState GoalState.unprovable |>.setIsIrrelevant true
return true)
(λ rref => do
let r ← rref.get
rref.set $ r.setState NodeState.unprovable |>.setIsIrrelevant true
r.children.forM λ cref => cref.markSubtreeIrrelevant
return true)
(λ cref => do
let c ← cref.get
if ! (← c.isUnprovableNoCache) then
return false
cref.set $ c.setState NodeState.unprovable |>.setIsIrrelevant true
return true)
def GoalRef.markUnprovable (gref : GoalRef) : BaseIO Unit := do
let g ← gref.get
gref.set $ g.setState GoalState.unprovable |>.setIsIrrelevant true
g.children.forM λ rref => rref.markSubtreeIrrelevant
markUnprovableCore (TreeRef.mvarCluster g.parent)
def GoalRef.markForcedUnprovable (gref : GoalRef) : BaseIO Unit := do
gref.modify (·.setIsForcedUnprovable true)
gref.markUnprovable
def GoalRef.checkAndMarkUnprovable (gref : GoalRef) : BaseIO Unit :=
markUnprovableCore (TreeRef.goal gref)
/-! ### Uncached Node States -/
/-
The following functions determine the state of a node (goal/rapp/mvar cluster),
assuming only that the state of the node's children is correct. So they can be
used to verify a tree 'bottom-up'.
-/
def Goal.stateNoCache (g : Goal) : BaseIO GoalState := do
if g.isProvenByNormalizationNoCache then
return GoalState.provenByNormalization
else if ← g.isProvenByRuleApplicationNoCache then
return GoalState.provenByRuleApplication
else if ← g.isUnprovableNoCache then
return GoalState.unprovable
else
return GoalState.unknown
def Rapp.stateNoCache (r : Rapp) : BaseIO NodeState := do
if ← r.isProvenNoCache then
return NodeState.proven
else if ← r.isUnprovableNoCache then
return NodeState.unprovable
else
return NodeState.unknown
def MVarCluster.stateNoCache (c : MVarCluster) : BaseIO NodeState := do
if ← c.isProvenNoCache then
return NodeState.proven
else if ← c.isUnprovableNoCache then
return NodeState.unprovable
else
return NodeState.unknown
end Aesop |
.lake/packages/aesop/Aesop/Tree/AddRapp.lean | module
public import Aesop.Tree.TreeM
import Aesop.Tree.Traversal
import Aesop.Util.UnionFind
import Aesop.Forward.State.ApplyGoalDiff
import Batteries.Lean.Meta.SavedState
public section
open Lean
open Lean.Meta
namespace Aesop
structure AddRapp extends RuleApplication where
parent : GoalRef
appliedRule : RegularRule
successProbability : Percent
namespace AddRapp
def consumedForwardRuleMatches (r : AddRapp) : Array ForwardRuleMatch :=
r.appliedRule.tac.forwardRuleMatches? |>.getD #[]
end AddRapp
def findPathForAssignedMVars (assignedMVars : UnorderedArraySet MVarId)
(start : GoalRef) : TreeM (Array RappRef × Std.HashSet GoalId) := do
if assignedMVars.isEmpty then
return (#[], {})
let unseen : IO.Ref (UnorderedArraySet MVarId) ← IO.mkRef assignedMVars
let pathRapps : IO.Ref (Array RappRef) ← IO.mkRef #[]
let pathGoals : IO.Ref (Std.HashSet GoalId) ← IO.mkRef {}
preTraverseUp
(λ gref => do
let id := (← gref.get).originalGoalId
pathGoals.modify (·.insert id)
return true)
(λ rref => do
pathRapps.modify (·.push rref)
for introducedMVar in (← rref.get).introducedMVars do
unseen.modify (·.erase introducedMVar)
if (← unseen.get).isEmpty then
return false
else
return true)
(λ _ =>
return true)
(TreeRef.goal start)
let unseen ← unseen.get
if ! unseen.isEmpty then
let rootGoalMVars := (← (← getRootGoal).get).mvars
if unseen.any (! rootGoalMVars.contains ·) then
let reallyUnseen :=
unseen.toArray.filter (! rootGoalMVars.contains ·) |>.map (·.name)
throwError "aesop: internal error: introducing rapps not found for these mvars: {reallyUnseen}"
return (← pathRapps.get, ← pathGoals.get)
def getGoalsToCopy (assignedMVars : UnorderedArraySet MVarId)
(start : GoalRef) : TreeM (Array GoalRef) := do
let (pathRapps, pathGoals) ← findPathForAssignedMVars assignedMVars start
let mut toCopy := #[]
let mut toCopyIds := (∅ : Std.HashSet GoalId)
for rref in pathRapps do
for cref in (← rref.get).children do
for gref in (← cref.get).goals do
let g ← gref.get
let id := g.originalGoalId
-- We copy goals which
-- - aren't on the path;
-- - haven't been copied already;
-- - contain at least one of the assigned metavariables.
-- For the first two checks, we identify goals by their
-- `originalGoalId`, i.e. 'up to copying'.
if ! pathGoals.contains id && ! toCopyIds.contains id &&
g.mvars.any (assignedMVars.contains ·) then
toCopy := toCopy.push gref
toCopyIds := toCopyIds.insert id
return toCopy
unsafe def copyGoals (assignedMVars : UnorderedArraySet MVarId)
(start : GoalRef) (parentMetaState : Meta.SavedState)
(parentSuccessProbability : Percent) (depth : Nat) :
TreeM (Array Goal) := do
let toCopy ← getGoalsToCopy assignedMVars start
toCopy.mapM λ gref => do
let g ← gref.get
let rs := (← read).ruleSet
let (forwardState, forwardRuleMatches, mvars) ←
runInMetaState parentMetaState do
let start ← start.get
let diff ← diffGoals start.currentGoal g.preNormGoal
let (forwardState, ms) ← start.forwardState.applyGoalDiff rs diff
let forwardRuleMatches :=
start.forwardRuleMatches.update ms diff.removedFVars
(consumedForwardRuleMatches := #[]) -- TODO unsure whether this is correct
let mvars ← .ofHashSet <$> g.preNormGoal.getMVarDependencies
pure (forwardState, forwardRuleMatches, mvars)
return Goal.mk {
id := ← getAndIncrementNextGoalId
parent := unsafeCast () -- will be filled in later
children := #[]
origin := .copied g.id g.originalGoalId
depth
state := GoalState.unknown
isIrrelevant := false
isForcedUnprovable := false
preNormGoal := g.preNormGoal
normalizationState := NormalizationState.notNormal
mvars
forwardState
forwardRuleMatches
successProbability := parentSuccessProbability
addedInIteration := (← read).currentIteration
lastExpandedInIteration := Iteration.none
unsafeRulesSelected := false
unsafeQueue := {}
failedRapps := #[]
}
def makeInitialGoal (goal : Subgoal) (mvars : UnorderedArraySet MVarId)
(parent : MVarClusterRef) (parentMetaState : Meta.SavedState)
(parentForwardState : ForwardState)
(parentForwardMatches : ForwardRuleMatches)
(consumedForwardRuleMatches : Array ForwardRuleMatch) (depth : Nat)
(successProbability : Percent) (origin : GoalOrigin) : TreeM Goal := do
let rs := (← read).ruleSet
let (forwardState, forwardRuleMatches) ← runInMetaState parentMetaState do
let (fs, newMatches) ← parentForwardState.applyGoalDiff rs goal.diff
let ms :=
parentForwardMatches.update newMatches goal.diff.removedFVars
consumedForwardRuleMatches
pure (fs, ms)
return Goal.mk {
id := ← getAndIncrementNextGoalId
children := #[]
state := GoalState.unknown
isIrrelevant := false
isForcedUnprovable := false
preNormGoal := goal.mvarId
normalizationState := NormalizationState.notNormal
forwardState
forwardRuleMatches
addedInIteration := (← read).currentIteration
lastExpandedInIteration := Iteration.none
unsafeRulesSelected := false
unsafeQueue := {}
failedRapps := #[]
parent, origin, depth, mvars, successProbability
}
unsafe def addRappUnsafe (r : AddRapp) : TreeM RappRef := do
let originalSubgoals := r.goals
-- We update the rapp's `auxDeclNGen` to ensure that tactics on different
-- branches of the search tree generate different names for auxiliary
-- declarations.
let auxDeclNGen ←
match ← (← r.parent.get).parentRapp? with
| none =>
let (child, parent) := (← getDeclNGen).mkChild
setDeclNGen parent
pure child
| some parentRapp => parentRapp.getChildAuxDeclNameGenerator
let metaState := { r.postState with core.auxDeclNGen := auxDeclNGen }
let rref : RappRef ← IO.mkRef $ Rapp.mk {
id := ← getAndIncrementNextRappId
parent := r.parent
children := #[] -- will be filled in later
state := NodeState.unknown
isIrrelevant := false
appliedRule := r.appliedRule
scriptSteps? := r.scriptSteps?
originalSubgoals := originalSubgoals.map (·.mvarId)
successProbability := r.successProbability
metaState
introducedMVars := {} -- will be filled in later
assignedMVars := {} -- will be filled in later
}
let parentGoal ← r.parent.get
let goalDepth := parentGoal.depth + 1
let (originalSubgoalMVars, assignedMVars, assignedOrDroppedMVars) ←
r.postState.runMetaM' do
-- Get mvars which the original subgoals depend on.
let originalSubgoalMVars : Std.HashSet MVarId ←
originalSubgoals.foldlM (init := ∅) λ acc subgoal =>
return acc.insertMany (← subgoal.mvarId.getMVarDependencies)
-- Get mvars which were either assigned or dropped by the rapp. We assume
-- that rules only assign mvars which appear in the rapp's parent goal. A
-- dropped mvar is one that appears in the parent of the rapp but is
-- neither assigned by the rapp nor does it appear in any of its subgoals.
-- A dropped mvar is treated like an assigned mvar for the purposes of
-- copying.
let mut assignedMVars : UnorderedArraySet MVarId := ∅
let mut assignedOrDroppedMVars : UnorderedArraySet MVarId := ∅
for mvarId in parentGoal.mvars do
if ← mvarId.isAssignedOrDelayedAssigned then
-- mvar was assigned
assignedMVars := assignedMVars.insert mvarId
assignedOrDroppedMVars := assignedOrDroppedMVars.insert mvarId
else if ! originalSubgoalMVars.contains mvarId then
-- mvar was dropped
assignedOrDroppedMVars := assignedOrDroppedMVars.insert mvarId
pure (originalSubgoalMVars, assignedMVars, assignedOrDroppedMVars)
-- If the rapp assigned or dropped any mvars, copy the related goals.
let copiedGoals : Array Goal ←
copyGoals assignedOrDroppedMVars r.parent r.postState
r.successProbability goalDepth
let copiedSubgoals : Array Subgoal :=
copiedGoals.map λ g =>
{ diff := { (default : GoalDiff) with newGoal := g.preNormGoal } }
-- The diff is irrelevant because we later add `g` to the tree (and the
-- forward state of `g` is already up to date).
-- Collect the mvars which occur in the original subgoals and copied goals.
let originalSubgoalAndCopiedGoalMVars :=
copiedGoals.foldl (init := originalSubgoalMVars)
λ copiedGoalMVars g => copiedGoalMVars.insertMany g.mvars
-- Turn the dropped mvars into subgoals. Note: an mvar that was dropped by the
-- rapp may occur in the copied goals, in which case we don't count it as
-- dropped any more.
let droppedSubgoals : Array Subgoal ← runInMetaState r.postState do
let mut droppedMVars := #[]
for mvarId in parentGoal.mvars do
unless ← (pure $ originalSubgoalAndCopiedGoalMVars.contains mvarId) <||>
mvarId.isAssignedOrDelayedAssigned do
let diff ← diffGoals parentGoal.currentGoal mvarId
droppedMVars := droppedMVars.push { diff }
pure droppedMVars
-- Partition the subgoals into 'proper goals' and 'proper mvars'. A proper
-- mvar is an mvar that occurs in any of the other subgoal mvars. Any other
-- mvar is a proper goal.
let (properGoals, _) ← r.postState.runMetaM' do
partitionGoalsAndMVars (·.mvarId) $
originalSubgoals ++ copiedSubgoals ++ droppedSubgoals
-- Construct the subgoals
let subgoals ← properGoals.mapM λ (goal, mvars) =>
if let some copiedGoal := copiedGoals.find? (·.preNormGoal == goal.mvarId) then
pure copiedGoal
else
let origin :=
if droppedSubgoals.find? (·.mvarId == goal.mvarId) |>.isSome then
.droppedMVar
else
.subgoal
try
makeInitialGoal goal mvars (unsafeCast ()) r.postState
parentGoal.forwardState parentGoal.forwardRuleMatches
r.consumedForwardRuleMatches goalDepth r.successProbability origin
-- The parent (`unsafeCast ()`) will be patched up later.
catch e =>
throwError "in rapp for rule {r.appliedRule.name}:{indentD e.toMessageData}"
-- Construct the new mvar clusters.
let crefs : Array MVarClusterRef ←
cluster (·.mvars.toArray) subgoals |>.mapM λ gs => do
let grefs ← gs.mapM (IO.mkRef ·)
let cref ← IO.mkRef $ MVarCluster.mk {
parent? := some rref
goals := grefs
isIrrelevant := false
state := NodeState.unknown
}
-- Patch up information we left out earlier (to break cyclic
-- dependencies).
grefs.forM λ gref => gref.modify λ g => g.setParent cref
return cref
-- Get the introduced mvars. An mvar counts as introduced by this rapp if it
-- appears in a subgoal, but not in the parent goal.
let mut introducedMVars : UnorderedArraySet MVarId := ∅
let mut allIntroducedMVars ← modifyGetThe Tree λ t =>
(t.allIntroducedMVars, { t with allIntroducedMVars := ∅ })
-- We set `allIntroducedMVars := ∅` to make sure that the hash set is used
-- linearly.
for g in subgoals do
for mvarId in g.mvars do
if ! parentGoal.mvars.contains mvarId &&
! allIntroducedMVars.contains mvarId then
introducedMVars := introducedMVars.insert mvarId
allIntroducedMVars := allIntroducedMVars.insert mvarId
modifyThe Tree λ t => { t with allIntroducedMVars }
-- Patch up more information we left out earlier.
rref.modify λ r =>
r.setChildren crefs
|>.setIntroducedMVars introducedMVars
|>.setAssignedMVars assignedMVars
r.parent.modify λ g => g.setChildren $ g.children.push rref
-- Increment goal and rapp counters.
incrementNumGoals subgoals.size
incrementNumRapps
return rref
/--
Adds a new rapp and its subgoals. If the rapp assigns mvars, all relevant
goals containing these mvars are copied as children of the rapp as well. If
the rapp drops mvars, these are treated as assigned mvars, in the sense that
the same goals are copied as if the dropped mvar had been assigned.
Note that adding a rapp may prove the parent goal, but this function does not
make the necessary changes. So after calling it, you should check whether the
rapp's parent goal is proven and mark it accordingly.
-/
@[implemented_by addRappUnsafe]
opaque addRapp : AddRapp → TreeM RappRef
end Aesop |
.lake/packages/aesop/Aesop/Tree/UnsafeQueue.lean | module
public import Aesop.Rule
import Aesop.Constants
public section
open Lean
namespace Aesop
structure PostponedSafeRule where
rule : SafeRule
output : RuleTacOutput
deriving Inhabited
namespace PostponedSafeRule
def toUnsafeRule (r : PostponedSafeRule) : UnsafeRule :=
{ r.rule with extra := ⟨postponedSafeRuleSuccessProbability⟩ }
end PostponedSafeRule
inductive UnsafeQueueEntry
| unsafeRule (r : IndexMatchResult UnsafeRule)
| postponedSafeRule (r : PostponedSafeRule)
deriving Inhabited
namespace UnsafeQueueEntry
instance : ToString UnsafeQueueEntry where
toString
| unsafeRule r => toString r.rule.name
| postponedSafeRule r => toString r.rule.name
def successProbability : UnsafeQueueEntry → Percent
| unsafeRule r => r.rule.extra.successProbability
| postponedSafeRule .. => postponedSafeRuleSuccessProbability
def name : UnsafeQueueEntry → RuleName
| unsafeRule r => r.rule.name
| postponedSafeRule r => r.rule.name
instance : Ord UnsafeQueueEntry :=
⟨ compareLex
(λ x y => compareOn successProbability x y |>.swap)
(compareOn name) ⟩
end UnsafeQueueEntry
@[expose] def UnsafeQueue := Subarray UnsafeQueueEntry
namespace UnsafeQueue
instance : EmptyCollection UnsafeQueue :=
inferInstanceAs $ EmptyCollection (Subarray _)
instance : Inhabited UnsafeQueue :=
inferInstanceAs $ Inhabited (Subarray _)
-- Precondition: `unsafeRules` is ordered lexicographically by descending
-- success probability, then by rule name.
def initial (postponedSafeRules : Array PostponedSafeRule)
(unsafeRules : Array (IndexMatchResult UnsafeRule)) : UnsafeQueue :=
let unsafeRules := unsafeRules.map .unsafeRule
let postponedSafeRules :=
postponedSafeRules.map .postponedSafeRule
|>.qsort (λ x y => compare x y |>.isLT)
postponedSafeRules.mergeDedup unsafeRules |>.toSubarray
def entriesToMessageData (q : UnsafeQueue) : Array MessageData :=
q.toArray.map toMessageData
end UnsafeQueue
end Aesop |
.lake/packages/aesop/Aesop/Tree/Free.lean | module
public import Aesop.Tree.TreeM
public section
namespace Aesop
-- In Lean 4, cylic structures -- such as our trees with their parent pointers
-- -- are not freed automatically. This is because the runtime uses reference
-- counting and a parent node and its child, holding references to each other,
-- will always have a reference count ≥ 1. So in order to free a tree, we must
-- break the cycles by removing the parent pointers.
mutual
variable
(dummyGoalRef : GoalRef)
(dummyMVarClusterRef : MVarClusterRef)
private partial def freeGoalRef (gref : GoalRef) : BaseIO Unit := do
gref.modify λ g => g.setParent dummyMVarClusterRef
(← gref.get).children.forM freeRappRef
private partial def freeRappRef (rref : RappRef) : BaseIO Unit := do
rref.modify λ r => r.setParent dummyGoalRef
(← rref.get).children.forM freeMVarClusterRef
private partial def freeMVarClusterRef (cref : MVarClusterRef) :
BaseIO Unit := do
cref.modify λ c => c.setParent none
(← cref.get).goals.forM freeGoalRef
end
private def mkDummyRefs : BaseIO (GoalRef × MVarClusterRef) := do
let cref ← IO.mkRef $ by refine' MVarCluster.mk {..} <;> exact default
let gref ← IO.mkRef $ by refine' Goal.mk { parent := cref, .. } <;> exact default
return (gref, cref)
def GoalRef.free (gref : GoalRef) : BaseIO Unit := do
let (dgref, dcref) ← mkDummyRefs
freeGoalRef dgref dcref gref
def RappRef.free (rref : RappRef) : BaseIO Unit := do
let (dgref, dcref) ← mkDummyRefs
freeRappRef dgref dcref rref
def MVarClusterRef.free (cref : MVarClusterRef) : BaseIO Unit := do
let (dgref, dcref) ← mkDummyRefs
freeMVarClusterRef dgref dcref cref
def freeTree : TreeM Unit := do
(← getThe Tree).root.free
end Aesop |
.lake/packages/aesop/Aesop/Tree/Data/ForwardRuleMatches.lean | module
public import Aesop.Rule
import Aesop.Forward.Match
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- Sets of complete matches for norm/safe/unsafe rules. -/
structure ForwardRuleMatches where
/-- Complete matches of norm rules. -/
normMatches : PHashSet ForwardRuleMatch
/-- Complete matches of safe rules. -/
safeMatches : PHashSet ForwardRuleMatch
/-- Complete matches of unsafe rules. -/
unsafeMatches : PHashSet ForwardRuleMatch
deriving Inhabited
namespace ForwardRuleMatches
/-- Empty `ForwardRuleMatches`. -/
protected def empty : ForwardRuleMatches where
normMatches := ∅
safeMatches := ∅
unsafeMatches := ∅
instance : EmptyCollection ForwardRuleMatches :=
⟨.empty⟩
/-- Add a complete match. -/
def insert (m : ForwardRuleMatch) (ms : ForwardRuleMatches) :
ForwardRuleMatches :=
match m.rule.name.phase with
| .norm => { ms with normMatches := ms.normMatches.insert m }
| .safe => { ms with safeMatches := ms.safeMatches.insert m }
| .unsafe => { ms with unsafeMatches := ms.unsafeMatches.insert m }
/-- Add several complete matches. -/
def insertMany (ms : Array ForwardRuleMatch) (ms' : ForwardRuleMatches) :
ForwardRuleMatches :=
ms.foldl (init := ms') λ ms' m => ms'.insert m
/-- Erase a complete match. -/
def erase (m : ForwardRuleMatch) (ms : ForwardRuleMatches) :
ForwardRuleMatches :=
match m.rule.name.phase with
| .norm => { ms with normMatches := ms.normMatches.erase m }
| .safe => { ms with safeMatches := ms.safeMatches.erase m }
| .unsafe => { ms with unsafeMatches := ms.unsafeMatches.erase m }
/-- Erase several complete matches. -/
def eraseMany (ms : Array ForwardRuleMatch) (ms' : ForwardRuleMatches) :
ForwardRuleMatches :=
ms.foldl (init := ms') λ ms' m => ms'.erase m
/-- Build a `ForwardRuleMatches` structure containing the matches from `ms`. -/
def ofArray (ms : Array ForwardRuleMatch) : ForwardRuleMatches :=
(∅ : ForwardRuleMatches).insertMany ms
/-- Erase matches containing any of the hypotheses `hs` from `ms`. -/
def eraseHyps (hs : Std.HashSet FVarId) (ms : ForwardRuleMatches) :
ForwardRuleMatches where
normMatches := go ms.normMatches
safeMatches := go ms.safeMatches
unsafeMatches := go ms.unsafeMatches
where
go (ms : PHashSet ForwardRuleMatch) : PHashSet ForwardRuleMatch :=
let toErase := ms.fold (init := #[]) λ toErase m =>
if m.anyHyp hs.contains then toErase.push m else toErase
toErase.foldl (init := ms) λ ms m => ms.erase m
/-- Erase matches containing the hypothesis `h` from `ms`. -/
def eraseHyp (h : FVarId) (ms : ForwardRuleMatches) : ForwardRuleMatches :=
ms.eraseHyps {h}
/-- Update the `ForwardRuleMatches` of a goal so that they are suitable for a
child goal. `newMatches` are new forward rule matches obtained by updating the
old goal's `ForwardState` with new hypotheses from the new goal. `erasedHyps`
are the hypotheses from the old goal that no longer appear in the new goal.
`consumedForwardRuleMatches` contains forward rule matches that were applied as
rules to transform the old goal into the new goal. -/
def update (newMatches : Array ForwardRuleMatch)
(erasedHyps : Std.HashSet FVarId)
(consumedForwardRuleMatches : Array ForwardRuleMatch)
(forwardRuleMatches : ForwardRuleMatches) : ForwardRuleMatches := Id.run do
let mut ms := forwardRuleMatches
for m in consumedForwardRuleMatches do
ms := ms.erase m
return forwardRuleMatches.eraseHyps erasedHyps |>.insertMany newMatches
private def pHashSetToArray [BEq α] [Hashable α] (s : PHashSet α) : Array α :=
s.fold (init := #[]) λ acc x => acc.push x
/-- Get the norm rules corresponding to the norm rule matches. -/
def normRules (ms : ForwardRuleMatches) : Array NormRule :=
forwardRuleMatchesToNormRules? (pHashSetToArray ms.normMatches) |>.get!
/-- Get the safe rules corresponding to the safe rule matches. -/
def safeRules (ms : ForwardRuleMatches) : Array SafeRule :=
forwardRuleMatchesToSafeRules? (pHashSetToArray ms.safeMatches) |>.get!
/-- Get the unsafe rules corresponding to the unsafe rule matches. -/
def unsafeRules (ms : ForwardRuleMatches) : Array UnsafeRule :=
forwardRuleMatchesToUnsafeRules? (pHashSetToArray ms.unsafeMatches) |>.get!
/-- `O(n)` Number of matches in `ms`. -/
def size (ms : ForwardRuleMatches) : Nat :=
ms.normMatches.fold (init := 0) (λ n _ => n + 1) +
ms.safeMatches.fold (init := 0) (λ n _ => n + 1) +
ms.unsafeMatches.fold (init := 0) (λ n _ => n + 1)
end ForwardRuleMatches
end Aesop |
.lake/packages/aesop/Aesop/Options/Public.lean | module
public import Lean.Data.Options
public section
open Lean Lean.Meta
namespace Aesop
set_option linter.missingDocs true
/--
Search strategies which Aesop can use.
-/
inductive Strategy
/--
Best-first search. This is the default strategy.
-/
| bestFirst
/--
Depth-first search. Whenever a rule is applied, Aesop immediately tries to
solve each of its subgoals (from left to right), up to the maximum rule
application depth. Goal and rule priorities are ignored, except to decide
which rule is applied first.
-/
| depthFirst
/--
Breadth-first search. Aesop always works on the oldest unsolved goal. Goal and
rule priorities are ignored, except to decide which rule is applied first.
-/
| breadthFirst
deriving Inhabited, BEq, Repr
/--
Options which modify the behaviour of the `aesop` tactic.
-/
structure Options where
/--
The search strategy used by Aesop.
-/
strategy := Strategy.bestFirst
/--
The maximum number of rule applications in any branch of the search tree
(i.e., the maximum search depth). When a branch exceeds this limit, it is
considered unprovable, but other branches may still be explored. 0 means no
limit.
-/
maxRuleApplicationDepth := 30
/--
Maximum total number of rule applications in the search tree. When this limit
is exceeded, the search ends. 0 means no limit.
-/
maxRuleApplications := 200
/--
Maximum total number of goals in the search tree. When this limit is exceeded,
the search ends. 0 means no limit.
-/
maxGoals := 0
/--
Maximum number of norm rules applied to a single goal. When this limit is
exceeded, normalisation is likely stuck in an infinite loop, so Aesop fails. 0
means no limit.
-/
maxNormIterations := 100
/--
When Aesop fails to prove a goal, it reports the goals that remain after safe
rules have been applied exhaustively to the root goal, the safe
descendants of the root goal, and so on (i.e., after the "safe prefix" of the
search tree has been unfolded). However, it is possible for the search to fail
before the safe prefix has been completely generated. In this case, Aesop
expands the safe prefix after the fact. This option limits the number of
additional rule applications generated during this process. 0 means no limit.
-/
maxSafePrefixRuleApplications := 50
/--
The transparency used by the `applyHyps` builtin rule. The rule applies a
hypothesis `h : T` if `T ≡ ∀ (x₁ : X₁) ... (xₙ : Xₙ), Y` at the given
transparency and if additionally the goal's target is defeq to `Y` at the
given transparency.
-/
applyHypsTransparency : TransparencyMode := .default
/--
The transparency used by the `assumption` builtin rule. The rule applies a
hypothesis `h : T` if `T` is defeq to the goal's target at the given
transparency.
-/
assumptionTransparency : TransparencyMode := .default
/--
The transparency used by the `destructProducts` builtin rule. The rule splits
a hypothesis `h : T` if `T` is defeq to a product-like type (e.g. `T ≡ A ∧ B`
or `T ≡ A × B`) at the given transparency.
Note: we can index this rule only if the transparency is `.reducible`. With
any other transparency, the rule becomes unindexed and is applied to every
goal.
-/
destructProductsTransparency : TransparencyMode := .reducible
/--
If this option is not `none`, the builtin `intros` rule unfolds the goal's
target with the given transparency to discover `∀` binders. For example, with
`def T := ∀ x y : Nat, x = y`, `introsTransparency? := some .default` and goal
`⊢ T`, the `intros` rule produces the goal `x, y : Nat ⊢ x = y`. With
`introsTransparency? := some .reducible`, it produces `⊢ T`. With
`introsTransparency? := none`, it only introduces arguments which are
syntactically bound by `∀` binders, so it also produces `⊢ T`.
-/
introsTransparency? : Option TransparencyMode := none
/--
If `true`, Aesop succeeds only if it proves the goal. If `false`, Aesop always
succeeds and reports the goals remaining after safe rules were applied.
-/
terminal := false
/--
If `true`, print a warning when Aesop does not prove the goal.
This can also be turned off globally with the option `aesop.warn.nonterminal`.
-/
warnOnNonterminal := true
/--
If Aesop proves a goal and this option is `true`, Aesop prints a tactic proof
as a `Try this:` suggestion.
-/
traceScript := false
/--
Enable the builtin `simp` normalisation rule.
-/
enableSimp := true
/--
Use `simp_all`, rather than `simp at *`, for the builtin `simp` normalisation
rule.
-/
useSimpAll := true
/--
Use simp theorems from the default `simp` set, i.e. those tagged with
`@[simp]`. If this option is `false`, Aesop uses only Aesop-specific simp
theorems, i.e. those tagged with `@[aesop simp]`. Note that the congruence
lemmas from the default `simp` set are always used.
-/
useDefaultSimpSet := true
/--
Enable the builtin `unfold` normalisation rule.
-/
enableUnfold := true
deriving Inhabited, BEq, Repr
/--
(aesop) Only for use by Aesop developers. Enables dynamic script structuring.
-/
register_option aesop.dev.dynamicStructuring : Bool := {
descr := "(aesop) Only for use by Aesop developers. Enables dynamic script structuring."
defValue := true
}
/--
(aesop) Only for use by Aesop developers. Uses static structuring instead of
dynamic structuring if no metavariables appear in the proof.
-/
register_option aesop.dev.optimizedDynamicStructuring : Bool := {
descr := "(aesop) Only for use by Aesop developers. Uses static structuring instead of dynamic structuring if no metavariables appear in the proof."
defValue := true
}
/--
(aesop) Only for use by Aesop developers. Generates a script even if none was requested.
-/
register_option aesop.dev.generateScript : Bool := {
descr := "(aesop) Only for use by Aesop developers. Generates a script even if none was requested."
defValue := false
}
/--
(aesop) Only for use by Aesop developers. Enables the new stateful forward reasoning engine.
-/
register_option aesop.dev.statefulForward : Bool := {
descr := "(aesop) Only for use by Aesop developers. Enables the new stateful forward reasoning engine."
defValue := true
}
/--
(aesop) Warn when apply builder is applied to a rule with conclusion of the form A ↔ B.
-/
register_option aesop.warn.applyIff : Bool := {
descr := "(aesop) Warn when apply builder is applied to a rule with conclusion of the form A ↔ B."
defValue := true
}
/--
(aesop) Warn when `aesop` does not close the goal, i.e. is used as a non-terminal tactic.
-/
register_option aesop.warn.nonterminal : Bool := {
descr := "(aesop) Warn when `aesop` does not close the goal, i.e. is used as a non-terminal tactic."
defValue := true
}
end Aesop |
.lake/packages/aesop/Aesop/Options/Internal.lean | module
public import Aesop.Check
public import Aesop.Options.Public
public section
open Lean
open Lean.Meta
namespace Aesop
structure Options' extends Options where
generateScript : Bool
forwardMaxDepth? : Option Nat
deriving Inhabited
def Options.toOptions' [Monad m] [MonadOptions m] (opts : Options)
(forwardMaxDepth? : Option Nat := none) : m Options' := do
let generateScript ←
pure (aesop.dev.generateScript.get (← getOptions)) <||>
pure opts.traceScript <||>
Check.script.isEnabled <||>
Check.script.steps.isEnabled
return { opts with generateScript, forwardMaxDepth? }
end Aesop |
.lake/packages/aesop/Aesop/RuleSet/Filter.lean | module
public import Aesop.RuleSet.Name
public import Aesop.Rule.Name
public section
open Lean
namespace Aesop
structure RuleFilter where
name : Name
scope : ScopeName
/--
`#[]` means 'match any builder'
-/
builders : Array BuilderName
/--
`#[]` means 'match any phase'
-/
phases : Array PhaseName
namespace RuleFilter
def matchesPhase (f : RuleFilter) (p : PhaseName) : Bool :=
f.phases.isEmpty || f.phases.contains p
def matchesBuilder (f : RuleFilter) (b : BuilderName) : Bool :=
f.builders.isEmpty || f.builders.contains b
def «matches» (f : RuleFilter) (n : RuleName) : Bool :=
f.name == n.name &&
f.scope == n.scope &&
f.matchesPhase n.phase &&
f.matchesBuilder n.builder
def matchesSimpTheorem? (f : RuleFilter) : Option Name :=
if f.scope == .global && f.matchesBuilder .simp then
some f.name
else
none
/--
Returns the identifier of the local norm simp rule matched by `f`, if any.
-/
def matchesLocalNormSimpRule? (f : RuleFilter) : Option Name := Id.run do
if f.scope == .local && f.matchesBuilder .simp then
return some f.name
return none
end RuleFilter
structure RuleSetNameFilter where
ns : Array RuleSetName -- #[] means 'match any rule set'
namespace RuleSetNameFilter
protected def all : RuleSetNameFilter :=
⟨#[]⟩
def matchesAll (f : RuleSetNameFilter) : Bool :=
f.ns.isEmpty
def «matches» (f : RuleSetNameFilter) (n : RuleSetName) : Bool :=
f.matchesAll || f.ns.contains n
def matchedRuleSetNames (f : RuleSetNameFilter) : Option (Array RuleSetName) :=
if f.matchesAll then none else some f.ns
end Aesop.RuleSetNameFilter |
.lake/packages/aesop/Aesop/RuleSet/Member.lean | module
public import Aesop.Rule
public section
namespace Aesop
inductive BaseRuleSetMember
| normRule (r : NormRule)
| unsafeRule (r : UnsafeRule)
| safeRule (r : SafeRule)
| unfoldRule (r : UnfoldRule)
| normForwardRule (r₁ : ForwardRule) (r₂ : NormRule)
| unsafeForwardRule (r₁ : ForwardRule) (r₂ : UnsafeRule)
| safeForwardRule (r₁ : ForwardRule) (r₂ : SafeRule)
deriving Inhabited
def BaseRuleSetMember.name : BaseRuleSetMember → RuleName
| normRule r => r.name
| unsafeRule r => r.name
| safeRule r => r.name
| unfoldRule r => r.name
| normForwardRule r _ => r.name
| unsafeForwardRule r _ => r.name
| safeForwardRule r _ => r.name
inductive GlobalRuleSetMember
| base (m : BaseRuleSetMember)
| normSimpRule (e : NormSimpRule)
deriving Inhabited
def GlobalRuleSetMember.name : GlobalRuleSetMember → RuleName
| base m => m.name
| normSimpRule r => r.name
inductive LocalRuleSetMember
| global (m : GlobalRuleSetMember)
| localNormSimpRule (r : LocalNormSimpRule)
deriving Inhabited
def LocalRuleSetMember.name : LocalRuleSetMember → RuleName
| global m => m.name
| localNormSimpRule r => r.name
def LocalRuleSetMember.toGlobalRuleSetMember? :
LocalRuleSetMember → Option GlobalRuleSetMember
| global m => some m
| _ => none
end Aesop |
.lake/packages/aesop/Aesop/RuleSet/Name.lean | module
public section
open Lean
namespace Aesop
abbrev RuleSetName := Name -- Not really an abbreviation is it?
def defaultRuleSetName : RuleSetName := `default
def builtinRuleSetName : RuleSetName := `builtin
def localRuleSetName : RuleSetName := `local
def builtinRuleSetNames : Array RuleSetName :=
#[defaultRuleSetName, builtinRuleSetName]
def RuleSetName.isReserved (n : RuleSetName) : Bool :=
n == localRuleSetName || builtinRuleSetNames.contains n
end Aesop |
.lake/packages/aesop/Aesop/Frontend/Command.lean | module
public meta import Aesop.Frontend.Basic
public meta import Aesop.Stats.Report
public meta import Aesop.Frontend.Extension
public meta import Aesop.Frontend.RuleExpr
public import Batteries.Linter.UnreachableTactic
import Aesop.Frontend.Extension
import Aesop.Stats.Report
public meta section
open Lean Lean.Elab Lean.Elab.Command
namespace Aesop.Frontend.Parser
syntax (name := declareRuleSets)
"declare_aesop_rule_sets " "[" ident,+,? "]"
(" (" &"default" " := " Aesop.bool_lit ")")? : command
elab_rules : command
| `(declare_aesop_rule_sets [ $ids:ident,* ]
$[(default := $dflt?:Aesop.bool_lit)]?) => do
let rsNames := (ids : Array Ident).map (·.getId)
let dflt := (← dflt?.mapM (elabBoolLit ·)).getD false
rsNames.forM checkRuleSetNotDeclared
elabCommand $ ← `(meta initialize ($(quote rsNames).forM $ declareRuleSetUnchecked (isDefault := $(quote dflt))))
elab (name := addRules)
attrKind:attrKind "add_aesop_rules " e:Aesop.rule_expr : command => do
let attrKind :=
match attrKind with
| `(Lean.Parser.Term.attrKind| local) => .local
| `(Lean.Parser.Term.attrKind| scoped) => .scoped
| _ => .global
let rules ← liftTermElabM do
let e ← RuleExpr.elab e |>.run (← ElabM.Context.forAdditionalGlobalRules)
e.buildAdditionalGlobalRules none
for (rule, rsNames) in rules do
for rsName in rsNames do
addGlobalRule rsName rule attrKind (checkNotExists := true)
initialize Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``addRules
elab (name := eraseRules)
"erase_aesop_rules " "[" es:Aesop.rule_expr,* "]" : command => do
let filters ← Elab.Command.liftTermElabM do
let ctx ← ElabM.Context.forGlobalErasing
(es : Array _).mapM λ e => do
let e ← RuleExpr.elab e |>.run ctx
e.toGlobalRuleFilters
for fs in filters do
for (rsFilter, rFilter) in fs do
eraseGlobalRules rsFilter rFilter (checkExists := true)
syntax (name := showRules)
withPosition("#aesop_rules" (colGt ppSpace ident)*) : command
elab_rules : command
| `(#aesop_rules $ns:ident*) => do
liftTermElabM do
let lt := λ (n₁, _) (n₂, _) => n₁.cmp n₂ |>.isLT
let rss ←
if ns.isEmpty then
let rss ← getDeclaredGlobalRuleSets
pure $ rss.qsort lt
else
ns.mapM λ n => return (n.getId, ← getGlobalRuleSet n.getId)
TraceOption.ruleSet.withEnabled do
for (name, rs, _) in rss do
withConstAesopTraceNode .ruleSet (return m!"Rule set '{name}'") do
rs.trace .ruleSet
def evalStatsReport? (name : Name) : CoreM (Option StatsReport) := do
try
unsafe evalConstCheck StatsReport ``StatsReport name
catch _ =>
return none
syntax (name := showStats) withPosition("#aesop_stats " (colGt ident)?) : command
elab_rules : command
| `(#aesop_stats) => do
logInfo $ StatsReport.default $ ← getStatsArray
| `(#aesop_stats $report:ident) => do
let openDecl := OpenDecl.simple ``Aesop.StatsReport []
withScope (λ s => { s with openDecls := openDecl :: s.openDecls }) do
let names ← resolveGlobalConst report
liftTermElabM do
for name in names do
if let some report ← evalStatsReport? name then
logInfo $ report $ ← getStatsArray
break
throwError "'{report}' is not a constant of type 'Aesop.StatsReport'"
end Aesop.Frontend.Parser |
.lake/packages/aesop/Aesop/Frontend/RuleExpr.lean | module
public import Aesop.RuleSet.Filter
public import Aesop.Builder.Basic
import Aesop.Builder.Apply
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
import Aesop.Index.DiscrTreeConfig
public section
open Lean
open Lean.Meta
open Lean.Elab
open Lean.Elab.Term
variable [Monad m] [MonadError m]
namespace Aesop.Frontend
namespace Parser
declare_syntax_cat Aesop.priority
syntax num "%" : Aesop.priority
syntax "-"? num : Aesop.priority
end Parser
inductive Priority
| int (i : Int)
| percent (p : Percent)
deriving Inhabited
namespace Priority
def «elab» (stx : Syntax) : ElabM Priority :=
withRef stx do
unless ← shouldParsePriorities do throwError
"unexpected priority."
match stx with
| `(priority| $p:num %) =>
let p := p.raw.toNat
match Percent.ofNat p with
| some p => return percent p
| none => throwError "percentage '{p}%' is not between 0 and 100."
| `(priority| - $i:num) =>
return int $ - i.raw.toNat
| `(priority| $i:num) =>
return int i.raw.toNat
| _ => throwUnsupportedSyntax
instance : ToString Priority where
toString
| int i => toString i
| percent p => p.toHumanString
def toInt? : Priority → Option Int
| int i => some i
| _ => none
def toPercent? : Priority → Option Percent
| percent p => some p
| _ => none
end Priority
namespace Parser
declare_syntax_cat Aesop.phase (behavior := symbol)
syntax "safe" : Aesop.phase
syntax "norm" : Aesop.phase
syntax "unsafe" : Aesop.phase
end Parser
def PhaseName.«elab» (stx : Syntax) : ElabM PhaseName :=
withRef stx do
match stx with
| `(phase| safe) => return .safe
| `(phase| norm) => return .norm
| `(phase| unsafe) => return .«unsafe»
| _ => throwUnsupportedSyntax
namespace Parser
declare_syntax_cat Aesop.builder_name (behavior := symbol)
syntax "apply" : Aesop.builder_name
syntax "simp" : Aesop.builder_name
syntax "unfold" : Aesop.builder_name
syntax "tactic" : Aesop.builder_name
syntax "constructors" : Aesop.builder_name
syntax "forward" : Aesop.builder_name
syntax "destruct" : Aesop.builder_name
syntax "cases" : Aesop.builder_name
syntax "default" : Aesop.builder_name
end Parser
inductive DBuilderName
| regular (b : BuilderName)
| «default»
deriving Inhabited
namespace DBuilderName
def «elab» (stx : Syntax) : ElabM DBuilderName :=
withRef stx do
match stx with
| `(builder_name| apply) => return regular .apply
| `(builder_name| simp) => return regular .simp
| `(builder_name| unfold) => return regular .unfold
| `(builder_name| tactic) => return regular .tactic
| `(builder_name| constructors) => return regular .constructors
| `(builder_name| forward) => return regular .forward
| `(builder_name| destruct) => return regular .destruct
| `(builder_name| cases) => return regular .cases
| `(builder_name| default) => return «default»
| _ => throwUnsupportedSyntax
instance : ToString DBuilderName where
toString
| regular b => toString b
| default => "default"
def toBuilderName? : DBuilderName → Option BuilderName
| regular b => some b
| _ => none
def toRuleBuilder : DBuilderName → RuleBuilder
| .regular .apply => RuleBuilder.apply
| .regular .cases => RuleBuilder.cases
| .regular .constructors => RuleBuilder.constructors
| .regular .destruct => RuleBuilder.forward (isDestruct := true)
| .regular .forward => RuleBuilder.forward (isDestruct := false)
| .regular .simp => RuleBuilder.simp
| .regular .tactic => RuleBuilder.tactic
| .regular .unfold => RuleBuilder.unfold
| .default => RuleBuilder.default
end DBuilderName
namespace Parser
declare_syntax_cat Aesop.indexing_mode (behavior := symbol)
syntax "target " term : Aesop.indexing_mode
syntax "hyp " term : Aesop.indexing_mode
syntax "unindexed " : Aesop.indexing_mode
end Parser
def elabSingleIndexingMode (stx : Syntax) : ElabM IndexingMode :=
withRef stx do
match stx with
| `(indexing_mode| target $t:term) => .target <$> elabKeys t
| `(indexing_mode| hyp $t:term) => .hyps <$> elabKeys t
| `(indexing_mode| unindexed) => return .unindexed
| _ => throwUnsupportedSyntax
where
elabKeys (stx : Syntax) : ElabM (Array DiscrTree.Key) :=
show TermElabM _ from withoutModifyingState do
mkDiscrTreePath (← elabPattern stx)
def IndexingMode.elab (stxs : Array Syntax) : ElabM IndexingMode :=
.or <$> stxs.mapM elabSingleIndexingMode
def CasesPattern.elab (stx : Syntax) : TermElabM CasesPattern := do
abstractMVars (← elabPattern stx)
namespace Parser
syntax transparency := &"default" <|> &"reducible" <|> &"instances" <|> &"all"
end Parser
open Parser in
def elabTransparency : TSyntax ``transparency → TermElabM TransparencyMode
| `(transparency| default) => return .default
| `(transparency| reducible) => return .reducible
| `(transparency| instances) => return .instances
| `(transparency| all) => return .all
| _ => throwUnsupportedSyntax
namespace Parser
declare_syntax_cat Aesop.builder_option
syntax " (" &"immediate" " := " "[" ident,+,? "]" ")" : Aesop.builder_option
syntax " (" &"index" " := " "[" Aesop.indexing_mode,+,? "]" ")" : Aesop.builder_option
syntax " (" &"pattern" " := " term ")" : Aesop.builder_option
syntax " (" &"cases_patterns" " := " "[" term,+,? "]" ")" : Aesop.builder_option
syntax " (" &"transparency" " := " transparency ")" : Aesop.builder_option
syntax " (" &"transparency!" " := " transparency ")" : Aesop.builder_option
end Parser
inductive BuilderOption
| immediate (names : Array Name)
| index (imode : IndexingMode)
| pattern (stx : Term)
| casesPatterns (pats : Array CasesPattern)
| transparency (md : TransparencyMode) (alsoForIndex : Bool)
namespace BuilderOption
def «elab» (stx : TSyntax `Aesop.builder_option) : ElabM BuilderOption :=
withRef stx do
match stx with
| `(builder_option| (immediate := [$ns:ident,*])) =>
return immediate $ (ns : Array Syntax).map (·.getId)
| `(builder_option| (index := [$imodes:Aesop.indexing_mode,*])) =>
index <$> IndexingMode.elab imodes
| `(builder_option| (pattern := $pat:term)) =>
return pattern pat
| `(builder_option| (cases_patterns := [$pats:term,*])) =>
casesPatterns <$> (pats : Array Syntax).mapM (CasesPattern.elab ·)
| `(builder_option| (transparency := $md)) =>
let md ← elabTransparency md
return transparency md (alsoForIndex := false)
| `(builder_option| (transparency! := $md)) =>
let md ← elabTransparency md
return transparency md (alsoForIndex := true)
| _ => throwUnsupportedSyntax
end BuilderOption
def addBuilderOption (bos : RuleBuilderOptions) :
BuilderOption → RuleBuilderOptions
| .immediate ns => { bos with immediatePremises? := ns }
| .index imode => { bos with indexingMode? := imode }
| .pattern pat => { bos with pattern? := pat }
| .casesPatterns ps => { bos with casesPatterns? := ps }
| .transparency md alsoForIndex =>
let bos := { bos with transparency? := md }
if alsoForIndex then
{ bos with indexTransparency? := md }
else
bos
namespace Parser
syntax ruleSetsFeature := "(" &"rule_sets" " := " "[" ident,+,? "]" ")"
end Parser
def RuleSetName.elab (stx : Syntax) : RuleSetName :=
stx.getId.eraseMacroScopes
-- We erase macro scopes to support macros such as
-- macro &"aesop_test" : tactic => `(tactic| aesop (rule_sets [test]))
-- Here the macro hygienifies `test` by appending macro scopes, but we want
-- to interpret `test` as a global name.
structure RuleSets where
ruleSets : Array RuleSetName
deriving Inhabited
namespace RuleSets
def «elab» (stx : Syntax) : ElabM RuleSets :=
withRef stx do
match stx with
| `(Parser.ruleSetsFeature| (rule_sets := [$ns:ident,*])) =>
return ⟨(ns : Array Syntax).map RuleSetName.elab⟩
| _ => throwUnsupportedSyntax
end RuleSets
namespace Parser
declare_syntax_cat Aesop.feature (behavior := symbol)
-- NOTE: This grammar has overlapping rules `ident`, `Aesop.phase` and
-- `Aesop.builder_name`, which can all consist of a single ident. For ambiguous
-- parses, a `choice` node with two children is created; one being an
-- `Aesop.phase` or `Aesop.builder_name` node and the other being a `featIdent`
-- node. When we process these `choice` nodes, we select the non-`ident` one.
syntax Aesop.phase : Aesop.feature
syntax Aesop.priority : Aesop.feature
syntax Aesop.builder_name : Aesop.feature
syntax Aesop.builder_option : Aesop.feature
syntax ruleSetsFeature : Aesop.feature
syntax (name := featIdent) ident : Aesop.feature
syntax "(" term ")" : Aesop.feature
end Parser
inductive Feature
| phase (p : PhaseName)
| priority (p : Priority)
| builder (b : DBuilderName)
| builderOption (o : BuilderOption)
| term (i : Term)
| ruleSets (rs : RuleSets)
deriving Inhabited
namespace Feature
-- Workaround for codegen bug, see #182
set_option compiler.extract_closed false in
partial def «elab» (stx : Syntax) : ElabM Feature :=
withRef stx do
match stx with
| `(feature| $p:Aesop.priority) => priority <$> Priority.elab p
| `(feature| $p:Aesop.phase) => phase <$> PhaseName.elab p
| `(feature| $b:Aesop.builder_name) => builder <$> DBuilderName.elab b
| `(feature| $o:Aesop.builder_option) => builderOption <$> BuilderOption.elab o
| `(feature| $rs:ruleSetsFeature) => ruleSets <$> RuleSets.elab rs
| `(feature| $i:ident) => return term i
| `(feature| ($t:term)) => return term t
| stx => do
if stx.isOfKind choiceKind then
let nonIdentAlts :=
stx.getArgs.filter λ stx => ! stx.isOfKind ``Parser.featIdent
if h : nonIdentAlts.size = 1 then
return ← «elab» $ nonIdentAlts[0]
throwUnsupportedSyntax
end Feature
namespace Parser
declare_syntax_cat Aesop.rule_expr (behavior := symbol)
syntax Aesop.feature : Aesop.rule_expr
syntax Aesop.feature ppSpace Aesop.rule_expr : Aesop.rule_expr
syntax Aesop.feature " [" Aesop.rule_expr,+,? "]" : Aesop.rule_expr
end Parser
inductive RuleExpr
| node (f : Feature) (children : Array RuleExpr)
deriving Inhabited
namespace RuleExpr
partial def «elab» (stx : Syntax) : ElabM RuleExpr :=
withRef stx do
match stx with
| `(rule_expr| $f:Aesop.feature $e:Aesop.rule_expr) => do
return node (← Feature.elab f) #[← «elab» e]
| `(rule_expr| $f:Aesop.feature [ $es:Aesop.rule_expr,* ]) => do
return node (← Feature.elab f) (← (es : Array Syntax).mapM «elab»)
| `(rule_expr| $f:Aesop.feature) => do
return node (← Feature.elab f) #[]
| _ => throwUnsupportedSyntax
-- Fold the branches of a `RuleExpr`. We treat each branch as a list of features
-- which we fold over. The result is an array containing one result per branch.
partial def foldBranchesM {m} [Monad m] (f : σ → Feature → m σ) (init : σ)
(e : RuleExpr) : m (Array σ) :=
go init #[] e
where
go (c : σ) (acc : Array σ) : RuleExpr → m (Array σ)
| RuleExpr.node feat cs => do
let c ← f c feat
if cs.isEmpty then
return acc.push c
else
cs.foldlM (init := acc) (go c)
end RuleExpr
structure RuleConfig where
term? : Option Term
phase? : Option PhaseName
priority? : Option Priority
builder? : Option DBuilderName
builderOptions : RuleBuilderOptions
ruleSets : RuleSets
namespace RuleConfig
def addFeature (c : RuleConfig) : Feature → m RuleConfig
| .phase phase => return { c with phase? := phase }
| .priority priority => return { c with priority? := priority }
| .term term => do
if let some oldTerm := c.term? then
throwError "duplicate rule '{term}'; rule '{oldTerm}' was already given.\nUse [<term>,...] to give multiple rules."
return { c with term? := term }
| .builder builder => return { c with builder? := builder }
| .builderOption opt =>
return { c with builderOptions := addBuilderOption c.builderOptions opt }
| .ruleSets newRuleSets =>
have _ : Ord RuleSetName := ⟨Name.quickCmp⟩
let ruleSets := ⟨Array.mergeDedup c.ruleSets.ruleSets newRuleSets.ruleSets.qsortOrd⟩
return { c with ruleSets := ruleSets }
def getPenalty (phase : PhaseName) (c : RuleConfig) : m Int := do
let (some priority) := c.priority? | throwError
"{phase} rules must specify an integer penalty"
let (some penalty) := priority.toInt? | throwError
"{phase} rules must specify an integer penalty (not a success probability)"
return penalty
def getSuccessProbability (c : RuleConfig) : m Percent := do
let (some priority) := c.priority? | throwError
"unsafe rules must specify a success probability"
let (some prob) := priority.toPercent? | throwError
"unsafe rules must specify a success probability (not an integer penalty)"
return prob
def getSimpPriority (c : RuleConfig) : m Nat := do
let prio? := do
let priority ← (← c.priority?).toInt?
guard $ priority ≥ 0
return priority.toNat
let (some prio) := prio? | throwError
"simp rules must specify a non-negative integer priority"
return prio
def getTerm (c : RuleConfig) : m Term := do
let some term := c.term? | throwError
"missing rule"
return term
def getPhase (c : RuleConfig) : m PhaseName := do
let some phase := c.phase? | throwError
"missing phase (norm/safe/unsafe)"
return phase
def getBuilder (c : RuleConfig) : m DBuilderName := do
let some builder := c.builder? | throwError
"missing rule builder (apply, forward, simp, ...)"
return builder
def getPhaseSpec (c : RuleConfig) : m PhaseSpec := do
match ← c.getPhase with
| .safe =>
return .safe { penalty := ← c.getPenalty .safe, safety := .safe }
| .unsafe =>
return .unsafe { successProbability := ← c.getSuccessProbability }
| .norm =>
return .norm { penalty := ← c.getPenalty .norm }
def getRuleBuilderInput (c : RuleConfig) : TermElabM RuleBuilderInput := do
let term ← c.getTerm
let phase ← c.getPhaseSpec
let options := c.builderOptions
return { term, options, phase }
def buildRule (c : RuleConfig) :
ElabM (LocalRuleSetMember × Array RuleSetName) := do
let builder ← c.getBuilder
let builderInput ← c.getRuleBuilderInput
let ruleSetMember ← builder.toRuleBuilder builderInput
return (ruleSetMember, c.ruleSets.ruleSets)
def buildGlobalRule (c : RuleConfig) :
ElabM (GlobalRuleSetMember × Array RuleSetName) := do
let (m, rsNames) ← buildRule c
if let some m := m.toGlobalRuleSetMember? then
return (m, rsNames)
else
throwError "internal error: buildGlobalRule: unexpected local rule"
def buildLocalRule (c : RuleConfig) : ElabM LocalRuleSetMember :=
(·.fst) <$> c.buildRule
def toRuleFilter (c : RuleConfig) : ElabM (RuleSetNameFilter × RuleFilter) := do
let term ← c.getTerm
if ! term.raw.isIdent then
throwError "erase rule must be a name, not a composite term"
let some e ← resolveId? term
| throwError "unknown identifier: {term}"
let (name, scope) ←
match e with
| .const decl _ => pure (decl, .global)
| .fvar fvarId => pure ((← fvarId.getDecl).userName, .local)
| _ => throwError "internal error: expected const or fvar, but got '{e}'"
let builders ←
match c.builder? with
| none => pure #[]
| some b => do
let (some builder) := b.toBuilderName? | throwError
"{b} cannot be used when erasing rules.\nUse the corresponding non-default builder (e.g. 'apply' or 'constructors') instead."
-- We could instead look for the correct non-default builder ourselves
-- by re-running the logic that determines which builder to use.
pure #[builder]
let phases :=
match c.phase? with
| none => #[]
| some p => #[p]
let ruleSetNames := c.ruleSets.ruleSets
return ({ ns := ruleSetNames }, { name, scope, builders, phases })
def validateForAdditionalRules (c : RuleConfig) (defaultRuleSet : RuleSetName) :
m RuleConfig := do
let term ← c.getTerm
let (phase, priority) ← getPhaseAndPriority c
let builder := c.builder?.getD .default
let builderOptions := c.builderOptions
let ruleSets :=
if c.ruleSets.ruleSets.isEmpty then
⟨#[defaultRuleSet]⟩
else
c.ruleSets
return {
term? := term
phase? := phase
priority? := priority
builder? := builder
builderOptions, ruleSets
}
where
getPhaseAndPriority (c : RuleConfig) : m (PhaseName × Priority) :=
match c.builder?, c.phase?, c.priority? with
| _, some phase, some prio =>
return (phase, prio)
| some (.regular .simp), none, none =>
return (.norm, .int defaultSimpRulePriority)
| some (.regular .simp), none, some prio =>
return (.norm, prio)
| some (.regular .simp), some phase, none =>
return (phase, .int defaultSimpRulePriority)
| _, some .unsafe, none =>
return (.unsafe, .percent defaultSuccessProbability)
| _, some .safe, none =>
return (.safe, .int defaultSafePenalty)
| _, some .norm, none =>
return (.norm, .int defaultNormPenalty)
| _, none, some prio@(.percent _) =>
return (.unsafe, prio)
| _, none, _ =>
throwError "phase (safe/unsafe/norm) not specified."
end RuleConfig
namespace RuleExpr
def toRuleConfigs (e : RuleExpr) (init : RuleConfig) :
m (Array RuleConfig) :=
e.foldBranchesM (init := init) λ c feature => c.addFeature feature
def toAdditionalRules (e : RuleExpr) (init : RuleConfig)
(defaultRuleSet : RuleSetName) : m (Array RuleConfig) := do
let cs ← e.toRuleConfigs init
cs.mapM (·.validateForAdditionalRules defaultRuleSet)
def toAdditionalGlobalRules (decl? : Option Name) (e : RuleExpr) :
m (Array RuleConfig) :=
let init := {
term? := decl?.map (mkIdent ·)
phase? := none
priority? := none
builder? := none
builderOptions := ∅
ruleSets := ⟨#[]⟩
}
toAdditionalRules e init defaultRuleSetName
def buildAdditionalGlobalRules (decl? : Option Name) (e : RuleExpr) :
TermElabM (Array (GlobalRuleSetMember × Array RuleSetName)) := do
let go : ElabM _ := do
(← e.toAdditionalGlobalRules decl?).mapM (·.buildGlobalRule)
go.run $ ← ElabM.Context.forAdditionalGlobalRules
def toAdditionalLocalRules (e : RuleExpr) : MetaM (Array RuleConfig) :=
let init := {
term? := none
phase? := none
priority? := none
builder? := none
builderOptions := ∅
ruleSets := ⟨#[]⟩
}
toAdditionalRules e init localRuleSetName
def buildAdditionalLocalRules (goal : MVarId) (e : RuleExpr) :
TermElabM (Array LocalRuleSetMember) :=
let go : ElabM _ := do (← e.toAdditionalLocalRules).mapM (·.buildLocalRule)
go.run $ .forAdditionalRules goal
def toRuleFilters (e : RuleExpr) :
ElabM (Array (RuleSetNameFilter × RuleFilter)) := do
let initialConfig := {
term? := none
phase? := none
priority? := none
builder? := none
builderOptions := ∅
ruleSets := ⟨#[]⟩
}
let configs ← e.toRuleConfigs initialConfig
configs.mapM (·.toRuleFilter)
def toGlobalRuleFilters (e : RuleExpr) :
TermElabM (Array (RuleSetNameFilter × RuleFilter)) := do
e.toRuleFilters |>.run $ ← ElabM.Context.forGlobalErasing
def toLocalRuleFilters (e : RuleExpr) : ElabM (Array RuleFilter) :=
return (← e.toRuleFilters).map (·.snd)
end Aesop.Frontend.RuleExpr |
.lake/packages/aesop/Aesop/Frontend/Saturate.lean | module
public meta import Aesop.Saturate
public meta import Aesop.Frontend.Extension
public meta import Aesop.Builder.Forward
import Aesop.RuleSet
public meta section
open Lean Lean.Meta Lean.Elab Lean.Elab.Term Lean.PrettyPrinter
namespace Aesop.Frontend.Parser
syntax usingRuleSets := "using " ident+
syntax additionalRule := "*" <|> term
syntax additionalRules := "[" additionalRule,* "]"
end Parser
open Parser
def _root_.Aesop.ElabM.runForwardElab (goal : MVarId) (x : ElabM α) :
TermElabM α :=
x |>.run { parsePriorities := true, goal }
def mkForwardOptions (maxDepth? : Option Nat) (traceScript : Bool) :
CoreM Options' :=
({ traceScript } : Aesop.Options).toOptions' maxDepth?
def elabGlobalRuleSets (rsNames : Array Ident) :
CoreM (Array (GlobalRuleSet × Name × Name)) := do
getGlobalRuleSets $
(← getDefaultRuleSetNames).toArray ++ rsNames.map (·.getId)
def elabForwardRule (term : Term) : ElabM LocalRuleSetMember := do
let builderInput := {
options := ∅
phase := .safe { penalty := 1, safety := .safe }
term
}
let ctx := { parsePriorities := true, goal := (← read).goal }
RuleBuilder.forward (isDestruct := false) builderInput |>.run ctx
def mkHypForwardRule (fvarId : FVarId) : ElabM LocalRuleSetMember := do
elabForwardRule (← delab $ .fvar fvarId)
-- TODO mv
def isImplication (e : Expr) : MetaM Bool :=
forallBoundedTelescope e (some 1) λ args body =>
pure (! args.isEmpty) <&&> isProp body
def mkHypImplicationRule? (fvarId : FVarId) :
ElabM (Option LocalRuleSetMember) := do
let goal := (← read).goal
goal.withContext do
withTransparency .reducible do
if ← isImplication (← fvarId.getType) then
mkHypForwardRule fvarId
else
return none
def addLocalImplications (rs : LocalRuleSet) : ElabM LocalRuleSet := do
let goal := (← read).goal
let mut rs := rs
for ldecl in (← goal.getDecl).lctx do
if ldecl.isImplementationDetail then
continue
if let some rsMember ← mkHypImplicationRule? ldecl.fvarId then
rs := rs.add rsMember
return rs
def elabAdditionalForwardRules (rs : LocalRuleSet) (rules : Array (TSyntax ``additionalRule)) : ElabM LocalRuleSet := do
let mut rs := rs
let mut addImplications := false
for rule in rules do
match rule with
| `(additionalRule| *) => addImplications := true
| `(additionalRule| $t:term) => do
rs := rs.add (← elabForwardRule t)
| _ => throwUnsupportedSyntax
if addImplications then
rs ← addLocalImplications rs
return rs
def elabForwardRuleSetCore (rsNames : Array Ident)
(additionalRules : Array (TSyntax ``additionalRule))
(options : Options') : ElabM LocalRuleSet := do
let rss ← elabGlobalRuleSets rsNames
let rs ← mkLocalRuleSet rss options
elabAdditionalForwardRules rs additionalRules
def elabForwardRuleSet (rsNames? : Option (TSyntax ``usingRuleSets))
(additionalRules? : Option (TSyntax ``additionalRules)) (options : Options') :
ElabM LocalRuleSet := do
let rsNames? ← rsNames?.mapM λ
| `(usingRuleSets| using $rs:ident*) => pure rs
| _ => throwUnsupportedSyntax
let additionalRules? ← additionalRules?.mapM λ
| `(additionalRules| [$rs:additionalRule,*]) => pure (rs : Array _)
| _ => throwUnsupportedSyntax
elabForwardRuleSetCore (rsNames?.getD #[]) (additionalRules?.getD #[]) options
open Lean.Elab.Tactic
def evalSaturate (depth? : Option (TSyntax `num))
(rules? : Option (TSyntax ``additionalRules))
(rs? : Option (TSyntax ``usingRuleSets)) (traceScript : Bool) :
TacticM Unit := do
let depth? := depth?.map (·.getNat)
let options ← mkForwardOptions depth? traceScript
let rs ← elabForwardRuleSet rs? rules? options
|>.runForwardElab (← getMainGoal)
liftMetaTactic1 (saturate rs · options)
elab "saturate " depth?:(num)? ppSpace rules?:(additionalRules)? ppSpace rs?:(usingRuleSets)? : tactic => do
evalSaturate depth? rules? rs? (traceScript := false)
elab "saturate? " depth?:(num)? ppSpace rules?:(additionalRules)? ppSpace rs?:(usingRuleSets)? : tactic => do
evalSaturate depth? rules? rs? (traceScript := true)
macro "forward " rules?:(additionalRules)? ppSpace rs?:(usingRuleSets)? : tactic =>
`(tactic| saturate 1 $[$rules?]? $[$rs?]?)
macro "forward? " rules?:(additionalRules)? ppSpace rs?:(usingRuleSets)? : tactic =>
`(tactic| saturate? 1 $[$rules?]? $[$rs?]?)
end Aesop.Frontend |
.lake/packages/aesop/Aesop/Frontend/Extension.lean | module
public import Aesop.Frontend.Extension.Init
public import Lean.Meta.Tactic.Simp.Simproc
import Lean.Meta.Tactic.Simp.Attr
public section
open Lean Lean.Meta
namespace Aesop.Frontend
def extensionDescr (rsName : RuleSetName) :
SimpleScopedEnvExtension.Descr BaseRuleSetMember BaseRuleSet where
name := rsName
addEntry rs r := rs.add r
initial := ∅
def declareRuleSetUnchecked (rsName : RuleSetName) (isDefault : Bool) :
IO Unit := do
let ext ← registerSimpleScopedEnvExtension $ extensionDescr rsName
let simpExtName := .mkStr1 s!"aesop_{rsName}"
discard $ registerSimpAttr simpExtName (ref := simpExtName)
s!"simp theorems in the Aesop rule set '{rsName}'"
let simprocExtName := .mkStr1 s!"aesop_{rsName}_proc"
discard $ Simp.registerSimprocAttr simprocExtName (name := simprocExtName)
(ref? := none) s!"simprocs in the Aesop rule set '{rsName}'"
declaredRuleSetsRef.modify λ rs =>
let ruleSets := rs.ruleSets.insert rsName (ext, simpExtName, simprocExtName)
let defaultRuleSets :=
if isDefault then
rs.defaultRuleSets.insert rsName
else
rs.defaultRuleSets
{ ruleSets, defaultRuleSets }
def isRuleSetDeclared (rsName : RuleSetName) : IO Bool :=
return (← getDeclaredRuleSets).contains rsName
variable [Monad m] [MonadError m] [MonadLiftT IO m]
[MonadLiftT (ST IO.RealWorld) m] [MonadEnv m] [MonadResolveName m]
def checkRuleSetNotDeclared (rsName : RuleSetName) : m Unit := do
if ← isRuleSetDeclared rsName then
throwError "rule set '{rsName}' already exists"
def declareRuleSet (rsName : RuleSetName) (isDefault : Bool) : m Unit := do
checkRuleSetNotDeclared rsName
declareRuleSetUnchecked rsName isDefault
initialize
builtinRuleSetNames.forM (declareRuleSetUnchecked (isDefault := true))
def getGlobalRuleSetData (rsName : RuleSetName) :
m (RuleSetExtension × Name × SimpExtension × Name × Simp.SimprocExtension) := do
let (some (ext, simpExtName, simprocExtName)) :=
(← getDeclaredRuleSets)[rsName]?
| throwError "no such rule set: '{rsName}'\n (Use 'declare_aesop_rule_set' to declare rule sets.\n Declared rule sets are not visible in the current file; they only become visible once you import the declaring file.)"
let some simpExt ← getSimpExtension? simpExtName
| throwError "internal error: expected '{simpExtName}' to be a declared simp extension"
let some simprocExt ← Simp.getSimprocExtension? simpExtName
| throwError "internal error: expected '{simpExtName}' to be a declared simp extension"
return (ext, simpExtName, simpExt, simprocExtName, simprocExt)
def getGlobalRuleSetFromData (ext : RuleSetExtension) (simpExt : SimpExtension)
(simprocExt : Simp.SimprocExtension) : m GlobalRuleSet := do
let env ← getEnv
let base := ext.getState env
let simpTheorems := simpExt.getState env
let simprocs := simprocExt.getState env
return { base with simpTheorems, simprocs }
def getGlobalRuleSet (rsName : RuleSetName) :
CoreM (GlobalRuleSet × Name × Name) := do
let (ext, simpExtName, simpExt, simprocExtName, simprocExt) ←
getGlobalRuleSetData rsName
let rs ← getGlobalRuleSetFromData ext simpExt simprocExt
return (rs , simpExtName, simprocExtName)
def getGlobalRuleSets (rsNames : Array RuleSetName) :
CoreM (Array (GlobalRuleSet × Name × Name)) :=
rsNames.mapM getGlobalRuleSet
def getDefaultGlobalRuleSets : CoreM (Array (GlobalRuleSet × Name × Name)) := do
getGlobalRuleSets (← getDefaultRuleSetNames).toArray
def getDeclaredGlobalRuleSets :
CoreM (Array (RuleSetName × GlobalRuleSet × Name × Name)) := do
(← getDeclaredRuleSets).toArray.mapM λ (rsName, _) =>
return (rsName, ← getGlobalRuleSet rsName)
def modifyGetGlobalRuleSet (rsName : RuleSetName)
(f : GlobalRuleSet → α × GlobalRuleSet) : m α := do
let (ext, _, simpExt, _, simprocExt) ← getGlobalRuleSetData rsName
let env ← getEnv
let base := ext.getState env
let simpTheorems := simpExt.getState env
let simprocs := simprocExt.getState env
let env := ext.modifyState env λ _ => default -- an attempt to preserve linearity
let env := simpExt.modifyState env λ _ => default -- ditto
let env := simprocExt.modifyState env λ _ => default -- ditto
let rs := { base with simpTheorems, simprocs }
let (a, rs) := f rs
let env := ext.modifyState env λ _ => rs.toBaseRuleSet
let env := simpExt.modifyState env λ _ => rs.simpTheorems
setEnv env
return a
def modifyGlobalRuleSet (rsName : RuleSetName)
(f : GlobalRuleSet → GlobalRuleSet) : CoreM Unit := do
modifyGetGlobalRuleSet rsName λ rs => ((), f rs)
def addGlobalRule (rsName : RuleSetName) (r : GlobalRuleSetMember)
(kind : AttributeKind) (checkNotExists : Bool) : m Unit := do
let (ext, _, simpExt, _, simprocExt) ← getGlobalRuleSetData rsName
if checkNotExists then
let rs ← getGlobalRuleSetFromData ext simpExt simprocExt
if rs.contains r.name then
throwError "aesop: rule '{r.name.name}' is already registered in rule set '{rsName}'"
match r with
| .base m => ext.add m kind
| .normSimpRule r => do
for e in r.entries do
simpExt.add e kind
-- Workaround for a Lean bug.
if let .thm l := e then
setEnv $ simpExt.modifyState (← getEnv) λ simpTheorems =>
{ simpTheorems with erased := simpTheorems.erased.erase l.origin }
def eraseGlobalRules (rsf : RuleSetNameFilter) (rf : RuleFilter)
(checkExists : Bool) : m Unit := do
match rsf.matchedRuleSetNames with
| none =>
let anyErased ←
(← getDeclaredRuleSets).foldM (init := false) λ b rsName _ => go b rsName
if checkExists && ! anyErased then
throwError "'{rf.name}' is not registered (with the given features) in any rule set."
| some rsNames =>
let anyErased ← rsNames.foldlM (init := false) go
if checkExists && ! anyErased then
throwError "'{rf.name}' is not registered (with the given features) in any of the rule sets {rsNames.map toString}."
where
go (anyErased : Bool) (rsName : RuleSetName) : m Bool :=
modifyGetGlobalRuleSet rsName λ rs =>
let (rs, anyErasedFromRs) := rs.erase rf
(anyErased || anyErasedFromRs, rs)
end Aesop.Frontend |
.lake/packages/aesop/Aesop/Frontend/Basic.lean | module
public import Lean.Elab.Exception
public section
open Lean Lean.Elab
namespace Aesop.Frontend.Parser
declare_syntax_cat Aesop.bool_lit (behavior := symbol)
syntax "true" : Aesop.bool_lit
syntax "false" : Aesop.bool_lit
end Parser
def elabBoolLit [Monad m] [MonadRef m] [MonadExceptOf Exception m]
(stx : TSyntax `Aesop.bool_lit) : m Bool :=
withRef stx do
match stx with
| `(bool_lit| true) => return true
| `(bool_lit| false) => return false
| _ => throwUnsupportedSyntax
end Aesop.Frontend |
.lake/packages/aesop/Aesop/Frontend/Tactic.lean | module
public import Aesop.Frontend.RuleExpr
public import Batteries.Linter.UnreachableTactic
public import Aesop.RuleSet
import Aesop.Frontend.Extension
import Lean.Elab.SyntheticMVars
import Lean.Meta.Eval
public section
open Lean
open Lean.Meta
open Lean.Elab
open Lean.Elab.Term
namespace Aesop.Frontend.Parser
declare_syntax_cat Aesop.tactic_clause
syntax ruleSetSpec := "-"? ident
syntax " (" &"add " Aesop.rule_expr,+,? ")" : Aesop.tactic_clause
syntax " (" &"erase " Aesop.rule_expr,+,? ")" : Aesop.tactic_clause
syntax " (" &"rule_sets" " := " "[" ruleSetSpec,+,? "]" ")" : Aesop.tactic_clause
syntax " (" &"config" " := " term ")" : Aesop.tactic_clause
syntax " (" &"simp_config" " := " term ")" : Aesop.tactic_clause
/--
`aesop <clause>*` tries to solve the current goal by applying a set of rules
registered with the `@[aesop]` attribute. See [its
README](https://github.com/JLimperg/aesop#readme) for a tutorial and a
reference.
The variant `aesop?` prints the proof it found as a `Try this` suggestion.
Clauses can be used to customise the behaviour of an Aesop call. Available
clauses are:
- `(add <phase> <priority> <builder> <rule>)` adds a rule. `<phase>` is
`unsafe`, `safe` or `norm`. `<priority>` is a percentage for unsafe rules and
an integer for safe and norm rules. `<rule>` is the name of a declaration or
local hypothesis. `<builder>` is the rule builder used to turn `<rule>` into
an Aesop rule. Example: `(add unsafe 50% apply Or.inl)`.
- `(erase <rule>)` disables a globally registered Aesop rule. Example: `(erase
Aesop.BuiltinRules.assumption)`.
- `(rule_sets := [<ruleset>,*])` enables or disables named sets of rules for
this Aesop call. Example: `(rule_sets := [-builtin, MyRuleSet])`.
- `(config { <opt> := <value> })` adjusts Aesop's search options. See
`Aesop.Options`.
- `(simp_config { <opt> := <value> })` adjusts options for Aesop's built-in
`simp` rule. The given options are directly passed to `simp`. For example,
`(simp_config := { zeta := false })` makes Aesop use
`simp (config := { zeta := false })`.
-/
syntax (name := aesopTactic) "aesop" Aesop.tactic_clause* : tactic
@[inherit_doc aesopTactic]
syntax (name := aesopTactic?) "aesop?" Aesop.tactic_clause* : tactic
meta initialize do
Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``aesopTactic
Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``aesopTactic?
end Parser
-- Inspired by declare_config_elab
unsafe def elabConfigUnsafe (type : Name) (stx : Syntax) : TermElabM α :=
withRef stx do
let e ← withoutModifyingStateWithInfoAndMessages <| withLCtx {} {} <| withSaveInfoContext <| Term.withSynthesize <| withoutErrToSorry do
let e ← Term.elabTermEnsuringType stx (Lean.mkConst type)
Term.synthesizeSyntheticMVarsNoPostponing
instantiateMVars e
evalExpr' α type e
def elabOptions : Syntax → TermElabM Aesop.Options :=
unsafe elabConfigUnsafe ``Aesop.Options
def elabSimpConfig : Syntax → TermElabM Simp.Config :=
unsafe elabConfigUnsafe ``Simp.Config
def elabSimpConfigCtx : Syntax → TermElabM Simp.ConfigCtx :=
unsafe elabConfigUnsafe ``Simp.ConfigCtx
structure TacticConfig where
additionalRules : Array RuleExpr
erasedRules : Array RuleExpr
enabledRuleSets : Std.HashSet RuleSetName
options : Aesop.Options
simpConfig : Simp.Config
simpConfigSyntax? : Option Term
namespace TacticConfig
def parse (stx : Syntax) (goal : MVarId) : TermElabM TacticConfig :=
withRef stx do
match stx with
| `(tactic| aesop $clauses:Aesop.tactic_clause*) =>
go (traceScript := false) clauses
| `(tactic| aesop? $clauses:Aesop.tactic_clause*) =>
go (traceScript := true) clauses
| _ => throwUnsupportedSyntax
where
go (traceScript : Bool) (clauses : Array (TSyntax `Aesop.tactic_clause)) :
TermElabM TacticConfig := do
let init : TacticConfig := {
additionalRules := #[]
erasedRules := #[]
enabledRuleSets := ← getDefaultRuleSetNames
options := { traceScript }
simpConfig := {}
simpConfigSyntax? := none
}
let (_, config) ← clauses.forM (addClause traceScript) |>.run init
let simpConfig ←
if let some stx := config.simpConfigSyntax? then
if config.options.useSimpAll then
(·.toConfig) <$> elabSimpConfigCtx stx
else
elabSimpConfig stx
else
if config.options.useSimpAll then
pure { : Simp.ConfigCtx}.toConfig
else
pure { : Simp.Config }
return { config with simpConfig }
addClause (traceScript : Bool) (stx : TSyntax `Aesop.tactic_clause) :
StateRefT TacticConfig TermElabM Unit :=
withRef stx do
match stx with
| `(tactic_clause| (add $es:Aesop.rule_expr,*)) => do
let rs ← (es : Array Syntax).mapM λ e =>
RuleExpr.elab e |>.run $ .forAdditionalRules goal
modify λ c => { c with additionalRules := c.additionalRules ++ rs }
| `(tactic_clause| (erase $es:Aesop.rule_expr,*)) => do
let rs ← (es : Array Syntax).mapM λ e =>
RuleExpr.elab e |>.run $ .forErasing goal
modify λ c => { c with erasedRules := c.erasedRules ++ rs }
| `(tactic_clause| (rule_sets := [ $specs:ruleSetSpec,* ])) => do
let mut enabledRuleSets := (← get).enabledRuleSets
for spec in (specs : Array Syntax) do
match spec with
| `(Parser.ruleSetSpec| - $rsName:ident) => do
let rsName := RuleSetName.elab rsName
unless enabledRuleSets.contains rsName do throwError
"aesop: trying to deactivate rule set '{rsName}', but it is not active"
enabledRuleSets := enabledRuleSets.erase rsName
| `(Parser.ruleSetSpec| $rsName:ident) => do
let rsName := RuleSetName.elab rsName
if enabledRuleSets.contains rsName then throwError
"aesop: rule set '{rsName}' is already active"
enabledRuleSets := enabledRuleSets.insert rsName
| _ => throwUnsupportedSyntax
modify λ c => { c with enabledRuleSets }
| `(tactic_clause| (config := $t:term)) =>
let options ← elabOptions t
let options :=
{ options with traceScript := options.traceScript || traceScript }
modify λ c => { c with options }
| `(tactic_clause| (simp_config := $t:term)) =>
modify λ c => { c with simpConfigSyntax? := some t }
| _ => throwUnsupportedSyntax
def updateRuleSet (rs : LocalRuleSet) (c : TacticConfig) (goal : MVarId):
TermElabM LocalRuleSet := do
let mut rs := rs
for ruleExpr in c.additionalRules do
let rules ← ruleExpr.buildAdditionalLocalRules goal
for rule in rules do
rs := rs.add rule
-- Erase erased rules
for ruleExpr in c.erasedRules do
let filters ← ruleExpr.toLocalRuleFilters |>.run $ .forErasing goal
for rFilter in filters do
let (rs', anyErased) := rs.erase rFilter
rs := rs'
if ! anyErased then
throwError "aesop: '{rFilter.name}' is not registered (with the given features) in any rule set."
return rs
def getRuleSet (goal : MVarId) (c : TacticConfig) :
TermElabM LocalRuleSet :=
goal.withContext do
let rss ← getGlobalRuleSets c.enabledRuleSets.toArray
c.updateRuleSet (← mkLocalRuleSet rss (← c.options.toOptions')) goal
end Aesop.Frontend.TacticConfig |
.lake/packages/aesop/Aesop/Frontend/Attribute.lean | module
public meta import Aesop.Frontend.Extension
public meta import Aesop.Frontend.RuleExpr
public import Aesop.Frontend.RuleExpr
public meta section
open Lean
open Lean.Elab
namespace Aesop.Frontend
namespace Parser
declare_syntax_cat Aesop.attr_rules
syntax Aesop.rule_expr : Aesop.attr_rules
syntax "[" Aesop.rule_expr,+,? "]" : Aesop.attr_rules
syntax (name := aesop) "aesop " Aesop.attr_rules : attr
end Parser
structure AttrConfig where
rules : Array RuleExpr
deriving Inhabited
namespace AttrConfig
def «elab» (stx : Syntax) : TermElabM AttrConfig :=
withRef stx do
match stx with
| `(attr| aesop $e:Aesop.rule_expr) => do
let r ← RuleExpr.elab e |>.run $ ← ElabM.Context.forAdditionalGlobalRules
return { rules := #[r] }
| `(attr| aesop [ $es:Aesop.rule_expr,* ]) => do
let ctx ← ElabM.Context.forAdditionalGlobalRules
let rs ← (es : Array Syntax).mapM λ e => RuleExpr.elab e |>.run ctx
return { rules := rs }
| _ => throwUnsupportedSyntax
end AttrConfig
initialize registerBuiltinAttribute {
name := `aesop
descr := "Register a declaration as an Aesop rule."
applicationTime := .afterCompilation
add := λ decl stx attrKind => withRef stx do
-- TODO: should be checked in any case where `decl` will be passed to `evalConst`
--ensureAttrDeclIsMeta `aesop decl attrKind
let rules ← runTermElabMAsCoreM do
let config ← AttrConfig.elab stx
config.rules.flatMapM (·.buildAdditionalGlobalRules decl)
for (rule, rsNames) in rules do
for rsName in rsNames do
addGlobalRule rsName rule attrKind (checkNotExists := true)
erase := λ decl =>
let ruleFilter :=
{ name := decl, scope := .global, builders := #[], phases := #[] }
eraseGlobalRules RuleSetNameFilter.all ruleFilter (checkExists := true)
}
end Aesop.Frontend |
.lake/packages/aesop/Aesop/Frontend/Extension/Init.lean | module
public import Aesop.RuleSet
public section
open Lean
namespace Aesop
/--
An environment extension containing an Aesop rule set. Each rule set has its
own extension.
-/
abbrev RuleSetExtension :=
SimpleScopedEnvExtension BaseRuleSetMember BaseRuleSet
/--
Structure containing information about all declared Aesop rule sets.
-/
structure DeclaredRuleSets where
/--
The collection of declared rule sets. Each rule set has an extension, the
name of the associated `SimpExtension` and the name of the associated
`SimprocExtension`. The two simp extensions are expected to be declared.
-/
ruleSets : Std.HashMap RuleSetName (RuleSetExtension × Name × Name)
/--
The set of Aesop rule sets that are enabled by default.
-/
defaultRuleSets : Std.HashSet RuleSetName
deriving Inhabited
instance : EmptyCollection DeclaredRuleSets :=
⟨∅, ∅⟩
initialize declaredRuleSetsRef : IO.Ref DeclaredRuleSets ←
IO.mkRef ∅
def getDeclaredRuleSets : IO (Std.HashMap RuleSetName (RuleSetExtension × Name × Name)) :=
return (← declaredRuleSetsRef.get).ruleSets
def getDefaultRuleSetNames : IO (Std.HashSet Name) :=
return (← declaredRuleSetsRef.get).defaultRuleSets
end Aesop |
.lake/packages/aesop/Aesop/RulePattern/Cache.lean | module
public import Aesop.Forward.Substitution
public import Aesop.Rule.Name
public section
open Lean
set_option linter.missingDocs true
namespace Aesop
/-- Entry of the rule pattern cache. -/
@[expose] def RulePatternCache.Entry := Array (RuleName × Substitution)
set_option linter.missingDocs false in
/-- A cache for the rule pattern index. -/
structure RulePatternCache where
map : Std.HashMap Expr RulePatternCache.Entry
deriving Inhabited
instance : EmptyCollection RulePatternCache :=
⟨⟨∅⟩⟩
end Aesop |
.lake/packages/aesop/Aesop/Util/Unfold.lean | module
public import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Delta
public section
open Lean Lean.Meta Lean.Elab.Tactic
namespace Aesop
-- Inspired by Lean.Meta.unfold, Lean.Meta.unfoldTarget,
-- Lean.Meta.unfoldLocalDecl.
def mkUnfoldSimpContext : MetaM Simp.Context := do
Simp.mkContext Simp.neutralConfig (simpTheorems := #[]) (congrTheorems := ← getSimpCongrTheorems)
@[inline]
def unfoldManyCore (ctx : Simp.Context) (unfold? : Name → Option (Option Name))
(e : Expr) : StateRefT (Array Name) MetaM Simp.Result :=
λ usedDeclsRef =>
(·.fst) <$> Simp.main e ctx (methods := { pre := (pre · usedDeclsRef) })
where
-- NOTE: once we succeed in unfolding something, we return `done`. This
-- means that `simp` won't recurse into the unfolded expression, missing
-- potential further opportunities for unfolding.
--
-- I've tried returning
-- `visit` instead, in which case we get recursive unfolding as desired, but
-- we also get different results than when we call the `unfold` tactic
-- multiple times.
--
-- Aesop calls `unfold` multiple times anyway, so the current implementation
-- is slow but correct.
pre (e : Expr) : StateRefT (Array Name) SimpM Simp.Step := do
let some decl := e.getAppFn'.constName?
| return .continue
match unfold? decl with
| none =>
return .continue
| some none =>
if let some e' ← delta? e (λ n => n == decl) then
modify (·.push decl)
return .done { expr := e' }
else
return .continue
| some (some unfoldThm) =>
let result? ← withReducible <|
Simp.tryTheorem? e
{ origin := .decl unfoldThm
proof := mkConst unfoldThm
rfl := ← isRflTheorem unfoldThm }
match result? with
| none => return .continue
| some r =>
modify (·.push decl)
match (← reduceMatcher? r.expr) with
| .reduced e' => return .done { r with expr := e' }
| _ => return .done r
def unfoldMany (unfold? : Name → Option (Option Name)) (e : Expr) :
MetaM (Option (Expr × Array Name)) := do
let e ← instantiateMVars e
let (r, usedDecls) ← unfoldManyCore (← mkUnfoldSimpContext) unfold? e |>.run {}
if (← instantiateMVars r.expr) == e then
return none
else
return some (r.expr, usedDecls)
def unfoldManyTarget (unfold? : Name → Option (Option Name)) (goal : MVarId) :
MetaM (Option (MVarId × Array Name)) := do
let tgt ← instantiateMVars $ ← goal.getType
let (result, usedDecls) ←
unfoldManyCore (← mkUnfoldSimpContext) unfold? tgt |>.run #[]
if result.expr == tgt then
return none
let goal ← applySimpResultToTarget goal tgt result
return some (goal, usedDecls)
def unfoldManyAt (unfold? : Name → Option (Option Name)) (goal : MVarId)
(fvarId : FVarId) : MetaM (Option (MVarId × Array Name)) :=
goal.withContext do
let type ← instantiateMVars $ ← fvarId.getType
let (result, usedDecls) ←
unfoldManyCore (← mkUnfoldSimpContext) unfold? type |>.run #[]
if result.expr == type then
return none
let some (_, goal) ←
applySimpResultToLocalDecl goal fvarId result (mayCloseGoal := false)
| throwTacticEx `aesop_unfold goal "internal error: unexpected result of applySimpResultToLocalDecl"
return some (goal, usedDecls)
def unfoldManyStar (unfold? : Name → Option (Option Name)) (goal : MVarId) :
MetaM (Option MVarId) :=
goal.withContext do
let initialGoal := goal
let mut goal := goal
if let some (goal', _) ← unfoldManyTarget unfold? goal then
goal := goal'
for ldecl in (← goal.getDecl).lctx do
if ldecl.isImplementationDetail then
continue
if let some (goal', _) ← unfoldManyAt unfold? goal ldecl.fvarId then
goal := goal'
if goal == initialGoal then
return none
else
return some goal
end Aesop |
.lake/packages/aesop/Aesop/Util/UnionFind.lean | module
public import Std.Data.HashMap.Basic
public section
namespace Aesop
structure UnionFind (α) [BEq α] [Hashable α] where
parents : Array USize
sizes : Array USize
toRep : Std.HashMap α USize
-- Invariant: `toRep` contains exactly the indices of `parents` as values
deriving Inhabited
namespace UnionFind
variable {α} [BEq α] [Hashable α]
instance : EmptyCollection (UnionFind α) :=
⟨{ parents := #[], sizes := #[], toRep := {} }⟩
def size (u : UnionFind α) : Nat :=
u.parents.size
def add (x : α) (u : UnionFind α) : UnionFind α := Id.run do
if u.toRep.contains x then
return u
let rep := u.parents.size.toUSize
{ parents := u.parents.push rep
sizes := u.parents.push 1
toRep := u.toRep.insert x rep }
def addArray (xs : Array α) (u : UnionFind α) : UnionFind α :=
xs.foldl (init := u) λ u x => u.add x
def ofArray (xs : Array α) : UnionFind α :=
({} : UnionFind α).addArray xs
private unsafe def findRepUnsafe (i : USize) (u : UnionFind α) :
USize × UnionFind α :=
let parent := u.parents.uget i lcProof
if parent == i then
(parent, u)
else
let (parent, u) := u.findRepUnsafe parent
(parent, { u with parents := u.parents.uset i parent lcProof })
@[implemented_by findRepUnsafe]
private opaque findRep : USize → UnionFind α → USize × UnionFind α
partial def find? (x : α) (u : UnionFind α) : Option USize × UnionFind α :=
match u.toRep[x]? with
| none => (none, u)
| some rep =>
let (rep, u) := u.findRep rep
(some rep, u)
private unsafe def mergeUnsafe (x y : α) (u : UnionFind α) :
UnionFind α := Id.run do
let (some xRep, u) := u.find? x | u
let (some yRep, u) := u.find? y | u
if xRep == yRep then
return u
else
let xSize := u.sizes.uget xRep lcProof
let ySize := u.sizes.uget yRep lcProof
if xSize < ySize then
return {
parents := u.parents.uset xRep yRep lcProof
sizes := u.sizes.uset yRep (xSize + ySize) lcProof
toRep := u.toRep
}
else
return {
parents := u.parents.uset yRep xRep lcProof
sizes := u.sizes.uset xRep (xSize + ySize) lcProof
toRep := u.toRep
}
@[implemented_by mergeUnsafe]
opaque merge (x y : α) : UnionFind α → UnionFind α
def sets {α : Type v} [BEq α] [Hashable α] (u : UnionFind α) : Array (Array α) × UnionFind α :=
let (sets, u) := u.toRep.fold (init := (∅, u)) λ ((sets : Std.HashMap USize _), u) x rep =>
let (rep, u) := u.findRep rep
let sets :=
match sets[rep]? with
| some set => sets.insert rep (set.push x)
| none => sets.insert rep #[x]
(sets, u)
let sets := sets.fold (init := Array.mkEmpty sets.size) λ (sets : Array _) _ v =>
sets.push v
(sets, u)
end UnionFind
/-- Cluster the `as` according to which `bs` are associated to them by `f`. Two
members `a₁, a₂` of `as` are put in the same cluster iff `f a₁ ∩ f a₂ ≠ ∅`. -/
def cluster [BEq α] [Hashable α] [BEq β] [Hashable β] (f : α → Array β)
(as : Array α) : Array (Array α) := Id.run do
let mut clusters := UnionFind.ofArray as
let mut aOccs : Std.HashMap β (Array α) := {}
for a in as do
for b in f a do
match aOccs[b]? with
| some as' =>
for a' in as' do
clusters := clusters.merge a a'
aOccs := aOccs.insert b (as'.push a)
| none =>
aOccs := aOccs.insert b #[a]
return clusters.sets.fst
end Aesop |
.lake/packages/aesop/Aesop/Util/Basic.lean | module
public import Aesop.Nanos
public import Aesop.Util.UnorderedArraySet
public import Lean.Util.ForEachExpr
public import Lean.Elab.Tactic.Basic
public import Lean.Meta.Tactic.Simp.SimpTheorems
import Aesop.Index.DiscrTreeConfig
import Lean.Elab.SyntheticMVars
import Lean.Meta.Tactic.TryThis
public section
open Lean
open Lean.Meta Lean.Elab.Tactic
namespace Aesop
@[inline]
def time [Monad m] [MonadLiftT BaseIO m] (x : m α) : m (α × Aesop.Nanos) := do
let start ← IO.monoNanosNow
let a ← x
let stop ← IO.monoNanosNow
return (a, ⟨stop - start⟩)
@[inline]
def time' [Monad m] [MonadLiftT BaseIO m] (x : m Unit) : m Aesop.Nanos := do
let start ← IO.monoNanosNow
x
let stop ← IO.monoNanosNow
return ⟨stop - start⟩
namespace PersistentHashSet
variable [BEq α] [Hashable α]
-- Elements are returned in unspecified order.
@[inline]
def toList (s : PersistentHashSet α) : List α :=
s.fold (init := []) λ as a => a :: as
-- Elements are returned in unspecified order. (In fact, they are currently
-- returned in reverse order of `toList`.)
@[inline]
def toArray (s : PersistentHashSet α) : Array α :=
s.fold (init := #[]) λ as a => as.push a
def toHashSet (s : PHashSet α) : Std.HashSet α :=
s.fold (init := ∅) fun result a ↦ result.insert a
def filter (p : α → Bool) (s : PHashSet α) : PHashSet α :=
s.fold (init := s) λ s a => if p a then s else s.erase a
end PersistentHashSet
section DiscrTree
open DiscrTree
/-
For `type = ∀ (x₁, ..., xₙ), T`, returns keys that match `T * ... *` (with
`n` stars).
-/
def getConclusionDiscrTreeKeys (type : Expr) : MetaM (Array Key) :=
withoutModifyingState do
let (_, _, conclusion) ← forallMetaTelescope type
mkDiscrTreePath conclusion
-- We use a meta telescope because `DiscrTree.mkPath` ignores metas (they
-- turn into `Key.star`) but not fvars.
def isEmptyTrie : Trie α → Bool
| .node vs children => vs.isEmpty && children.isEmpty
@[specialize]
private partial def filterTrieM [Monad m] [Inhabited σ] (f : σ → α → m σ)
(p : α → m (ULift Bool)) (init : σ) : Trie α → m (Trie α × σ)
| .node vs children => do
let (vs, acc) ← vs.foldlM (init := (#[], init)) λ (vs, acc) v => do
if (← p v).down then
return (vs.push v, acc)
else
return (vs, ← f acc v)
let (children, acc) ← go acc 0 children
let children := children.filter λ (_, c) => ! isEmptyTrie c
return (.node vs children, acc)
where
go (acc : σ) (i : Nat) (children : Array (Key × Trie α)) :
m (Array (Key × Trie α) × σ) := do
if h : i < children.size then
let (key, t) := children[i]'h
let (t, acc) ← filterTrieM f p acc t
go acc (i + 1) (children.set i (key, t))
else
return (children, acc)
/--
Remove elements for which `p` returns `false` from the given `DiscrTree`.
The removed elements are monadically folded over using `f` and `init`, so `f`
is called once for each removed element and the final state of type `σ` is
returned.
-/
@[specialize]
def filterDiscrTreeM [Monad m] [Inhabited σ] (p : α → m (ULift Bool))
(f : σ → α → m σ) (init : σ) (t : DiscrTree α) :
m (DiscrTree α × σ) := do
let (root, acc) ←
t.root.foldlM (init := (.empty, init)) λ (root, acc) key t => do
let (t, acc) ← filterTrieM f p acc t
let root := if isEmptyTrie t then root else root.insert key t
return (root, acc)
return (⟨root⟩, acc)
/--
Remove elements for which `p` returns `false` from the given `DiscrTree`.
The removed elements are folded over using `f` and `init`, so `f` is called
once for each removed element and the final state of type `σ` is returned.
-/
def filterDiscrTree [Inhabited σ] (p : α → Bool) (f : σ → α → σ) (init : σ)
(t : DiscrTree α) : DiscrTree α × σ := Id.run $
filterDiscrTreeM (λ a => pure ⟨p a⟩) (λ s a => pure (f s a)) init t
end DiscrTree
namespace SimpTheorems
def addSimpEntry (s : SimpTheorems) : SimpEntry → SimpTheorems
| SimpEntry.thm l =>
{ s.addSimpTheorem l with erased := s.erased.erase l.origin }
| SimpEntry.toUnfold d =>
{ s with toUnfold := s.toUnfold.insert d }
| SimpEntry.toUnfoldThms n thms => s.registerDeclToUnfoldThms n thms
def foldSimpEntriesM [Monad m] (f : σ → SimpEntry → m σ) (init : σ)
(thms : SimpTheorems) : m σ := do
let s ← thms.pre.foldValuesM (init := init) processTheorem
let s ← thms.post.foldValuesM (init := s) processTheorem
let s ← thms.toUnfold.foldM (init := s) λ s n => f s (SimpEntry.toUnfold n)
thms.toUnfoldThms.foldlM (init := s) λ s n thms =>
f s (SimpEntry.toUnfoldThms n thms)
where
@[inline]
processTheorem (s : σ) (thm : SimpTheorem) : m σ :=
if thms.erased.contains thm.origin then
return s
else
f s (SimpEntry.thm thm)
def foldSimpEntries (f : σ → SimpEntry → σ) (init : σ) (thms : SimpTheorems) :
σ :=
Id.run $ foldSimpEntriesM f init thms
def simpEntries (thms : SimpTheorems) : Array SimpEntry :=
foldSimpEntries (thms := thms) (init := #[]) λ s thm => s.push thm
def containsDecl (thms : SimpTheorems) (decl : Name) : Bool :=
thms.isLemma (.decl decl) ||
thms.isDeclToUnfold decl ||
thms.toUnfoldThms.contains decl
end SimpTheorems
section ForEachExpr
variable {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m]
[Monad m] [MonadControlT MetaM m] [MonadLiftT MetaM m]
def forEachExprInLDeclCore (ldecl : LocalDecl) (g : Expr → m Bool) :
MonadCacheT Expr Unit m Unit := do
if ! ldecl.isImplementationDetail then
ForEachExpr.visit g ldecl.toExpr
ForEachExpr.visit g ldecl.type
if let some value := ldecl.value? then
ForEachExpr.visit g value
@[inline, always_inline]
def forEachExprInLDecl' (ldecl : LocalDecl) (g : Expr → m Bool) :
m Unit :=
forEachExprInLDeclCore ldecl g |>.run
@[inline, always_inline]
def forEachExprInLDecl (ldecl : LocalDecl) (g : Expr → m Unit) :
m Unit :=
forEachExprInLDeclCore ldecl (λ e => do g e; return true) |>.run
@[inline, always_inline]
def forEachExprInLCtxCore (lctx : LocalContext) (g : Expr → m Bool) :
MonadCacheT Expr Unit m Unit :=
for ldecl in lctx do
forEachExprInLDeclCore ldecl g
@[inline, always_inline]
def forEachExprInLCtx' (mvarId : MVarId) (g : Expr → m Bool) : m Unit :=
mvarId.withContext do
forEachExprInLCtxCore (← mvarId.getDecl).lctx g |>.run
@[inline, always_inline]
def forEachExprInLCtx (mvarId : MVarId) (g : Expr → m Unit) : m Unit :=
forEachExprInLCtx' mvarId (λ e => do g e; return true)
@[inline, always_inline]
def forEachExprInGoalCore (mvarId : MVarId) (g : Expr → m Bool) :
MonadCacheT Expr Unit m Unit :=
mvarId.withContext do
forEachExprInLCtxCore (← mvarId.getDecl).lctx g
ForEachExpr.visit g (← mvarId.getType)
@[inline, always_inline]
def forEachExprInGoal' (mvarId : MVarId) (g : Expr → m Bool) : m Unit :=
forEachExprInGoalCore mvarId g |>.run
@[inline, always_inline]
def forEachExprInGoal (mvarId : MVarId) (g : Expr → m Unit) : m Unit :=
forEachExprInGoal' mvarId λ e => do g e; return true
end ForEachExpr
@[inline]
def setThe (σ) {m} [MonadStateOf σ m] (s : σ) : m PUnit :=
MonadStateOf.set s
@[inline]
def runMetaMAsCoreM (x : MetaM α) : CoreM α :=
Prod.fst <$> x.run {} {}
@[inline]
def runTermElabMAsCoreM (x : Elab.TermElabM α) : CoreM α :=
runMetaMAsCoreM x.run'
def runTacticMAsMetaM (x : TacticM α) (goals : List MVarId) :
MetaM (α × List MVarId) := do
let (a, s) ← x |>.run { elaborator := .anonymous } |>.run { goals } |>.run'
return (a, s.goals)
def runTacticSyntaxAsMetaM (stx : Syntax) (goals : List MVarId) :
MetaM (List MVarId) :=
return (← runTacticMAsMetaM (evalTactic stx) goals).snd
def updateSimpEntryPriority (priority : Nat) (e : SimpEntry) : SimpEntry :=
match e with
| .thm t => .thm { t with priority }
| .toUnfoldThms .. | .toUnfold .. => e
partial def hasSorry [Monad m] [MonadMCtx m] (e : Expr) : m Bool :=
return go (← getMCtx) e
where
go (mctx : MetavarContext) (e : Expr) : Bool :=
Option.isSome $ e.find? λ e =>
if e.isSorry then
true
else if let .mvar mvarId := e then
if let some ass := mctx.getExprAssignmentCore? mvarId then
go mctx ass
else if let some ass := mctx.dAssignment.find? mvarId then
go mctx $ .mvar ass.mvarIdPending
else
false
else
false
def isAppOfUpToDefeq (f : Expr) (e : Expr) : MetaM Bool :=
withoutModifyingState do
let type ← inferType f
let (mvars, _, _) ← forallMetaTelescope type
let app := mkAppN f mvars
if ← isDefEq app e then
return true
else
return false
/--
If the input expression `e` reduces to `f x₁ ... xₙ` via repeated `whnf`, this
function returns `f` and `[x₁, ⋯, xₙ]`. Otherwise it returns `e` (unchanged, not
in WHNF!) and `[]`.
-/
partial def getAppUpToDefeq (e : Expr) : MetaM (Expr × Array Expr) :=
go #[] e
where
go (args : Array Expr) (e : Expr) : MetaM (Expr × Array Expr) := do
match ← whnf e with
| .app f e => go (args.push e) f
| _ => return (e, args.reverse)
/--
Partition an array of structures containing `MVarId`s into 'goals' and
'proper mvars'. An `MVarId` from the input array `goals` is classified as a
proper mvar if any of the `MVarId`s depend on it, and as a goal otherwise.
Additionally, for each goal, we report the set of mvars that the goal depends
on.
-/
def partitionGoalsAndMVars (mvarId : α → MVarId) (goals : Array α) :
MetaM (Array (α × UnorderedArraySet MVarId) × UnorderedArraySet MVarId) := do
let mut goalsAndMVars := #[]
let mut mvars : UnorderedArraySet MVarId := {}
for g in goals do
let gMVars ← .ofHashSet <$> (mvarId g).getMVarDependencies
mvars := mvars.merge gMVars
goalsAndMVars := goalsAndMVars.push (g, gMVars)
let goals :=
if mvars.isEmpty then
goalsAndMVars
else
goalsAndMVars.filter λ (g, _) => ! mvars.contains (mvarId g)
return (goals, mvars)
section RunTactic
open Lean.Elab.Tactic
def runTacticMCapturingPostState (t : TacticM Unit) (preState : Meta.SavedState)
(preGoals : List MVarId) : MetaM (Meta.SavedState × List MVarId) :=
withoutModifyingState do
let go : TacticM (Meta.SavedState × List MVarId) := do
preState.restore
t
pruneSolvedGoals
let postState ← show MetaM _ from saveState
let postGoals ← getGoals
pure (postState, postGoals)
go |>.run { elaborator := .anonymous, recover := false }
|>.run' { goals := preGoals }
|>.run'
def runTacticCapturingPostState (t : Syntax.Tactic) (preState : Meta.SavedState)
(preGoals : List MVarId) : MetaM (Meta.SavedState × List MVarId) := do
runTacticMCapturingPostState (evalTactic t) preState preGoals
def runTacticSeqCapturingPostState (t : TSyntax ``Lean.Parser.Tactic.tacticSeq)
(preState : Meta.SavedState) (preGoals : List MVarId) :
MetaM (Meta.SavedState × List MVarId) := do
runTacticMCapturingPostState (evalTactic t) preState preGoals
def runTacticsCapturingPostState (ts : Array Syntax.Tactic)
(preState : Meta.SavedState) (preGoals : List MVarId) :
MetaM (Meta.SavedState × List MVarId) := do
let t ← `(Lean.Parser.Tactic.tacticSeq| $ts*)
runTacticSeqCapturingPostState t preState preGoals
end RunTactic
section TransparencySyntax
variable [Monad m] [MonadQuotation m]
open Parser.Tactic
def withTransparencySeqSyntax (md : TransparencyMode)
(k : TSyntax ``tacticSeq) : TSyntax ``tacticSeq := Unhygienic.run do
match md with
| .default => return k
| .all => `(tacticSeq| with_unfolding_all $k)
| .reducible => `(tacticSeq| with_reducible $k)
| .instances => `(tacticSeq| with_reducible_and_instances $k)
def withAllTransparencySeqSyntax (md : TransparencyMode)
(k : TSyntax ``tacticSeq) : TSyntax ``tacticSeq :=
match md with
| .all => Unhygienic.run `(tacticSeq| with_unfolding_all $k)
| _ => k
def withTransparencySyntax (md : TransparencyMode) (k : TSyntax `tactic) :
TSyntax `tactic := Unhygienic.run do
match md with
| .default => return k
| .all => `(tactic| with_unfolding_all $k:tactic)
| .reducible => `(tactic| with_reducible $k:tactic)
| .instances => `(tactic| with_reducible_and_instances $k:tactic)
def withAllTransparencySyntax (md : TransparencyMode) (k : TSyntax `tactic) :
TSyntax `tactic :=
match md with
| .all => Unhygienic.run `(tactic| with_unfolding_all $k:tactic)
| _ => k
end TransparencySyntax
/--
Register a "Try this" suggestion for a tactic sequence.
It works when the tactic to replace appears on its own line:
```lean
by
aesop?
```
It doesn't work (i.e., the suggestion will appear but in the wrong place) when
the tactic to replace is preceded by other text on the same line:
```lean
have x := by aesop?
```
The `Try this:` suggestion in the infoview is not correctly formatted, but
there's nothing we can do about this at the moment.
-/
def addTryThisTacticSeqSuggestion (ref : Syntax)
(suggestion : TSyntax ``Lean.Parser.Tactic.tacticSeq)
(origSpan? : Option Syntax := none) : MetaM Unit := do
let fmt ← PrettyPrinter.ppCategory ``Lean.Parser.Tactic.tacticSeq suggestion
let msgText := fmt.pretty (indent := 0) (column := 0)
if let some range := (origSpan?.getD ref).getRange? then
let map ← getFileMap
let (indent, column) := Lean.Meta.Tactic.TryThis.getIndentAndColumn map range
let text := fmt.pretty (indent := indent) (column := column)
let suggestion := {
-- HACK: The `tacticSeq` syntax category is pretty-printed with each line
-- indented by two spaces (for some reason), so we remove this
-- indentation.
suggestion := .string $ dedent text
toCodeActionTitle? := some λ _ => "Replace aesop with the proof it found"
messageData? := some msgText
preInfo? := " "
}
Lean.Meta.Tactic.TryThis.addSuggestion ref suggestion (origSpan? := origSpan?)
(header := "Try this:\n")
where
dedent (s : String) : String :=
s.splitOn "\n"
|>.map (λ line => line.dropPrefix? " " |>.map (·.toString) |>.getD line)
|> String.intercalate "\n"
open Lean.Elab Lean.Elab.Term in
def elabPattern (stx : Syntax) : TermElabM Expr :=
withRef stx $ withReader adjustCtx $ withSynthesize $ elabTerm stx none
where
adjustCtx (old : Term.Context) : Term.Context := {
old with
mayPostpone := false
errToSorry := false
autoBoundImplicit := false
sectionVars := {}
sectionFVars := {}
isNoncomputableSection := false
ignoreTCFailures := true
inPattern := true
saveRecAppSyntax := false
holesAsSyntheticOpaque := false
}
register_option aesop.smallErrorMessages : Bool := {
defValue := false
group := "aesop"
descr := "(aesop) Print smaller error messages. Used for testing."
}
def tacticsToMessageData (ts : Array Syntax.Tactic) : MessageData :=
MessageData.joinSep (ts.map toMessageData |>.toList) "\n"
/--
Note: the returned local context contains invalid `LocalDecl`s.
-/
def getUnusedNames (lctx : LocalContext) (suggestions : Array Name) : Array Name × LocalContext :=
go 0 (Array.mkEmpty suggestions.size) lctx
where
go (i : Nat) (acc : Array Name) (lctx : LocalContext) : Array Name × LocalContext :=
if h : i < suggestions.size then
let name := lctx.getUnusedName suggestions[i]
let lctx := lctx.addDecl $ dummyLDecl name
go (i + 1) (acc.push name) lctx
else
(acc, lctx)
dummyLDecl (name : Name) : LocalDecl :=
.cdecl 0 ⟨`_⟩ name (.sort levelZero) .default .default
def Name.ofComponents (cs : List Name) : Name :=
cs.foldl (init := .anonymous) λ
| result, .str _ s => .str result s
| result, .num _ n => .num result n
| result, .anonymous => result
@[macro_inline, expose]
def withExceptionTransform [Monad m] [MonadError m]
(f : MessageData → MessageData) (x : m α) : m α := do
try
x
catch e =>
match e with
| .internal _ _ => throw e
| .error ref msg => throw $ .error ref (f msg)
@[macro_inline, expose]
def withExceptionPrefix [Monad m] [MonadError m] (pre : MessageData) :
m α → m α :=
withExceptionTransform (λ msg => pre ++ msg)
def withPPAnalyze [Monad m] [MonadWithOptions m] (x : m α) : m α :=
withOptions (·.setBool `pp.analyze true |>.setBool `pp.proofs true) x
-- `pp.proofs` works around lean4#6216
-- TODO upstream
scoped instance [MonadCache α β m] : MonadCache α β (StateRefT' ω σ m) where
findCached? a := MonadCache.findCached? (m := m) a
cache a b := MonadCache.cache (m := m) a b
/-- A generalized variant of `Meta.SavedState.runMetaM` -/
def runInMetaState [Monad m] [MonadLiftT MetaM m] [MonadFinally m]
(s : Meta.SavedState) (x : m α) : m α := do
let initialState ← show MetaM _ from saveState
try
s.restore
x
finally
initialState.restore
def lBoolOr : (x y : LBool) → LBool
| .true, _ => .true
| .false, y => y
| .undef, .true => .true
| .undef, _ => .undef
-- Core's `arrayOrd` goes through lists. -.-
def compareArrayLex (cmp : α → α → Ordering) (xs ys : Array α) :
Ordering := Id.run do
let s := max xs.size ys.size
for i in [:s] do
if let some x := xs[i]? then
if let some y := ys[i]? then
let c := cmp x y
if c.isNe then
return c
else
return .gt
else
return .lt
return .eq
def compareArraySizeThenLex (cmp : α → α → Ordering) (xs ys : Array α) :
Ordering :=
compare xs.size ys.size |>.then $
compareArrayLex cmp xs ys
end Aesop |
.lake/packages/aesop/Aesop/Util/UnorderedArraySet.lean | module
public import Batteries.Data.Array.Merge
public import Lean.Message
public section
open Lean Std
namespace Aesop
structure UnorderedArraySet (α) [BEq α] where
private mk ::
private rep : Array α
deriving Inhabited
namespace UnorderedArraySet
variable [BEq α]
/-- O(1) -/
protected def empty : UnorderedArraySet α :=
⟨#[]⟩
instance : EmptyCollection (UnorderedArraySet α) :=
⟨UnorderedArraySet.empty⟩
/-- O(1) -/
protected def singleton (a : α) : UnorderedArraySet α :=
⟨#[a]⟩
/-- O(n) -/
def insert (x : α) : UnorderedArraySet α → UnorderedArraySet α
| ⟨rep⟩ => if rep.contains x then ⟨rep⟩ else ⟨rep.push x⟩
/-- Precondition: `xs` contains no duplicates. -/
protected def ofDeduplicatedArray (xs : Array α) : UnorderedArraySet α :=
⟨xs⟩
/-- Precondition: `xs` is sorted. -/
protected def ofSortedArray (xs : Array α) : UnorderedArraySet α :=
⟨xs.dedupSorted⟩
set_option linter.unusedVariables false in
/-- O(n*log(n)) -/
protected def ofArray [ord : Ord α] (xs : Array α) :
UnorderedArraySet α :=
⟨xs.sortDedup⟩
/-- O(n^2) -/
protected def ofArraySlow (xs : Array α) : UnorderedArraySet α :=
xs.foldl (init := {}) λ s x => s.insert x
protected def ofHashSet [Hashable α] (xs : Std.HashSet α) : UnorderedArraySet α :=
⟨xs.toArray⟩
protected def ofPersistentHashSet [Hashable α] (xs : PersistentHashSet α) : UnorderedArraySet α :=
⟨xs.fold (init := #[]) λ as a => as.push a⟩
protected def toArray (s : UnorderedArraySet α) : Array α :=
s.rep
/-- O(n) -/
def erase (x : α) (s : UnorderedArraySet α) : UnorderedArraySet α :=
⟨s.rep.erase x⟩
/-- O(n) -/
def filterM [Monad m] (p : α → m Bool) (s : UnorderedArraySet α) :
m (UnorderedArraySet α) :=
return ⟨← s.rep.filterM p⟩
/-- O(n) -/
def filter (p : α → Bool) (s : UnorderedArraySet α) : UnorderedArraySet α :=
⟨s.rep.filter p⟩
/-- O(n*m) -/
def merge (s t : UnorderedArraySet α) : UnorderedArraySet α :=
⟨s.rep.mergeUnsortedDedup t.rep⟩
instance : Append (UnorderedArraySet α) :=
⟨merge⟩
/-- O(n) -/
def contains (x : α) (s : UnorderedArraySet α) : Bool :=
s.rep.contains x
/-- O(n) -/
def foldM [Monad m] (f : σ → α → m σ) (init : σ) (s : UnorderedArraySet α) :
m σ :=
s.rep.foldlM f init
instance : ForIn m (UnorderedArraySet α) α where
forIn s := private forIn s.rep
/-- O(n) -/
def fold (f : σ → α → σ) (init : σ) (s : UnorderedArraySet α) : σ :=
s.rep.foldl f init
def partition (f : α → Bool) (s : UnorderedArraySet α) :
(UnorderedArraySet α × UnorderedArraySet α) :=
let (xs, ys) := s.rep.partition f
(⟨xs⟩, ⟨ys⟩)
/-- O(1) -/
def size (s : UnorderedArraySet α) : Nat :=
s.rep.size
/-- O(1) -/
def isEmpty (s : UnorderedArraySet α) : Bool :=
s.rep.isEmpty
/-- O(n) -/
def anyM [Monad m] (p : α → m Bool) (s : UnorderedArraySet α) (start := 0)
(stop := s.size) : m Bool :=
s.rep.anyM p start stop
/-- O(n) -/
def any (p : α → Bool) (s : UnorderedArraySet α) (start := 0) (stop := s.size) :
Bool :=
s.rep.any p start stop
/-- O(n) -/
def allM [Monad m] (p : α → m Bool) (s : UnorderedArraySet α) (start := 0)
(stop := s.size) : m Bool :=
s.rep.allM p start stop
/-- O(n) -/
def all (p : α → Bool) (s : UnorderedArraySet α) (start := 0) (stop := s.size) :
Bool :=
s.rep.all p start stop
instance [ToString α] : ToString (UnorderedArraySet α) where
toString s := private toString s.rep
instance [ToFormat α] : ToFormat (UnorderedArraySet α) where
format s := private format s.rep
instance [ToMessageData α] : ToMessageData (UnorderedArraySet α) where
toMessageData s := private toMessageData s.rep
end Aesop.UnorderedArraySet |
.lake/packages/aesop/Aesop/Util/Tactic.lean | module
public import Lean.Meta.Basic
import Lean.Meta.Tactic.Assert
public section
open Lean Lean.Meta Lean.Elab.Tactic
namespace Aesop
/--
A `MetaM` version of the `replace` tactic. If `fvarId` refers to the
hypothesis `h`, this tactic asserts a new hypothesis `h : type` with proof
`proof : type` and then tries to clear `fvarId`. Unlike `replaceLocalDecl`,
`replaceFVar` always adds the new hypothesis at the end of the local context.
`replaceFVar` returns the new goal, the `FVarId` of the newly asserted
hypothesis and whether the old hypothesis was cleared.
-/
def replaceFVar (goal : MVarId) (fvarId : FVarId) (type : Expr) (proof : Expr) :
MetaM (MVarId × FVarId × Bool) := do
let userName ← goal.withContext $ fvarId.getUserName
let preClearGoal ← goal.assert userName type proof
let goal ← preClearGoal.tryClear fvarId
let clearSuccess := preClearGoal != goal
let (newFVarId, goal) ← intro1Core goal (preserveBinderNames := true)
return (goal, newFVarId, clearSuccess)
/-- Introduce as many binders as possible while unfolding definitions with the
ambient transparency. -/
partial def introsUnfolding (mvarId : MVarId) : MetaM (Array FVarId × MVarId) :=
run mvarId #[]
where
run (mvarId : MVarId) (fvars : Array FVarId) : MetaM (Array FVarId × MVarId) :=
mvarId.withContext do
let type ← whnf (← mvarId.getType)
let size := getIntrosSize type
if 0 < size then
let (fvars', mvarId') ← mvarId.introN size
run mvarId' (fvars ++ fvars')
else
return (fvars, mvarId)
end Aesop |
.lake/packages/aesop/Aesop/Util/OrderedHashSet.lean | module
public import Std.Data.HashSet.Lemmas
public section
open Std (HashSet)
namespace Aesop
/-- A hash set that preserves the order of insertions. -/
structure OrderedHashSet (α) [BEq α] [Hashable α] where
toArray : Array α
toHashSet : HashSet α
deriving Inhabited
namespace OrderedHashSet
variable [BEq α] [Hashable α]
instance : EmptyCollection (OrderedHashSet α) :=
⟨⟨#[], ∅⟩⟩
def emptyWithCapacity (n : Nat) : OrderedHashSet α where
toArray := Array.emptyWithCapacity n
toHashSet := HashSet.emptyWithCapacity n
def insert (x : α) (s : OrderedHashSet α) : OrderedHashSet α :=
if x ∈ s.toHashSet then
s
else {
toArray := s.toArray.push x
toHashSet := s.toHashSet.insert x
}
def insertMany [ForIn Id ρ α] (xs : ρ) (s : OrderedHashSet α) :
OrderedHashSet α := Id.run do
let mut result := s
for x in xs do
result := result.insert x
return result
def ofArray (xs : Array α) : OrderedHashSet α :=
(∅ : OrderedHashSet α).insertMany xs
def contains (x : α) (s : OrderedHashSet α) : Bool :=
s.toHashSet.contains x
instance : Membership α (OrderedHashSet α) where
mem s x := x ∈ s.toHashSet
instance {s : OrderedHashSet α} : Decidable (x ∈ s) :=
inferInstanceAs (Decidable (x ∈ s.toHashSet))
@[specialize]
def foldlM [Monad m] (f : β → α → m β) (init : β)
(s : OrderedHashSet α) : m β :=
s.toArray.foldlM f init
def foldl (f : β → α → β) (init : β) (s : OrderedHashSet α) : β :=
s.toArray.foldl f init
@[specialize]
def foldrM [Monad m] (f : α → β → m β) (init : β)
(s : OrderedHashSet α) : m β :=
s.toArray.foldrM f init
def foldr (f : α → β → β) (init : β) (s : OrderedHashSet α) : β :=
s.toArray.foldr f init
instance : ForIn m (OrderedHashSet α) α where
forIn s b f := ForIn.forIn s.toArray b f
end Aesop.OrderedHashSet |
.lake/packages/aesop/Aesop/Util/EqualUpToIds.lean | module
public import Batteries.Lean.Meta.Basic
public section
open Lean Std Lean.Meta
namespace Aesop
initialize registerTraceClass `Aesop.Util.EqualUpToIds
namespace EqualUpToIdsM
structure Context where
commonMCtx? : Option MetavarContext
mctx₁ : MetavarContext
mctx₂ : MetavarContext
/-- Allow metavariables to be unassigned on one side of the comparison and
assigned on the other. So when we compare two expressions and we encounter
a metavariable `?x` in one of them and a subexpression `e` in the other (at
the same position), we consider `?x` equal to `e`. -/
-- TODO we should also allow ?P x₁ ... xₙ = e
allowAssignmentDiff : Bool
structure State where
equalMVarIds : Std.HashMap MVarId MVarId := {}
equalLMVarIds : Std.HashMap LMVarId LMVarId := {}
/-- A map from metavariables which are unassigned in the left goal
to their corresponding expression in the right goal. Only used when
`allowAssignmentDiff = true`. -/
leftUnassignedMVarValues : Std.HashMap MVarId Expr := {}
/-- A map from metavariables which are unassigned in the right goal
to their corresponding expression in the left goal. Only used when
`allowAssignmentDiff = true`. -/
rightUnassignedMVarValues : Std.HashMap MVarId Expr := {}
end EqualUpToIdsM
abbrev EqualUpToIdsM :=
ReaderT EqualUpToIdsM.Context $ StateRefT EqualUpToIdsM.State MetaM
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
@[inline, always_inline]
instance : Monad EqualUpToIdsM :=
{ inferInstanceAs (Monad EqualUpToIdsM) with }
protected def EqualUpToIdsM.run' (x : EqualUpToIdsM α)
(commonMCtx? : Option MetavarContext) (mctx₁ mctx₂ : MetavarContext)
(allowAssignmentDiff : Bool) :
MetaM (α × EqualUpToIdsM.State) :=
x { commonMCtx?, mctx₁, mctx₂, allowAssignmentDiff, } |>.run {}
protected def EqualUpToIdsM.run (x : EqualUpToIdsM α)
(commonMCtx? : Option MetavarContext) (mctx₁ mctx₂ : MetavarContext)
(allowAssignmentDiff : Bool) : MetaM α :=
(·.fst) <$> x.run' commonMCtx? mctx₁ mctx₂ allowAssignmentDiff
namespace EqualUpToIds
@[inline]
def readCommonMCtx? : EqualUpToIdsM (Option MetavarContext) :=
return (← read).commonMCtx?
@[inline]
def readMCtx₁ : EqualUpToIdsM MetavarContext :=
return (← read).mctx₁
@[inline]
def readMCtx₂ : EqualUpToIdsM MetavarContext :=
return (← read).mctx₂
@[inline]
def readAllowAssignmentDiff : EqualUpToIdsM Bool :=
return (← read).allowAssignmentDiff
@[specialize]
def equalCommonLMVars? (lmvarId₁ lmvarId₂ : LMVarId) :
EqualUpToIdsM (Option Bool) := do
match ← readCommonMCtx? with
| none => return none
| some mctx =>
if mctx.lDepth.contains lmvarId₁ || mctx.lDepth.contains lmvarId₂ then
return some $ lmvarId₁ == lmvarId₂
else
return none
@[specialize]
def equalCommonMVars? (mvarId₁ mvarId₂ : MVarId) :
EqualUpToIdsM (Option Bool) := do
match ← readCommonMCtx? with
| none => return none
| some mctx =>
if mctx.isExprMVarDeclared mvarId₁ || mctx.isExprMVarDeclared mvarId₂ then
return some $ mvarId₁ == mvarId₂
else
return none
structure GoalContext where
lctx₁ : LocalContext
localInstances₁ : LocalInstances
lctx₂ : LocalContext
localInstances₂ : LocalInstances
equalFVarIds : Std.HashMap FVarId FVarId := {}
inductive MVarValue where
| mvarId (mvarId : MVarId)
| expr (e : Expr)
| delayedAssignment (da : DelayedMetavarAssignment)
namespace Unsafe
@[inline]
private def namesEqualUpToMacroScopes (n₁ n₂ : Name) : Bool :=
n₁.hasMacroScopes == n₂.hasMacroScopes &&
n₁.eraseMacroScopes == n₂.eraseMacroScopes
mutual
@[specialize]
unsafe def levelsEqualUpToIdsCore (l₁ l₂ : Level) : EqualUpToIdsM Bool :=
if ptrEq l₁ l₂ then
return true
else
levelsEqualUpToIdsCore' l₁ l₂
@[specialize]
unsafe def levelsEqualUpToIdsCore' : Level → Level → EqualUpToIdsM Bool
| .zero, .zero => return true
| .succ l₁, .succ l₂ => levelsEqualUpToIdsCore l₁ l₂
| .max l₁ m₁, .max l₂ m₂ =>
levelsEqualUpToIdsCore l₁ l₂ <&&> levelsEqualUpToIdsCore m₁ m₂
| .imax l₁ m₁, .imax l₂ m₂ =>
levelsEqualUpToIdsCore l₁ l₂ <&&> levelsEqualUpToIdsCore m₁ m₂
| .param n₁, .param n₂ =>
return n₁ == n₂
| .mvar m₁, .mvar m₂ => do
if let some result ← equalCommonLMVars? m₁ m₂ then
return result
else if let some m₂' := (← get).equalLMVarIds[m₁]? then
return m₂' == m₂
else
modify λ s => { s with equalLMVarIds := s.equalLMVarIds.insert m₁ m₂ }
return true
| _, _ => return false
end
end Unsafe
@[implemented_by Unsafe.levelsEqualUpToIdsCore]
opaque levelsEqualUpToIdsCore (l₁ l₂ : Level) : EqualUpToIdsM Bool
@[inline]
private def lctxDecls (lctx : LocalContext) : EqualUpToIdsM (Array LocalDecl) := do
return lctx.foldl (init := Array.mkEmpty lctx.numIndices) λ decls d =>
if d.isImplementationDetail then decls else decls.push d
abbrev ExprsEqualUpToIdsM :=
MonadCacheT (ExprStructEq × ExprStructEq) Bool $
ReaderT GoalContext EqualUpToIdsM
namespace Unsafe
mutual
@[specialize]
unsafe def exprsEqualUpToIdsCore₁ (e₁ e₂ : Expr) :
ReaderT GoalContext EqualUpToIdsM Bool := do
let e₁ ← withMCtx (← readMCtx₁) (instantiateMVars e₁)
let e₂ ← withMCtx (← readMCtx₂) (instantiateMVars e₂)
exprsEqualUpToIdsCore₂ e₁ e₂ |>.run
@[specialize]
unsafe def exprsEqualUpToIdsCore₂ (e₁ e₂ : Expr) : ExprsEqualUpToIdsM Bool :=
withIncRecDepth do
withTraceNodeBefore `Aesop.Util.EqualUpToIds (return m!"{← printExpr (← readMCtx₁) (← read).lctx₁ (← read).localInstances₁ e₁} ≟ {← printExpr (← readMCtx₂) (← read).lctx₂ (← read).localInstances₂ e₂}") do
if ptrEq e₁ e₂ then
trace[Aesop.Util.EqualUpToIds] "pointer-equal"
return true
else if ! e₁.hasMVar && ! e₂.hasMVar && e₁.equal e₂ then
trace[Aesop.Util.EqualUpToIds] "structurally equal"
return true
-- If e₁ and e₂ don't contain mvars and are not structurally equal, they
-- may still be equal up to IDs because we ignore macro scopes on names.
else
checkCache ((e₁ : ExprStructEq), (e₂ : ExprStructEq)) λ _ => do
exprsEqualUpToIdsCore₃ e₁ e₂
where
printExpr (mctx : MetavarContext) (lctx : LocalContext)
(localInstances : LocalInstances) (e : Expr) : MetaM MessageData :=
withMCtx mctx do
withLCtx lctx localInstances do
addMessageContext m!"{e}"
@[specialize]
unsafe def exprsEqualUpToIdsCore₃ : Expr → Expr → ExprsEqualUpToIdsM Bool
| .bvar i, .bvar j => return i == j
| .fvar fvarId₁, .fvar fvarId₂ =>
return fvarId₁ == fvarId₂ ||
(← read).equalFVarIds[fvarId₁]? == some fvarId₂
| .sort u, .sort v => levelsEqualUpToIdsCore u v
| .const decl₁ lvls₁, .const decl₂ lvls₂ => do
if decl₁ == decl₂ && lvls₁.length == lvls₂.length then
for l₁ in lvls₁, l₂ in lvls₂ do
if ! (← levelsEqualUpToIdsCore l₁ l₂) then
return false
return true
else
return false
| .app f₁ x₁, .app f₂ x₂ =>
exprsEqualUpToIdsCore₂ f₁ f₂ <&&> exprsEqualUpToIdsCore₂ x₁ x₂
| .lam n₁ t₁ e₁ bi₁, .lam n₂ t₂ e₂ bi₂ =>
pure (namesEqualUpToMacroScopes n₁ n₂ && bi₁ == bi₂) <&&>
exprsEqualUpToIdsCore₂ t₁ t₂ <&&>
exprsEqualUpToIdsCore₂ e₁ e₂
| .forallE n₁ t₁ e₁ bi₁, .forallE n₂ t₂ e₂ bi₂ =>
pure (namesEqualUpToMacroScopes n₁ n₂ && bi₁ == bi₂) <&&>
exprsEqualUpToIdsCore₂ t₁ t₂ <&&>
exprsEqualUpToIdsCore₂ e₁ e₂
| .letE n₁ t₁ v₁ e₁ _, .letE n₂ t₂ v₂ e₂ _ =>
pure (namesEqualUpToMacroScopes n₁ n₂) <&&>
exprsEqualUpToIdsCore₂ t₁ t₂ <&&>
exprsEqualUpToIdsCore₂ v₁ v₂ <&&>
exprsEqualUpToIdsCore₂ e₁ e₂
| .lit l₁, .lit l₂ => return l₁ == l₂
| .mdata _ e₁, e₂ => exprsEqualUpToIdsCore₂ e₁ e₂
| e₁, .mdata _ e₂ => exprsEqualUpToIdsCore₂ e₁ e₂
| .proj n₁ i₁ e₁, .proj n₂ i₂ e₂ =>
pure (n₁ == n₂ && i₁ == i₂) <&&> exprsEqualUpToIdsCore₂ e₁ e₂
| .mvar m₁, .mvar m₂ => do
let v₁ ← normalizeMVar (← readMCtx₁) m₁
let v₂ ← normalizeMVar (← readMCtx₂) m₂
compareMVarValues v₁ v₂
| .mvar m₁, e₂ => do
let v₁ ← normalizeMVar (← readMCtx₁) m₁
compareMVarValues v₁ (.expr e₂)
| e₁, .mvar m₂ => do
let v₂ ← normalizeMVar (← readMCtx₂) m₂
compareMVarValues (.expr e₁) v₂
| _, _ => return false
where
normalizeMVar (mctx : MetavarContext) (m : MVarId) : MetaM MVarValue :=
withMCtx mctx do
if let some dAss ← getDelayedMVarAssignment? m then
return .delayedAssignment dAss
else
return .mvarId m
compareMVarValues : MVarValue → MVarValue → ExprsEqualUpToIdsM Bool
| .expr _, .expr _ => unreachable!
| .mvarId m₁, .mvarId m₂ => unassignedMVarsEqualUpToIdsCore m₁ m₂
| .delayedAssignment dAss₁, .delayedAssignment dAss₂ =>
unassignedMVarsEqualUpToIdsCore dAss₁.mvarIdPending dAss₂.mvarIdPending
-- TODO I'm not sure whether this suffices -- do we also need to check
-- that the `fvars` in `dAss₁` correspond to the `fvars` in `dAss₂`?
| .mvarId m₁, .expr e₂ => do
if ! (← readAllowAssignmentDiff) then
return false
let map := (← get).leftUnassignedMVarValues
if let some e₁ := map[m₁]? then
exprsEqualUpToIdsCore₂ e₁ e₂
else
modify λ s => {
s with
leftUnassignedMVarValues := s.leftUnassignedMVarValues.insert m₁ e₂
}
return true
| .expr e₁, .mvarId m₂ => do
if ! (← readAllowAssignmentDiff) then
return false
let map := (← get).rightUnassignedMVarValues
if let some e₂ := map[m₂]? then
exprsEqualUpToIdsCore₂ e₁ e₂
else
modify λ s => {
s with
rightUnassignedMVarValues := s.rightUnassignedMVarValues.insert m₂ e₁
}
return true
| _, _ => return false
@[specialize]
unsafe def localDeclsEqualUpToIdsCore (ldecl₁ ldecl₂ : LocalDecl) :
ReaderT GoalContext EqualUpToIdsM Bool :=
match ldecl₁.isLet, ldecl₂.isLet with
| false, false =>
pure (namesEqualUpToMacroScopes ldecl₁.userName ldecl₂.userName && ldecl₁.binderInfo == ldecl₂.binderInfo &&
ldecl₁.kind == ldecl₂.kind) <&&>
exprsEqualUpToIdsCore₁ ldecl₁.type ldecl₂.type
| true, true =>
pure (namesEqualUpToMacroScopes ldecl₁.userName ldecl₂.userName &&
ldecl₁.kind == ldecl₂.kind) <&&>
exprsEqualUpToIdsCore₁ ldecl₁.type ldecl₂.type <&&>
exprsEqualUpToIdsCore₁ ldecl₁.value ldecl₂.value
| _, _ => return false
@[specialize]
unsafe def localContextsEqualUpToIdsCore (lctx₁ lctx₂ : LocalContext)
(localInstances₁ localInstances₂ : LocalInstances) :
EqualUpToIdsM (Option GoalContext) := do
let decls₁ ← lctxDecls lctx₁
let decls₂ ← lctxDecls lctx₂
if h : decls₁.size = decls₂.size then
go decls₁ decls₂ h 0 { lctx₁, lctx₂, localInstances₁, localInstances₂ }
else
trace[Aesop.Util.EqualUpToIds] "number of hyps differs"
return none
where
go (decls₁ decls₂ : Array LocalDecl) (h : decls₁.size = decls₂.size)
(i : Nat) (gctx : GoalContext) : EqualUpToIdsM (Option GoalContext) := do
if h' : i < decls₁.size then
let ldecl₁ := decls₁[i]
let ldecl₂ := decls₂[i]'(by simp [← h, h'])
let eq ← withTraceNodeBefore `Aesop.Util.EqualUpToIds (return m!"comparing hyps {ldecl₁.userName}, {ldecl₂.userName}") do
localDeclsEqualUpToIdsCore ldecl₁ ldecl₂ |>.run gctx
if ! eq then
return none
let equalFVarIds :=
gctx.equalFVarIds.insert ldecl₁.fvarId ldecl₂.fvarId
go decls₁ decls₂ h (i + 1) { gctx with equalFVarIds }
else
return some gctx
@[specialize]
unsafe def unassignedMVarsEqualUpToIdsCore (mvarId₁ mvarId₂ : MVarId) :
EqualUpToIdsM Bool :=
withTraceNodeBefore `Aesop.Util.EqualUpToIds (return m!"comparing mvars {mvarId₁.name}, {mvarId₂.name}") do
if let some result ← equalCommonMVars? mvarId₁ mvarId₂ then
trace[Aesop.Util.EqualUpToIds] "common mvars are {if result then "identical" else "different"}"
return result
else if let some m₂ := (← get).equalMVarIds[mvarId₁]? then
if mvarId₂ == m₂ then
trace[Aesop.Util.EqualUpToIds] "mvars already known to be equal"
return true
else
trace[Aesop.Util.EqualUpToIds] "mvar {mvarId₁.name} known to be equal to different mvar {m₂.name}"
return false
else
let ctx ← read
let (some mdecl₁) := ctx.mctx₁.decls.find? mvarId₁ | throwError
"unknown metavariable '?{mvarId₁.name}'"
let (some mdecl₂) := ctx.mctx₂.decls.find? mvarId₂ | throwError
"unknown metavariable '?{mvarId₂.name}'"
let gctx? ←
localContextsEqualUpToIdsCore mdecl₁.lctx mdecl₂.lctx
mdecl₂.localInstances mdecl₂.localInstances
let some gctx := gctx?
| return false
withTraceNodeBefore `Aesop.Util.EqualUpToIds (return m!"comparing targets") do
if ← exprsEqualUpToIdsCore₁ mdecl₁.type mdecl₂.type |>.run gctx then
modify λ s =>
{ s with equalMVarIds := s.equalMVarIds.insert mvarId₁ mvarId₂ }
return true
else
return false
end
end Unsafe
@[implemented_by Unsafe.exprsEqualUpToIdsCore₁]
opaque exprsEqualUpToIdsCore (e₁ e₂ : Expr) : ReaderT GoalContext EqualUpToIdsM Bool
@[implemented_by Unsafe.unassignedMVarsEqualUpToIdsCore]
opaque unassignedMVarsEqualUpToIdsCore (mvarId₁ mvarId₂ : MVarId) :
EqualUpToIdsM Bool
@[specialize]
def tacticStatesEqualUpToIdsCore (goals₁ goals₂ : Array MVarId) :
EqualUpToIdsM Bool := do
if goals₁.size != goals₂.size then
return false
for g₁ in goals₁, g₂ in goals₂ do
if ! (← unassignedMVarsEqualUpToIdsCore g₁ g₂) then
return false
return true
end EqualUpToIds
def exprsEqualUpToIds (mctx₁ mctx₂ : MetavarContext)
(lctx₁ lctx₂ : LocalContext)
(localInstances₁ localInstances₂ : LocalInstances) (e₁ e₂ : Expr)
(allowAssignmentDiff := false) : MetaM Bool := do
EqualUpToIds.exprsEqualUpToIdsCore e₁ e₂
|>.run { lctx₁, lctx₂, localInstances₁, localInstances₂ }
|>.run (commonMCtx? := none) mctx₁ mctx₂ allowAssignmentDiff
def exprsEqualUpToIds' (e₁ e₂ : Expr) (allowAssignmentDiff := false) :
MetaM Bool := do
let mctx ← getMCtx
let lctx ← getLCtx
let localInstances ← getLocalInstances
exprsEqualUpToIds mctx mctx lctx lctx localInstances localInstances e₁ e₂
allowAssignmentDiff
def unassignedMVarsEqualUptoIds (commonMCtx? : Option MetavarContext)
(mctx₁ mctx₂ : MetavarContext) (mvarId₁ mvarId₂ : MVarId)
(allowAssignmentDiff := false) : MetaM Bool :=
EqualUpToIds.unassignedMVarsEqualUpToIdsCore mvarId₁ mvarId₂
|>.run commonMCtx? mctx₁ mctx₂ allowAssignmentDiff
def unassignedMVarsEqualUptoIds' (commonMCtx? : Option MetavarContext)
(mctx₁ mctx₂ : MetavarContext) (mvarId₁ mvarId₂ : MVarId)
(allowAssignmentDiff := false) :
MetaM (Bool × EqualUpToIdsM.State) :=
EqualUpToIds.unassignedMVarsEqualUpToIdsCore mvarId₁ mvarId₂
|>.run' commonMCtx? mctx₁ mctx₂ allowAssignmentDiff
def tacticStatesEqualUpToIds (commonMCtx? : Option MetavarContext)
(mctx₁ mctx₂ : MetavarContext) (goals₁ goals₂ : Array MVarId)
(allowAssignmentDiff := false) : MetaM Bool :=
EqualUpToIds.tacticStatesEqualUpToIdsCore goals₁ goals₂
|>.run commonMCtx? mctx₁ mctx₂ allowAssignmentDiff
def tacticStatesEqualUpToIds' (commonMCtx? : Option MetavarContext)
(mctx₁ mctx₂ : MetavarContext) (goals₁ goals₂ : Array MVarId)
(allowAssignmentDiff := false) :
MetaM (Bool × EqualUpToIdsM.State) :=
EqualUpToIds.tacticStatesEqualUpToIdsCore goals₁ goals₂
|>.run' commonMCtx? mctx₁ mctx₂ allowAssignmentDiff
end Aesop |
.lake/packages/aesop/Aesop/Util/Tactic/Unfold.lean | module
public meta import Aesop.Util.Unfold
public meta import Lean.Elab.Tactic.Basic
import Lean.Message
public section
open Lean Lean.Meta Lean.Elab.Tactic
namespace Aesop
private meta def mkToUnfold (ids : Array Ident) :
MetaM (Std.HashMap Name (Option Name)) := do
let mut toUnfold : Std.HashMap Name (Option Name) := {}
for id in (ids : Array Ident) do
let decl ← resolveGlobalConstNoOverload id
toUnfold := toUnfold.insert decl (← getUnfoldEqnFor? decl)
return toUnfold
elab "aesop_unfold " ids:ident+ : tactic => do
let toUnfold ← mkToUnfold ids
liftMetaTactic λ goal => do
match ← unfoldManyTarget (toUnfold[·]?) goal with
| none => throwTacticEx `aesop_unfold goal "could not unfold any of the given constants"
| some (goal, _) => return [goal]
elab "aesop_unfold " ids:ident+ " at " hyps:ident+ : tactic => do
let toUnfold ← mkToUnfold ids
liftMetaTactic λ goal => do
let mut goal := goal
for hypId in hyps do
let fvarId := (← getLocalDeclFromUserName hypId.getId).fvarId
match ← unfoldManyAt (toUnfold[·]?) goal fvarId with
| none => throwTacticEx `aesop_unfold goal m!"could not unfold any of the given constants at hypothesis '{hypId}'"
| some (goal', _) => goal := goal'
return [goal]
end Aesop |
.lake/packages/aesop/Aesop/Util/Tactic/Ext.lean | module
public import Lean.Meta.Basic
import Aesop.Tracing
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Ext
import Lean.Meta.Tactic.Intro
public section
open Lean Lean.Meta Lean.Elab.Tactic.Ext
namespace Aesop
structure ExtResult where
depth : Nat
commonFVarIds : Array FVarId
goals : Array (MVarId × Array FVarId)
partial def straightLineExt (goal : MVarId) : MetaM ExtResult :=
go goal 0 #[]
where
go (goal : MVarId) (depth : Nat) (commonFVarIds : Array FVarId) :
MetaM ExtResult:= do
withConstAesopTraceNode .debug (return m!"straightLineExt") do
aesop_trace[debug] "goal:{indentD goal}"
let goals? ← show MetaM _ from observing? $ applyExtTheoremAt goal
if let some goals := goals? then
aesop_trace[debug] "ext lemma applied; new goals:{indentD $ Elab.goalsToMessageData goals}"
let goals := goals.toArray
if goals.isEmpty then
return { depth := depth + 1, goals := #[], commonFVarIds := #[] }
let goals ← goals.mapM λ goal => do
let (fvarIds, goal) ← goal.intros
return (goal, fvarIds)
if h : goals.size = 1 then
let (goal, fvarIds) := goals[0]
go goal (depth + 1) (commonFVarIds ++ fvarIds)
else
return { depth := depth + 1, goals, commonFVarIds }
else
aesop_trace[debug] "no applicable ext lemma"
return { depth, goals := #[(goal, #[])], commonFVarIds }
def straightLineExtProgress (goal : MVarId) : MetaM ExtResult := do
let result ← straightLineExt goal
if result.depth == 0 then
throwError "no applicable extensionality theorem found"
return result
end Aesop |
.lake/packages/aesop/Aesop/Script/OptimizeSyntax.lean | module
public import Std.Data.HashSet.Basic
meta import Lean.Parser.Term.Basic
import Lean.Parser.Term.Basic
public section
namespace Aesop
open Lean Lean.Meta Lean.Parser.Tactic
variable [Monad m] [MonadQuotation m]
partial def optimizeFocusRenameI : Syntax → m Syntax
| stx@.missing | stx@(.atom ..) | stx@(.ident ..) => return stx
| .node info kind args => do
let stx := .node info kind (← args.mapM optimizeFocusRenameI)
match stx with
| `(tactic| · $tacs:tactic*)
| `(tactic| · { $tacs:tactic* }) => do
let tacs := tacs.getElems
let some (tac : TSyntax `tactic) := tacs[0]?
| return stx
match tac with
| `(tactic| rename_i $[$ns:ident]*) =>
`(tactic| next $[$ns:ident]* => $(tacs[1:]):tactic*)
| _ => return stx
| _ => return stx
private partial def addIdents (acc : Std.HashSet Name) : Syntax → Std.HashSet Name
| .missing | .atom .. => acc
| .ident (val := val) .. => acc.insert val
| .node _ _ args =>
args.foldl (init := acc) λ acc stx => addIdents acc stx
def optimizeInitialRenameI : Syntax → m Syntax
| stx@`(tacticSeq| $tacs:tactic*) => do
let tacs := tacs.getElems
let some (tac : TSyntax `tactic) := tacs[0]?
| return stx
match tac with
| `(tactic| rename_i $[$ns:ident]*) =>
let usedNames := tacs[1:].foldl (init := ∅) λ usedNames stx =>
addIdents usedNames stx.raw
let mut dropUntil := 0
for n in ns do
if usedNames.contains n.getId then
break
else
dropUntil := dropUntil + 1
if dropUntil == 0 then
return stx
else if dropUntil == ns.size then
tacsToTacticSeq tacs[1:]
else
let ns : TSyntaxArray `ident := ns[dropUntil:].toArray
let tac ← `(tactic| rename_i $[$ns:ident]*)
let mut result : Array (TSyntax `tactic) := Array.mkEmpty tacs.size
result := result.push tac
result := result ++ tacs[1:]
tacsToTacticSeq result
| _ => return stx
| stx => return stx
where
-- Inlining this helper function triggers a code gen issue:
-- https://github.com/leanprover/lean4/issues/4548
tacsToTacticSeq (tacs : Array (TSyntax `tactic)) : m (TSyntax ``tacticSeq) :=
`(tacticSeq| $tacs:tactic*)
def optimizeSyntax (stx : TSyntax kind) : m (TSyntax kind) := do
let mut stx := stx.raw
stx ← optimizeFocusRenameI stx
stx ← optimizeInitialRenameI stx
return ⟨stx⟩
end Aesop |
.lake/packages/aesop/Aesop/Script/Check.lean | module
public import Aesop.Script.UScript
import Aesop.Check
import Lean.Elab.Tactic.Basic
public section
open Lean Lean.Elab.Tactic
open Lean.Parser.Tactic (tacticSeq)
namespace Aesop.Script
def UScript.checkIfEnabled (uscript : UScript) : MetaM Unit := do
unless ← Check.script.steps.isEnabled do
return
try
uscript.validate
catch e =>
throwError "{Check.script.steps.name}: {e.toMessageData}"
end Script
def checkRenderedScriptIfEnabled (script : TSyntax ``tacticSeq)
(preState : Meta.SavedState) (goal : MVarId) (expectCompleteProof : Bool) :
MetaM Unit := do
if ! (← Check.script.isEnabled) then
return
let go : TacticM Unit := do
setGoals [goal]
evalTactic script
if expectCompleteProof && ! (← getUnsolvedGoals).isEmpty then
throwError "script executed successfully but did not solve the main goal"
try
show MetaM Unit from withoutModifyingState do
preState.restore
go.run { elaborator := .anonymous, recover := false }
|>.run' { goals := [goal] }
|>.run'
catch e => throwError
"{Check.script.name}: error while executing generated script:{indentD e.toMessageData}"
end Aesop |
.lake/packages/aesop/Aesop/Script/GoalWithMVars.lean | module
public import Lean.Meta.Basic
import Lean.Meta.CollectMVars
public section
open Lean Std Lean.Meta
namespace Aesop
structure GoalWithMVars where
goal : MVarId
mvars : Std.HashSet MVarId
deriving Inhabited
instance : Repr GoalWithMVars where
reprPrec
| g, _ => s!"\{ goal := {repr g.goal}, mvars := {repr g.mvars.toArray} }"
instance : BEq GoalWithMVars :=
⟨λ g₁ g₂ => g₁.goal == g₂.goal⟩
namespace GoalWithMVars
def ofMVarId (goal : MVarId) : MetaM GoalWithMVars := do
return { goal, mvars := ← goal.getMVarDependencies }
end Aesop.GoalWithMVars |
.lake/packages/aesop/Aesop/Script/Util.lean | module
public import Lean.Meta.Basic
import Aesop.Util.Basic
import Aesop.Util.EqualUpToIds
import Batteries.Lean.Meta.SavedState
public section
open Lean Std Lean.Meta
namespace Aesop.Script
-- Without {α β : Type} universe inference goes haywire.
@[specialize]
def findFirstStep? {α β : Type} (goals : Array α) (step? : α → Option β)
(stepOrder : β → Nat) : Option (Nat × α × β) := Id.run do
let mut firstStep? := none
for h : pos in [:goals.size] do
let g := goals[pos]
if let some step := step? g then
if let some (_, _, currentFirstStep) := firstStep? then
if stepOrder step < stepOrder currentFirstStep then
firstStep? := some (pos, g, step)
else
firstStep? := some (pos, g, step)
else
continue
return firstStep?
def matchGoals (postState₁ postState₂ : Meta.SavedState)
(goals₁ goals₂ : Array MVarId) : MetaM (Option (Std.HashMap MVarId MVarId)) := do
let goals₁ ← getProperGoals postState₁ goals₁
let goals₂ ← getProperGoals postState₂ goals₂
let (equal, s) ←
tacticStatesEqualUpToIds' none postState₁.meta.mctx
postState₂.meta.mctx goals₁ goals₂ (allowAssignmentDiff := true)
if ! equal then
return none
else
return s.equalMVarIds
where
getProperGoals (state : Meta.SavedState) (goals : Array MVarId) :
MetaM (Array MVarId) :=
state.runMetaM' do
let (properGoals, _) ← partitionGoalsAndMVars id goals
return properGoals.map (·.fst)
end Aesop.Script |
.lake/packages/aesop/Aesop/Script/ScriptM.lean | module
public import Aesop.BaseM
public import Aesop.Script.Step
public section
open Lean Aesop.Script
namespace Aesop
abbrev ScriptT m := StateRefT' IO.RealWorld (Array LazyStep) m
namespace ScriptT
protected def run [Monad m] [MonadLiftT (ST IO.RealWorld) m] (x : ScriptT m α) :
m (α × Array LazyStep) :=
StateRefT'.run x #[]
end ScriptT
abbrev ScriptM := ScriptT BaseM
variable [MonadStateOf (Array LazyStep) m]
def recordScriptStep (step : LazyStep) : m Unit :=
modify (·.push step)
def recordScriptSteps (steps : Array LazyStep) : m Unit :=
modify (· ++ steps)
def withScriptStep (preGoal : MVarId) (postGoals : α → Array MVarId)
(success : α → Bool) (tacticBuilder : α → TacticBuilder) (x : MetaM α) :
ScriptM α := do
let preState ← show MetaM _ from saveState
let a ← x
if success a then
let postState ← show MetaM _ from saveState
recordScriptStep {
tacticBuilders := #[tacticBuilder a]
postGoals := postGoals a
preGoal, preState, postState
}
return a
def withOptScriptStep (preGoal : MVarId) (postGoals : α → Array MVarId)
(tacticBuilder : α → TacticBuilder) (x : MetaM (Option α)) :
ScriptM (Option α) := do
let preState ← show MetaM _ from saveState
let some a ← x
| return none
let postState ← show MetaM _ from saveState
recordScriptStep {
tacticBuilders := #[tacticBuilder a]
postGoals := postGoals a
preGoal, preState, postState
}
return some a
end Aesop |
.lake/packages/aesop/Aesop/Script/TacticState.lean | module
public import Aesop.Script.GoalWithMVars
import Lean.Meta.CollectMVars
import Batteries.Lean.Meta.Basic
public section
open Lean
namespace Aesop.Script
variable [Monad m] [MonadError m]
structure TacticState where
visibleGoals : Array GoalWithMVars
invisibleGoals : Std.HashSet MVarId
deriving Inhabited
namespace TacticState
def mkInitial (goal : MVarId) : MetaM TacticState :=
return {
visibleGoals := #[⟨goal, ← goal.getMVarDependencies⟩]
invisibleGoals := ∅
}
private def throwUnknownGoalError (goal : MVarId) (pre : MessageData) : m α :=
throwError "internal error: {pre}: unknown goal '?{goal.name}'"
def getVisibleGoalIndex? (ts : TacticState) (goal : MVarId) : Option Nat :=
ts.visibleGoals.findIdx? (·.goal == goal)
def getVisibleGoalIndex (ts : TacticState) (goal : MVarId) : m Nat := do
if let (some idx) := ts.getVisibleGoalIndex? goal then
return idx
else
throwUnknownGoalError goal "getVisibleGoalIndex"
def getMainGoal? (ts : TacticState) : Option MVarId :=
ts.visibleGoals[0]?.map (·.goal)
def visibleGoalsHaveMVars (ts : TacticState) : Bool :=
ts.visibleGoals.any λ g => ! g.mvars.isEmpty
def solveVisibleGoals (ts : TacticState) : TacticState :=
{ ts with visibleGoals := #[] }
private def replaceWithArray [BEq α] (xs : Array α) (x : α) (r : Array α) :
Option (Array α) := Id.run do
let mut found := false
let mut ys := Array.mkEmpty (xs.size - 1 + r.size)
for x' in xs do
if x' == x then
ys := ys ++ r
found := true
else
ys := ys.push x'
return if found then some ys else none
def eraseSolvedGoals (ts : TacticState) (preMCtx postMCtx : MetavarContext) :
TacticState := {
ts with
visibleGoals := ts.visibleGoals.filter (! mvarWasSolved ·.goal)
invisibleGoals := ts.invisibleGoals.filter (! mvarWasSolved ·)
}
where
mvarWasSolved (mvarId : MVarId) : Bool :=
postMCtx.isExprMVarAssignedOrDelayedAssigned mvarId &&
! preMCtx.isExprMVarAssignedOrDelayedAssigned mvarId
def applyTactic (ts : TacticState) (inGoal : MVarId)
(outGoals : Array GoalWithMVars) (preMCtx postMCtx : MetavarContext) :
m TacticState := do
let (some visibleGoals) :=
replaceWithArray ts.visibleGoals ⟨inGoal, {}⟩ outGoals
| throwUnknownGoalError inGoal "applyTactic"
let ts := { ts with visibleGoals }
return eraseSolvedGoals ts preMCtx postMCtx
-- Focus the visible goal `goal` and move all other previously visible goals
-- to `invisibleGoals`.
def focus (ts : TacticState) (goal : MVarId) : m TacticState := do
let (some goalWithMVars) := ts.visibleGoals.find? (·.goal == goal)
| throwUnknownGoalError goal "focus"
let mut invisibleGoals := ts.invisibleGoals
for g in ts.visibleGoals do
if g.goal != goal then
invisibleGoals := invisibleGoals.insert g.goal
return { visibleGoals := #[goalWithMVars], invisibleGoals }
@[inline, always_inline]
def onGoalM (ts : TacticState) (g : MVarId)
(f : TacticState → m (α × TacticState)) : m (α × TacticState) := do
let (a, postTs) ← f (← ts.focus g)
let mut visibleGoals := #[]
for preGoal in ts.visibleGoals do
if preGoal.goal == g then
visibleGoals := visibleGoals ++ postTs.visibleGoals
else if postTs.invisibleGoals.contains preGoal.goal then
visibleGoals := visibleGoals.push preGoal
let mut invisibleGoals := ∅
for g in ts.invisibleGoals do
if postTs.invisibleGoals.contains g then
invisibleGoals := invisibleGoals.insert g
return (a, { visibleGoals, invisibleGoals })
end Aesop.Script.TacticState |
.lake/packages/aesop/Aesop/Script/SScript.lean | module
public import Aesop.Script.Step
import Batteries.Tactic.PermuteGoals
public section
open Lean Lean.Meta
variable [Monad m] [MonadError m] [MonadQuotation m]
namespace Aesop.Script
inductive SScript
| empty
| onGoal (goalPos : Nat) (step : Step) (tail : SScript)
| focusAndSolve (goalPos : Nat) (here tail : SScript)
deriving Inhabited
namespace SScript
def takeNConsecutiveFocusAndSolve? (acc : Array SScript) :
Nat → SScript → Option (Array SScript × SScript)
| 0, tail => some (acc, tail)
| _ + 1, empty => none
| _ + 1, onGoal .. => none
| n + 1, focusAndSolve 0 here tail =>
takeNConsecutiveFocusAndSolve? (acc.push here) n tail
| _ + 1, focusAndSolve (_ + 1) .. => none
partial def render (script : SScript) : m (Array Syntax.Tactic) := do
go #[] script
where
go (acc : Array Syntax.Tactic) :
SScript → m (Array Syntax.Tactic)
| empty => return acc
| onGoal goalPos step tail => do
if let some (tactic, tail) ← renderSTactic? goalPos step tail then
let script := acc.push tactic
go script tail
else
let script := acc.push $ mkOnGoal goalPos step.uTactic
go script tail
| focusAndSolve goalPos here tail => do
let nestedScript ← go #[] here
let t ←
if goalPos == 0 then
`(tactic| · $[$nestedScript:tactic]*)
else
let posLit := mkOneBasedNumLit goalPos
`(tactic| on_goal $posLit:num => { $nestedScript:tactic* })
go (acc.push t) tail
renderSTactic? (goalPos : Nat) (step : Step) (tail : SScript) :
m (Option (Syntax.Tactic × SScript)) := do
let some sTactic := step.sTactic?
| return none
let some (nested, tail) :=
takeNConsecutiveFocusAndSolve? #[] sTactic.numSubgoals tail
| return none
let nestedScripts ← nested.mapM (go #[])
let tactic := mkOnGoal goalPos $ sTactic.run nestedScripts
return (tactic, tail)
end Aesop.Script.SScript |
.lake/packages/aesop/Aesop/Script/CtorNames.lean | module
public import Lean.Meta.Tactic.Induction
import Aesop.Util.Basic
public section
open Lean Lean.Meta
namespace Aesop
structure CtorNames where
ctor : Name
args : Array Name
/-- Whether the constructor has at least one implicit argument. -/
hasImplicitArg : Bool
namespace CtorNames
def toRCasesPat (cn : CtorNames) : TSyntax `rcasesPat := Unhygienic.run do
let ns ← cn.args.mapM λ n =>
`(Lean.Parser.Tactic.rcasesPatLo| $(mkIdent n):ident)
if cn.hasImplicitArg then
`(rcasesPat| @⟨ $ns,* ⟩)
else
`(rcasesPat| ⟨ $ns,* ⟩)
private def nameBase : Name → Name
| .anonymous => .anonymous
| .str _ s => .str .anonymous s
| .num _ n => .num .anonymous n
open Lean.Parser.Tactic in
def toInductionAltLHS (cn : CtorNames) :
TSyntax ``inductionAltLHS := Unhygienic.run do
let ns := cn.args.map mkIdent
let ctor := mkIdent $ nameBase cn.ctor
if cn.hasImplicitArg then
`(inductionAltLHS| | @$ctor $ns:ident*)
else
`(inductionAltLHS| | $ctor $ns:ident*)
open Lean.Parser.Tactic in
def toInductionAlt (cn : CtorNames) (tacticSeq : Array Syntax.Tactic) :
TSyntax ``inductionAlt := Unhygienic.run do
`(inductionAlt| $(cn.toInductionAltLHS):inductionAltLHS => $tacticSeq:tactic*)
def toAltVarNames (cn : CtorNames) : AltVarNames where
explicit := true
varNames := cn.args.toList
def mkFreshArgNames (lctx : LocalContext) (cn : CtorNames) :
CtorNames × LocalContext :=
let (args, lctx) := getUnusedNames lctx cn.args
({ cn with args }, lctx)
end CtorNames
open Lean.Parser.Tactic in
def ctorNamesToRCasesPats (cns : Array CtorNames) : TSyntax ``rcasesPatMed :=
Unhygienic.run do `(rcasesPatMed| $(cns.map (·.toRCasesPat)):rcasesPat|*)
open Lean.Parser.Tactic in
def ctorNamesToInductionAlts (cns : Array (CtorNames × Array Syntax.Tactic)) :
TSyntax ``inductionAlts := Unhygienic.run do
let alts := cns.map λ (cn, tacticSeq) => cn.toInductionAlt tacticSeq
`(inductionAlts| with $alts:inductionAlt*)
def mkCtorNames (iv : InductiveVal) : CoreM (Array CtorNames) := MetaM.run' do
iv.ctors.toArray.mapM λ ctor => do
let cv ← getConstInfoCtor ctor
let arity := cv.numParams + cv.numFields
forallBoundedTelescope cv.type arity λ args _ => do
let mut result := Array.mkEmpty cv.numFields
let mut hasImplicitArg := false
for arg in args[cv.numParams:] do
let ldecl ← arg.fvarId!.getDecl
result := result.push ldecl.userName
hasImplicitArg := hasImplicitArg || ! ldecl.binderInfo.isExplicit
return { args := result, ctor, hasImplicitArg }
end Aesop |
.lake/packages/aesop/Aesop/Script/Tactic.lean | module
public import Lean.Meta.Basic
public section
open Lean
namespace Aesop.Script
abbrev UTactic := Syntax.Tactic
structure STactic where
numSubgoals : Nat
run : Array (Array Syntax.Tactic) → Syntax.Tactic
structure Tactic where
uTactic : UTactic
sTactic? : Option STactic
namespace Tactic
instance : ToMessageData Tactic where
toMessageData t := toMessageData t.uTactic
def unstructured (uTactic : UTactic) : Tactic where
uTactic := uTactic
sTactic? := none
def structured (uTactic : UTactic) (sTactic : STactic) : Tactic where
uTactic := uTactic
sTactic? := some sTactic
end Tactic
abbrev TacticBuilder := MetaM Tactic
end Aesop.Script |
.lake/packages/aesop/Aesop/Script/StructureStatic.lean | module
public import Aesop.Script.SScript
public import Aesop.Script.UScript
import Aesop.Tracing
import Aesop.Script.UScriptToSScript
import Aesop.Script.Util
public section
open Lean Lean.Meta
namespace Aesop.Script
namespace StaticStructureM
structure State where
perfect : Bool := true
structure Context where
steps : Std.HashMap MVarId (Nat × Step)
end StaticStructureM
abbrev StaticStructureM :=
ReaderT StaticStructureM.Context $ StateRefT StaticStructureM.State CoreM
protected def StaticStructureM.run (script : UScript) (x : StaticStructureM α) :
CoreM (α × Bool) := do
let mut steps : Std.HashMap MVarId (Nat × Step) := Std.HashMap.emptyWithCapacity script.size
for h : i in [:script.size] do
let step := script[i]
if h : step.postGoals.size = 1 then
if step.postGoals[0].goal == step.preGoal then
continue
steps := steps.insert step.preGoal (i, step)
let (a, s) ← ReaderT.run x { steps } |>.run {}
return (a, s.perfect)
partial def structureStaticCore (tacticState : TacticState) (script : UScript) :
CoreM (UScript × Bool) :=
withConstAesopTraceNode .script (return m!"statically structuring the tactic script") do
aesop_trace[script] "unstructured script:{indentD $ MessageData.joinSep (script.toList.map λ step => m!"{step}") "\n"}"
let ((script, _), perfect) ← go tacticState |>.run script
return (script.toArray, perfect)
where
go (tacticState : TacticState) : StaticStructureM (List Step × TacticState) :=
withIncRecDepth do
if let some goal := tacticState.visibleGoals[0]? then
let step ← nextStep tacticState goal
aesop_trace[script] "rendering step:{indentD $ toMessageData step}"
let tacticState ← tacticState.applyStep step
let (tailScript, tacticState) ← go tacticState
return (step :: tailScript, tacticState)
else
return ([], tacticState)
nextStep (tacticState : TacticState) (mainGoal : GoalWithMVars) :
StaticStructureM Step := do
let steps := (← read).steps
if mainGoal.mvars.isEmpty then
let some (_, step) := steps[mainGoal.goal]?
| throwError "aesop: internal error while structuring script: no script step for main goal {mainGoal.goal.name}"
return step
let firstStep? :=
findFirstStep? tacticState.visibleGoals (steps[·.goal]?) (·.fst)
let some (_, _, _, firstStep) := firstStep?
| throwError "aesop: internal error while structuring script: no script step found for any of the goals {tacticState.visibleGoals.map (·.goal.name)}"
if firstStep.preGoal != mainGoal.goal then
modify ({ · with perfect := false })
return firstStep
def UScript.toSScriptStatic (tacticState : TacticState) (uscript : UScript) :
CoreM (SScript × Bool) := do
let (script, perfect) ← structureStaticCore tacticState uscript
return (← orderedUScriptToSScript script tacticState, perfect)
end Aesop.Script |
.lake/packages/aesop/Aesop/Script/UScript.lean | module
public import Aesop.Script.Step
public import Lean.Parser.Term.Basic
import Batteries.Lean.Meta.SavedState
meta import Lean.Parser.Term.Basic
public section
open Lean Lean.Meta
open Lean.Parser.Tactic (tacticSeq)
namespace Aesop.Script
abbrev UScript := Array Step
namespace UScript
variable [Monad m] [MonadError m] [MonadQuotation m] in
def render (tacticState : TacticState) (s : UScript) :
m (Array Syntax.Tactic) := do
let mut script := Array.mkEmpty s.size
let mut tacticState := tacticState
for step in s do
let (script', tacticState') ← step.render script tacticState
script := script'
tacticState := tacticState'
return script
def renderTacticSeq (uscript : UScript) (preState : Meta.SavedState)
(goal : MVarId) : MetaM (TSyntax ``tacticSeq) := do
let tacticState ← preState.runMetaM' $ Script.TacticState.mkInitial goal
`(tacticSeq| $(← uscript.render tacticState):tactic*)
def validate (s : UScript) : MetaM Unit :=
s.forM (·.validate)
end Aesop.Script.UScript |
.lake/packages/aesop/Aesop/Script/SpecificTactics.lean | module
public import Aesop.Util.Tactic.Ext
public import Aesop.Script.CtorNames
public import Aesop.Script.ScriptM
public import Lean.Meta.Tactic.Cases
public import Lean.Meta.Tactic.Simp.Types
import Aesop.Util.Tactic
import Aesop.Util.Unfold
import Aesop.Util.Tactic.Unfold
import Batteries.Lean.Meta.Basic
import Batteries.Lean.Meta.Inaccessible
import Lean.Elab.Tactic.RCases
import Lean.Elab.Tactic.Simp
import Lean.Meta.Tactic.Split
public section
open Lean
open Lean.Meta
open Lean.PrettyPrinter (delab)
namespace Aesop.Script
def Tactic.skip : Tactic :=
.unstructured $ Unhygienic.run `(tactic| skip)
namespace TacticBuilder
def applyStx (e : Term) (md : TransparencyMode) : TacticBuilder := do
let tac := withAllTransparencySyntax md (← `(tactic| apply $e))
return .unstructured tac
def apply (mvarId : MVarId) (e : Expr) (md : TransparencyMode) :
TacticBuilder := do
let e ← mvarId.withContext $ delab e
let tac := withAllTransparencySyntax md (← `(tactic| apply $e))
return .unstructured tac
def exactFVar (goal : MVarId) (fvarId : FVarId) (md : TransparencyMode) :
TacticBuilder := do
let ident := mkIdent (← goal.withContext $ fvarId.getUserName)
let tac := withAllTransparencySyntax md $ ← `(tactic| exact $ident)
return .unstructured tac
def replace (preGoal postGoal : MVarId) (fvarId : FVarId) (type : Expr)
(proof : Expr) : TacticBuilder := do
let userName ← preGoal.withContext $ fvarId.getUserName
let proof ← preGoal.withContext $ delab proof
let type ← postGoal.withContext $ delab type
let tac ← `(tactic| replace $(mkIdent userName) : $type := $proof)
return .unstructured tac
def assertHypothesis (goal : MVarId) (h : Hypothesis) (md : TransparencyMode) :
TacticBuilder :=
goal.withContext do
let tac ← `(tactic| have $(mkIdent h.userName) : $(← delab h.type) := $(← delab h.value))
return .unstructured $ withAllTransparencySyntax md tac
def clear (goal : MVarId) (fvarIds : Array FVarId) : TacticBuilder :=
goal.withContext do
let userNames ← fvarIds.mapM (mkIdent <$> ·.getUserName)
return .unstructured $ ← `(tactic| clear $userNames*)
def cases (goal : MVarId) (e : Expr) (ctorNames : Array CtorNames) :
TacticBuilder := do
goal.withContext do
let rcasesPat := ctorNamesToRCasesPats ctorNames
let e ← delab e
let uTactic ← `(tactic| rcases $e:term with $rcasesPat)
let sTactic := {
numSubgoals := ctorNames.size
run := λ conts =>
Unhygienic.run do
let alts := ctorNamesToInductionAlts (ctorNames.zip conts)
`(tactic| cases $e:term $alts:inductionAlts)
}
return .structured uTactic sTactic
def obtain (goal : MVarId) (e : Expr) (ctorNames : CtorNames) : TacticBuilder :=
goal.withContext do
let tac ← `(tactic| obtain $(ctorNames.toRCasesPat) := $(← delab e))
return .unstructured tac
def casesOrObtain (goal : MVarId) (e : Expr) (ctorNames : Array CtorNames) :
TacticBuilder :=
if h : ctorNames.size = 1 then
obtain goal e ctorNames[0]
else
cases goal e ctorNames
def renameInaccessibleFVars (postGoal : MVarId) (renamedFVars : Array FVarId) :
TacticBuilder :=
if renamedFVars.isEmpty then
return .skip
else
postGoal.withContext do
let ids ← renamedFVars.mapM λ fvarId => do
let userName := mkIdent (← fvarId.getDecl).userName
`(binderIdent| $userName:ident)
return .unstructured $ ← `(tactic| rename_i $ids:binderIdent*)
def unfold (usedDecls : Array Name) (aesopUnfold : Bool) : TacticBuilder := do
let usedDecls := usedDecls.map mkIdent
let tac ←
if aesopUnfold then
`(tactic | aesop_unfold $usedDecls:ident*)
else
`(tactic | unfold $usedDecls:ident*)
return .unstructured tac
def unfoldAt (goal : MVarId) (fvarId : FVarId) (usedDecls : Array Name)
(aesopUnfold : Bool) : TacticBuilder :=
goal.withContext do
let hypIdent := mkIdent (← goal.withContext $ fvarId.getUserName)
let usedDecls := usedDecls.map mkIdent
let tac ←
if aesopUnfold then
`(tactic| aesop_unfold $usedDecls:ident* at $hypIdent:ident)
else
`(tactic| unfold $usedDecls:ident* at $hypIdent:ident)
return .unstructured tac
open Lean.Parser.Tactic in
def extN (r : ExtResult) : TacticBuilder := do
if r.depth == 0 then
return .skip
let mut pats := #[]
if h : 0 < r.goals.size then
let pats' ← r.goals[0].1.withContext do r.commonFVarIds.mapM mkPat
pats := pats ++ pats'
for (g, fvarIds) in r.goals do
let pats' ← g.withContext do fvarIds.mapM mkPat
pats := pats ++ pats'
let depthStx := Syntax.mkNumLit $ toString r.depth
let tac ← `(tactic| ext $pats:rintroPat* : $depthStx)
return .unstructured tac
where
mkPat (fvarId : FVarId) : MetaM (TSyntax `rintroPat) := do
`(rintroPat| $(mkIdent $ ← fvarId.getUserName):ident)
private def simpAllOrSimpAtStarStx [Monad m] [MonadQuotation m] (simpAll : Bool)
(configStx? : Option Term) : m (Syntax.Tactic) :=
if simpAll then
match configStx? with
| none => `(tactic| simp_all)
| some cfg => `(tactic| simp_all ($(mkIdent `config):ident := $cfg))
else
match configStx? with
| none => `(tactic| simp at *)
| some cfg => `(tactic| simp ($(mkIdent `config):ident := $cfg) at *)
private def simpAllOrSimpAtStarOnlyStx (simpAll : Bool) (inGoal : MVarId)
(configStx? : Option Term) (usedTheorems : Simp.UsedSimps) :
MetaM Syntax.Tactic := do
let originalStx ← simpAllOrSimpAtStarStx simpAll configStx?
let stx ← inGoal.withContext do
Elab.Tactic.mkSimpOnly originalStx usedTheorems
return ⟨stx⟩
def simpAllOrSimpAtStarOnly (simpAll : Bool) (inGoal : MVarId)
(configStx? : Option Term) (usedTheorems : Simp.UsedSimps) :
TacticBuilder :=
.unstructured <$>
simpAllOrSimpAtStarOnlyStx simpAll inGoal configStx? usedTheorems
private def isGlobalSimpTheorem (thms : SimpTheorems) (simprocs : Simprocs) : Origin → Bool
| origin@(.decl decl) =>
simprocs.simprocNames.contains decl ||
thms.lemmaNames.contains origin ||
thms.toUnfold.contains decl ||
thms.toUnfoldThms.contains decl
| _ => false
def simpAllOrSimpAtStar (simpAll : Bool) (inGoal : MVarId)
(configStx? : Option Term) (usedTheorems : Simp.UsedSimps) :
TacticBuilder := do
let simpTheorems ← getSimpTheorems
let simprocs ← Simp.getSimprocs
let (map, size) ←
usedTheorems.map.foldlM (init := ({}, 0)) λ (map, size) origin thm => do
if isGlobalSimpTheorem simpTheorems simprocs origin then
return (map, size)
else
return (map.insert origin thm, size + 1)
let stx ←
match ← simpAllOrSimpAtStarOnlyStx simpAll inGoal configStx? { map, size } with
| `(tactic| simp_all $cfg:optConfig only [$lems,*]) =>
`(tactic| simp_all $cfg:optConfig [$lems,*])
| `(tactic| simp $cfg:optConfig only [$lems,*] at *) =>
`(tactic| simp $cfg:optConfig [$lems,*] at *)
| `(tactic| simp_all $cfg:optConfig only) =>
`(tactic| simp_all $cfg:optConfig)
| `(tactic| simp $cfg:optConfig only at *) =>
`(tactic| simp $cfg:optConfig at *)
| stx => throwError "simp tactic builder: unexpected syntax:{indentD stx}"
return .unstructured ⟨stx⟩
def intros (postGoal : MVarId) (newFVarIds : Array FVarId)
(md : TransparencyMode) : TacticBuilder := do
let newFVarUserNames ← postGoal.withContext $
newFVarIds.mapM (mkIdent <$> ·.getUserName)
let tac ← `(tactic| intro $newFVarUserNames:ident*)
let tac := withAllTransparencySyntax md tac
return .unstructured ⟨tac⟩
def splitTarget : TacticBuilder :=
return .unstructured $ ← `(tactic| split)
def splitAt (goal : MVarId) (fvarId : FVarId) : TacticBuilder := do
let name ← goal.withContext fvarId.getUserName
let tac ← `(tactic| split at $(mkIdent name):ident)
return .unstructured tac
def substFVars (goal : MVarId) (fvarIds : Array FVarId) : TacticBuilder := do
let names ← goal.withContext $ fvarIds.mapM λ fvarId =>
return mkIdent (← fvarId.getUserName)
let tac ← `(tactic| subst $names:ident*)
return .unstructured tac
def substFVars' (fvarUserNames : Array Name) : TacticBuilder := do
let fvarUserNames := fvarUserNames.map mkIdent
let tac ← `(tactic| subst $fvarUserNames:ident*)
return .unstructured tac
end Script.TacticBuilder
open Script
def assertHypothesisS (goal : MVarId) (h : Hypothesis) (md : TransparencyMode) :
ScriptM (MVarId × Array FVarId) :=
withScriptStep goal (#[·.1]) (λ _ => true) tacticBuilder do
let (fvarIds, goal) ← withTransparency md $ goal.assertHypotheses #[h]
return (goal, fvarIds)
where
tacticBuilder _ := TacticBuilder.assertHypothesis goal h md
def applyS (goal : MVarId) (e : Expr) (eStx? : Option Term)
(md : TransparencyMode) : ScriptM (Array MVarId) :=
withScriptStep goal id (λ _ => true) tacticBuilder do
(·.toArray) <$> withTransparency md (goal.apply e)
where
tacticBuilder _ :=
match eStx? with
| none => TacticBuilder.apply goal e md
| some eStx => TacticBuilder.applyStx eStx md
def replaceFVarS (goal : MVarId) (fvarId : FVarId) (type : Expr) (proof : Expr) :
ScriptM (MVarId × FVarId × Bool) :=
withScriptStep goal (#[·.1]) (λ _ => true) tacticBuilder do
replaceFVar goal fvarId type proof
where
tacticBuilder := (TacticBuilder.replace goal ·.1 fvarId type proof)
def clearS (goal : MVarId) (fvarId : FVarId) : ScriptM MVarId :=
withScriptStep goal (#[·]) (λ _ => true) tacticBuilder do
goal.clear fvarId
where
tacticBuilder _ := TacticBuilder.clear goal #[fvarId]
def tryClearS (goal : MVarId) (fvarId : FVarId) : ScriptM (Option MVarId) :=
withOptScriptStep goal (#[·]) tacticBuilder do
goal.tryClear fvarId
where
tacticBuilder _ := TacticBuilder.clear goal #[fvarId]
def tryClearManyS (goal : MVarId) (fvarIds : Array FVarId) :
ScriptM (MVarId × Array FVarId) :=
withScriptStep goal (#[·.fst]) (! ·.2.isEmpty) tacticBuilder do
goal.tryClearMany' fvarIds
where
tacticBuilder := λ (_, fvarIds) => TacticBuilder.clear goal fvarIds
def tryCasesS (goal : MVarId) (fvarId : FVarId) (ctorNames : Array CtorNames) :
ScriptM (Option (Array CasesSubgoal)) := do
let ctorNames := getUnusedCtorNames (← goal.getDecl).lctx
let tacticBuilder _ :=
TacticBuilder.casesOrObtain goal (.fvar fvarId) ctorNames
withOptScriptStep goal (·.map (·.mvarId)) tacticBuilder do
observing? $ goal.cases fvarId (ctorNames.map (·.toAltVarNames))
(useNatCasesAuxOn := true)
where
getUnusedCtorNames (lctx : LocalContext) : Array CtorNames :=
Prod.fst $ ctorNames.foldl (init := (Array.mkEmpty ctorNames.size, lctx))
λ (ctorNames, lctx) cn =>
let (cn, lctx) := cn.mkFreshArgNames lctx
(ctorNames.push cn, lctx)
def renameInaccessibleFVarsS (goal : MVarId) :
ScriptM (MVarId × Array FVarId) :=
withScriptStep goal (#[·.1]) (! ·.snd.isEmpty) tacticBuilder do
goal.renameInaccessibleFVars
where
tacticBuilder := λ (goal, renamedFVars) =>
TacticBuilder.renameInaccessibleFVars goal renamedFVars
def unfoldManyTargetS (unfold? : Name → Option (Option Name)) (goal : MVarId) :
ScriptM (Option (MVarId × Array Name)) := do
let preState ← show MetaM _ from saveState
let some (postGoal, usedDecls) ← unfoldManyTarget unfold? goal
| return none
let postState ← show MetaM _ from saveState
recordScriptStep {
preGoal := goal
tacticBuilders :=
#[TacticBuilder.unfold usedDecls (aesopUnfold := false),
TacticBuilder.unfold usedDecls (aesopUnfold := true)]
postGoals := #[postGoal]
preState, postState
}
return some (postGoal, usedDecls)
def unfoldManyAtS (unfold? : Name → Option (Option Name)) (goal : MVarId)
(fvarId : FVarId) : ScriptM (Option (MVarId × Array Name)) := do
let preState ← show MetaM _ from saveState
let some (postGoal, usedDecls) ← unfoldManyAt unfold? goal fvarId
| return none
let postState ← show MetaM _ from saveState
recordScriptStep {
preGoal := goal
tacticBuilders :=
#[TacticBuilder.unfoldAt goal fvarId usedDecls (aesopUnfold := false),
TacticBuilder.unfoldAt goal fvarId usedDecls (aesopUnfold := true)]
postGoals := #[postGoal]
preState, postState
}
return some (postGoal, usedDecls)
def unfoldManyStarS (goal : MVarId) (unfold? : Name → Option (Option Name)) :
ScriptM (Option MVarId) :=
goal.withContext do
let initialGoal := goal
let mut goal := goal
if let some (goal', _) ← unfoldManyTargetS unfold? goal then
goal := goal'
for ldecl in (← goal.getDecl).lctx do
if ldecl.isImplementationDetail then
continue
if let some (goal', _) ← unfoldManyAtS unfold? goal ldecl.fvarId then
goal := goal'
if goal == initialGoal then
return none
else
return some goal
def introsS (goal : MVarId) : ScriptM (MVarId × Array FVarId) :=
withScriptStep goal (#[·.fst]) (! ·.2.isEmpty) tacticBuilder do
let (newFVarIds, mvarId) ← unhygienic $ goal.intros
return (mvarId, newFVarIds)
where
tacticBuilder := λ (postGoal, newFVarIds) =>
TacticBuilder.intros postGoal newFVarIds .default
def introsUnfoldingS (goal : MVarId) (md : TransparencyMode) :
ScriptM (MVarId × Array FVarId) :=
withScriptStep goal (#[·.fst]) (! ·.2.isEmpty) tacticBuilder do
let (newFVarIds, mvarId) ← withTransparency md $ unhygienic $
introsUnfolding goal
return (mvarId, newFVarIds)
where
tacticBuilder := λ (postGoal, newFVarIds) =>
TacticBuilder.intros postGoal newFVarIds md
def straightLineExtS (goal : MVarId) : ScriptM ExtResult :=
withScriptStep goal (·.goals.map (·.1)) (·.depth != 0) tacticBuilder do
unhygienic $ straightLineExt goal
where
tacticBuilder := TacticBuilder.extN
def tryExactFVarS (goal : MVarId) (fvarId : FVarId) (md : TransparencyMode) :
ScriptM Bool := do
let preState ← show MetaM _ from saveState
let ldecl ← fvarId.getDecl
let tgt ← goal.getType
if ! (← withTransparency md $ isDefEq ldecl.type tgt) then
show MetaM _ from restoreState preState
return false
goal.assign ldecl.toExpr
let postState ← show MetaM _ from saveState
let step := {
preGoal := goal
postGoals := #[]
tacticBuilders := #[TacticBuilder.exactFVar goal fvarId md]
preState, postState
}
recordScriptStep step
return true
private def renameInaccessibleFVarsS' (goals : Array MVarId) :
ScriptM (Array MVarId) :=
goals.mapM ((·.fst) <$> renameInaccessibleFVarsS ·)
def splitTargetS? (goal : MVarId) :
ScriptM (Option (Array MVarId)) := do
let some subgoals ← withOptScriptStep goal id tacticBuilder do
(·.map (·.toArray)) <$> splitTarget? goal
| return none
some <$> renameInaccessibleFVarsS' subgoals
where
tacticBuilder _ := TacticBuilder.splitTarget
def splitFirstHypothesisS? (goal : MVarId) :
ScriptM (Option (Array MVarId)) := do
let some (subgoals, _) ← withOptScriptStep goal (·.1) tacticBuilder do
for ldecl in (← goal.getDecl).lctx do
if ldecl.isImplementationDetail then
continue
if let some goals ← splitLocalDecl? goal ldecl.fvarId then
return some (goals.toArray, ldecl.fvarId)
return none
| return none
some <$> renameInaccessibleFVarsS' subgoals
where
tacticBuilder := λ (_, fvarId) => TacticBuilder.splitAt goal fvarId
end Aesop |
.lake/packages/aesop/Aesop/Script/StructureDynamic.lean | module
public import Aesop.Script.SScript
public import Aesop.Script.UScript
import Aesop.Tracing
import Aesop.Script.UScriptToSScript
import Aesop.Script.Util
import Aesop.Util.Basic
import Batteries.Lean.Meta.SavedState
public section
open Lean Lean.Meta
namespace Aesop.Script
private def goalsToMessageData (state : Meta.SavedState) (goals : Array MVarId) :
MetaM MessageData :=
state.runMetaM' do
addMessageContext $
MessageData.joinSep
(goals.map λ g => m!"?{g.name}:{indentD $ toMessageData g}").toList
"\n"
namespace DynStructureM
structure Context where
/-- The tactic invocation steps corresponding to the original unstructured
script, but with `MVarId` keys adjusted to fit the current `MetaM` state. This
state evolves during dynamic structuring and we continually update the `steps`
so that this map's keys refer to metavariables which exist in the current
`MetaM` state. -/
steps : PHashMap MVarId (Nat × Step)
deriving Inhabited
structure State where
perfect : Bool := true
/--
Given a bijective map `map` from new `MVarId`s to old `MVarId`s, update the
`steps` of the context `c` such that each entry whose key is an old `MVarId` `m`
is replaced with an entry whose key is the corresponding new `MVarId`
`map⁻¹ m`.
-/
def Context.updateMVarIds (c : Context) (map : Std.HashMap MVarId MVarId) :
Context :=
let steps := map.fold (init := c.steps) λ steps newMVarId oldMVarId =>
if let (some step) := steps.find? oldMVarId then
steps.erase oldMVarId |>.insert newMVarId step
else
steps
{ c with steps }
end DynStructureM
abbrev DynStructureM :=
ReaderT DynStructureM.Context $ StateRefT DynStructureM.State MetaM
def DynStructureM.run (x : DynStructureM α) (script : UScript) :
MetaM (α × Bool) := do
let mut steps : PHashMap MVarId (Nat × Step) := {}
for h : i in [:script.size] do
let step := script[i]
steps := steps.insert step.preGoal (i, step)
let (a, s) ← ReaderT.run x { steps } |>.run {}
return (a, s.perfect)
def withUpdatedMVarIds
(oldPostState newPostState : Meta.SavedState)
(oldPostGoals newPostGoals : Array MVarId) (onFailure : DynStructureM α)
(onSuccess : DynStructureM α) : DynStructureM α := do
match ← matchGoals newPostState oldPostState newPostGoals oldPostGoals with
| some m => withReader (·.updateMVarIds m) onSuccess
| none => onFailure
structure DynStructureResult where
script : List Step
postState : Meta.SavedState
partial def structureDynamicCore (preState : Meta.SavedState) (preGoal : MVarId)
(uscript : UScript) : MetaM (Option (UScript × Bool)) :=
withAesopTraceNode .script (λ r => return m!"{exceptOptionEmoji r} Dynamically structuring the script") do
aesop_trace[script] "unstructured script:{indentD $ MessageData.joinSep (uscript.map toMessageData |>.toList) "\n"}"
let (result?, perfect) ← go preState #[preGoal] |>.run uscript
let some result := result?
| return none
return some (result.script.toArray, perfect)
where
go (preState : Meta.SavedState) (preGoals : Array MVarId) :
DynStructureM (Option DynStructureResult) :=
withIncRecDepth do
if h : 0 < preGoals.size then
-- Try to apply the step for the main goal, then solve the remaining goals.
let firstGoal := preGoals[0]
let result? ← withAesopTraceNode .script (λ r => return m!"{exceptOptionEmoji r} Focusing main goal {firstGoal.name}") do
aesop_trace[script] "goal: {firstGoal.name}{← preState.runMetaM' $ addMessageContext $ indentD firstGoal}"
goStructured preState preGoals preGoals[0]
match result? with
| some result => return result
| none =>
-- If this fails, apply the chronologically next step and solve the remaining goals.
modify ({ · with perfect := false })
withAesopTraceNode .script (λ r => return m!"{exceptOptionEmoji r} Applying step to chronologically first goal") do
goUnstructured preState preGoals
else
return some { script := [], postState := preState }
goStructured (preState : Meta.SavedState) (preGoals : Array MVarId)
(firstPreGoal : MVarId) : DynStructureM (Option DynStructureResult) := do
let (some (_, step)) := (← read).steps[firstPreGoal]
| throwError "aesop: internal error while structuring the script: no step for goal {preGoal.name}:{indentD $ ← preState.runMetaM' $ addMessageContext $ toMessageData preGoal}"
applyStepAndSolveRemaining preState preGoals firstPreGoal 0 step
goUnstructured (preState : Meta.SavedState) (preGoals : Array MVarId) :
DynStructureM (Option DynStructureResult) := do
let steps := (← read).steps
let firstStep? := findFirstStep? preGoals (steps[·]) (·.fst)
let some (goalPos, goal, _, step) := firstStep?
| throwError "aesop: internal error while structuring the script: no step for any of the visible goals{indentD $ ← goalsToMessageData preState preGoals}"
aesop_trace[script] "goal: {goal.name}{← preState.runMetaM' $ addMessageContext $ indentD goal}"
applyStepAndSolveRemaining preState preGoals goal goalPos step
applyStepAndSolveRemaining (preState : Meta.SavedState)
(preGoals : Array MVarId) (preGoal : MVarId) (goalPos : Nat)
(step : Step) : DynStructureM (Option DynStructureResult) := do
aesop_trace[script] "applying step:{indentD $ toMessageData step}"
aesop_trace[script] "expected post goals:{indentD $ ← goalsToMessageData step.postState (step.postGoals.map (·.goal))}"
let (postState, postGoals) ←
try
runTacticCapturingPostState step.uTactic preState [preGoal]
catch e =>
aesop_trace[script] "tactic failed with error:{indentD e.toMessageData}"
return none
let postGoals := postGoals.toArray
withUpdatedMVarIds step.postState postState (step.postGoals.map (·.goal)) postGoals
(onFailure := do
aesop_trace[script] "post goals don't match; actual post goals:{indentD $ ← goalsToMessageData postState postGoals}"
return none) do
aesop_trace[script] "post goals match"
let postGoalsWithMVars ← postState.runMetaM' do
postGoals.mapM λ goal =>
return { goal, mvars := ← goal.getMVarDependencies }
-- We need to construct a new step here because the old step's postState
-- is equivalent to the new postState *only up to mvar assignments*.
let step := {
tactic := step.tactic
postGoals := postGoalsWithMVars
preState, preGoal, postState
}
let postGoals := preGoals[:goalPos] ++ postGoals ++ preGoals[goalPos+1:]
let postGoals ← postState.runMetaM' do
postGoals.filterM λ mvarId =>
return ! (← mvarId.isAssignedOrDelayedAssigned)
let some { script := tailScript, postState } ← go postState postGoals
| return none
let script := step :: tailScript
return some { script, postState }
def UScript.toSScriptDynamic (preState : Meta.SavedState) (preGoal : MVarId)
(uscript : UScript) : MetaM (Option (SScript × Bool)) := do
let some (uscript, perfect) ← structureDynamicCore preState preGoal uscript
| return none
let preGoalMVars ← preState.runMetaM' preGoal.getMVarDependencies
let tacticState := {
visibleGoals := #[⟨preGoal, preGoalMVars⟩]
invisibleGoals := ∅
}
return some (← orderedUScriptToSScript uscript tacticState, perfect)
end Aesop.Script |
.lake/packages/aesop/Aesop/Script/Step.lean | module
public import Aesop.Script.Tactic
public import Aesop.Script.TacticState
import Aesop.Tracing
import Aesop.Script.Util
import Aesop.Util.Basic
import Aesop.Util.EqualUpToIds
import Batteries.Tactic.PermuteGoals
import Batteries.Lean.Meta.SavedState
public section
open Lean Lean.Meta
variable [Monad m] [MonadError m] [MonadQuotation m]
namespace Aesop.Script
@[inline]
def mkOneBasedNumLit (n : Nat) : NumLit :=
Syntax.mkNumLit $ toString $ n + 1
def mkOnGoal (goalPos : Nat) (tac : Syntax.Tactic) : Syntax.Tactic :=
if goalPos == 0 then
tac
else
let posLit := mkOneBasedNumLit goalPos
Unhygienic.run `(tactic| on_goal $posLit:num => $tac:tactic)
structure Step where
preState : Meta.SavedState
preGoal : MVarId
tactic : Tactic
postState : Meta.SavedState
postGoals : Array GoalWithMVars
def TacticState.applyStep (tacticState : TacticState) (step : Step) :
m TacticState :=
tacticState.applyTactic step.preGoal step.postGoals step.preState.meta.mctx
step.postState.meta.mctx
namespace Step
def uTactic (s : Step) : UTactic :=
s.tactic.uTactic
def sTactic? (s : Step) : Option STactic :=
s.tactic.sTactic?
instance : ToMessageData Step where
toMessageData step :=
m!"{step.preGoal.name} → {step.postGoals.map (·.goal.name)}:{indentD $ toMessageData step.tactic}"
def mkSorry (preGoal : MVarId) (preState : Meta.SavedState) : MetaM Step := do
let (_, postState) ← preState.runMetaM do
preGoal.admit (synthetic := false)
let tactic ← .unstructured <$> `(tactic| sorry)
return {
postGoals := #[]
preState, postState, preGoal, tactic
}
def render (acc : Array Syntax.Tactic) (step : Step)
(tacticState : TacticState) : m (Array Syntax.Tactic × TacticState) := do
let pos ← tacticState.getVisibleGoalIndex step.preGoal
let tacticState ← tacticState.applyStep step
let acc := acc.push $ mkOnGoal pos step.tactic.uTactic
return (acc, tacticState)
open Lean.Elab.Tactic (evalTactic) in
def validate (step : Step) : MetaM Unit := do
let preMCtx := step.preState.meta.mctx
let expectedPostMCtx := step.postState.meta.mctx
let expectedPostGoals := step.postGoals |>.map (·.goal)
let tac := step.uTactic
let (actualPostState, actualPostGoals) ←
try
runTacticMCapturingPostState (evalTactic tac) step.preState [step.preGoal]
catch e =>
throwError "tactic{indentD step.uTactic}\nfailed with error{indentD e.toMessageData}"
let actualPostGoals := actualPostGoals.toArray
unless ← tacticStatesEqualUpToIds preMCtx expectedPostMCtx
actualPostState.meta.mctx expectedPostGoals actualPostGoals do
throwError "tactic{indentD tac}\nsucceeded but did not generate expected state. Initial goal:{indentD $ ← fmtGoals step.preState #[step.preGoal]}\nExpected goals:{indentD $ ← fmtGoals step.postState $ step.postGoals.map (·.goal)}\nActual goals:{indentD $ ← fmtGoals actualPostState actualPostGoals}"
where
fmtGoals (state : Meta.SavedState) (goals : Array MVarId) :
MetaM MessageData :=
state.runMetaM' do
addMessageContext $
MessageData.joinSep (← goals.mapM (λ g => return m!"{g}")).toList "\n"
end Step
structure LazyStep where
preState : Meta.SavedState
preGoal : MVarId
/--
A nonempty list of tactic builders. During script generation, Aesop tries to
execute the builders from left to right. It then uses the first builder that
succceds (in the sense that when run in `preState` on `preGoal` it produces
the `postState` and `postGoals`). The last builder must succeed and is used
unconditionally.
-/
tacticBuilders : Array TacticBuilder
tacticBuilders_ne : 0 < tacticBuilders.size := by simp
postState : Meta.SavedState
postGoals : Array MVarId
namespace LazyStep
def runFirstSuccessfulTacticBuilder (s : LazyStep) : MetaM Tactic :=
withConstAesopTraceNode .script (return m!"converting lazy step to step") do
withPPAnalyze do
let initialState ← saveState
for b in s.tacticBuilders[:s.tacticBuilders.size - 1] do
if let some tactic ← tryTacticBuilder b then
return tactic
initialState.restore
have := s.tacticBuilders_ne
let fallback ← s.tacticBuilders[s.tacticBuilders.size - 1]
aesop_trace[script] "fallback: {fallback}"
return fallback
where
tryTacticBuilder (b : TacticBuilder) : MetaM (Option Tactic) := do
let tactic ← b
withAesopTraceNode .script (λ res => return m!"{exceptOptionEmoji res} {tactic}") do
let tacticResult ← observing? do
runTacticCapturingPostState tactic.uTactic s.preState [s.preGoal]
let some (actualPostState, actualPostGoals) := tacticResult
| return none
let actualPostGoals := actualPostGoals.toArray
let some _ ← matchGoals s.postState actualPostState s.postGoals actualPostGoals
| return none
return tactic
def toStep (s : LazyStep) : MetaM Step :=
s.postState.runMetaM' do
return {
s with
tactic := ← runFirstSuccessfulTacticBuilder s
postGoals := ← s.postGoals.mapM GoalWithMVars.ofMVarId
}
structure BuildInput (α) where
tac : MetaM α
postGoals : α → Array MVarId
tacticBuilder : α → TacticBuilder
@[inline, always_inline]
def build (preGoal : MVarId) (i : BuildInput α) : MetaM (LazyStep × α) := do
let preState ← saveState
let a ← i.tac
let postState ← saveState
let step := {
tacticBuilders := #[i.tacticBuilder a]
postGoals := i.postGoals a
preGoal, preState, postState
}
return (step, a)
def erasePostStateAssignments (s : LazyStep) (gs : Array MVarId) : LazyStep :=
{ s with
postState.meta.mctx :=
gs.foldl (init := s.postState.meta.mctx) λ mctx g =>
mctx.eraseExprMVarAssignment g }
end Aesop.Script.LazyStep |
.lake/packages/aesop/Aesop/Script/Main.lean | module
public import Aesop.Script.Check
public import Aesop.Stats.Basic
public import Aesop.Options.Internal
public import Aesop.Util.Basic
import Aesop.Script.OptimizeSyntax
import Aesop.Script.StructureDynamic
import Aesop.Script.StructureStatic
import Batteries.Lean.Meta.SavedState
public section
open Lean
open Lean.Parser.Tactic (tacticSeq)
namespace Aesop.Script
def UScript.optimize (uscript : UScript) (proofHasMVar : Bool)
(preState : Meta.SavedState) (goal : MVarId) :
MetaM (Option (TSyntax ``tacticSeq × ScriptGenerated)) := do
let structureResult? ← do
let opts ← getOptions
if aesop.dev.dynamicStructuring.get opts &&
! (aesop.dev.optimizedDynamicStructuring.get opts && ! proofHasMVar) then
structureDynamic
else
structureStatic
let some (sscript, gen) := structureResult?
| return none
let tacticSeq ← `(tacticSeq| $(← sscript.render):tactic*)
let tacticSeq ← optimizeSyntax tacticSeq
return some (tacticSeq, gen)
where
structureStatic : MetaM (Option (SScript × ScriptGenerated)) := do
let tacticState ← preState.runMetaM' $ TacticState.mkInitial goal
let (sscript, perfect) ← uscript.toSScriptStatic tacticState
let gen :=
.staticallyStructured (perfect := perfect) (hasMVar := proofHasMVar)
pure $ some (sscript, gen)
structureDynamic : MetaM (Option (SScript × ScriptGenerated)) := do
let some (script, perfect) ← uscript.toSScriptDynamic preState goal
| return none
let gen :=
.dynamicallyStructured (perfect := perfect) (hasMVar := proofHasMVar)
return some (script, gen)
end Script
open Script
variable [Monad m] [MonadLog m] [MonadRef m] [MonadError m] [AddMessageContext m]
[MonadStats m] [MonadLiftT MetaM m] in
def checkAndTraceScript (uscript : UScript)
(sscript? : Option (TSyntax ``tacticSeq × ScriptGenerated)) (preState : Meta.SavedState)
(goal : MVarId) (options : Aesop.Options') (expectCompleteProof : Bool)
(tacticName : String) :
m Unit := do
if let some (script, scriptGenerated) := sscript? then
recordScriptGenerated scriptGenerated
if options.traceScript then
addTryThisTacticSeqSuggestion (← getRef) script
checkRenderedScriptIfEnabled script preState goal
(expectCompleteProof := expectCompleteProof)
else
if options.traceScript then
let tacticSeq ← uscript.renderTacticSeq preState goal
addTryThisTacticSeqSuggestion (← getRef) tacticSeq
if ← Check.script.isEnabled then
throwError "{Check.script.name}: structuring the script failed"
else if options.traceScript then
logWarning m!"{tacticName}: structuring the script failed. Reporting unstructured script."
end Aesop |
.lake/packages/aesop/Aesop/Script/UScriptToSScript.lean | module
public import Aesop.Script.UScript
public import Aesop.Script.SScript
public import Batteries.Data.Array.Merge
import Aesop.Tracing
public section
open Lean Lean.Meta
namespace Aesop.Script
inductive StepTree where
| empty
| node (step : Step) (index : Nat) (children : Array StepTree)
deriving Nonempty
namespace StepTree
protected partial def toMessageData? : StepTree → Option MessageData
| empty => none
| node step index children =>
m!"- {index}: {step}{if children.isEmpty then m!"" else indentD $ MessageData.joinSep (children.filterMap (·.toMessageData?) |>.toList) "\n"}"
protected def toMessageData (t : StepTree) : MessageData :=
t.toMessageData?.getD "empty"
end StepTree
instance : ToMessageData StepTree :=
⟨StepTree.toMessageData⟩
partial def UScript.toStepTree (s : UScript) : StepTree := Id.run do
let mut preGoalMap : Std.HashMap MVarId (Nat × Step) := ∅
for h : i in [:s.size] do
preGoalMap := preGoalMap.insert s[i].preGoal (i, s[i])
if h : 0 < s.size then
go preGoalMap s[0].preGoal
else
return .empty
where
go (m : Std.HashMap MVarId (Nat × Step)) (goal : MVarId) : StepTree :=
if let some (i, step) := m[goal]? then
.node step i (step.postGoals.map (go m ·.goal))
else
.empty
def sortDedupArrays [Ord α] (as : Array (Array α)) : Array α :=
let sz := as.foldl (init := 0) (· + ·.size)
let as := as.foldl (init := Array.mkEmpty sz) (· ++ ·)
as.sortDedup
def isConsecutiveSequence (ns : Array Nat) : Bool := Id.run do
if let some hd := ns[0]? then
let mut prev := hd
for n in ns[1:] do
if n != prev + 1 then
return false
prev := n
return true
namespace StepTree
partial def focusableGoals (t : StepTree) : Std.HashMap MVarId Nat :=
runST (λ _ => go t |>.run ∅) |>.2
where
go {σ} : StepTree → StateRefT (Std.HashMap MVarId Nat) (ST σ) (Array Nat)
| .empty => return #[]
| .node step i children => do
let childIndexes := sortDedupArrays $ ← children.mapM go
let indexes :=
(Array.mkEmpty $ childIndexes.size + 1).push i ++ childIndexes
if isConsecutiveSequence indexes then
let lastIndex := childIndexes[childIndexes.size - 1]?.getD i
modify (·.insert step.preGoal lastIndex)
return indexes
partial def numSiblings (t : StepTree) : Std.HashMap MVarId Nat :=
runST (λ _ => go 0 t |>.run ∅) |>.2
where
go {σ} (parentNumGoals : Nat) :
StepTree → StateRefT (Std.HashMap MVarId Nat) (ST σ) Unit
| .empty => return
| .node step _ children => do
modify (·.insert step.preGoal (parentNumGoals - 1))
children.forM (go children.size)
end StepTree
partial def orderedUScriptToSScript (uscript : UScript) (tacticState : TacticState) : CoreM SScript :=
withAesopTraceNode .script (λ e => return m!"{exceptEmoji e} Converting ordered unstructured script to structured script") do
aesop_trace[script] "unstructured script:{indentD $ MessageData.joinSep (uscript.map toMessageData |>.toList) "\n"}"
let stepTree := uscript.toStepTree
aesop_trace[script] "step tree:{indentD $ toMessageData stepTree}"
let focusable := stepTree.focusableGoals
let numSiblings := stepTree.numSiblings
aesop_trace[script] "focusable goals: {focusable.toArray.map λ (mvarId, n) => (mvarId.name, n)}"
(·.fst) <$> go focusable numSiblings 0 (uscript.size - 1) tacticState
where
go (focusable : Std.HashMap MVarId Nat) (numSiblings : Std.HashMap MVarId Nat)
(start stop : Nat) (tacticState : TacticState) :
CoreM (SScript × TacticState) := do
if start > stop then
return (.empty, tacticState)
if let some step := uscript[start]? then
aesop_trace[script] "applying step:{indentD $ toMessageData step}"
let some siblings := numSiblings[step.preGoal]?
| throwError "aesop: internal error while structuring script: unknown sibling count for goal {step.preGoal.name}"
aesop_trace[script] "siblings: {siblings}"
let innerStop? := focusable[step.preGoal]?
aesop_trace[script] "focusable: {innerStop?.isSome}"
aesop_trace[script] "visible goals: {tacticState.visibleGoals.map (·.goal.name)}"
let some goalPos := tacticState.getVisibleGoalIndex? step.preGoal
-- I think his can be `none` if the step is for an mvar that was already
-- assigned by some other step.
| return (.empty, tacticState)
aesop_trace[script] "goal position: {goalPos}"
if innerStop?.isNone || siblings == 0 then
let tacticState ← tacticState.applyStep step
let (tailScript, tacticState) ← go focusable numSiblings (start + 1) stop tacticState
return (.onGoal goalPos step tailScript, tacticState)
else
let innerStop := innerStop?.get!
let (nestedScript, tacticState) ←
tacticState.onGoalM step.preGoal λ tacticState => do
let tacticState ← tacticState.applyStep step
let (tailScript, tacticState) ←
go focusable numSiblings (start + 1) innerStop tacticState
return (.onGoal 0 step tailScript, tacticState)
let (tailScript, tacticState) ←
go focusable numSiblings (innerStop + 1) stop tacticState
let script := .focusAndSolve goalPos nestedScript tailScript
return (script, tacticState)
else
return (.empty, tacticState)
end Aesop.Script |
.lake/packages/aesop/Aesop/Rule/Basic.lean | module
public import Aesop.RuleTac.Descr
public section
open Lean
namespace Aesop
structure Rule (α : Type) where
name : RuleName
indexingMode : IndexingMode
pattern? : Option RulePattern
extra : α
tac : RuleTacDescr
deriving Inhabited
namespace Rule
instance : BEq (Rule α) where
beq r s := r.name == s.name
instance : Ord (Rule α) where
compare r s := compare r.name s.name
instance : Hashable (Rule α) where
hash r := hash r.name
def compareByPriority [Ord α] (r s : Rule α) : Ordering :=
compare r.extra s.extra
def compareByName (r s : Rule α) : Ordering :=
r.name.compare s.name
def compareByPriorityThenName [Ord α] (r s : Rule α) : Ordering :=
compareByPriority r s |>.then $ compareByName r s
@[inline]
protected def map (f : α → β) (r : Rule α) : Rule β :=
{ r with extra := f r.extra }
@[inline]
protected def mapM [Monad m] (f : α → m β) (r : Rule α) : m (Rule β) :=
return { r with extra := ← f r.extra }
end Aesop.Rule |
.lake/packages/aesop/Aesop/Rule/Name.lean | module
public import Lean.Meta.Basic
public section
open Lean
open Lean.Meta
namespace Aesop
inductive PhaseName
| norm
| safe
| «unsafe»
deriving Inhabited, BEq, Hashable
-- NOTE: Constructors should be listed in alphabetical order for the Ord
-- instance.
namespace PhaseName
instance : Ord PhaseName where
compare s₁ s₂ := compare s₁.ctorIdx s₂.ctorIdx
instance : ToString PhaseName where
toString
| norm => "norm"
| safe => "safe"
| «unsafe» => "unsafe"
end PhaseName
inductive ScopeName
| global
| «local»
deriving Inhabited, BEq, Hashable
-- NOTE: Constructors should be listed in alphabetical order for the Ord
-- instance.
namespace ScopeName
instance : Ord ScopeName where
compare s₁ s₂ := compare s₁.ctorIdx s₂.ctorIdx
instance : ToString ScopeName where
toString
| global => "global"
| «local» => "local"
end ScopeName
inductive BuilderName
| apply
| cases
| constructors
| destruct
| forward
| simp
| tactic
| unfold
deriving Inhabited, BEq, Hashable
-- NOTE: Constructors should be listed in alphabetical order for the Ord
-- instance.
namespace BuilderName
instance : Ord BuilderName where
compare b₁ b₂ := compare b₁.ctorIdx b₂.ctorIdx
instance : ToString BuilderName where
toString
| apply => "apply"
| cases => "cases"
| constructors => "constructors"
| destruct => "destruct"
| forward => "forward"
| simp => "simp"
| tactic => "tactic"
| unfold => "unfold"
end BuilderName
-- Rules are identified by a `RuleName` throughout Aesop. We assume that rule
-- names are unique within our 'universe', i.e. within the rule sets that we are
-- working with. All data structures should enforce this invariant.
structure RuleName where
name : Name
builder : BuilderName
phase : PhaseName
scope : ScopeName
protected hash : UInt64 :=
mixHash (hash name) $ mixHash (hash builder) $ mixHash (hash phase)
(hash scope)
deriving Inhabited
namespace RuleName
instance : Hashable RuleName where
hash n := n.hash
instance : BEq RuleName where
beq n₁ n₂ :=
n₁.hash == n₂.hash && n₁.builder == n₂.builder && n₁.phase == n₂.phase &&
n₁.scope == n₂.scope && n₁.name == n₂.name
protected def compare : (_ _ : RuleName) → Ordering :=
compareLex (compareOn (·.builder)) $
compareLex (compareOn (·.phase)) $
compareLex (compareOn (·.scope)) $
(λ n₁ n₂ => n₁.name.cmp n₂.name)
protected def quickCompare (n₁ n₂ : RuleName) : Ordering :=
match compare n₁.hash n₂.hash with
| Ordering.eq => n₁.compare n₂
| ord => ord
instance : Ord RuleName :=
⟨RuleName.compare⟩
instance : ToString RuleName where
toString n :=
toString n.phase ++ "|" ++ toString n.builder ++ "|" ++ toString n.scope ++
"|" ++ toString n.name
end RuleName
def getRuleNameForExpr : Expr → MetaM Name
| .const decl _ => return decl
| .fvar fvarId => return (← fvarId.getDecl).userName
| _ => mkFreshId
inductive DisplayRuleName
| ruleName (n : RuleName)
| normSimp
| normUnfold
deriving Inhabited, BEq, Ord, Hashable
namespace DisplayRuleName
instance : Coe RuleName DisplayRuleName :=
⟨DisplayRuleName.ruleName⟩
instance : ToString DisplayRuleName where
toString
| ruleName n => toString n
| normSimp => "<norm simp>"
| normUnfold => "<norm unfold>"
end Aesop.DisplayRuleName |
.lake/packages/aesop/Aesop/Rule/Forward.lean | module
public import Aesop.Forward.RuleInfo
public import Aesop.Percent
public import Aesop.RuleTac.RuleTerm
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- The priority of a forward rule. -/
inductive ForwardRulePriority : Type where
/-- If the rule is a norm or safe rule, its priority is an integer. -/
| normSafe (n : Int) : ForwardRulePriority
/-- If the rule is an unsafe rule, its priority is a percentage representing
the rule's success probability. -/
| «unsafe» (p : Percent) : ForwardRulePriority
deriving Inhabited, BEq
namespace ForwardRulePriority
/-- If a `ForwardRulePriority` contains a penalty, extract it. -/
def penalty? : ForwardRulePriority → Option Int
| .normSafe n => some n
| .unsafe .. => none
/-- If a `ForwardRulePriority` contains a success probability, extract it. -/
def successProbability? : ForwardRulePriority → Option Percent
| .unsafe p => some p
| .normSafe .. => none
/-- Compare two rule priorities. Less means higher priority ('better').
Norm/safe rules have higher priority than unsafe rules. Among norm/safe rules,
lower penalty is better. Among unsafe rules, higher percentage is better. -/
protected def compare : (p₁ p₂ : ForwardRulePriority) → Ordering
| .normSafe .., .unsafe .. => .lt
| .unsafe .., .normSafe .. => .gt
| .normSafe n₁, .normSafe n₂ => compare n₁ n₂
| .unsafe p₁, .unsafe p₂ => compare p₁ p₂ |>.swap
instance : Ord ForwardRulePriority :=
⟨ForwardRulePriority.compare⟩
instance : ToString ForwardRulePriority where
toString
| .normSafe n => toString n
| .unsafe p => p.toHumanString
end ForwardRulePriority
/-- A forward rule. -/
structure ForwardRule extends ForwardRuleInfo where
/-- The rule's name. Should be unique among all rules in a rule set. -/
name : RuleName
/-- The theorem from which this rule is derived. -/
term : RuleTerm
/-- The rule's priority. -/
prio : ForwardRulePriority
deriving Inhabited
namespace ForwardRule
instance : BEq ForwardRule :=
⟨λ r₁ r₂ => r₁.name == r₂.name⟩
instance : Hashable ForwardRule :=
⟨λ r => hash r.name⟩
instance : Ord ForwardRule :=
⟨λ r₁ r₂ => compare r₁.prio r₂.prio |>.then (compare r₁.name r₂.name)⟩
instance : ToString ForwardRule where
toString r := s!"[{r.prio}] {r.name}"
/-- Is this rule a `destruct` rule (i.e., should we clear matched hyps)? -/
def destruct (r : ForwardRule) : Bool :=
r.name.builder matches .destruct
end Aesop.ForwardRule |
.lake/packages/aesop/Aesop/Search/SearchM.lean | module
public import Aesop.Search.Queue.Class
public import Aesop.Tree.TreeM
public import Lean.Meta.Tactic.Simp.Simproc
public section
open Lean
open Lean.Meta
namespace Aesop
structure NormSimpContext where
toContext : Simp.Context
enabled : Bool
useHyps : Bool
configStx? : Option Term
simprocs : Simp.SimprocsArray
deriving Inhabited
namespace SearchM
structure Context where
ruleSet : LocalRuleSet
normSimpContext : NormSimpContext
options : Aesop.Options'
deriving Nonempty
structure State (Q) [Aesop.Queue Q] where
iteration : Iteration
queue : Q
maxRuleApplicationDepthReached : Bool
deriving Inhabited
end SearchM
abbrev SearchM Q [Aesop.Queue Q] :=
ReaderT SearchM.Context $ StateRefT (SearchM.State Q) $
StateRefT TreeM.State BaseM
variable [Aesop.Queue Q]
namespace SearchM
-- Generate specialized pure/bind implementations so we don't need to optimise
-- them on the fly at each use site.
instance : Monad (SearchM Q) :=
{ inferInstanceAs (Monad (SearchM Q)) with }
instance : MonadRef (SearchM Q) :=
{ inferInstanceAs (MonadRef (SearchM Q)) with }
instance : Inhabited (SearchM Q α) where
default := failure
instance : MonadState (State Q) (SearchM Q) :=
{ inferInstanceAs (MonadStateOf (State Q) (SearchM Q)) with }
instance : MonadReader Context (SearchM Q) :=
{ inferInstanceAs (MonadReaderOf Context (SearchM Q)) with }
instance : MonadLift TreeM (SearchM Q) where
monadLift x := do
let ctx := {
currentIteration := (← get).iteration
ruleSet := (← read).ruleSet
}
liftM $ ReaderT.run x ctx
protected def run' (ctx : SearchM.Context) (σ : SearchM.State Q) (tree : Tree)
(x : SearchM Q α) : BaseM (α × SearchM.State Q × Tree) := do
let ((a, σ), t) ←
x.run ctx |>.run σ |>.run { tree }
return (a, σ, t.tree)
protected def run (ruleSet : LocalRuleSet) (options : Aesop.Options')
(simpConfig : Simp.Config) (simpConfigStx? : Option Term)
(goal : MVarId) (x : SearchM Q α) : BaseM (α × State Q × Tree) := do
let t ← mkInitialTree goal ruleSet
let normSimpContext := {
toContext := ← Simp.mkContext simpConfig (simpTheorems := ruleSet.simpTheoremsArray.map (·.snd))
(congrTheorems := ← getSimpCongrTheorems)
simprocs := ruleSet.simprocsArray.map (·.snd)
configStx? := simpConfigStx?
enabled := options.enableSimp
useHyps := options.useSimpAll
}
let ctx := { ruleSet, options, normSimpContext }
let #[rootGoal] := (← t.root.get).goals
| throwError "aesop: internal error: root mvar cluster does not contain exactly one goal."
let state := {
queue := ← Queue.init' #[rootGoal]
iteration := Iteration.one
maxRuleApplicationDepthReached := false
}
x.run' ctx state t
end SearchM
def getTree : SearchM Q Tree :=
getThe Tree
def setTree : Tree → SearchM Q Unit :=
setThe Tree
def modifyTree : (Tree → Tree) → SearchM Q Unit :=
modifyThe Tree
def getIteration : SearchM Q Iteration :=
return (← get).iteration
def incrementIteration : SearchM Q Unit :=
modify λ s => { s with iteration := s.iteration.succ }
def popGoal? : SearchM Q (Option GoalRef) := do
let s ← get
let (goal?, queue) ← Queue.popGoal s.queue
set { s with queue }
return goal?
def enqueueGoals (gs : Array GoalRef) : SearchM Q Unit := do
let s ← get
let queue ← Queue.addGoals s.queue gs
set { s with queue }
def setMaxRuleApplicationDepthReached : SearchM Q Unit :=
modify λ s => { s with maxRuleApplicationDepthReached := true }
def wasMaxRuleApplicationDepthReached : SearchM Q Bool :=
return (← get).maxRuleApplicationDepthReached
end Aesop |
.lake/packages/aesop/Aesop/Search/Queue.lean | module
public import Aesop.Search.Queue.Class
public import Batteries.Data.BinomialHeap.Basic
public section
open Lean
open Batteries (BinomialHeap)
namespace Aesop.BestFirstQueue
structure ActiveGoal where
goal : GoalRef
priority : Percent
lastExpandedInIteration : Iteration
-- Iteration of the search loop when this goal was last expanded (counting
-- from 1), or 0 if the goal was never expanded.
addedInIteration : Iteration
-- Iteration of the search loop when this goal was added. 0 for the root
-- goal.
namespace ActiveGoal
-- We prioritise active goals lexicographically by the following criteria:
--
-- 1. Goals with higher priority have priority.
-- 2. Goals which were last expanded in an earlier iteration have priority.
-- 3. Goals which were added in an earlier iteration have priority.
--
-- The last two criteria ensure a very weak form of fairness: if a search
-- produces infinitely many goals with the same success probability, each of
-- them will be expanded infinitely often.
--
-- Note that since we use a min-queue, `le x y` means `x` has priority over `y`.
protected def le (g h : ActiveGoal) : Bool :=
g.priority > h.priority ||
(g.priority == h.priority &&
(g.lastExpandedInIteration ≤ h.lastExpandedInIteration ||
(g.lastExpandedInIteration == h.lastExpandedInIteration &&
g.addedInIteration ≤ h.addedInIteration)))
protected def ofGoalRef (gref : GoalRef) : BaseIO ActiveGoal := do
let g ← gref.get
return {
goal := gref
priority := g.priority
lastExpandedInIteration := g.lastExpandedInIteration
addedInIteration := g.addedInIteration
}
end BestFirstQueue.ActiveGoal
@[expose] def BestFirstQueue :=
BinomialHeap BestFirstQueue.ActiveGoal BestFirstQueue.ActiveGoal.le
namespace BestFirstQueue
protected def init : BestFirstQueue :=
BinomialHeap.empty
protected def addGoals (q : BestFirstQueue) (grefs : Array GoalRef) :
BaseIO BestFirstQueue :=
grefs.foldlM (init := q) λ q gref =>
return q.insert (← ActiveGoal.ofGoalRef gref)
protected def popGoal (q : BestFirstQueue) : Option GoalRef × BestFirstQueue :=
match q.deleteMin with
| none => (none, q)
| some (ag, q) => (some ag.goal, q)
end BestFirstQueue
instance : Queue BestFirstQueue where
init := return BestFirstQueue.init
addGoals := BestFirstQueue.addGoals
popGoal q := return BestFirstQueue.popGoal q
structure LIFOQueue where
goals : Array GoalRef
namespace LIFOQueue
protected def init : LIFOQueue :=
⟨#[]⟩
protected def addGoals (q : LIFOQueue) (grefs : Array GoalRef) : LIFOQueue :=
⟨q.goals ++ grefs.reverse⟩
protected def popGoal (q : LIFOQueue) : Option GoalRef × LIFOQueue :=
match q.goals.back? with
| some g => (some g, ⟨q.goals.pop⟩)
| none => (none, q)
instance : Queue LIFOQueue where
init := return .init
addGoals q grefs := return q.addGoals grefs
popGoal q := return q.popGoal
end LIFOQueue
structure FIFOQueue where
goals : Array GoalRef
pos : Nat
namespace FIFOQueue
protected def init : FIFOQueue :=
⟨#[], 0⟩
protected def addGoals (q : FIFOQueue) (grefs : Array GoalRef) : FIFOQueue :=
{ q with goals := q.goals ++ grefs }
protected def popGoal (q : FIFOQueue) : Option GoalRef × FIFOQueue :=
if h : q.pos < q.goals.size then
(some q.goals[q.pos], { q with pos := q.pos + 1 })
else
(none, q)
instance : Queue FIFOQueue where
init := return .init
addGoals q grefs := return q.addGoals grefs
popGoal q := return q.popGoal
end FIFOQueue
def Options.queue (opts : Aesop.Options) : Σ Q, Queue Q :=
match opts.strategy with
| .bestFirst => ⟨BestFirstQueue, inferInstance⟩
| .depthFirst => ⟨LIFOQueue, inferInstance⟩
| .breadthFirst => ⟨FIFOQueue, inferInstance⟩
end Aesop |
.lake/packages/aesop/Aesop/Search/Expansion.lean | module
public import Aesop.Search.Expansion.Norm
public import Aesop.Tree.AddRapp
public import Aesop.RuleTac
public import Aesop.Search.RuleSelection
public import Batteries.Data.Array.Basic
import Aesop.Search.Expansion.Basic
public section
open Lean
open Lean.Meta
namespace Aesop
variable [Aesop.Queue Q]
inductive RuleResult
| proved (newRapps : Array RappRef)
| succeeded (newRapps : Array RappRef)
| failed
namespace RuleResult
def toEmoji : RuleResult → String
| proved .. => ruleProvedEmoji
| succeeded .. => ruleSuccessEmoji
| failed => ruleFailureEmoji
def isSuccessful
| proved .. | succeeded .. => true
| failed => false
end RuleResult
inductive SafeRuleResult
| regular (result : RuleResult)
| postponed (result : PostponedSafeRule)
namespace SafeRuleResult
def toEmoji : SafeRuleResult → String
| regular r => r.toEmoji
| postponed .. => rulePostponedEmoji
def isSuccessfulOrPostponed
| regular r => r.isSuccessful
| postponed .. => true
end SafeRuleResult
def runRegularRuleTac (goal : Goal) (tac : RuleTac) (ruleName : RuleName)
(indexMatchLocations : Array IndexMatchLocation)
(patternSubsts? : Option (Array Substitution))
(options : Options') (hypTypes : PHashSet RPINF) :
BaseM (Except Exception RuleTacOutput) := do
let some (postNormGoal, postNormState) := goal.postNormGoalAndMetaState? | throwError
"aesop: internal error during expansion: expected goal {goal.id} to be normalised (but not proven by normalisation)."
let input := {
goal := postNormGoal
mvars := goal.mvars
hypTypes, indexMatchLocations, patternSubsts?, options
}
runRuleTac tac ruleName postNormState input
def addRapps (parentRef : GoalRef) (rule : RegularRule)
(rapps : Array RuleApplication) : SearchM Q RuleResult := do
let parent ← parentRef.get
let mut rrefs := Array.mkEmpty rapps.size
let mut subgoals := Array.mkEmpty $ rapps.size * 3
for h : i in [:rapps.size] do
let rapp := rapps[i]
let successProbability :=
parent.successProbability *
(rapp.successProbability?.getD rule.successProbability)
let rref ← addRapp {
rapp with
parent := parentRef
appliedRule := rule
successProbability }
rrefs := rrefs.push rref
for cref in (← rref.get).children do
for gref in (← cref.get).goals do
subgoals := subgoals.push gref
enqueueGoals subgoals
rrefs.forM (·.markProven)
-- `markProven` is a no-op if the rapp is not, in fact, proven. We must
-- perform this computation after all rapps have been added to ensure
-- that if one is proven, the others are all marked as irrelevant.
let provenRref? ← rrefs.findM? λ rref => return (← rref.get).state.isProven
if let (some _) := provenRref? then
return .proved rrefs
else
return .succeeded rrefs
private def addRuleFailure (rule : RegularRule) (parentRef : GoalRef) :
SearchM Q Unit := do
parentRef.modify λ g => g.setFailedRapps $ g.failedRapps.push rule
@[inline, always_inline]
def withRuleTraceNode (ruleName : RuleName)
(toEmoji : α → String) (suffix : String) (k : SearchM Q α) : SearchM Q α :=
withAesopTraceNode .steps fmt k
where
fmt (result : Except Exception α) : SearchM Q MessageData := do
let emoji := exceptRuleResultToEmoji toEmoji result
return m!"{emoji} {ruleName}{suffix}"
def runRegularRuleCore (parentRef : GoalRef) (rule : RegularRule)
(indexMatchLocations : Array IndexMatchLocation)
(patternSubsts? : Option (Array Substitution)) :
SearchM Q (Option RuleTacOutput) := do
let parent ← parentRef.get
let ruleOutput? ←
runRegularRuleTac parent rule.tac.run rule.name indexMatchLocations
patternSubsts? (← read).options parent.forwardState.hypTypes
match ruleOutput? with
| .error exc =>
aesop_trace[steps] exc.toMessageData
return none
| .ok { applications := #[], .. } =>
aesop_trace[steps] "Rule returned no rule applications"
return none
| .ok output =>
return some output
def runSafeRule (parentRef : GoalRef) (matchResult : IndexMatchResult SafeRule) :
SearchM Q SafeRuleResult := do
profilingRule (.ruleName matchResult.rule.name) (·.isSuccessfulOrPostponed) do
let rule := matchResult.rule
withRuleTraceNode rule.name (·.toEmoji) "" do
let some output ←
runRegularRuleCore parentRef (.safe matchResult.rule)
matchResult.locations matchResult.patternSubsts?
| do addRuleFailure (.safe rule) parentRef; return .regular .failed
let parentMVars := (← parentRef.get).mvars
let rapps := output.applications
if rapps.size != 1 then
aesop_trace[steps] "Safe rule did not produce exactly one rule application"
addRuleFailure (.safe rule) parentRef
return .regular .failed
let anyParentMVarAssigned ← rapps.anyM λ rapp => do
rapp.postState.runMetaM' do
parentMVars.anyM (·.isAssignedOrDelayedAssigned)
if anyParentMVarAssigned then
aesop_trace[steps] "Safe rule assigned metavariables, so we postpone it"
return .postponed ⟨rule, output⟩
else
return .regular (← addRapps parentRef (.safe rule) rapps)
def runUnsafeRule (parentRef : GoalRef)
(matchResult : IndexMatchResult UnsafeRule) : SearchM Q RuleResult := do
let rule := matchResult.rule
profilingRule (.ruleName rule.name) (·.isSuccessful) do
withRuleTraceNode rule.name (·.toEmoji) "" do
let some output ←
runRegularRuleCore parentRef (.unsafe rule) matchResult.locations
matchResult.patternSubsts?
| do addRuleFailure (.unsafe rule) parentRef; return .failed
addRapps parentRef (.unsafe rule) output.applications
inductive SafeRulesResult
| proved (newRapps : Array RappRef)
| succeeded (newRapps : Array RappRef)
| failed (postponed : Array PostponedSafeRule)
| skipped
def SafeRulesResult.toEmoji : SafeRulesResult → String
| proved .. => ruleProvedEmoji
| succeeded .. => ruleSuccessEmoji
| failed .. => ruleFailureEmoji
| skipped => ruleSkippedEmoji
def runFirstSafeRule (gref : GoalRef) : SearchM Q SafeRulesResult := do
let g ← gref.get
if g.unsafeRulesSelected then
return .skipped
-- If the unsafe rules have been selected, we have already tried all the
-- safe rules.
let rules ← selectSafeRules g
let mut postponedRules := {}
for r in rules do
let result ← runSafeRule gref r
match result with
| .regular .failed => continue
| .regular (.proved newRapps) => return .proved newRapps
| .regular (.succeeded newRapps) => return .succeeded newRapps
| .postponed r =>
postponedRules := postponedRules.push r
return .failed postponedRules
def applyPostponedSafeRule (r : PostponedSafeRule) (parentRef : GoalRef) :
SearchM Q RuleResult := do
withRuleTraceNode r.rule.name (·.toEmoji) " (postponed)" do
addRapps parentRef (.unsafe r.toUnsafeRule) r.output.applications
partial def runFirstUnsafeRule (postponedSafeRules : Array PostponedSafeRule)
(parentRef : GoalRef) : SearchM Q RuleResult := do
let queue ← selectUnsafeRules postponedSafeRules parentRef
let (remainingQueue, result) ← loop queue
parentRef.modify λ g => g.setUnsafeQueue remainingQueue
if remainingQueue.isEmpty then
let parent ← parentRef.get
if ← pure (! parent.state.isProven) <&&> parent.isUnprovableNoCache then
parentRef.markUnprovable
return result
where
loop (queue : UnsafeQueue) : SearchM Q (UnsafeQueue × RuleResult) := do
let (some (r, queue)) := Subarray.popHead? queue
| return (queue, RuleResult.failed)
match r with
| .unsafeRule r =>
let result ← runUnsafeRule parentRef r
match result with
| .proved .. => return (queue, result)
| .succeeded .. => return (queue, result)
| .failed => loop queue
| .postponedSafeRule r =>
return (queue, ← applyPostponedSafeRule r parentRef)
def expandGoal (gref : GoalRef) : SearchM Q RuleResult := do
let provedByNorm ←
withAesopTraceNode .steps fmtNorm (normalizeGoalIfNecessary gref)
aesop_trace[steps] do
unless provedByNorm do
let (goal, metaState) ←
(← gref.get).currentGoalAndMetaState (← getRootMetaState)
metaState.runMetaM' do
aesop_trace![steps] "Goal after normalisation:{indentD goal}"
if provedByNorm then
return .proved #[]
let safeResult ←
withAesopTraceNode .steps fmtSafe (runFirstSafeRule gref)
match safeResult with
| .succeeded newRapps => return .succeeded newRapps
| .proved newRapps => return .proved newRapps
| .failed postponedSafeRules => doUnsafe postponedSafeRules
| .skipped => doUnsafe #[]
where
doUnsafe (postponedSafeRules : Array PostponedSafeRule) :
SearchM Q RuleResult := do
withAesopTraceNode .steps fmtUnsafe do
runFirstUnsafeRule postponedSafeRules gref
fmtNorm (result : Except Exception Bool) : SearchM Q MessageData :=
let emoji :=
match result with
| .error _ => ruleErrorEmoji
| .ok true => ruleProvedEmoji
| .ok false => ruleSuccessEmoji
return m!"{emoji} Normalisation"
fmtSafe (result : Except Exception SafeRulesResult) :
SearchM Q MessageData :=
return m!"{exceptRuleResultToEmoji (·.toEmoji) result} Safe rules"
fmtUnsafe (result : Except Exception RuleResult) : SearchM Q MessageData :=
return m!"{exceptRuleResultToEmoji (·.toEmoji) result} Unsafe rules"
end Aesop |
.lake/packages/aesop/Aesop/Search/RuleSelection.lean | module
public import Aesop.Tree.RunMetaM
public import Aesop.Search.SearchM
public section
open Lean
namespace Aesop
variable [Aesop.Queue Q]
def selectNormRules (rs : LocalRuleSet) (fms : ForwardRuleMatches)
(goal : MVarId) : BaseM (Array (IndexMatchResult NormRule)) :=
profilingRuleSelection do rs.applicableNormalizationRules fms goal
def preprocessRule : SafeRule where
name := {
name := `Aesop.BuiltinRule.preprocess
builder := .tactic
phase := .safe
scope := .global
}
indexingMode := .unindexed
pattern? := none
extra := { penalty := 0, safety := .safe }
tac := .preprocess
def selectSafeRules (g : Goal) :
SearchM Q (Array (IndexMatchResult SafeRule)) := do
profilingRuleSelection do
if ← g.isRoot then
return #[{
rule := preprocessRule
locations := ∅
patternSubsts? := none
}]
let ruleSet := (← read).ruleSet
g.runMetaMInPostNormState' λ postNormGoal =>
ruleSet.applicableSafeRules g.forwardRuleMatches postNormGoal
def selectUnsafeRules (postponedSafeRules : Array PostponedSafeRule)
(gref : GoalRef) : SearchM Q UnsafeQueue := do
profilingRuleSelection do
let g ← gref.get
match g.unsafeQueue? with
| some rules => return rules
| none => do
let ruleSet := (← read).ruleSet
let unsafeRules ←
g.runMetaMInPostNormState' λ postNormGoal =>
ruleSet.applicableUnsafeRules g.forwardRuleMatches postNormGoal
let unsafeQueue := UnsafeQueue.initial postponedSafeRules unsafeRules
gref.set $ g.setUnsafeRulesSelected true |>.setUnsafeQueue unsafeQueue
return unsafeQueue
end Aesop |
.lake/packages/aesop/Aesop/Search/Main.lean | module
public import Aesop.Script.Main
public import Aesop.Search.ExpandSafePrefix
public import Aesop.Tree.Check
public import Aesop.Tree.ExtractProof
public import Aesop.Tree.ExtractScript
public import Aesop.Tree.Tracing
import Aesop.Frontend.Extension
import Aesop.Search.Queue
import Aesop.Tree.Free
public section
open Lean
open Lean.Elab.Tactic (liftMetaTacticAux TacticM)
open Lean.Parser.Tactic (tacticSeq)
open Lean.Meta
namespace Aesop
variable [Aesop.Queue Q]
partial def nextActiveGoal : SearchM Q GoalRef := do
let some gref ← popGoal?
| throwError "aesop/expandNextGoal: internal error: no active goals left"
if ! (← (← gref.get).isActive) then
nextActiveGoal
else
return gref
def expandNextGoal : SearchM Q Unit := do
let gref ← nextActiveGoal
let g ← gref.get
let (initialGoal, initialMetaState) ←
g.currentGoalAndMetaState (← getRootMetaState)
let result ← withAesopTraceNode .steps
(fmt g.id g.priority initialGoal initialMetaState) do
initialMetaState.runMetaM' do
aesop_trace[steps] "Initial goal:{indentD initialGoal}"
let maxRappDepth := (← read).options.maxRuleApplicationDepth
if maxRappDepth != 0 && (← gref.get).depth >= maxRappDepth then
aesop_trace[steps] "Treating the goal as unprovable since it is beyond the maximum rule application depth ({maxRappDepth})."
gref.markForcedUnprovable
setMaxRuleApplicationDepthReached
return .failed
let result ← expandGoal gref
let currentIteration ← getIteration
gref.modify λ g => g.setLastExpandedInIteration currentIteration
if ← (← gref.get).isActive then
enqueueGoals #[gref]
return result
match result with
| .proved newRapps | .succeeded newRapps => traceNewRapps newRapps
| .failed => return
where
fmt (id : GoalId) (priority : Percent) (initialGoal : MVarId)
(initialMetaState : Meta.SavedState)
(result : Except Exception RuleResult) : SearchM Q MessageData := do
let tgt ← initialMetaState.runMetaM' do
initialGoal.withContext do
addMessageContext $ toMessageData (← initialGoal.getType)
return m!"{exceptRuleResultToEmoji (·.toEmoji) result} (G{id}) [{priority.toHumanString}] ⋯ ⊢ {tgt}"
traceNewRapps (newRapps : Array RappRef) : SearchM Q Unit := do
aesop_trace[steps] do
for rref in newRapps do
let r ← rref.get
r.withHeadlineTraceNode .steps
(transform := λ msg => return m!"{newNodeEmoji} " ++ msg) do
withAesopTraceNode .steps (λ _ => return "Metadata") do
r.traceMetadata .steps
r.metaState.runMetaM' do
r.forSubgoalsM λ gref => do
let g ← gref.get
g.withHeadlineTraceNode .steps
(transform := λ msg => return m!"{newNodeEmoji} " ++ msg) do
aesop_trace![steps] g.preNormGoal
withAesopTraceNode .steps (λ _ => return "Metadata") do
g.traceMetadata .steps
def checkGoalLimit : SearchM Q (Option MessageData) := do
let maxGoals := (← read).options.maxGoals
let currentGoals := (← getTree).numGoals
if maxGoals != 0 && currentGoals >= maxGoals then
return m!"maximum number of goals ({maxGoals}) reached. Set the 'maxGoals' option to increase the limit."
return none
def checkRappLimit : SearchM Q (Option MessageData) := do
let maxRapps := (← read).options.maxRuleApplications
let currentRapps := (← getTree).numRapps
if maxRapps != 0 && currentRapps >= maxRapps then
return m!"maximum number of rule applications ({maxRapps}) reached. Set the 'maxRuleApplications' option to increase the limit."
return none
def checkRootUnprovable : SearchM Q (Option MessageData) := do
let root := (← getTree).root
if (← root.get).state.isUnprovable then
let msg ←
if ← wasMaxRuleApplicationDepthReached then
pure m!"failed to prove the goal. Some goals were not explored because the maximum rule application depth ({(← read).options.maxRuleApplicationDepth}) was reached. Set option 'maxRuleApplicationDepth' to increase the limit."
else
pure m!"failed to prove the goal after exhaustive search."
return msg
return none
def getProof? : SearchM Q (Option Expr) := do
getExprMVarAssignment? (← getRootMVarId)
def finalizeProof : SearchM Q Unit := do
(← getRootMVarId).withContext do
extractProof
let (some proof) ← getProof? | throwError
"aesop: internal error: root goal is proven but its metavariable is not assigned"
if (← instantiateMVars proof).hasExprMVar then
let inner :=
m!"Proof: {proof}\nUnassigned metavariables: {(← getMVarsNoDelayed proof).map (·.name)}"
throwError "aesop: internal error: extracted proof has metavariables.{indentD inner}"
withPPAnalyze do
aesop_trace[proof] "Final proof:{indentExpr proof}"
def traceScript (completeProof : Bool) : SearchM Q Unit :=
profiling (λ stats _ elapsed => { stats with script := elapsed }) do
let options := (← read).options
if ! options.generateScript then
return
let (uscript, proofHasMVars) ←
if completeProof then extractScript else extractSafePrefixScript
uscript.checkIfEnabled
let rootGoal ← getRootMVarId
let rootState ← getRootMetaState
aesop_trace[script] "Unstructured script:{indentD $ toMessageData $ ← uscript.renderTacticSeq rootState rootGoal}"
let sscript? ← uscript.optimize proofHasMVars rootState rootGoal
checkAndTraceScript uscript sscript? rootState rootGoal options
(expectCompleteProof := completeProof) "aesop"
def traceTree : SearchM Q Unit := do
(← (← getRootGoal).get).traceTree .tree
def finishIfProven : SearchM Q Bool := do
unless (← (← getRootMVarCluster).get).state.isProven do
return false
finalizeProof
traceScript (completeProof := true)
traceTree
return true
-- TODO move to Tree directory
/--
This function detects whether the search has made progress, meaning that the
remaining goals after safe prefix expansion are different from the initial goal.
We approximate this by checking whether, after safe prefix expansion, either
of the following statements is true.
- There is a safe rapp.
- A subgoal of the preprocessing rule has been modified during normalisation.
This is an approximation because a safe rule could, in principle, leave the
initial goal unchanged.
-/
def treeHasProgress : TreeM Bool := do
let resultRef ← IO.mkRef false
preTraverseDown
(λ gref => do
let g ← gref.get
if let some postGoal := g.normalizationState.normalizedGoal? then
if postGoal != g.preNormGoal then
resultRef.set true
return false
return true)
(λ rref => do
let rule := (← rref.get).appliedRule
if rule.name == preprocessRule.name then
return true
else if rule.isUnsafe then
return false
else
resultRef.set true
return false)
(λ _ => return true)
(.mvarCluster (← getThe Tree).root)
resultRef.get
def throwAesopEx (mvarId : MVarId) (remainingSafeGoals : Array MVarId)
(safePrefixExpansionSuccess : Bool) (msg? : Option MessageData) :
SearchM Q α := do
if aesop.smallErrorMessages.get (← getOptions) then
match msg? with
| none => throwError "tactic 'aesop' failed"
| some msg => throwError "tactic 'aesop' failed, {msg}"
else
let maxRapps := (← read).options.maxSafePrefixRuleApplications
let suffix :=
if remainingSafeGoals.isEmpty then
m!""
else
let gs := .joinSep (remainingSafeGoals.toList.map toMessageData) "\n\n"
let suffix' :=
if safePrefixExpansionSuccess then
m!""
else
m!"\nThe safe prefix was not fully expanded because the maximum number of rule applications ({maxRapps}) was reached."
m!"\nRemaining goals after safe rules:{indentD gs}{suffix'}"
-- Copy-pasta from `Lean.Meta.throwTacticEx`
match msg? with
| none => throwError "tactic 'aesop' failed\nInitial goal:{indentD mvarId}{suffix}"
| some msg => throwError "tactic 'aesop' failed, {msg}\nInitial goal:{indentD mvarId}{suffix}"
-- When we hit a non-fatal error (i.e. the search terminates without a proof
-- because the root goal is unprovable or because we hit a search limit), we
-- usually:
--
-- - Expand all safe rules as much as possible, starting from the root node,
-- until we hit an unsafe rule. We call this the safe prefix.
-- - Extract the proof term for the safe prefix and report the remaining goals.
--
-- The first step is necessary because a goal can become unprovable due to a
-- sibling being unprovable, without the goal ever being expanded. So if we did
-- not expand the safe rules after the fact, the tactic's output would be
-- sensitive to minor changes in, e.g., rule priority.
def handleNonfatalError (err : MessageData) : SearchM Q (Array MVarId) := do
let safeExpansionSuccess ← expandSafePrefix
let safeGoals ← extractSafePrefix
aesop_trace[proof] do
match ← getProof? with
| some proof =>
(← getRootMVarId).withContext do
aesop_trace![proof] "{proof}"
| none => aesop_trace![proof] "<no proof>"
traceTree
traceScript (completeProof := false)
let opts := (← read).options
if opts.terminal then
throwAesopEx (← getRootMVarId) safeGoals safeExpansionSuccess err
if ! (← treeHasProgress) then
throwAesopEx (← getRootMVarId) #[] safeExpansionSuccess "made no progress"
if opts.warnOnNonterminal && aesop.warn.nonterminal.get (← getOptions) then
logWarning m!"aesop: {err}"
if ! safeExpansionSuccess then
logWarning m!"aesop: safe prefix was not fully expanded because the maximum number of rule applications ({(← read).options.maxSafePrefixRuleApplications}) was reached."
safeGoals.mapM (clearForwardImplDetailHyps ·)
partial def searchLoop : SearchM Q (Array MVarId) :=
withIncRecDepth do
checkSystem "aesop"
if let (some err) ← checkRootUnprovable then
handleNonfatalError err
else if ← finishIfProven then
return #[]
else if let (some err) ← checkGoalLimit then
handleNonfatalError err
else if let (some err) ← checkRappLimit then
handleNonfatalError err
else
expandNextGoal
checkInvariantsIfEnabled
incrementIteration
searchLoop
def search (goal : MVarId) (ruleSet? : Option LocalRuleSet := none)
(options : Aesop.Options := {}) (simpConfig : Simp.Config := {})
(simpConfigSyntax? : Option Term := none) (stats : Stats := {}) :
MetaM (Array MVarId × Stats) := do
goal.checkNotAssigned `aesop
let options ← options.toOptions'
let ruleSet ←
match ruleSet? with
| none =>
let rss ← Frontend.getDefaultGlobalRuleSets
mkLocalRuleSet rss options
| some ruleSet => pure ruleSet
let ⟨Q, _⟩ := options.queue
let go : SearchM _ _ := do
show SearchM Q _ from
try searchLoop
finally freeTree
let ((goals, _, _), stats) ←
go.run ruleSet options simpConfig simpConfigSyntax? goal |>.run stats
return (goals, stats)
end Aesop |
.lake/packages/aesop/Aesop/Search/ExpandSafePrefix.lean | module
public import Aesop.Search.Expansion
import Aesop.Exception
public section
open Lean Lean.Meta
namespace Aesop
declare_aesop_exception
safeExpansionFailedException safeExpansionFailedExceptionId
isSafeExpansionFailedException
structure SafeExpansionM.State where
numRapps : Nat := 0
abbrev SafeExpansionM Q [Queue Q] := StateRefT SafeExpansionM.State (SearchM Q)
variable [Queue Q]
private def Goal.isSafeExpanded (g : Goal) : BaseIO Bool :=
(pure g.unsafeRulesSelected) <||> g.hasSafeRapp
-- Typeclass inference struggles with inferring Q, so we have to lift
-- explicitly.
private def liftSearchM (x : SearchM Q α) : SafeExpansionM Q α :=
x
mutual
private partial def expandSafePrefixGoal (gref : GoalRef) :
SafeExpansionM Q Unit := do
let g ← gref.get
if g.state.isProven then
aesop_trace[steps] "Skipping safe rule expansion of goal {g.id} since it is already proven."
return
if ! (← g.isSafeExpanded) then
aesop_trace[steps] "Applying safe rules to goal {g.id}."
if ← liftSearchM $ normalizeGoalIfNecessary gref then
-- Goal was already proved by normalisation.
return
let maxRapps := (← read).options.maxSafePrefixRuleApplications
if maxRapps > 0 && (← getThe SafeExpansionM.State).numRapps > maxRapps then
throw safeExpansionFailedException
discard $ liftSearchM $ runFirstSafeRule gref
modifyThe SafeExpansionM.State λ s =>
{ s with numRapps := s.numRapps + 1 }
else
aesop_trace[steps] "Skipping safe rule expansion of goal {g.id} since safe rules have already been applied."
let g ← gref.get
if g.state.isProven then
return
let safeRapps ← g.safeRapps
if h₁ : 0 < safeRapps.size then
if safeRapps.size > 1 then
throwError "aesop: internal error: goal {g.id} has multiple safe rapps"
expandFirstPrefixRapp safeRapps[0]
private partial def expandFirstPrefixRapp (rref : RappRef) :
SafeExpansionM Q Unit := do
(← rref.get).children.forM expandSafePrefixMVarCluster
private partial def expandSafePrefixMVarCluster (cref : MVarClusterRef) :
SafeExpansionM Q Unit := do
(← cref.get).goals.forM expandSafePrefixGoal
end
def expandSafePrefix : SearchM Q Bool := do
aesop_trace[steps] "Expanding safe subtree of the root goal."
try
expandSafePrefixGoal (← getRootGoal) |>.run' {}
return true
catch e =>
if isSafeExpansionFailedException e then
return false
else
throw e
end Aesop |
.lake/packages/aesop/Aesop/Search/Expansion/Norm.lean | module
public import Aesop.Tree.State
public import Aesop.Search.SearchM
public import Aesop.Tree.RunMetaM
public import Batteries.Lean.Meta.SavedState
import Aesop.RuleTac
import Aesop.RuleTac.ElabRuleTerm
import Aesop.Script.SpecificTactics
import Aesop.Search.RuleSelection
import Batteries.Lean.HashSet
import Aesop.Forward.State.ApplyGoalDiff
import Aesop.Search.Expansion.Basic
import Aesop.Search.Expansion.Simp
public section
open Lean Lean.Meta Aesop.Script
namespace Aesop
namespace NormM
structure Context where
options : Options'
ruleSet : LocalRuleSet
normSimpContext : NormSimpContext
structure State where
forwardState : ForwardState
forwardRuleMatches : ForwardRuleMatches
deriving Inhabited
end NormM
abbrev NormM := ReaderT NormM.Context $ StateRefT NormM.State BaseM
def getForwardState : NormM ForwardState :=
return (← getThe NormM.State).forwardState
def getResetForwardState : NormM ForwardState := do
modifyGetThe NormM.State λ s => (s.forwardState, { s with forwardState := ∅ })
def updateForwardState (fs : ForwardState) (newMatches : Array ForwardRuleMatch)
(erasedHyps : Std.HashSet FVarId) : NormM Unit :=
modifyThe NormM.State λ s => { s with
forwardState := fs
forwardRuleMatches :=
s.forwardRuleMatches.update newMatches erasedHyps
(consumedForwardRuleMatches := #[]) -- We erase the consumed matches separately.
}
def eraseForwardRuleMatch (m : ForwardRuleMatch) : NormM Unit := do
modifyThe NormM.State λ s => { s with forwardRuleMatches := s.forwardRuleMatches.erase m }
def applyDiffToForwardState (diff : GoalDiff) : NormM Unit := do
let fs ← getResetForwardState
let (fs, ms) ← fs.applyGoalDiff (← read).ruleSet diff
updateForwardState fs ms diff.removedFVars
inductive NormRuleResult
| succeeded (goal : MVarId) (steps? : Option (Array Script.LazyStep))
| proved (steps? : Option (Array Script.LazyStep))
namespace NormRuleResult
def newGoal? : NormRuleResult → Option MVarId
| succeeded goal .. => goal
| proved .. => none
def steps? : NormRuleResult → Option (Array Script.LazyStep)
| .succeeded (steps? := steps?) .. | .proved (steps? := steps?) .. => steps?
end NormRuleResult
def optNormRuleResultEmoji : Option NormRuleResult → String
| some (.succeeded ..) => ruleSuccessEmoji
| some (.proved ..) => ruleProvedEmoji
| none => ruleFailureEmoji
@[inline, always_inline]
def withNormTraceNode (ruleName : DisplayRuleName)
(k : NormM (Option NormRuleResult)) : NormM (Option NormRuleResult) :=
withAesopTraceNode .steps fmt do
let result? ← k
if let some newGoal := result?.bind (·.newGoal?) then
aesop_trace[steps] newGoal
return result?
where
fmt (r : Except Exception (Option NormRuleResult)) : NormM MessageData := do
let emoji := exceptRuleResultToEmoji (optNormRuleResultEmoji ·) r
return m!"{emoji} {ruleName}"
/-- On success, returns the rule tactic's result, the new forward state and the
new forward rule matches. If `rule` corresponds to some forward rule matches,
returns the matches as well. -/
def runNormRuleTac (rule : NormRule) (input : RuleTacInput) (fs : ForwardState)
(rs : LocalRuleSet) :
NormM $
Option (NormRuleResult × ForwardState × Array ForwardRuleMatch × Std.HashSet FVarId) ×
Array ForwardRuleMatch := do
let preMetaState ← show MetaM _ from saveState
let result? ← runRuleTac rule.tac.run rule.name preMetaState input
let forwardRuleMatches := rule.tac.forwardRuleMatches? |>.getD #[]
match result? with
| .error e =>
aesop_trace[steps] e.toMessageData
return (none, forwardRuleMatches)
| .ok result =>
let #[rapp] := result.applications
| err m!"rule did not produce exactly one rule application."
show MetaM _ from restoreState rapp.postState
if rapp.goals.isEmpty then
return (some (.proved rapp.scriptSteps?, fs, #[], ∅), forwardRuleMatches)
let (#[{ diff }]) := rapp.goals
| err m!"rule produced more than one subgoal."
let (fs, ms) ← fs.applyGoalDiff rs diff
let g := diff.newGoal
if ← Check.rules.isEnabled then
let mvars := .ofArray input.mvars.toArray
let actualMVars ← rapp.postState.runMetaM' g.getMVarDependencies
if ! actualMVars == mvars then
err "the goal produced by the rule depends on different metavariables than the original goal."
let result := .succeeded g rapp.scriptSteps?
return (some (result, fs, ms, diff.removedFVars), forwardRuleMatches)
where
err {α} (msg : MessageData) : MetaM α := throwError
"aesop: error while running norm rule {rule.name}: {msg}\nThe rule was run on this goal:{indentD $ MessageData.ofGoal input.goal}"
def runNormRule (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(rule : IndexMatchResult NormRule) : NormM (Option NormRuleResult) := do
profilingRule (.ruleName rule.rule.name) (λ result => result.isSome) do
let ruleInput := {
indexMatchLocations := rule.locations
patternSubsts? := rule.patternSubsts?
options := (← read).options
hypTypes := (← get).forwardState.hypTypes
goal, mvars
}
withNormTraceNode (.ruleName rule.rule.name) do
let fs ← getForwardState
let (result?, consumedForwardRuleMatches) ←
runNormRuleTac rule.rule ruleInput fs (← read).ruleSet
for m in consumedForwardRuleMatches do
eraseForwardRuleMatch m
let (some (result, fs, ms, removedFVars)) := result?
| return none
updateForwardState fs ms removedFVars
return result
def runFirstNormRule (goal : MVarId) (mvars : UnorderedArraySet MVarId)
(rules : Array (IndexMatchResult NormRule)) :
NormM (Option (DisplayRuleName × NormRuleResult)) := do
for rule in rules do
let result? ← runNormRule goal mvars rule
if let some result := result? then
return some (rule.rule.name, result)
return none
def mkNormSimpScriptStep
(preGoal : MVarId) (postGoal? : Option MVarId)
(preState postState : Meta.SavedState) (usedTheorems : Simp.UsedSimps) :
NormM Script.LazyStep := do
let ctx := (← read).normSimpContext
let simpBuilder :=
TacticBuilder.simpAllOrSimpAtStar (simpAll := ctx.useHyps) preGoal
ctx.configStx? usedTheorems
let simpOnlyBuilder :=
TacticBuilder.simpAllOrSimpAtStarOnly (simpAll := ctx.useHyps) preGoal
ctx.configStx? usedTheorems
let tacticBuilders :=
if (← read).options.useDefaultSimpSet then
#[simpOnlyBuilder, simpBuilder]
else
#[simpOnlyBuilder]
return {
postGoals := postGoal?.toArray
tacticBuilders
tacticBuilders_ne := by simp only [tacticBuilders]; split <;> simp
preGoal, preState, postState
}
def normSimpCore (goal : MVarId) (goalMVars : Std.HashSet MVarId) :
NormM (Option NormRuleResult) := do
let ctx := (← read).normSimpContext
goal.withContext do
let preState ← show MetaM _ from saveState
let localRules := (← read).ruleSet.localNormSimpRules
let result ←
if ctx.useHyps then
let (ctx, simprocs) ←
addLocalRules localRules ctx.toContext ctx.simprocs
(isSimpAll := true)
Aesop.simpAll goal ctx simprocs
else
let (ctx, simprocs) ←
addLocalRules localRules ctx.toContext ctx.simprocs
(isSimpAll := false)
Aesop.simpGoalWithAllHypotheses goal ctx simprocs
-- It can happen that simp 'solves' the goal but leaves some mvars
-- unassigned. In this case, we treat the goal as unchanged.
let result ←
match result with
| .solved .. =>
let anyMVarDropped ← goalMVars.anyM (notM ·.isAssignedOrDelayedAssigned)
if anyMVarDropped then
aesop_trace[steps] "Normalisation simp solved the goal but dropped some metavariables. Skipping normalisation simp."
show MetaM _ from restoreState preState
pure .unchanged
else
pure result
| .unchanged .. =>
aesop_trace[steps] "norm simp left the goal unchanged"
pure result
| .simplified .. =>
pure result
let postState ← show MetaM _ from saveState
match result with
| .unchanged => return none
| .solved usedTheorems => do
let step ←
mkNormSimpScriptStep goal none preState postState usedTheorems
return some $ .proved #[step]
| .simplified newGoal usedTheorems => do
let step ←
mkNormSimpScriptStep goal newGoal preState postState usedTheorems
applyDiffToForwardState (← diffGoals goal newGoal)
return some $ .succeeded newGoal #[step]
where
addLocalRules (localRules : Array LocalNormSimpRule) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (isSimpAll : Bool) :
NormM (Simp.Context × Simp.SimprocsArray) :=
localRules.foldlM (init := (ctx, simprocs)) λ (ctx, simprocs) r =>
try
elabRuleTermForSimpMetaM goal r.simpTheorem ctx simprocs isSimpAll
catch _ =>
return (ctx, simprocs)
@[inline, always_inline]
def checkSimp (name : String) (mayCloseGoal : Bool) (goal : MVarId)
(x : NormM (Option NormRuleResult)) : NormM (Option NormRuleResult) := do
if ! (← Check.rules.isEnabled) then
x
else
let preMetaState ← show MetaM _ from saveState
let result? ← x
let newGoal? := result?.bind (·.newGoal?)
let postMetaState ← show MetaM _ from saveState
let introduced :=
(← getIntroducedExprMVars preMetaState postMetaState).filter
(some · != newGoal?)
unless introduced.isEmpty do throwError
"{Check.rules.name}: {name} introduced mvars:{introduced.map (·.name)}"
let assigned :=
(← getAssignedExprMVars preMetaState postMetaState).filter (· != goal)
unless assigned.isEmpty do throwError
"{Check.rules.name}: {name} assigned mvars:{introduced.map (·.name)}"
if ← pure (! mayCloseGoal && newGoal?.isNone) <&&> goal.isAssigned then
throwError "{Check.rules.name}: {name} solved the goal"
return result?
def normSimp (goal : MVarId) (goalMVars : Std.HashSet MVarId) :
NormM (Option NormRuleResult) := do
profilingRule .normSimp (wasSuccessful := λ _ => true) do
checkSimp "norm simp" (mayCloseGoal := true) goal do
withNormTraceNode .normSimp do
try
normSimpCore goal goalMVars
catch e =>
throwError "aesop: error in norm simp: {e.toMessageData}"
def normUnfoldCore (goal : MVarId) : NormM (Option NormRuleResult) := do
let unfoldRules := (← read).ruleSet.unfoldRules
let (result, steps) ← unfoldManyStarS goal (unfoldRules.find? ·) |>.run
match result with
| none =>
aesop_trace[steps] "nothing to unfold"
return none
| some newGoal =>
applyDiffToForwardState (← diffGoals goal newGoal)
return some $ .succeeded newGoal steps
def normUnfold (goal : MVarId) : NormM (Option NormRuleResult) := do
profilingRule .normUnfold (wasSuccessful := λ _ => true) do
checkSimp "unfold simp" (mayCloseGoal := false) goal do
withNormTraceNode .normUnfold do
try
normUnfoldCore goal
catch e =>
throwError "aesop: error in norm unfold: {e.toMessageData}"
inductive NormSeqResult where
| proved (script : Array (DisplayRuleName × Option (Array Script.LazyStep)))
| changed (goal : MVarId)
(script : Array (DisplayRuleName × Option (Array Script.LazyStep)))
| unchanged
def NormRuleResult.toNormSeqResult (ruleName : DisplayRuleName) :
NormRuleResult → NormSeqResult
| .proved steps? => .proved #[(ruleName, steps?)]
| .succeeded goal steps? => .changed goal #[(ruleName, steps?)]
def optNormRuleResultToNormSeqResult :
Option (DisplayRuleName × NormRuleResult) → NormSeqResult
| some (ruleName, r) => r.toNormSeqResult ruleName
| none => .unchanged
abbrev NormStep :=
MVarId → Array (IndexMatchResult NormRule) →
Array (IndexMatchResult NormRule) → NormM NormSeqResult
def runNormSteps (goal : MVarId) (steps : Array NormStep)
(stepsNe : 0 < steps.size) : NormM NormSeqResult := do
let ctx ← readThe NormM.Context
let maxIterations := ctx.options.maxNormIterations
let mut iteration := 0
let mut step : Fin steps.size := ⟨0, stepsNe⟩
let mut goal := goal
let mut scriptSteps := #[]
let mut preSimpRules := ∅
let mut postSimpRules := ∅
let mut anySuccess := false
while iteration < maxIterations do
if step.val == 0 then
let rules ←
selectNormRules ctx.ruleSet (← getThe NormM.State).forwardRuleMatches
goal
let (preSimpRules', postSimpRules') :=
rules.partition λ r => r.rule.extra.penalty < (0 : Int)
preSimpRules := preSimpRules'
postSimpRules := postSimpRules'
match ← steps[step] goal preSimpRules postSimpRules with
| .changed newGoal scriptSteps' =>
anySuccess := true
goal := newGoal
scriptSteps := scriptSteps ++ scriptSteps'
iteration := iteration + 1
step := ⟨0, stepsNe⟩
| .proved scriptSteps' =>
scriptSteps := scriptSteps ++ scriptSteps'
return .proved scriptSteps
| .unchanged =>
if h : step.val + 1 < steps.size then
step := ⟨step.val + 1, h⟩
else
if anySuccess then
return .changed goal scriptSteps
else
return .unchanged
throwError "aesop: exceeded maximum number of normalisation iterations ({maxIterations}). This means normalisation probably got stuck in an infinite loop."
namespace NormStep
def runPreSimpRules (mvars : UnorderedArraySet MVarId) : NormStep
| goal, preSimpRules, _ => do
optNormRuleResultToNormSeqResult <$>
runFirstNormRule goal mvars preSimpRules
def runPostSimpRules (mvars : UnorderedArraySet MVarId) : NormStep
| goal, _, postSimpRules =>
optNormRuleResultToNormSeqResult <$>
runFirstNormRule goal mvars postSimpRules
def unfold : NormStep
| goal, _, _ => do
if ! (← readThe NormM.Context).options.enableUnfold then
aesop_trace[steps] "norm unfold is disabled (options := \{ ..., enableUnfold := false })"
return .unchanged
let r := (← normUnfold goal).map (.normUnfold, ·)
return optNormRuleResultToNormSeqResult r
def simp (mvars : Std.HashSet MVarId) : NormStep
| goal, _, _ => do
if ! (← readThe NormM.Context).normSimpContext.enabled then
aesop_trace[steps] "norm simp is disabled (simp_options := \{ ..., enabled := false })"
return .unchanged
let r := (← normSimp goal mvars).map (.normSimp, ·)
return optNormRuleResultToNormSeqResult r
end NormStep
partial def normalizeGoalMVar (goal : MVarId)
(mvars : UnorderedArraySet MVarId) : NormM NormSeqResult := do
let mvarsHashSet := .ofArray mvars.toArray
let mut normSteps := #[
NormStep.runPreSimpRules mvars,
NormStep.unfold,
NormStep.simp mvarsHashSet,
NormStep.runPostSimpRules mvars
]
runNormSteps goal normSteps
(by simp (config := { decide := true }) [normSteps])
-- Returns true if the goal was solved by normalisation.
def normalizeGoalIfNecessary (gref : GoalRef) [Aesop.Queue Q] :
SearchM Q Bool := do
let g ← gref.get
let preGoal := g.preNormGoal
if ← g.isRoot then
-- For the root goal, we skip normalization.
let rootState ← getRootMetaState
gref.modify (·.setNormalizationState (.normal preGoal rootState #[]))
return false
match g.normalizationState with
| .provenByNormalization .. => return true
| .normal .. => return false
| .notNormal => pure ()
let normCtx := { (← read) with }
let normState := {
forwardState := g.forwardState
forwardRuleMatches := g.forwardRuleMatches
}
let ((normResult, { forwardState, forwardRuleMatches }), postState) ←
g.runMetaMInParentState do
normalizeGoalMVar preGoal g.mvars |>.run normCtx |>.run normState
match normResult with
| .changed postGoal script? =>
gref.modify λ g =>
g.setNormalizationState (.normal postGoal postState script?)
|>.setForwardState forwardState
|>.setForwardRuleMatches forwardRuleMatches
return false
| .unchanged =>
gref.modify (·.setNormalizationState (.normal preGoal postState #[]))
return false
| .proved script? =>
gref.modify
(·.setNormalizationState (.provenByNormalization postState script?))
gref.markProvenByNormalization
return true
end Aesop |
.lake/packages/aesop/Aesop/Search/Expansion/Basic.lean | module
public import Aesop.RuleTac.Basic
public section
open Lean
open Lean.Meta
namespace Aesop
def runRuleTac (tac : RuleTac) (ruleName : RuleName)
(preState : Meta.SavedState) (input : RuleTacInput) :
BaseM (Except Exception RuleTacOutput) := do
let result ←
try
Except.ok <$> runInMetaState preState do tac input
catch e =>
return .error e
if ← Check.rules.isEnabled then
if let .ok ruleOutput := result then
ruleOutput.applications.forM λ rapp => do
if let (some err) ← rapp.check input then
throwError "{Check.rules.name}: while applying rule {ruleName}: {err}"
return result
end Aesop |
.lake/packages/aesop/Aesop/Search/Expansion/Simp.lean | module
public import Lean.Meta.Tactic.Simp.Rewrite
import Lean.Meta.Tactic.Simp.SimpAll
public section
open Lean Lean.Meta
open Simp (UsedSimps)
namespace Aesop
inductive SimpResult
| solved (usedTheorems : Simp.UsedSimps)
| unchanged
| simplified (newGoal : MVarId) (usedTheorems : UsedSimps)
namespace SimpResult
def newGoal? : SimpResult → Option MVarId
| solved .. => none
| unchanged => none
| simplified g .. => some g
end SimpResult
/--
Add all `let` hypotheses in the local context as `simp` theorems.
Background: by default, in the goal `x : _ := v ⊢ P[x]`, `simp` does not
substitute `x` by `v` in the target. The `simp` option `zetaDelta` can be used
to make `simp` perform this substitution, but we don't want to set it because
then Aesop `simp` would diverge from default `simp`, so we would have to adjust
the `aesop?` output as well. Instead, we add `let` hypotheses explicitly. This
way, `simp?` picks them up as well.
See lean4#3520.
-/
def addLetDeclsToSimpTheorems (ctx : Simp.Context) : MetaM Simp.Context := do
let mut simpTheoremsArray := ctx.simpTheorems
if simpTheoremsArray.isEmpty then
simpTheoremsArray := #[{}]
for ldecl in ← getLCtx do
if ldecl.hasValue && ! ldecl.isImplementationDetail then
simpTheoremsArray := simpTheoremsArray.modify 0 λ simpTheorems =>
simpTheorems.addLetDeclToUnfold ldecl.fvarId
return ctx.setSimpTheorems simpTheoremsArray
def addLetDeclsToSimpTheoremsUnlessZetaDelta (ctx : Simp.Context) :
MetaM Simp.Context := do
if ctx.config.zetaDelta then
return ctx
else
addLetDeclsToSimpTheorems ctx
def simpGoal (mvarId : MVarId) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (discharge? : Option Simp.Discharge := none)
(simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[])
(stats : Simp.Stats := {}) : MetaM SimpResult := do
let mvarIdOld := mvarId
let ctx := ctx.setFailIfUnchanged false
let (result, { usedTheorems := usedSimps, .. }) ←
Meta.simpGoal mvarId ctx simprocs discharge? simplifyTarget fvarIdsToSimp
stats
if let some (_, mvarId) := result then
if mvarId == mvarIdOld then
return .unchanged
else
return .simplified mvarId usedSimps
else
return .solved usedSimps
def simpGoalWithAllHypotheses (mvarId : MVarId) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (discharge? : Option Simp.Discharge := none)
(simplifyTarget : Bool := true) (stats : Simp.Stats := {}) :
MetaM SimpResult :=
mvarId.withContext do
let lctx ← getLCtx
let mut fvarIdsToSimp := Array.mkEmpty lctx.decls.size
for ldecl in lctx do
if ldecl.isImplementationDetail then
continue
fvarIdsToSimp := fvarIdsToSimp.push ldecl.fvarId
let ctx ← addLetDeclsToSimpTheoremsUnlessZetaDelta ctx
Aesop.simpGoal mvarId ctx simprocs discharge? simplifyTarget fvarIdsToSimp
stats
def simpAll (mvarId : MVarId) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (stats : Simp.Stats := {}) :
MetaM SimpResult :=
mvarId.withContext do
let ctx := ctx.setFailIfUnchanged false
let ctx ← addLetDeclsToSimpTheoremsUnlessZetaDelta ctx
match ← Lean.Meta.simpAll mvarId ctx simprocs stats with
| (none, stats) => return .solved stats.usedTheorems
| (some mvarIdNew, stats) =>
if mvarIdNew == mvarId then
return .unchanged
else
return .simplified mvarIdNew stats.usedTheorems
end Aesop |
.lake/packages/aesop/Aesop/Search/Queue/Class.lean | module
public import Aesop.Tree.Data
public section
open Lean
namespace Aesop
class Queue (Q : Type) where
init : BaseIO Q
addGoals : Q → Array GoalRef → BaseIO Q
popGoal : Q → BaseIO (Option GoalRef × Q)
namespace Queue
def init' [Queue Q] (grefs : Array GoalRef) : BaseIO Q := do
addGoals (← init) grefs
end Aesop.Queue |
.lake/packages/aesop/Aesop/RuleTac/GoalDiff.lean | module
public import Aesop.BaseM
import Aesop.RPINF
public section
open Lean Lean.Meta
namespace Aesop
/--
A representation of the differences between two goals. Each Aesop rule produces
a `GoalDiff` between the goal on which the rule was run (the 'old goal') and
each of the subgoals produced by the rule (the 'new goals').
We use the produced `GoalDiff`s to update stateful data structures which cache
information about Aesop goals and for which it is more efficient to update the
cached information than to recompute it for each goal.
Hypotheses are identified by their `FVarId` *and* the RPINF of their type and
value (if any). This means that when a hypothesis `h : T` with `FVarId` `i`
appears in the old goal and `h : T'` with `FVarId` `i` appears in the new goal,
but the RPINF of `T` is not equal to the RPINF of `T'`, then `h` is treated as
both added (with the new type) and removed (with the old type). This can happen
when the type of a hyp changes to another type that is definitionally equal at
`default`, but not at `reducible` transparency.
The target is identified by RPINF.
-/
-- TODO Lean theoretically has an invariant that the type of an fvar cannot
-- change without the `FVarId` also changing. However, this invariant is
-- currently sometimes violated, notably by `simp`:
--
-- https://github.com/leanprover/lean4/issues/6226
--
-- If we could rely on this invariant, we could greatly simplify the computation
-- of goal diffs because we could trust that if an fvar is present in the old
-- and new goal, it has the same type in both.
structure GoalDiff where
/-- The old goal. -/
oldGoal : MVarId
/-- The new goal. -/
newGoal : MVarId
/-- `FVarId`s that appear in the new goal, but not (or with a different type)
in the old goal. -/
addedFVars : Std.HashSet FVarId
/-- `FVarId`s that appear in the old goal, but not (or with a different type)
in the new goal. -/
removedFVars : Std.HashSet FVarId
/-- Is the old goal's target RPINF equal to the new goal's target RPINF? -/
targetChanged : LBool
deriving Inhabited
protected def GoalDiff.empty (oldGoal newGoal : MVarId) : GoalDiff := {
addedFVars := ∅
removedFVars := ∅
targetChanged := .undef
oldGoal, newGoal
}
def isRPINFEqual (goal₁ goal₂ : MVarId) (e₁ e₂ : Expr) : BaseM Bool :=
return (← goal₁.withContext $ rpinf e₁) == (← goal₂.withContext $ rpinf e₂)
def isRPINFEqualLDecl (goal₁ goal₂ : MVarId) (ldecl₁ ldecl₂ : LocalDecl) : BaseM Bool :=
match ldecl₁.isLet, ldecl₂.isLet with
| false, false =>
isRPINFEqual goal₁ goal₂ ldecl₁.type ldecl₂.type
| true, true =>
isRPINFEqual goal₁ goal₂ ldecl₁.type ldecl₂.type <&&>
isRPINFEqual goal₁ goal₂ ldecl₁.value ldecl₂.value
| _, _ => return false
def getNewFVars (oldGoal newGoal : MVarId) (oldLCtx newLCtx : LocalContext) :
BaseM (Std.HashSet FVarId) :=
newLCtx.foldlM (init := ∅) λ newFVars ldecl => do
if ldecl.isImplementationDetail then
return newFVars
if let some oldLDecl := oldLCtx.find? ldecl.fvarId then
if ← isRPINFEqualLDecl oldGoal newGoal oldLDecl ldecl then
return newFVars
else
return newFVars.insert ldecl.fvarId
else
return newFVars.insert ldecl.fvarId
/--
Diff two goals.
-/
def diffGoals (old new : MVarId) : BaseM GoalDiff := do
let oldLCtx := (← old.getDecl).lctx
let newLCtx := (← new.getDecl).lctx
return {
oldGoal := old
newGoal := new
addedFVars := ← getNewFVars old new oldLCtx newLCtx
removedFVars := ← getNewFVars new old newLCtx oldLCtx
targetChanged :=
! (← isRPINFEqual old new (← old.getType) (← new.getType)) |>.toLBool
}
namespace GoalDiff
def targetChanged' (diff : GoalDiff) : BaseM Bool :=
match diff.targetChanged with
| .true => return true
| .false => return false
| .undef => do
let eq ←
isRPINFEqual diff.oldGoal diff.newGoal (← diff.oldGoal.getType)
(← diff.newGoal.getType)
return ! eq
/--
If `diff₁` is the difference between goals `g₁` and `g₂` and `diff₂` is the
difference between `g₂` and `g₃`, then `diff₁.comp diff₂` is the difference
between `g₁` and `g₃`.
We assume that a hypothesis whose RPINF changed between `g₁` and `g₂` does not
change back, i.e. the hypothesis' RPINF is still different between `g₁` and `g₃`.
-/
def comp (diff₁ diff₂ : GoalDiff) : GoalDiff where
oldGoal := diff₁.oldGoal
newGoal := diff₂.newGoal
addedFVars :=
diff₁.addedFVars.fold (init := diff₂.addedFVars) λ addedFVars fvarId =>
if diff₂.removedFVars.contains fvarId then
addedFVars
else
addedFVars.insert fvarId
removedFVars :=
diff₂.removedFVars.fold (init := diff₁.removedFVars) λ removedFVars fvarId =>
if diff₁.addedFVars.contains fvarId then
removedFVars
else
removedFVars.insert fvarId
targetChanged := lBoolOr diff₁.targetChanged diff₂.targetChanged
def checkCore (diff : GoalDiff) (old new : MVarId) :
BaseM (Option MessageData) := do
if diff.oldGoal != old then
return some m!"incorrect old goal: expected {old.name}, got {diff.oldGoal.name}"
if diff.newGoal != new then
return some m!"incorrect new goal: expected {new.name}, got {diff.newGoal.name}"
let oldLCtx := (← old.getDecl).lctx
let newLCtx := (← new.getDecl).lctx
-- Check that the added hypotheses were indeed added
for fvarId in diff.addedFVars do
if let some oldLDecl := oldLCtx.find? fvarId then
if ← isRPINFEqualLDecl old new oldLDecl (← fvarId.getDecl) then
return some m!"addedFVars contains hypothesis {oldLDecl.userName} which was already present in the old goal"
unless newLCtx.contains fvarId do
return some m!"addedFVars contains hypothesis {fvarId.name} but this fvar does not exist in the new goal"
-- Check that the removed hypotheses were indeed removed
for fvarId in diff.removedFVars do
if let some newLDecl := newLCtx.find? fvarId then
if ← isRPINFEqualLDecl old new (← fvarId.getDecl) newLDecl then
return some m!"removedFVars contains hypothesis {newLDecl.userName} but it is still present in the new goal"
unless oldLCtx.contains fvarId do
return some m!"removedFVars contains hypothesis {fvarId.name} but this fvar does not exist in the old goal"
-- Check that all added hypotheses appear in addedFVars
for newLDecl in newLCtx do
if newLDecl.isImplementationDetail then
continue
let newFVarId := newLDecl.fvarId
if ! oldLCtx.contains newFVarId &&
! diff.addedFVars.contains newFVarId then
return some m!"hypothesis {newLDecl.userName} was added, but does not appear in addedFVars"
-- Check that all removed hypotheses appear in removedFVars
for oldLDecl in oldLCtx do
if oldLDecl.isImplementationDetail then
continue
let oldFVarId := oldLDecl.fvarId
if ! newLCtx.contains oldFVarId &&
! diff.removedFVars.contains oldFVarId then
return some m!"hypothesis {oldLDecl.userName} was removed, but does not appear in removedFVars"
-- Check that all common hypotheses have equal RPINFs
for newLDecl in newLCtx do
if newLDecl.isImplementationDetail then
continue
if let some oldLDecl := oldLCtx.find? newLDecl.fvarId then
unless ← isRPINFEqualLDecl old new oldLDecl newLDecl do
return some m!"hypotheses {oldLDecl.userName} and {newLDecl.userName} have the same FVarId but their types/values are not reducibly defeq"
-- Check the target
let oldTgt ← old.getType
let newTgt ← new.getType
if ← (pure $ diff.targetChanged == .true) <&&>
isRPINFEqual old new oldTgt newTgt then
let oldTgt ← old.withContext do addMessageContext m!"{oldTgt}"
let newTgt ← new.withContext do addMessageContext m!"{newTgt}"
return some m!"diff says target changed, but old target{indentD oldTgt}\nis reducibly defeq to new target{indentD newTgt}"
if ← (pure $ diff.targetChanged == .false) <&&>
notM (isRPINFEqual old new oldTgt newTgt) then
let oldTgt ← old.withContext do addMessageContext m!"{oldTgt}"
let newTgt ← new.withContext do addMessageContext m!"{newTgt}"
return some m!"diff says target did not change, but old target{indentD oldTgt}\nis not reducibly defeq to new target{indentD newTgt}"
return none
def check (diff : GoalDiff) (old new : MVarId) :
BaseM (Option MessageData) := do
if let some err ← diff.checkCore old new then
addMessageContext m!"rule produced incorrect diff:{indentD err}\nold goal:{indentD old}\nnew goal:{indentD new}"
else
return none
end Aesop.GoalDiff |
.lake/packages/aesop/Aesop/RuleTac/Cases.lean | module
public import Aesop.RuleTac.Basic
public import Aesop.Script.CtorNames
import Aesop.Script.SpecificTactics
public section
open Lean
open Lean.Meta
namespace Aesop
-- NOTE: introduces fresh metavariables for the 'holes' in `p`.
def CasesPattern.toExpr (p : CasesPattern) : MetaM Expr := do
let (_, _, p) ← openAbstractMVarsResult p
return p
inductive CasesTarget' where
| decl (decl : Name)
| patterns (ps : Array (Expr × Meta.SavedState))
def CasesTarget.toCasesTarget' : CasesTarget → MetaM CasesTarget'
| decl d => return .decl d
| patterns ps => withoutModifyingState do
let initialState ← saveState
.patterns <$> ps.mapM λ p => do
initialState.restore
let e ← p.toExpr
let s ← saveState
return (e, s)
namespace RuleTac
partial def cases (target : CasesTarget) (md : TransparencyMode)
(isRecursiveType : Bool) (ctorNames : Array CtorNames) : RuleTac :=
SingleRuleTac.toRuleTac λ input => do
match ← go input.goal #[] #[] input.goal |>.run with
| (none, _) => throwError "No matching hypothesis found."
| (some goals, steps) => return (goals, steps, none)
where
findFirstApplicableHyp (excluded : Array FVarId) (goal : MVarId) :
MetaM (Option FVarId) :=
withTransparency md do goal.withContext do
let target ← target.toCasesTarget'
let «match» ldecl : MetaM Bool :=
match target with
| .decl d => do
isAppOfUpToDefeq (← mkConstWithFreshMVarLevels d) ldecl.type
| .patterns ps => withoutModifyingState do
ps.anyM λ (e, state) => do state.restore; isDefEq e ldecl.type
return ← (← getLCtx).findDeclM? λ ldecl => do
if ldecl.isImplementationDetail || excluded.contains ldecl.fvarId then
return none
else if ← «match» ldecl then
return some ldecl.fvarId
else
return none
go (initialGoal : MVarId) (newGoals : Array Subgoal) (excluded : Array FVarId)
(goal : MVarId) : ScriptM (Option (Array Subgoal)) := do
let some hyp ← findFirstApplicableHyp excluded goal
| return none
let some goals ← tryCasesS goal hyp ctorNames
| return none
let mut newGoals := newGoals
for h : i in [:goals.size] do
let g := goals[i]
let newDiff ← diffGoals goal g.mvarId
let mut excluded := excluded
if isRecursiveType then
excluded := excluded.map λ fvarId =>
if let .fvar fvarId' := g.subst.get fvarId then fvarId' else fvarId
excluded := excluded ++ newDiff.addedFVars.toArray
match ← go initialGoal newGoals excluded g.mvarId with
| some newGoals' => newGoals := newGoals'
| none =>
-- TODO We used to use a method that produces a more clever goal diff,
-- using the fvarSubst reported by `cases`. Restore this once
-- ForwardState.applyGoalDiff can deal with nonempty fvarSubsts.
let diff ← diffGoals initialGoal g.mvarId
newGoals := newGoals.push { diff }
return some newGoals
end Aesop.RuleTac |
.lake/packages/aesop/Aesop/RuleTac/Apply.lean | module
public import Aesop.RuleTac.Basic
public import Aesop.RuleTac.RuleTerm
import Aesop.RuleTac.ElabRuleTerm
import Aesop.Script.SpecificTactics
public section
open Lean
open Lean.Meta
namespace Aesop.RuleTac
def applyExpr' (goal : MVarId) (e : Expr) (eStx : Term)
(patSubst? : Option Substitution) (md : TransparencyMode) :
BaseM RuleApplication :=
withTransparency md do
let e ←
if let some patSubst := patSubst? then
patSubst.specializeRule e
else
pure e
let (goals, #[step]) ← applyS goal e eStx md |>.run
| throwError "aesop: internal error in applyExpr': multiple steps"
let goals := goals.map λ newGoal => { diff := .empty goal newGoal }
return {
goals
postState := step.postState
scriptSteps? := #[step]
successProbability? := none
}
def applyExpr (goal : MVarId) (e : Expr) (eStx : Term)
(patSubsts? : Option (Array Substitution)) (md : TransparencyMode) :
BaseM RuleTacOutput := do
if let some patSubsts := patSubsts? then
let mut rapps := Array.mkEmpty patSubsts.size
let initialState ← saveState
for patSubst in patSubsts do
try
let rapp ← applyExpr' goal e eStx patSubst md
rapps := rapps.push rapp
catch _ =>
continue
finally
restoreState initialState
if rapps.isEmpty then
throwError "failed to apply '{e}' with any of the matched instances of the rule pattern"
return { applications := rapps }
else
let rapp ← applyExpr' goal e eStx none md
return { applications := #[rapp] }
def applyConst (decl : Name) (md : TransparencyMode) :
RuleTac := λ input => do
applyExpr input.goal (← mkConstWithFreshMVarLevels decl) (mkIdent decl)
input.patternSubsts? md
def applyTerm (stx : Term) (md : TransparencyMode) : RuleTac :=
λ input => input.goal.withContext do
applyExpr input.goal (← elabRuleTermForApplyLikeMetaM input.goal stx) stx
input.patternSubsts? md
def apply (t : RuleTerm) (md : TransparencyMode) : RuleTac :=
match t with
| .const decl => applyConst decl md
| .term tm => applyTerm tm md
-- Tries to apply each constant in `decls`. For each one that applies, a rule
-- application is returned. If none applies, the tactic fails.
def applyConsts (decls : Array Name) (md : TransparencyMode) :
RuleTac := λ input => do
let initialState ← saveState
let apps ← decls.filterMapM λ decl => do
try
let e ← mkConstWithFreshMVarLevels decl
some <$> applyExpr' input.goal e (mkIdent decl) none md
catch _ =>
return none
finally
restoreState initialState
if apps.isEmpty then throwError
"failed to apply any of these declarations: {decls}"
return ⟨apps⟩
end RuleTac |
.lake/packages/aesop/Aesop/RuleTac/Preprocess.lean | module
public import Aesop.RuleTac.Basic
import Aesop.Script.SpecificTactics
public section
open Lean Lean.Meta
namespace Aesop.RuleTac
/--
This `RuleTac` is applied once to the root goal, before any other rules are
tried.
-/
def preprocess : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let ((mvarId, _), steps) ← renameInaccessibleFVarsS input.goal |>.run
return (#[{ diff := .empty input.goal mvarId }], steps, none)
end Aesop.RuleTac |
.lake/packages/aesop/Aesop/RuleTac/Basic.lean | module
public import Aesop.Index.Basic
public import Aesop.RuleTac.GoalDiff
public import Aesop.Script.Step
public import Aesop.Options.Internal
public import Aesop.Percent
public section
open Lean
open Lean.Elab.Tactic
open Lean.Meta
namespace Aesop
/-! # Rule Tactic Types -/
/-- Input for a rule tactic. -/
structure RuleTacInput where
/-- The goal on which the rule is run. -/
goal : MVarId
/-- The set of mvars that `goal` depends on. -/
mvars : UnorderedArraySet MVarId
/-- If the rule is indexed, the locations (i.e. hyps or the target) matched by
the rule's index entries. Otherwise an empty set. The array contains no
duplicates. -/
indexMatchLocations : Array IndexMatchLocation
/-- If the rule has a pattern, the pattern substitutions that were found in
the goal. Each substitution is a list of expressions which were found by
matching the pattern against expressions in the goal. For example, if `h : max
a b = max a c` appears in the goal and the rule has pattern `max x y`, there
will be two substitutions `{x ↦ a, y ↦ b}`) and `{x ↦ a, y ↦ c}`.
If the rule does not have a pattern, this is `none`. Otherwise it is
guaranteed to be `some xs` with `xs` non-empty and duplicate-free. -/
patternSubsts? : Option (Array Substitution)
/-- The options given to Aesop. -/
options : Options'
/-- Normalised types of all non-implementation detail hypotheses in the local
context of `goal`. -/
hypTypes : PHashSet RPINF
deriving Inhabited
/-- A subgoal produced by a rule. -/
structure Subgoal where
/--
A diff between the goal the rule was run on and this goal. Many `MetaM`
tactics report information that allows you to easily construct a `GoalDiff`.
If you don't have access to such information, use `diffGoals`, but note that
it may not give optimal results.
-/
diff : GoalDiff
deriving Inhabited
namespace Subgoal
def mvarId (g : Subgoal) : MVarId :=
g.diff.newGoal
end Subgoal
def mvarIdToSubgoal (parentMVarId mvarId : MVarId) : BaseM Subgoal :=
return { diff := ← diffGoals parentMVarId mvarId }
/--
A single rule application, representing the application of a tactic to the input
goal. Must accurately report the following information:
- `goals`: the goals generated by the tactic.
- `postState`: the `MetaM` state after the tactic was run.
- `scriptSteps?`: script steps which produce the same effect as the rule tactic.
If `input.options.generateScript = false` (where `input` is the
`RuleTacInput`), this field is ignored. If the tactic does not support script
generation, use `none`.
- `successProbability`: The success probability of this rule application. If
`none`, we use the success probability of the applied rule.
-/
structure RuleApplication where
goals : Array Subgoal
postState : Meta.SavedState
scriptSteps? : Option (Array Script.LazyStep)
successProbability? : Option Percent
namespace RuleApplication
def check (r : RuleApplication) (input : RuleTacInput) :
BaseM (Option MessageData) :=
runInMetaState r.postState do
for goal in r.goals do
if ← goal.mvarId.isAssignedOrDelayedAssigned then
return some m!"subgoal metavariable ?{goal.mvarId.name} is already assigned."
if let some err ← goal.diff.check input.goal goal.mvarId then
return some err
return none
end RuleApplication
/--
The result of a rule tactic is a list of rule applications.
-/
structure RuleTacOutput where
applications : Array RuleApplication
deriving Inhabited
/--
A `RuleTac` is the tactic that is run when a rule is applied to a goal.
-/
@[expose] def RuleTac := RuleTacInput → BaseM RuleTacOutput
instance : Inhabited RuleTac := by
unfold RuleTac; exact inferInstance
/--
A `RuleTac` which generates only a single `RuleApplication`.
-/
@[expose] def SingleRuleTac :=
RuleTacInput →
BaseM (Array Subgoal × Option (Array Script.LazyStep) × Option Percent)
@[inline]
def SingleRuleTac.toRuleTac (t : SingleRuleTac) : RuleTac := λ input => do
let (goals, scriptSteps?, successProbability?) ← t input
let postState ← saveState
return ⟨#[{ postState, goals, scriptSteps?, successProbability? }]⟩
@[inline]
def RuleTac.ofSingleRuleTac := SingleRuleTac.toRuleTac
def RuleTac.ofTacticSyntax (t : RuleTacInput → MetaM Syntax.Tactic) : RuleTac :=
RuleTac.ofSingleRuleTac λ input => do
let stx ← t input
let preState ← saveState
let postGoals ← Lean.Elab.Tactic.run input.goal (evalTactic stx) |>.run'
let postState ← saveState
let postGoals := postGoals.toArray
let step := {
preGoal := input.goal
tacticBuilders := #[return .unstructured stx]
preState, postState, postGoals
}
let postGoals ← postGoals.mapM (mvarIdToSubgoal input.goal ·)
return (postGoals, some #[step], none)
/--
A tactic generator is a special sort of rule tactic, intended for use with
generative machine learning methods. It generates zero or more tactics
(represented as strings) that could be applied to the goal, plus a success
probability for each tactic. When Aesop executes a tactic generator, it executes
each of the tactics and, if the tactic succeeds, adds a rule application for it.
The tactic's success probability (which must be between 0 and 1, inclusive)
becomes the success probability of the rule application. A `TacGen` rule
succeeds if at least one of its suggested tactics succeeds.
-/
abbrev TacGen := MVarId → MetaM (Array (String × Float))
/-! # Rule Tactic Descriptions -/
@[expose] def CasesPattern := AbstractMVarsResult
deriving Inhabited
inductive CasesTarget
| decl (decl : Name)
| patterns (patterns : Array CasesPattern)
deriving Inhabited
end Aesop |
.lake/packages/aesop/Aesop/RuleTac/RuleTerm.lean | module
public import Aesop.Rule.Name
public section
open Lean Lean.Meta
namespace Aesop
inductive RuleTerm
| const (decl : Name)
| term (term : Term)
deriving Inhabited
instance : ToMessageData RuleTerm where
toMessageData
| .const decl => m!"{decl}"
| .term tm => m!"{tm}"
inductive ElabRuleTerm
| const (decl : Name)
| term (term : Term) (expr : Expr)
deriving Inhabited
namespace ElabRuleTerm
instance : ToMessageData ElabRuleTerm where
toMessageData
| .const decl => m!"{decl}"
| .term tm _ => m!"{tm}"
def expr : ElabRuleTerm → MetaM Expr
| const decl => mkConstWithFreshMVarLevels decl
| term _ e => return e
def scope : ElabRuleTerm → ScopeName
| const .. => .global
| term .. => .local
def name : ElabRuleTerm → MetaM Name
| const decl => return decl
| term _ e => getRuleNameForExpr e
def toRuleTerm : ElabRuleTerm → RuleTerm
| const decl => .const decl
| term t _ => .term t
def ofElaboratedTerm (tm : Term) (expr : Expr) : ElabRuleTerm :=
if let some decl := expr.constName? then
.const decl
else
.term tm expr
end Aesop.ElabRuleTerm |
.lake/packages/aesop/Aesop/RuleTac/Tactic.lean | module
public import Aesop.RuleTac.Basic
public section
open Lean Lean.Meta Lean.Elab.Tactic
open Lean.Elab.Tactic (TacticM evalTactic withoutRecover)
namespace Aesop.RuleTac
-- Precondition: `decl` has type `TacticM Unit`.
unsafe def tacticMImpl (decl : Name) : RuleTac :=
SingleRuleTac.toRuleTac λ input => do
let tac ← evalConst (TacticM Unit) decl
let goals ← run input.goal tac |>.run'
let goals ← goals.mapM (mvarIdToSubgoal (parentMVarId := input.goal) ·)
return (goals.toArray, none, none)
-- Precondition: `decl` has type `TacticM Unit`.
@[implemented_by tacticMImpl]
opaque tacticM (decl : Name) : RuleTac
-- Precondition: `decl` has type `RuleTac`.
unsafe def ruleTacImpl (decl : Name) : RuleTac := λ input => do
let tac ← evalConst RuleTac decl
tac input
-- Precondition: `decl` has type `RuleTac`.
@[implemented_by ruleTacImpl]
opaque ruleTac (decl : Name) : RuleTac
-- Precondition: `decl` has type `SimpleRuleTac`.
unsafe def singleRuleTacImpl (decl : Name) : RuleTac :=
SingleRuleTac.toRuleTac λ input => do
let tac ← evalConst SingleRuleTac decl
tac input
-- Precondition: `decl` has type `SimpleRuleTac`.
@[implemented_by singleRuleTacImpl]
opaque singleRuleTac (decl : Name) : RuleTac
/--
Elaborates and runs the given tactic syntax `stx`. The syntax `stx` must be of
kind `tactic` or `tacticSeq`.
-/
def tacticStx (stx : Syntax) : RuleTac :=
SingleRuleTac.toRuleTac λ input => do
let preState ← saveState
let tac := withoutRecover $ evalTactic stx
let postGoals := (← Elab.Tactic.run input.goal tac |>.run').toArray
let postState ← saveState
let tacticBuilder : Script.TacticBuilder := do
if stx.isOfKind `tactic then
return .unstructured ⟨stx⟩
else if stx.isOfKind ``Parser.Tactic.tacticSeq then
let stx := ⟨stx⟩
(.unstructured ·) <$> `(tactic| ($stx:tacticSeq))
else
throwError "expected either a single tactic or a sequence of tactics"
let step := {
preGoal := input.goal
tacticBuilders := #[tacticBuilder]
preState, postState, postGoals
}
let postGoals ←
postGoals.mapM (mvarIdToSubgoal (parentMVarId := input.goal) ·)
return (postGoals, some #[step], none)
-- Precondition: `decl` has type `TacGen`.
unsafe def tacGenImpl (decl : Name) : RuleTac := λ input => do
let tacGen ← evalConst TacGen decl
let initialState ← saveState
let suggestions ← tacGen input.goal
let mut apps := Array.mkEmpty suggestions.size
let mut errors : Array (String × Exception) := Array.mkEmpty suggestions.size
for (tacticStr, successProbability) in suggestions do
initialState.restore
let env ← getEnv
try
let some successProbability := Percent.ofFloat successProbability
| throwError "invalid success probability '{successProbability}', must be between 0 and 1"
let .ok stx :=
Parser.runParserCategory env `tactic tacticStr (fileName := "<stdin>")
| throwError "failed to parse tactic syntax{indentD tacticStr}"
let postGoals := (← run input.goal (evalTactic stx) |>.run').toArray
let postState ← saveState
if let some proof ← getExprMVarAssignment? input.goal then
if ← hasSorry proof then
throwError "generated proof contains sorry"
let step := {
preState := initialState
preGoal := input.goal
tacticBuilders := #[return .unstructured ⟨stx⟩]
postState, postGoals
}
let postGoals ←
postGoals.mapM (mvarIdToSubgoal (parentMVarId := input.goal) ·)
apps := apps.push {
goals := postGoals
scriptSteps? := some #[step]
successProbability? := successProbability
postState
}
catch e =>
errors := errors.push (tacticStr, e)
if apps.isEmpty then throwError
"Failed to apply any tactics generated. Errors:{indentD $ MessageData.joinSep (errors.toList.map (λ (tac, e) => m!"{tac}: {e.toMessageData}")) "\n"}"
return ⟨apps⟩
-- Precondition: `decl` has type `TacGen`.
@[implemented_by tacGenImpl]
opaque tacGen (decl : Name) : RuleTac
end Aesop.RuleTac |
.lake/packages/aesop/Aesop/RuleTac/Descr.lean | module
public import Aesop.RuleTac.Basic
public import Aesop.Script.CtorNames
public import Aesop.Forward.Match.Types
public section
open Lean Lean.Meta
namespace Aesop
inductive RuleTacDescr
| apply (term : RuleTerm) (md : TransparencyMode)
| constructors (constructorNames : Array Name) (md : TransparencyMode)
| forward (term : RuleTerm) (immediate : UnorderedArraySet PremiseIndex)
(isDestruct : Bool)
| cases (target : CasesTarget) (md : TransparencyMode)
(isRecursiveType : Bool) (ctorNames : Array CtorNames)
| tacticM (decl : Name)
| ruleTac (decl : Name)
| tacGen (decl : Name)
| singleRuleTac (decl : Name)
| tacticStx (stx : Syntax)
| preprocess
| forwardMatches (ms : Array ForwardRuleMatch)
deriving Inhabited
namespace RuleTacDescr
def forwardRuleMatches? : RuleTacDescr → Option (Array ForwardRuleMatch)
| forwardMatches ms => ms
| _ => none
end RuleTacDescr
end Aesop |
.lake/packages/aesop/Aesop/RuleTac/ElabRuleTerm.lean | module
public import Aesop.ElabM
public import Lean.Elab.Tactic.Basic
public import Lean.Meta.Tactic.Simp.Simproc
import Lean.Elab.Tactic.Simp
public section
open Lean Lean.Meta Lean.Elab.Term Lean.Elab.Tactic
namespace Aesop
def elabGlobalRuleIdent? (stx : Term) : TermElabM (Option Name) :=
try
if ! stx.raw.isIdent then
return none
let some (.const n _) ← resolveId? stx
| return none
return some n
catch _ =>
return none
def matchInductiveTypeSynonym? (decl : Name) : MetaM (Option InductiveVal) :=
withoutModifyingState do
let decl ← mkConstWithFreshMVarLevels decl
let type ← inferType decl
forallTelescope type λ args _ => do
let app ← whnf <| mkAppN decl args
let .const redDecl _ := app.getAppFn'
| return none
try
getConstInfoInduct redDecl
catch _ =>
return none
/-- Elaborate an identifier for a rule that applies to inductive types, e.g.
`cases`. The identifier must unambiguously refer to a global constant that is
either an inductive type or reduces to one. For the reduction test, we use
the larger transparency among `default` and `md`. -/
def elabInductiveRuleIdent? (stx : Term) (md : TransparencyMode) :
TermElabM (Option (Name × InductiveVal)) := do
let some decl ← elabGlobalRuleIdent? stx
| return none
let indVal? ←
try
some <$> getConstInfoInduct decl
catch _ =>
withAtLeastTransparency md do
matchInductiveTypeSynonym? decl
return indVal?.map ((decl, ·))
-- HACK: We ignore the output goals, so this is only likely to work for
-- functions that might as well be in `TermElabM`.
def runTacticMAsTermElabM (goal : MVarId) (x : TacticM α) : TermElabM α := do
x.run { elaborator := .anonymous } |>.run' { goals := [goal] }
-- HACK: We ignore the output goals, so this is only likely to work for
-- functions that might as well be in `TermElabM`.
def runTacticMAsElabM (x : TacticM α) : ElabM α := do
runTacticMAsTermElabM (← read).goal x
def withFullElaboration (x : TermElabM α) : TermElabM α :=
withSynthesize $ withoutErrToSorry $ withoutAutoBoundImplicit x
def elabRuleTermForApplyLikeCore (goal : MVarId) (stx : Term): TermElabM Expr :=
withFullElaboration $ runTacticMAsTermElabM goal do
elabTermForApply stx (mayPostpone := false)
def elabRuleTermForApplyLikeMetaM (goal : MVarId) (stx : Term) : MetaM Expr :=
elabRuleTermForApplyLikeCore goal stx |>.run'
def elabRuleTermForApplyLike (stx : Term) : ElabM Expr := do
elabRuleTermForApplyLikeCore (← read).goal stx
-- `stx` is of the form `"[" simpTheorem,* "]"`
def elabSimpTheorems (stx : Syntax) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (isSimpAll : Bool) :
TacticM (Simp.Context × Simp.SimprocsArray) :=
withoutRecover do
let kind : SimpKind := if isSimpAll then .simpAll else .simp
let result ←
elabSimpArgs stx ctx simprocs (eraseLocal := true) (kind := kind)
if result.simpArgs.any fun | (_, .star) => true | _ => false then
throwError "aesop: simp builder currently does not support wildcard '*'"
return (result.ctx, result.simprocs)
-- HACK: This produces the syntax "[" lemmas,* "]" which is parsed by
-- `elabSimpArgs`. This syntax doesn't have an associated parser, so I don't
-- know how to ensure that the produced syntax is valid.
def mkSimpArgs (simpTheorem : Term) : Syntax :=
mkNullNode #[
mkAtom "[",
mkNullNode
#[Unhygienic.run `(Lean.Parser.Tactic.simpLemma| $simpTheorem:term)],
mkAtom "]"
]
def elabRuleTermForSimpCore (goal : MVarId) (term : Term) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (isSimpAll : Bool) :
TermElabM (Simp.Context × Simp.SimprocsArray) := do
withFullElaboration $ runTacticMAsTermElabM goal do
elabSimpTheorems (mkSimpArgs term) ctx simprocs isSimpAll
def checkElabRuleTermForSimp (term : Term) (isSimpAll : Bool) : ElabM Unit := do
let ctx ← Simp.mkContext (simpTheorems := #[{}] )
let simprocs := #[{}]
discard $ elabRuleTermForSimpCore (← read).goal term ctx simprocs isSimpAll
def elabRuleTermForSimpMetaM (goal : MVarId) (term : Term) (ctx : Simp.Context)
(simprocs : Simp.SimprocsArray) (isSimpAll : Bool) :
MetaM (Simp.Context × Simp.SimprocsArray) :=
elabRuleTermForSimpCore goal term ctx simprocs isSimpAll |>.run'
end Aesop |
.lake/packages/aesop/Aesop/RuleTac/FVarIdSubst.lean | module
public import Lean.Meta.Tactic.FVarSubst
public section
open Lean Lean.Meta
namespace Aesop
structure FVarIdSubst where
map : Std.HashMap FVarId FVarId
deriving Inhabited
namespace FVarIdSubst
def isEmpty (s : FVarIdSubst) : Bool :=
s.map.isEmpty
def contains (s : FVarIdSubst) (fvarId : FVarId) : Bool :=
s.map.contains fvarId
def find? (s : FVarIdSubst) (fvarId : FVarId) : Option FVarId :=
s.map[fvarId]?
def get (s : FVarIdSubst) (fvarId : FVarId) : FVarId :=
s.find? fvarId |>.getD fvarId
def apply (s : FVarIdSubst) (e : Expr) : Expr :=
if s.isEmpty || ! e.hasFVar then
e
else
e.replace λ
| .fvar fvarId => s.find? fvarId |>.map mkFVar
| _ => none
def applyToLocalDecl (s : FVarIdSubst) : LocalDecl → LocalDecl
| .cdecl i id n t bi k => .cdecl i id n (s.apply t) bi k
| .ldecl i id n t v nd k => .ldecl i id n (s.apply t) (s.apply v) nd k
def domain (s : FVarIdSubst) : Std.HashSet FVarId :=
s.map.fold (init := ∅) λ r k _ => r.insert k
def codomain (s : FVarIdSubst) : Std.HashSet FVarId :=
s.map.fold (init := ∅) λ r _ v => r.insert v
protected def empty : FVarIdSubst :=
⟨∅⟩
instance : EmptyCollection FVarIdSubst :=
⟨.empty⟩
def insert (s : FVarIdSubst) (old new : FVarId) : FVarIdSubst :=
let map : Std.HashMap _ _ := s.map.fold (init := ∅) λ map k v =>
map.insert k $ if v == old then new else v
⟨map.insert old new⟩
def erase (s : FVarIdSubst) (fvarId : FVarId) : FVarIdSubst :=
⟨s.map.erase fvarId⟩
def append (s t : FVarIdSubst) : FVarIdSubst :=
let map : Std.HashMap _ _ := s.map.fold (init := ∅) λ map k v =>
map.insert k $ t.get v
⟨t.map.fold (init := map) λ s k v => s.insert k v⟩
def ofFVarSubstIgnoringNonFVarIds (s : FVarSubst) : FVarIdSubst := .mk $
s.map.foldl (init := ∅) λ map k v =>
if let .fvar fvarId := v then map.insert k fvarId else map
def ofFVarSubst? (s : FVarSubst) : Option FVarIdSubst := Id.run do
let mut result := ∅
for (k, v) in s.map do
if let .fvar fvarId := v then
result := result.insert k fvarId
else
return none
return some result
end Aesop.FVarIdSubst |
.lake/packages/aesop/Aesop/RuleTac/Forward.lean | module
public import Aesop.RuleTac.Forward.Basic
public import Aesop.RuleTac.Basic
public import Aesop.Script.ScriptM
public import Aesop.Forward.Match.Types
public import Lean.Meta.Tactic.Assert
import Aesop.RPINF
import Aesop.Forward.Match
import Aesop.RuleTac.ElabRuleTerm
import Aesop.Script.SpecificTactics
import Lean.Meta.CollectFVars
import Batteries.Lean.Meta.UnusedNames
public section
open Lean
open Lean.Meta
namespace Aesop.RuleTac
partial def makeForwardHyps (e : Expr) (patSubst? : Option Substitution)
(immediate : UnorderedArraySet PremiseIndex) (maxDepth? : Option Nat)
(forwardHypData : ForwardHypData) (existingHypTypes : PHashSet RPINF) :
BaseM (Array (Expr × Nat) × Array FVarId) :=
withNewMCtxDepth (allowLevelAssignments := true) do
let type ← inferType e
let (argMVars, binderInfos, _) ← openRuleType patSubst? e
let app := mkAppN e (argMVars.map .mvar)
let mut instMVars := Array.mkEmpty argMVars.size
let mut immediateMVars := Array.mkEmpty argMVars.size
for h : i in [:argMVars.size] do
let mvarId := argMVars[i]
if ← mvarId.isAssignedOrDelayedAssigned then
continue
if immediate.contains ⟨i⟩ then
immediateMVars := immediateMVars.push mvarId
else if binderInfos[i]!.isInstImplicit then
instMVars := instMVars.push mvarId
let (proofs, usedHyps, _) ←
loop app instMVars immediateMVars 0 #[] 0 #[] #[] ∅
return (proofs, usedHyps)
where
loop (app : Expr) (instMVars : Array MVarId) (immediateMVars : Array MVarId)
(i : Nat) (proofsAcc : Array (Expr × Nat)) (currentMaxHypDepth : Nat)
(currentUsedHyps : Array FVarId) (usedHypsAcc : Array FVarId)
(proofTypesAcc : Std.HashSet RPINF) :
BaseM (Array (Expr × Nat) × Array FVarId × Std.HashSet RPINF) := do
if h : immediateMVars.size > 0 ∧ i < immediateMVars.size then
-- We go through the immediate mvars back to front. This is more
-- efficient because assigning later mvars may already determine the
-- assignments of earlier mvars.
let mvarId := immediateMVars[immediateMVars.size - 1 - i]
if ← mvarId.isAssignedOrDelayedAssigned then
-- If the mvar is already assigned, we still need to update and check
-- the hyp depth.
let mut currentMaxHypDepth := currentMaxHypDepth
let (_, fvarIds) ← (← instantiateMVars (.mvar mvarId)).collectFVars |>.run {}
for fvarId in fvarIds.fvarIds do
let hypDepth := forwardHypData.depths.getD fvarId 0
currentMaxHypDepth := max currentMaxHypDepth hypDepth
if let some maxDepth := maxDepth? then
if currentMaxHypDepth + 1 > maxDepth then
return (proofsAcc, usedHypsAcc, proofTypesAcc)
return ← loop app instMVars immediateMVars (i + 1) proofsAcc
currentMaxHypDepth currentUsedHyps usedHypsAcc proofTypesAcc
let type ← mvarId.getType
(← getLCtx).foldlM (init := (proofsAcc, usedHypsAcc, proofTypesAcc)) λ s@(proofsAcc, usedHypsAcc, proofTypesAcc) ldecl => do
if ldecl.isImplementationDetail then
return s
let hypDepth := forwardHypData.depths.getD ldecl.fvarId 0
let currentMaxHypDepth := max currentMaxHypDepth hypDepth
if let some maxDepth := maxDepth? then
if currentMaxHypDepth + 1 > maxDepth then
return s
withoutModifyingState do
if ← isDefEq ldecl.type type then
mvarId.assign (mkFVar ldecl.fvarId)
let currentUsedHyps := currentUsedHyps.push ldecl.fvarId
loop app instMVars immediateMVars (i + 1) proofsAcc
currentMaxHypDepth currentUsedHyps usedHypsAcc proofTypesAcc
else
return s
else
for instMVar in instMVars do
instMVar.withContext do
let inst ← synthInstance (← instMVar.getType)
instMVar.assign inst
let proof := (← abstractMVars app).expr
let type ← rpinf (← inferType proof)
let redundant :=
proofTypesAcc.contains type || existingHypTypes.contains type
if redundant then
return (proofsAcc, usedHypsAcc, proofTypesAcc)
else
let depth := currentMaxHypDepth + 1
let proofsAcc := proofsAcc.push (proof, depth)
let proofTypesAcc := proofTypesAcc.insert type
let usedHypsAcc := usedHypsAcc ++ currentUsedHyps
return (proofsAcc, usedHypsAcc, proofTypesAcc)
def assertForwardHyp (goal : MVarId) (hyp : Hypothesis) (depth : Nat) :
ScriptM (FVarId × MVarId) := do
withScriptStep goal (λ (_, g) => #[g]) (λ _ => true) tacticBuilder do
withReducible do
let hyp := {
hyp with
binderInfo := .default
kind := .default
}
let implDetailHyp := {
hyp with
userName := forwardImplDetailHypName hyp.userName depth
binderInfo := .default
kind := .implDetail
}
let (#[fvarId, _], goal) ← goal.assertHypotheses #[hyp, implDetailHyp]
| throwError "aesop: internal error in assertForwardHyp: unexpected number of asserted fvars"
return (fvarId, goal)
where
tacticBuilder _ := Script.TacticBuilder.assertHypothesis goal hyp .reducible
def applyForwardRule (goal : MVarId) (e : Expr)
(patSubsts? : Option (Array Substitution))
(immediate : UnorderedArraySet PremiseIndex) (clear : Bool)
(maxDepth? : Option Nat) (existingHypTypes : PHashSet RPINF) :
ScriptM Subgoal :=
withReducible $ goal.withContext do
let initialGoal := goal
let forwardHypData ← getForwardHypData
let mut newHypProofs := #[]
let mut usedHyps := ∅
if let some patSubsts := patSubsts? then
for patSubst in patSubsts do
let (newHypProofs', usedHyps') ←
makeForwardHyps e patSubst immediate maxDepth? forwardHypData
existingHypTypes
newHypProofs := newHypProofs ++ newHypProofs'
usedHyps := usedHyps ++ usedHyps'
else
let (newHypProofs', usedHyps') ←
makeForwardHyps e none immediate maxDepth? forwardHypData
existingHypTypes
newHypProofs := newHypProofs'
usedHyps := usedHyps'
usedHyps :=
usedHyps.sortDedup (ord := ⟨λ x y => x.name.quickCmp y.name⟩)
if newHypProofs.isEmpty then
err
let newHypUserNames ← getUnusedUserNames newHypProofs.size forwardHypPrefix
let mut newHyps := #[]
for (proof, depth) in newHypProofs, userName in newHypUserNames do
let type ← inferType proof
newHyps := newHyps.push ({ value := proof, type, userName }, depth)
let mut goal := goal
let mut addedFVars := ∅
for (newHyp, depth) in newHyps do
let (fvarId, goal') ← assertForwardHyp goal newHyp depth
goal := goal'
addedFVars := addedFVars.insert fvarId
let mut diff := {
oldGoal := initialGoal
newGoal := goal
addedFVars
removedFVars := ∅
targetChanged := .false
}
if clear then
let usedPropHyps ← goal.withContext do
usedHyps.filterM λ fvarId => isProof (.fvar fvarId)
let (goal', removedFVars) ← tryClearManyS goal usedPropHyps
let removedFVars := removedFVars.foldl (init := ∅) λ set fvarId =>
set.insert fvarId
goal := goal'
diff := { diff with newGoal := goal, removedFVars }
return { diff }
where
err {α} : MetaM α := throwError
"found no instances of {e} (other than possibly those which had been previously added by forward rules)"
@[inline]
def forwardExpr (e : Expr) (immediate : UnorderedArraySet PremiseIndex)
(clear : Bool) : RuleTac :=
SingleRuleTac.toRuleTac λ input => input.goal.withContext do
let (goal, steps) ←
applyForwardRule input.goal e input.patternSubsts? immediate
(clear := clear) input.options.forwardMaxDepth? input.hypTypes
|>.run
return (#[goal], steps, none)
def forwardConst (decl : Name) (immediate : UnorderedArraySet PremiseIndex)
(clear : Bool) : RuleTac := λ input => do
let e ← mkConstWithFreshMVarLevels decl
forwardExpr e immediate (clear := clear) input
def forwardTerm (stx : Term) (immediate : UnorderedArraySet PremiseIndex)
(clear : Bool) : RuleTac := λ input =>
input.goal.withContext do
let e ← elabRuleTermForApplyLikeMetaM input.goal stx
forwardExpr e immediate (clear := clear) input
def forward (t : RuleTerm) (immediate : UnorderedArraySet PremiseIndex)
(clear : Bool) : RuleTac :=
match t with
| .const decl => forwardConst decl immediate clear
| .term tm => forwardTerm tm immediate clear
def forwardMatches (ms : Array ForwardRuleMatch) : RuleTac :=
SingleRuleTac.toRuleTac λ input => do
let skip type := input.hypTypes.contains type
let mut goal := input.goal
let mut addedFVars := ∅
let mut removedFVars := ∅
let mut anySuccess := false
let mut steps := #[]
for m in ms do
let (some (goal', hyp, removedFVars'), steps') ← m.apply goal (some skip) |>.run
| continue
anySuccess := true
goal := goal'
addedFVars := addedFVars.insert hyp
removedFVars := removedFVars.insertMany removedFVars'
steps := steps ++ steps'
if ! anySuccess then
throwError "failed to add hyps for any of the following forward rule matches:{indentD $ MessageData.joinSep (ms.map toMessageData |>.toList) "\n"}"
let diff := {
oldGoal := input.goal
newGoal := goal
targetChanged := .false
addedFVars, removedFVars
}
return (#[{ diff }], some steps, none)
def forwardMatch (m : ForwardRuleMatch) : RuleTac :=
.forwardMatches #[m]
end Aesop.RuleTac |
.lake/packages/aesop/Aesop/RuleTac/Forward/Basic.lean | module
public import Lean.Meta.Basic
import Aesop.Util.Basic
import Lean.Meta.Tactic.Clear
public section
namespace Aesop
open Lean Lean.Meta
/-
Forward rules must only succeed once for each combination of immediate
hypotheses; otherwise any forward rule could be applied infinitely often (if
it can be applied at all). We use the following scheme to ensure this:
- Whenever we add a hypothesis `h : T` as an instance of a forward rule, we also
add an `implDetail` hypothesis `h' : T`.
- Before we add a hypothesis `h : T`, we check whether there is already an
`implDetail` `h' : T`. If so, `h` is not added.
This scheme ensures that forward rules never add more than one hypothesis of
any given type. `h'` is added as an `implDetail`, rather than as a regular
hypothesis, to ensure that future rule applications do not change its type.
We also encode two pieces of data in the name of `h`: the name `h` and the
*forward depth* of `h`. The forward depth of a hypothesis not generated by
forward reasoning is 0. The forward depth of a hypothesis `h` generated by
forward reasoning is one plus the maximal forward depth of any hypothesis used
in the proof of `h`. The `saturate` tactic uses this information to limit its
reasoning depth.
-/
/-- Prefix of the regular hyps added by `forward`. -/
def forwardHypPrefix := `fwd
/-- Prefix of the `implDetail` hyps added by `forward`. -/
def forwardImplDetailHypPrefix := `__aesop.fwd
/-- Name of the `implDetail` hyp corresponding to the forward `hyp` with name
`fwdHypName` and depth `depth`. -/
def forwardImplDetailHypName (fwdHypName : Name) (depth : Nat) : Name :=
.num forwardImplDetailHypPrefix depth ++ fwdHypName
/--
Parse a name generated by `forwardImplDetailHypName`, obtaining the
`fwdHypName` and `depth`.
-/
def matchForwardImplDetailHypName (n : Name) : Option (Nat × Name) :=
match n.components with
| `__aesop :: `fwd :: .num .anonymous depth :: components =>
let name := Name.ofComponents components
some (depth, name)
| _ => none
/--
Check whether the given name was generated by `forwardImplDetailHypName`.
We assume that nobody else adds hyps with the `forwardImplHypDetailPrefix`
prefix.
-/
def isForwardImplDetailHypName (n : Name) : Bool :=
(`__aesop.fwd).isPrefixOf n
def isForwardImplDetailHyp (ldecl : LocalDecl) : Bool :=
ldecl.isImplementationDetail && isForwardImplDetailHypName ldecl.userName
def getForwardImplDetailHyps : MetaM (Array LocalDecl) := do
let mut result := #[]
for ldecl in ← getLCtx do
if isForwardImplDetailHyp ldecl then
result := result.push ldecl
return result
def _root_.Aesop.clearForwardImplDetailHyps (goal : MVarId) : MetaM MVarId :=
goal.withContext do
let hyps ← getForwardImplDetailHyps
goal.tryClearMany $ hyps.map (·.fvarId)
structure ForwardHypData where
/--
Depths of the hypotheses that have already been added by forward reasoning.
-/
depths : Std.HashMap FVarId Nat
def getForwardHypData : MetaM ForwardHypData := do
let ldecls ← getForwardImplDetailHyps
let mut depths := ∅
for ldecl in ldecls do
if let some (depth, name) := matchForwardImplDetailHypName ldecl.userName then
if let some ldecl := (← getLCtx).findFromUserName? name then
depths := depths.insert ldecl.fvarId depth
return { depths }
/--
Mark hypotheses that, according to their name, are forward implementation detail
hypotheses, as implementation details. This is a hack that works around the
fact that certain tactics (particularly anything based on the revert-intro
pattern) can turn implementation detail hyps into regular hyps.
-/
def hideForwardImplDetailHyps (goal : MVarId) : MetaM MVarId :=
goal.withContext do
let mut lctx ← getLCtx
let mut localInsts ← getLocalInstances
let mut anyChange := false
for ldecl in ← getLCtx do
if ! ldecl.isImplementationDetail &&
isForwardImplDetailHypName ldecl.userName then
lctx := lctx.setKind ldecl.fvarId .implDetail
localInsts := localInsts.erase ldecl.fvarId
anyChange := true
if ! anyChange then
return goal
let goal' ← mkFreshExprMVarAt lctx localInsts (← goal.getType)
goal.assign goal'
return goal'.mvarId!
end Aesop |
.lake/packages/aesop/Aesop/BuiltinRules/Intros.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Aesop.Script.SpecificTactics
import Aesop.Frontend.Attribute
public section
open Lean
open Lean.Meta
namespace Aesop.BuiltinRules
@[aesop norm -100 (rule_sets := [builtin])]
meta def intros : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let md? := input.options.introsTransparency?
let ((goal, newFVarIds), steps) ←
match md? with
| none => introsS input.goal |>.run
| some md => introsUnfoldingS input.goal md |>.run
if newFVarIds.size == 0 then
throwError "nothing to introduce"
let addedFVars := newFVarIds.foldl (init := ∅) λ set fvarId =>
set.insert fvarId
let diff := {
oldGoal := input.goal
newGoal := goal
addedFVars
removedFVars := ∅
targetChanged := .true
}
return (#[{ diff }], steps, none)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/DestructProducts.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Aesop.Script.ScriptM
import Aesop.Frontend.Attribute
import Aesop.Script.ScriptM
public meta import Aesop.Script.SpecificTactics
public meta import Lean.Meta.Tactic.Apply
public meta import Lean.Meta.Tactic.Revert
public meta import Lean.Meta.Tactic.Intro
public section
open Lean Lean.Meta Aesop.Script
namespace Aesop.BuiltinRules
private meta def destructProductHyp? (goal : MVarId) (hyp : FVarId)
(md : TransparencyMode) : MetaM (Option (LazyStep × MVarId)) :=
goal.withContext do
let hypType ← hyp.getType
let (f, args) ← withTransparency md $ getAppUpToDefeq hypType
match args with
| #[α, β] =>
match f with
| (.const ``And _) =>
go hypType (.const ``And.casesOn [← mkFreshLevelMVar]) α β
``And.intro `left `right
| (.const ``Prod lvls) =>
go hypType (.const ``Prod.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``Prod.mk `fst `snd
| (.const ``PProd lvls) =>
go hypType (.const ``PProd.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``PProd.mk `fst `snd
| (.const ``MProd lvls) =>
go hypType (.const ``MProd.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``MProd.mk `fst `snd
| (.const ``Exists lvls) =>
go hypType (.const ``Exists.casesOn lvls) α β ``Exists.intro `w `h
| (.const ``Subtype lvls) =>
go hypType (.const ``Subtype.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``Subtype.mk `val `property
| (.const ``Sigma lvls) =>
go hypType (.const ``Sigma.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``Sigma.mk `fst `snd
| (.const ``PSigma lvls) =>
go hypType (.const ``PSigma.casesOn ((← mkFreshLevelMVar) :: lvls)) α β
``PSigma.mk `fst `snd
| _ => return none
| _ => return none
where
-- `rec` is the partially applied recursor. Missing arguments to `rec` are
-- the motive, the hypothesis and the new proof.
go (hypType rec lType rType : Expr) (ctor lName rName : Name) :
MetaM (LazyStep × MVarId) := do
let (step, mvarId, _) ← LazyStep.build goal {
tac := tac hypType rec lType rType lName rName
postGoals := (#[·.1])
tacticBuilder := λ (_, lName, rName) =>
TacticBuilder.obtain goal (.fvar hyp)
{ ctor, args := #[lName, rName], hasImplicitArg := false }
}
return (step, mvarId)
tac (hypType rec lType rType : Expr) (lName rName : Name) :
MetaM (MVarId × Name × Name) := do
let (genHyps, goal) ← goal.revert #[hyp] (preserveOrder := true)
let (hyp, goal) ← intro1Core goal (preserveBinderNames := true)
let hypExpr := mkFVar hyp
let tgt ← instantiateMVars (← goal.getType)
let motive := mkLambda `h .default hypType $ tgt.abstract #[hypExpr]
let prf := mkApp4 rec lType rType motive hypExpr
goal.withContext $ check prf
let [goal] ← goal.apply prf
| throwError "destructProducts: apply did not return exactly one goal"
let goal ← goal.clear hyp
let lctx := (← goal.getDecl).lctx
-- The following is only valid if `lName` and `rName` are distinct.
-- Otherwise they could yield two identical unused names.
let lName := lctx.getUnusedName lName
let rName := lctx.getUnusedName rName
let (_, goal) ← goal.introN 2 [lName, rName]
let (_, goal) ← introNCore goal (genHyps.size - 1) []
(preserveBinderNames := true) (useNamesForExplicitOnly := false)
return (goal, lName, rName)
meta def destructProductsCore (goal : MVarId) (md : TransparencyMode) :
BaseM (MVarId × Array LazyStep) := do
let result ← go 0 goal |>.run
if result.fst == goal then
throwError "destructProducts: found no hypothesis with a product-like type"
return result
where
go (i : Nat) (goal : MVarId) : ScriptM MVarId := do
withIncRecDepth $ goal.withContext do
let lctx ← getLCtx
if h : i < lctx.decls.size then
match lctx.decls[i] with
| none => go (i + 1) goal
| some ldecl =>
if ldecl.isImplementationDetail then
go (i + 1) goal
else
let result? ← destructProductHyp? goal ldecl.fvarId md
if let some (newScriptStep, newGoal) := result? then
recordScriptStep newScriptStep
go i newGoal
else
go (i + 1) goal
else
return goal
-- This tactic splits hypotheses of product-like types: `And`, `Prod`, `PProd`,
-- `MProd`, `Exists`, `Subtype`, `Sigma` and `PSigma`. It's a restricted version
-- of `cases`. We have this separate tactic because `cases` interacts badly with
-- metavariables and therefore can't be used for norm rules.
--
-- NOTE: If `destructProductsTransparency` != `.reducible`, then this rule is
-- moved from the by-hyp index to the unindexed rules. The rule is identified by
-- name, so if you change its name, you must also adjust the function
-- responsible for dynamically unindexing rules.
@[aesop norm 0 (rule_sets := [builtin]) tactic
(index := [hyp And _ _, hyp Prod _ _, hyp PProd _ _, hyp MProd _ _,
hyp Exists _, hyp Subtype _, hyp Sigma _, hyp PSigma _])]
meta def destructProducts : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let md := input.options.destructProductsTransparency
let (goal, steps) ← destructProductsCore input.goal md
return (#[{ diff := ← diffGoals input.goal goal }], steps, none)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/Split.lean | module
public meta import Aesop.RuleTac.Basic
public import Aesop.Script.ScriptM
public meta import Aesop.Script.SpecificTactics
import Aesop.Frontend.Attribute
import Aesop.Script.SpecificTactics
public section
open Lean
open Lean.Meta
namespace Aesop.BuiltinRules
@[aesop (rule_sets := [builtin]) safe 100]
meta def splitTarget : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let (some goals, steps) ← splitTargetS? input.goal |>.run | throwError
"nothing to split in target"
let goals ← goals.mapM (mvarIdToSubgoal input.goal ·)
return (goals, steps, none)
meta def splitHypothesesCore (goal : MVarId) :
ScriptM (Option (Array MVarId)) :=
withIncRecDepth do
let some goals ← splitFirstHypothesisS? goal
| return none
let mut subgoals := #[]
for g in goals do
if let some subgoals' ← splitHypothesesCore g then
subgoals := subgoals ++ subgoals'
else
subgoals := subgoals.push g
return subgoals
@[aesop (rule_sets := [builtin]) safe 1000]
meta def splitHypotheses : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let (some goals, steps) ← splitHypothesesCore input.goal |>.run
| throwError "no splittable hypothesis found"
let goals ← goals.mapM (mvarIdToSubgoal input.goal ·)
return (goals, steps, none)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/Rfl.lean | module
public meta import Aesop.RuleTac.Basic
import Aesop.Frontend.Attribute
public section
open Lean Lean.Elab.Tactic
namespace Aesop.BuiltinRules
@[aesop safe 0 (rule_sets := [builtin])]
meta def rfl : RuleTac :=
RuleTac.ofTacticSyntax λ _ => `(tactic| rfl)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/Assumption.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Batteries.Lean.Meta.InstantiateMVars
import Aesop.Frontend.Attribute
public meta import Aesop.Script.SpecificTactics
public section
open Lean
open Lean.Meta
namespace Aesop.BuiltinRules
@[aesop safe -50 (rule_sets := [builtin])]
meta def assumption : RuleTac := λ input => do
let goal := input.goal
let md := input.options.assumptionTransparency
goal.withContext do
goal.checkNotAssigned `Aesop.BuiltinRules.assumption
goal.instantiateMVars
let tgt ← goal.getType
let tgtHasMVar := tgt.hasMVar
let initialState ← saveState
let mut applications := #[]
for ldecl in ← getLCtx do
if ldecl.isImplementationDetail then
continue
restoreState initialState
let (some (application, proofHasMVar)) ← tryHyp goal ldecl.fvarId md
| continue
if ! tgtHasMVar && ! proofHasMVar then
applications := #[application]
break
else
applications := applications.push application
if applications.isEmpty then
throwTacticEx `Aesop.BuiltinRules.assumption goal "no matching assumption found"
return ⟨applications⟩
where
tryHyp (goal : MVarId) (fvarId : FVarId) (md : TransparencyMode) :
BaseM (Option (RuleApplication × Bool)) := do
let (true, steps) ← tryExactFVarS goal fvarId md |>.run
| return none
let #[step] := steps
| throwError "aesop: internal error in assumption: multiple steps"
let proofHasMVar := (← fvarId.getType).hasMVar
let app := {
goals := #[]
postState := step.postState
scriptSteps? := #[step]
successProbability? := none
}
return some (app, proofHasMVar)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/Ext.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Aesop.Script.SpecificTactics
public meta import Batteries.Lean.Meta.Basic
import Aesop.Frontend.Attribute
public section
namespace Aesop.BuiltinRules
open Lean Lean.Meta
meta def extCore (goal : MVarId) : ScriptM (Option (Array MVarId)) :=
saturate1 goal λ goal => do
let r ← straightLineExtS goal
if r.depth == 0 then
return none
else
return r.goals.map (·.1)
@[aesop 80% tactic (index := [target _ = _]) (rule_sets := [builtin])]
meta def ext : RuleTac := RuleTac.ofSingleRuleTac λ input => do
let (some goals, steps) ← extCore input.goal |>.run
| throwError "found no applicable ext lemma"
let goals ← goals.mapM (mvarIdToSubgoal (parentMVarId := input.goal) ·)
return (goals, steps, none)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/Subst.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Aesop.Script.SpecificTactics
public meta import Aesop.RuleTac.Forward.Basic
import Aesop.Frontend.Attribute
import Aesop.Script.SpecificTactics
public section
open Lean Lean.Meta Aesop.Script
namespace Aesop.BuiltinRules
meta def matchSubstitutableIff? (e : Expr) : Option (Expr × Expr) := do
let some (lhs, rhs) := e.iff?
| failure
if lhs.isFVar || rhs.isFVar then
return (lhs, rhs)
else
failure
meta def prepareIff? (mvarId : MVarId) (fvarId : FVarId) :
ScriptM (Option (MVarId × FVarId)) :=
mvarId.withContext do
let ty ← fvarId.getType
let some (lhs, rhs) ← matchHelper? ty (pure ∘ matchSubstitutableIff?)
| return none
let eqPrf ← mkPropExt (.fvar fvarId)
let eqType ← mkEq lhs rhs
let preState ← show MetaM _ from saveState
let (newMVarId, newFVarId, clearSuccess) ←
replaceFVarS mvarId fvarId eqType eqPrf
if ! clearSuccess then
preState.restore
return none
return some (newMVarId, newFVarId)
meta def prepareIffs (mvarId : MVarId) (fvarIds : Array FVarId) :
ScriptM (MVarId × Array FVarId) := do
let mut mvarId := mvarId
let mut newFVarIds := Array.mkEmpty fvarIds.size
for fvarId in fvarIds do
if let some (newMVarId, newFVarId) ← prepareIff? mvarId fvarId then
mvarId := newMVarId
newFVarIds := newFVarIds.push newFVarId
else
newFVarIds := newFVarIds.push fvarId
return (mvarId, newFVarIds)
meta def substEqs? (goal : MVarId) (fvarIds : Array FVarId) :
ScriptM (Option MVarId) := do
let preGoal := goal
let preState ← show MetaM _ from saveState
let userNames ← goal.withContext do fvarIds.mapM (·.getUserName)
let mut goal := goal
let mut substitutedUserNames := Array.mkEmpty userNames.size
for userName in userNames do
let ldecl ← goal.withContext $ getLocalDeclFromUserName userName
if let some goal' ← subst? goal ldecl.fvarId then
goal := goal'
substitutedUserNames := substitutedUserNames.push userName
if goal == preGoal then
return none
goal ← hideForwardImplDetailHyps goal -- HACK
let postState ← show MetaM _ from saveState
recordScriptStep {
postGoals := #[goal]
tacticBuilders := #[TacticBuilder.substFVars' substitutedUserNames]
preGoal, preState, postState
}
return goal
meta def substEqsAndIffs? (goal : MVarId) (fvarIds : Array FVarId) :
ScriptM (Option MVarId) := do
let preState ← show MetaM _ from saveState
let (goal, fvarIds) ← prepareIffs goal fvarIds
if let some goal ← substEqs? goal fvarIds then
return goal
else
preState.restore
return none
@[aesop (rule_sets := [builtin]) norm -50 tactic (index := [hyp _ = _, hyp _ ↔ _])]
meta def subst : RuleTac := RuleTac.ofSingleRuleTac λ input =>
input.goal.withContext do
let hyps ← input.indexMatchLocations.mapM λ
| .hyp ldecl => pure ldecl.fvarId
| _ => throwError "unexpected index match location"
let (some goal, steps) ← substEqsAndIffs? input.goal hyps |>.run
| throwError "no suitable hypothesis found"
-- TODO we can construct a better diff here, and doing so would be important
-- since `subst` often renames fvars.
let goal ← mvarIdToSubgoal input.goal goal
return (#[goal], steps, none)
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/BuiltinRules/ApplyHyps.lean | module
public meta import Aesop.RuleTac.Basic
public meta import Aesop.Script.SpecificTactics
import Aesop.Frontend.Attribute
public section
namespace Aesop.BuiltinRules
open Lean
open Lean.Meta
meta def applyHyp (hyp : FVarId) (goal : MVarId) (md : TransparencyMode) :
BaseM RuleApplication := do
let (goals, #[step]) ← applyS goal (.fvar hyp) none md |>.run
| throwError "aesop: internal error in applyHyps: multiple steps"
return {
goals := goals.map λ mvarId => { diff := .empty goal mvarId }
postState := step.postState
scriptSteps? := #[step]
successProbability? := none
}
@[aesop unsafe 75% tactic (rule_sets := [builtin])]
meta def applyHyps : RuleTac := λ input =>
input.goal.withContext do
let lctx ← getLCtx
let md := input.options.applyHypsTransparency
let mut rapps := Array.mkEmpty lctx.decls.size
for localDecl in lctx do
if localDecl.isImplementationDetail then continue
let initialState ← saveState
try
let rapp ← applyHyp localDecl.fvarId input.goal md
rapps := rapps.push rapp
catch _ => continue
finally restoreState initialState
return ⟨rapps⟩
end Aesop.BuiltinRules |
.lake/packages/aesop/Aesop/Index/DiscrKeyConfig.lean | import Lean
open Lean Lean.Meta
namespace Aesop
/-- The configuration used by all Aesop indices. -/
-- I don't really know what I'm doing here. I'm just copying the config used
-- by `simp`; see `Meta/Simp/Types.lean:mkIndexConfig`.
def indexConfig : ConfigWithKey :=
({ proj := .no, transparency := .reducible : Config }).toConfigWithKey
def mkDiscrTreePath (e : Expr) : MetaM (Array DiscrTree.Key) :=
withConfigWithKey indexConfig $ DiscrTree.mkPath e
def getUnify (t : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withConfigWithKey indexConfig $ t.getUnify e
def getMatch (t : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withConfigWithKey indexConfig $ t.getMatch e
end Aesop |
.lake/packages/aesop/Aesop/Index/RulePattern.lean | module
public import Aesop.RulePattern
public import Aesop.Util.OrderedHashSet
import Aesop.Index.DiscrTreeConfig
import Batteries.Lean.Meta.DiscrTree
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- A map from rule names to rule pattern substitutions. When run on a goal,
the rule pattern index returns such a map. -/
abbrev RulePatternSubstMap := Std.HashMap RuleName (OrderedHashSet Substitution)
namespace RulePatternSubstMap
/-- Insert an array of rule pattern substitutions into a rule pattern
substitution map. -/
def insertArray (xs : Array (RuleName × Substitution))
(m : RulePatternSubstMap) : RulePatternSubstMap :=
xs.foldl (init := m) λ m (r, inst) =>
match m[r]? with
| none => m.insert r $ (∅ : OrderedHashSet _).insert inst
| some insts => m.insert r $ insts.insert inst
/-- Build a rule pattern substitution map from an array of substitutions. -/
def ofArray (xs : Array (RuleName × Substitution)) : RulePatternSubstMap :=
(∅ : RulePatternSubstMap).insertArray xs
/-- Convert a rule pattern substitution map to a flat array of substitutions. -/
def toFlatArray (m : RulePatternSubstMap) : Array (RuleName × Substitution) :=
m.fold (init := #[]) λ acc r patInsts =>
patInsts.foldl (init := acc) λ acc patInst =>
acc.push (r, patInst)
end RulePatternSubstMap
/-- An entry of the rule pattern index. -/
structure RulePatternIndex.Entry where
/-- The name of the rule to which the pattern belongs. -/
name : RuleName
/-- The rule's pattern. We assume that there is at most one pattern per
rule. -/
pattern : RulePattern
deriving Inhabited
instance : BEq RulePatternIndex.Entry where
beq e₁ e₂ := e₁.name == e₂.name
set_option linter.missingDocs false in
/-- A rule pattern index. Maps expressions `e` to rule patterns that likely
unify with `e`. -/
structure RulePatternIndex where
/-- The index. -/
tree : DiscrTree RulePatternIndex.Entry
/-- `true` iff the index contains no patterns. -/
isEmpty : Bool
deriving Inhabited
namespace RulePatternIndex
instance : EmptyCollection RulePatternIndex :=
⟨⟨{}, true⟩⟩
/-- Add a rule pattern to the index. -/
def add (name : RuleName) (pattern : RulePattern) (idx : RulePatternIndex) :
RulePatternIndex :=
⟨idx.tree.insertCore pattern.discrTreeKeys { name, pattern }, false⟩
/-- Merge two rule pattern indices. Patterns that appear in both indices appear
twice in the result. -/
def merge (idx₁ idx₂ : RulePatternIndex) : RulePatternIndex :=
if idx₁.isEmpty then
idx₂
else if idx₂.isEmpty then
idx₁
else
⟨idx₁.tree.mergePreservingDuplicates idx₂.tree, false⟩
section Get
/-- Get rule pattern substitutions for the patterns that match `e`. -/
def getSingle (e : Expr) (idx : RulePatternIndex) :
BaseM (Array (RuleName × Substitution)) := do
if idx.isEmpty then
return #[]
let ms ← getUnify idx.tree e
ms.filterMapM λ { name := r, pattern } => do
let some subst ← pattern.match e
| return none
return (r, subst)
/-- Get all substitutions of the rule patterns that match a subexpression of
`e`. Subexpressions containing bound variables are not considered. The returned
array may contain duplicates. -/
def getCore (e : Expr) (idx : RulePatternIndex) :
BaseM (Array (RuleName × Substitution)) := do
if idx.isEmpty then
return #[]
let e ← instantiateMVars e
checkCache (β := RulePatternCache.Entry) e λ _ => do
let (_, ms) ← e.forEach getSubexpr |>.run #[]
return ms
where
getSubexpr (e : Expr) :
StateRefT (Array (RuleName × Substitution)) BaseM Unit := do
if e.hasLooseBVars then
-- We don't visit subexpressions with loose bvars. Substitutions
-- derived from such subexpressions would not be valid in the goal's
-- context. E.g. if a rule `(x : T) → P x` has pattern `x` and we
-- have the expression `λ (y : T), y` in the goal, then it makes no
-- sense to match `y` and generate `P y`.
return
let ms ← idx.getSingle e
modifyThe (Array _) (· ++ ms)
@[inherit_doc getCore]
def get (e : Expr) (idx : RulePatternIndex) : BaseM RulePatternSubstMap :=
.ofArray <$> idx.getCore e
/-- Get all substitutions of the rule patterns that match a subexpression of
the given local declaration. Subexpressions containing bound variables are not
considered. -/
def getInLocalDeclCore (acc : RulePatternSubstMap) (ldecl : LocalDecl)
(idx : RulePatternIndex) : BaseM RulePatternSubstMap := do
if idx.isEmpty then
return acc
let mut result := acc
result := result.insertArray $ ← idx.getCore ldecl.toExpr
result := result.insertArray $ ← idx.getCore ldecl.type
if let some val := ldecl.value? then
result := result.insertArray $ ← idx.getCore val
return result
@[inherit_doc getInLocalDeclCore]
def getInLocalDecl (ldecl : LocalDecl) (idx : RulePatternIndex) :
BaseM RulePatternSubstMap :=
idx.getInLocalDeclCore ∅ ldecl
/-- Get all substitutions of the rule patterns that match a subexpression of
a hypothesis or the target. Subexpressions containing bound variables are not
considered. -/
def getInGoal (goal : MVarId) (idx : RulePatternIndex) :
BaseM RulePatternSubstMap :=
goal.withContext do
if idx.isEmpty then
return ∅
let mut result := ∅
for ldecl in (← goal.getDecl).lctx do
unless ldecl.isImplementationDetail do
result ← idx.getInLocalDeclCore result ldecl
result := result.insertArray $ ← idx.getCore (← goal.getType)
return result
end Get
end Aesop.RulePatternIndex |
.lake/packages/aesop/Aesop/Index/DiscrTreeConfig.lean | module
public import Lean.Meta.Basic
public import Lean.Meta.DiscrTreeTypes
import Lean.Meta.DiscrTree
public section
namespace Aesop
open Lean Lean.Meta
/-- The configuration used by all Aesop indices. -/
-- I don't really know what I'm doing here. I'm just copying the config used
-- by `simp`; see `Meta/Simp/Types.lean:mkIndexConfig`.
def indexConfig : ConfigWithKey :=
({ proj := .no, transparency := .reducible : Config }).toConfigWithKey
def mkDiscrTreePath (e : Expr) : MetaM (Array DiscrTree.Key) :=
withConfigWithKey indexConfig $ DiscrTree.mkPath e
def getUnify (t : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withConfigWithKey indexConfig $ t.getUnify e
def getMatch (t : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withConfigWithKey indexConfig $ t.getMatch e
end Aesop |
.lake/packages/aesop/Aesop/Index/Basic.lean | module
public import Aesop.Forward.Substitution
public section
open Lean Lean.Meta
namespace Aesop
inductive IndexingMode : Type
| unindexed
| target (keys : Array DiscrTree.Key)
| hyps (keys : Array DiscrTree.Key)
| or (imodes : Array IndexingMode)
deriving Inhabited
namespace IndexingMode
protected partial def format : IndexingMode → Format
| unindexed => "unindexed"
| target keys => f!"target {keys}"
| hyps keys => f!"hyps {keys}"
| or imodes => f!"or {imodes.map IndexingMode.format}"
instance : ToFormat IndexingMode :=
⟨IndexingMode.format⟩
def targetMatchingConclusion (type : Expr) : MetaM IndexingMode := do
let path ← getConclusionDiscrTreeKeys type
return target path
def hypsMatchingConst (decl : Name) : MetaM IndexingMode :=
withoutModifyingState do
withReducible do
let c ← mkConstWithFreshMVarLevels decl
let (args, _) ← forallMetaTelescope (← inferType c)
let app := mkAppN c args
hyps <$> DiscrTree.mkPath app
end IndexingMode
/-- The source of a rule match reported by the index. We assume that
only IndexMatchLocations belonging to the same goal are equated or compared. -/
inductive IndexMatchLocation
| none
| target
| hyp (ldecl : LocalDecl)
deriving Inhabited
namespace IndexMatchLocation
instance : ToMessageData IndexMatchLocation where
toMessageData
| none => "none"
| target => "target"
| hyp ldecl => m!"hyp {ldecl.userName}"
instance : BEq IndexMatchLocation where
beq
| none, none => true
| target, target => true
| hyp ldecl₁, hyp ldecl₂ => ldecl₁.index == ldecl₂.index
| _, _ => false
instance : Ord IndexMatchLocation where
compare
| target, target => .eq
| target, none => .lt
| target, hyp .. => .lt
| none, target => .gt
| none, none => .eq
| none, hyp .. => .lt
| hyp .., target => .gt
| hyp .., none => .gt
| hyp ldecl₁, hyp ldecl₂ => compare ldecl₁.index ldecl₂.index
instance : Hashable IndexMatchLocation where
hash
| none => 7
| target => 13
| hyp ldecl => mixHash 17 <| hash ldecl.index
end IndexMatchLocation
/-- A rule that, according to the index, should be applied to the current goal.
In addition to the rule, this data structure contains information about how the
rule should be applied. For example, if the rule has rule patterns, we report
the substitutions obtained by matching the rule patterns against the current
goal. -/
structure IndexMatchResult (α : Type) where
/-- The rule that should be applied. -/
rule : α
/-- Goal locations where the rule matched. The rule's `indexingMode`
determines which locations can be contained in this set. The array contains
no duplicates. -/
locations : Array IndexMatchLocation
/-- Pattern substitutions for this rule that were found in the goal. `none`
iff the rule doesn't have a pattern. The array contains no duplicates. -/
patternSubsts? : Option (Array Substitution)
deriving Inhabited
namespace IndexMatchResult
instance [Ord α] : Ord (IndexMatchResult α) where
compare r s := compare r.rule s.rule
instance [Ord α] : LT (IndexMatchResult α) :=
ltOfOrd
instance [ToMessageData α] : ToMessageData (IndexMatchResult α) where
toMessageData r := toMessageData r.rule
end Aesop.IndexMatchResult |
.lake/packages/aesop/Aesop/Index/Forward.lean | module
public import Aesop.Forward.Match.Types
import Aesop.Index.DiscrTreeConfig
import Batteries.Lean.Meta.DiscrTree
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- Index for forward rules. -/
structure ForwardIndex where
/-- Maps expressions `T` to all tuples `(r, i)` where `r : ForwardRule`,
`i : PremiseIndex` and the `i`-th argument of the type of `r.expr` (counting
from zero) likely unifies with `T`. -/
tree : DiscrTree (ForwardRule × PremiseIndex)
/-- Indexes the forward rules contained in `tree` by name. -/
nameToRule : PHashMap RuleName ForwardRule
/-- Constant forward rules, i.e. forward rules that have no premises and no
rule pattern. -/
constRules : PHashSet ForwardRule
deriving Inhabited
namespace ForwardIndex
instance : EmptyCollection ForwardIndex := by
refine' ⟨{..}⟩ <;> exact {}
/-- Trace the rules contained in `idx` if `traceOpt` is enabled. -/
protected def trace (traceOpt : TraceOption) (idx : ForwardIndex) : CoreM Unit := do
if ! (← traceOpt.isEnabled) then
return
else
have : Ord (ForwardRule × PremiseIndex) := ⟨λ (r₁, _) (r₂, _) => compare r₁ r₂⟩
have : BEq (ForwardRule × PremiseIndex) := ⟨λ (r₁, _) (r₂, _) => r₁ == r₂⟩
let rs := idx.tree.values.qsortOrd.dedupSorted
rs.forM λ (r, _) => do aesop_trace![traceOpt] r
/-- Merge two indices. -/
def merge (idx₁ idx₂ : ForwardIndex) : ForwardIndex where
tree := idx₁.tree.mergePreservingDuplicates idx₂.tree
nameToRule := idx₁.nameToRule.mergeWith idx₂.nameToRule λ _ r₁ _ => r₁
constRules := idx₂.constRules.fold (init := idx₁.constRules) λ s r => s.insert r
/-- Insert a forward rule into the `ForwardIndex`. -/
def insert (r : ForwardRule) (idx : ForwardIndex) : ForwardIndex := Id.run do
if r.isConstant then
return {
idx with
constRules := idx.constRules.insert r
nameToRule := idx.nameToRule.insert r.name r
}
else
let mut tree := idx.tree
for cluster in r.slotClusters do
for slot in cluster do
let some discrTreeKeys := slot.typeDiscrTreeKeys?
| continue
tree := tree.insertCore discrTreeKeys (r, slot.premiseIndex)
let nameToRule := idx.nameToRule.insert r.name r
return { idx with tree, nameToRule }
/-- Get the forward rules whose maximal premises likely unify with `e`.
Each returned pair `(r, i)` contains a rule `r` and the index `i` of the premise
of `r` that likely unifies with `e`. -/
def get (idx : ForwardIndex) (e : Expr) :
MetaM (Array (ForwardRule × PremiseIndex)) :=
getUnify idx.tree e
/-- Get the forward rule with the given rule name. -/
def getRuleWithName? (n : RuleName) (idx : ForwardIndex) : Option ForwardRule :=
idx.nameToRule[n]
/-- Get forward rule matches for the constant forward rules (i.e., those with no
premises and no rule pattern). Accordingly, the returned matches contain no
hypotheses. -/
def getConstRuleMatches (idx : ForwardIndex) : Array ForwardRuleMatch :=
idx.constRules.fold (init := #[]) λ ms r =>
ms.push { rule := r, «match» := ∅ }
end Aesop.ForwardIndex |
.lake/packages/aesop/Aesop/RPINF/Basic.lean | module
public import Lean.Message
import Lean.Expr
import Lean.Util.MonadCache
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- `MData` tag for expressions that are proofs. -/
def mdataPINFIsProofName : Name :=
`Aesop.pinfIsProof
/-- Modify `d` to indicate that the enclosed expression is a proof. -/
def mdataSetIsProof (d : MData) : MData :=
d.insert mdataPINFIsProofName true
/-- Check whether `d` indicates that the enclosed expression is a proof. -/
def mdataIsProof (d : MData) : Bool :=
d.getBool mdataPINFIsProofName (defVal := false)
mutual
/-- Check whether two expressions in PINF are equal. We assume that the two
expressions are type-correct, in PINF and have defeq types. -/
def pinfEqCore : (x y : Expr) → Bool
| .bvar i₁, .bvar i₂ => i₁ == i₂
| .fvar id₁, .fvar id₂
| .mvar id₁, .mvar id₂ => id₁ == id₂
| .sort u, .sort v => u == v
| .const n₁ us, .const n₂ vs => n₁ == n₂ && us == vs
| .app f₁ e₁, .app f₂ e₂ => pinfEq f₁ f₂ && pinfEq e₁ e₂
| .lam _ t₁ e₁ bi₁, .lam _ t₂ e₂ bi₂
| .forallE _ t₁ e₁ bi₁, .forallE _ t₂ e₂ bi₂ => bi₁ == bi₂ && pinfEq t₁ t₂ && pinfEq e₁ e₂
| .letE _ t₁ v₁ e₁ _, .letE _ t₂ v₂ e₂ _ => pinfEq v₁ v₂ && pinfEq t₁ t₂ && pinfEq e₁ e₂
| .lit l₁, .lit l₂ => l₁ == l₂
| .proj n₁ i₁ e₁, .proj n₂ i₂ e₂ => i₁ == i₂ && n₁ == n₂ && pinfEq e₁ e₂
| .mdata d e₁, e₂
| e₁, .mdata d e₂ => mdataIsProof d || pinfEq e₁ e₂
| _, _ => false
@[inherit_doc pinfEqCore]
def pinfEq (x y : Expr) : Bool :=
(unsafe ptrEq x y) || pinfEqCore x y
end
/-- Compute the PINF hash of an expression in PINF. The hash ignores binder
names, binder info and proofs marked by `mdataPINFIsProofName`. -/
partial def pinfHashCore (e : Expr) :
StateRefT (Std.HashMap UInt64 UInt64) (ST s) UInt64 :=
have : MonadHashMapCacheAdapter UInt64 UInt64
(StateRefT (Std.HashMap UInt64 UInt64) (ST s)) := {
getCache := get
modifyCache := modify
}
checkCache e.hash λ _ => do
match e with
| .app .. =>
let h ← pinfHashCore e.getAppFn
e.getAppArgs.foldlM (init := h) λ h arg =>
return mixHash h (← pinfHashCore arg)
| .lam _ t b _ | .forallE _ t b _ =>
return mixHash (← pinfHashCore t) (← pinfHashCore b)
| .letE _ t v b _ =>
return mixHash (← pinfHashCore t) $
mixHash (← pinfHashCore v) (← pinfHashCore b)
| .proj t i e =>
return mixHash (← pinfHashCore e) $ mixHash (hash t) (hash i)
| .mdata d e => if mdataIsProof d then return 13 else pinfHashCore e
| .sort .. | .mvar .. | .lit .. | .const .. | .fvar .. | .bvar .. =>
return e.hash
@[inherit_doc pinfHashCore]
def pinfHash (e : Expr) : UInt64 :=
runST λ _ => pinfHashCore e |>.run' ∅
set_option linter.missingDocs false in
/-- An expression in PINF at transparency `md`. -/
structure PINFRaw (md : TransparencyMode) where
toExpr : Expr
deriving Inhabited
instance : BEq (PINFRaw md) where
beq x y := pinfEq x.toExpr y.toExpr
instance : Hashable (PINFRaw md) where
hash x := pinfHash x.toExpr
instance : ToString (PINFRaw md) where
toString x := toString x.toExpr
instance : ToFormat (PINFRaw md) where
format x := format x.toExpr
instance : ToMessageData (PINFRaw md) where
toMessageData x := toMessageData x.toExpr
/-- An expression in PINF at `reducible` transparency. -/
abbrev RPINFRaw := PINFRaw .reducible
set_option linter.missingDocs false in
/-- Cache for `rpinf`. -/
structure RPINFCache where
map : Std.HashMap Expr RPINFRaw
deriving Inhabited
instance : EmptyCollection RPINFCache :=
⟨⟨∅⟩⟩
set_option linter.missingDocs false in
/-- An expression in PINF at transparency `md`, together with its PINF hash as
computed by `pinfHash`. -/
structure PINF (md : TransparencyMode) where
toExpr : Expr
hash : UInt64
deriving Inhabited
instance : BEq (PINF md) where
beq x y := pinfEq x.toExpr y.toExpr
instance : Hashable (PINF md) where
hash x := x.hash
instance : Ord (PINF md) where
compare x y :=
if x == y then .eq else if x.toExpr.lt y.toExpr then .lt else .gt
instance : ToString (PINF md) where
toString x := toString x.toExpr
instance : ToFormat (PINF md) where
format x := format x.toExpr
instance : ToMessageData (PINF md) where
toMessageData x := toMessageData x.toExpr
/-- An expression in RPINF together with its RPINF hash. -/
abbrev RPINF := PINF .reducible
end Aesop |
.lake/packages/aesop/Aesop/Builder/NormSimp.lean | module
public import Aesop.Builder.Basic
import Aesop.RuleTac.ElabRuleTerm
public section
open Lean
open Lean.Meta
namespace Aesop
private def getSimpEntriesFromPropConst (decl : Name) :
MetaM (Array SimpEntry) := do
let thms ← ({} : SimpTheorems).addConst decl
return SimpTheorems.simpEntries thms
private def getSimpEntriesForConst (decl : Name) : MetaM (Array SimpEntry) := do
let info ← getConstInfo decl
let mut thms : SimpTheorems := {}
if (← isProp info.type) then
thms ← thms.addConst decl
else if info.hasValue then
thms ← thms.addDeclToUnfold decl
return SimpTheorems.simpEntries thms
def PhaseSpec.getSimpPrio [Monad m] [MonadError m] : PhaseSpec → m Nat
| .norm info =>
if info.penalty ≥ 0 then
return info.penalty.toNat
else
throwError "aesop: simp rules must be given a non-negative integer priority"
| _ => throwError "aesop: simp builder can only construct 'norm' rules"
namespace RuleBuilder
def simpCore (decl : Name) (phase : PhaseSpec) : MetaM LocalRuleSetMember :=
withExceptionTransform (λ msg => m!"aesop: simp builder: exception while trying to add {decl} as a simp theorem:{indentD msg}") do
let entries ← getSimpEntriesForConst decl
let prio ← phase.getSimpPrio
let entries := entries.map (updateSimpEntryPriority prio)
let name :=
{ name := decl, scope := .global, builder := .simp, phase := .norm }
return .global $ .normSimpRule { name, entries }
def simp : RuleBuilder := λ input => do
if let some decl ← elabGlobalRuleIdent? input.term then
simpCore decl input.phase
else
checkElabRuleTermForSimp input.term (isSimpAll := true) -- TODO (isSimpAll := true) correct?
return .localNormSimpRule {
id := ← mkFreshId
simpTheorem := input.term
}
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Cases.lean | module
public import Aesop.Builder.Basic
import Aesop.Index.DiscrTreeConfig
import Aesop.RuleTac.Cases
import Batteries.Lean.Expr
public section
open Lean
open Lean.Meta
namespace Aesop
namespace CasesPattern
def check (decl : Name) (p : CasesPattern) : MetaM Unit :=
withoutModifyingState do
let p ← p.toExpr
unless p.isAppOf' decl do
throwError "expected pattern '{p}' ({toString p}) to be an application of '{decl}'"
def toIndexingMode (p : CasesPattern) : MetaM IndexingMode :=
withoutModifyingState do .hyps <$> mkDiscrTreePath (← p.toExpr)
end CasesPattern
namespace RuleBuilderOptions
def casesTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.transparency?.getD .reducible
def casesIndexTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.indexTransparency?.getD .reducible
def casesPatterns (opts : RuleBuilderOptions) : Array CasesPattern :=
opts.casesPatterns?.getD #[]
end RuleBuilderOptions
namespace RuleBuilder
def mkCasesTarget (decl : Name) (casesPatterns : Array CasesPattern) :
CasesTarget :=
if casesPatterns.isEmpty then
.decl decl
else
.patterns casesPatterns
def getCasesIndexingMode (decl : Name) (indexMd : TransparencyMode)
(casesPatterns : Array CasesPattern) : MetaM IndexingMode := do
if indexMd != .reducible then
return .unindexed
if casesPatterns.isEmpty then
IndexingMode.hypsMatchingConst decl
else
.or <$> casesPatterns.mapM (·.toIndexingMode)
/-- `decl` is either the name of the inductive type described by `info`, or a
type synonym for it at transparency `default` or `md` (whichever is larger). -/
def casesCore (decl : Name) (info : InductiveVal) (pats : Array CasesPattern)
(imode? : Option IndexingMode) (md indexMd : TransparencyMode)
(phase : PhaseSpec) : MetaM LocalRuleSetMember := do
pats.forM (·.check decl)
let imode ← imode?.getDM $ getCasesIndexingMode decl indexMd pats
let target := mkCasesTarget decl pats
let ctorNames ← mkCtorNames info
let tac := .cases target md info.isRec ctorNames
return .global $ .base $ phase.toRule decl .cases .global tac imode none
def cases : RuleBuilder := λ input => do
let opts := input.options
if input.phase.phase == .norm then throwError
"aesop: cases builder cannot currently be used for norm rules."
-- TODO `Meta.cases` may assign and introduce metavariables.
-- (Specifically, it can *replace* existing metavariables, which Aesop
-- counts as an assignment and an introduction.)
let (decl, info) ← elabInductiveRuleIdent .cases input.term opts.casesTransparency
casesCore decl info opts.casesPatterns opts.indexingMode? opts.casesTransparency
opts.casesIndexTransparency input.phase
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Apply.lean | module
public import Aesop.Builder.Basic
import Aesop.RuleTac.ElabRuleTerm
import Batteries.Lean.Expr
import Lean.Meta.MatchUtil
public section
open Lean
open Lean.Meta
namespace Aesop
namespace RuleBuilderOptions
def applyTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.transparency?.getD .default
def applyIndexTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.indexTransparency?.getD .reducible
end RuleBuilderOptions
namespace RuleBuilder
def getApplyIndexingMode (indexMd : TransparencyMode) (type : Expr) :
MetaM IndexingMode :=
if indexMd != .reducible then
return .unindexed
else
IndexingMode.targetMatchingConclusion type
def checkNoIff (type : Expr) : MetaM Unit := do
if aesop.warn.applyIff.get (← getOptions) then
forallTelescope type λ _ conclusion => do
if ← testHelper conclusion λ e => return e.isAppOf' ``Iff then
logWarning m!"Apply builder was used for a theorem with conclusion A ↔ B.\nYou probably want to use the simp builder or create an alias that applies the theorem in one direction.\nUse `set_option aesop.warn.applyIff false` to disable this warning."
def applyCore (t : ElabRuleTerm) (pat? : Option RulePattern)
(imode? : Option IndexingMode) (md indexMd : TransparencyMode)
(phase : PhaseSpec) : MetaM LocalRuleSetMember := do
let e ← t.expr
let type ← inferType e
let imode ← imode?.getDM $ getApplyIndexingMode indexMd type
let tac := .apply t.toRuleTerm md
return .global $ .base $ phase.toRule (← t.name) .apply t.scope tac imode pat?
def apply : RuleBuilder := λ input => do
let opts := input.options
let e ← elabRuleTermForApplyLike input.term
let t := ElabRuleTerm.ofElaboratedTerm input.term e
let type ← inferType e
checkNoIff type
let pat? ← opts.pattern?.mapM (RulePattern.elab · e)
applyCore t pat? opts.indexingMode? opts.applyTransparency
opts.applyIndexTransparency input.phase
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Unfold.lean | module
public import Aesop.Builder.Basic
import Aesop.Util.Unfold
public section
open Lean
open Lean.Meta
namespace Aesop.RuleBuilder
-- Somewhat inefficient since `foldConsts` doesn't short-circuit.
def hasConst (c : Name) (e : Expr) : Bool :=
e.foldConsts (init := false) λ c' acc => acc || c' == c
def checkUnfoldableConst (decl : Name) : MetaM (Option Name) :=
withoutModifyingState do
let e ← mkConstWithFreshMVarLevels decl
let t := (← getConstInfo decl).type
let unfoldThm? ← getUnfoldEqnFor? decl
forallTelescope t λ args _ => do
let testExpr := mkAppN e args
let unfoldResult ←
unfoldMany (if · == decl then some unfoldThm? else none) testExpr
match unfoldResult with
| none =>
throwError "Declaration '{decl}' cannot be unfolded."
| some (e', _) =>
if hasConst decl e' then
throwError "Recursive definition '{decl}' cannot be used as an unfold rule (it would be unfolded infinitely often). Try adding a simp rule for it."
return unfoldThm?
def unfoldCore (decl : Name) : MetaM LocalRuleSetMember := do
let unfoldThm? ← checkUnfoldableConst decl
return .global $ .base $ .unfoldRule { decl, unfoldThm? }
-- TODO support local unfold rules
def unfold : RuleBuilder := λ input => do
let decl ← elabGlobalRuleIdent .unfold input.term
unfoldCore decl
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Default.lean | module
public import Aesop.Builder.Basic
import Aesop.Builder.Apply
import Aesop.Builder.Constructors
import Aesop.Builder.NormSimp
import Aesop.Builder.Tactic
public section
open Lean
open Lean.Meta
namespace Aesop
-- TODO In the default builders below, we should distinguish between fatal and
-- nonfatal errors. E.g. if the `tactic` builder finds a declaration that is not
-- of tactic type, this is a nonfatal error and we should continue with the next
-- builder. But if the simp builder finds an equation that cannot be interpreted
-- as a simp lemma for some reason, this is a fatal error. Continuing with the
-- next builder is more confusing than anything because the user probably
-- intended to add a simp lemma.
def RuleBuilder.default : RuleBuilder := λ input =>
match input.phase.phase with
| .safe =>
constructors input <|>
tactic input <|>
apply input <|>
err "a safe" input
| .unsafe =>
constructors input <|>
tactic input <|>
apply input <|>
err "an unsafe" input
| .norm =>
constructors input <|>
tactic input <|>
simp input <|>
apply input <|>
err "a norm" input
where
err (ruleType : String) : RuleBuilder := λ input =>
throwError m!"aesop: Unable to interpret '{input.term}' as {ruleType} rule. Try specifying a builder."
end Aesop |
.lake/packages/aesop/Aesop/Builder/Basic.lean | module
public import Aesop.RuleSet.Member
public import Aesop.ElabM
import Aesop.RuleTac.ElabRuleTerm
public section
open Lean Lean.Meta Lean.Elab.Term
namespace Aesop
/--
Options for the builders. Most options are only relevant for certain builders.
-/
structure RuleBuilderOptions where
immediatePremises? : Option (Array Name)
indexingMode? : Option IndexingMode
casesPatterns? : Option (Array CasesPattern)
pattern? : Option Term
/-- The transparency used by the rule tactic. -/
transparency? : Option TransparencyMode
/-- The transparency used for indexing the rule. Currently, the rule is not
indexed unless this is `.reducible`. -/
indexTransparency? : Option TransparencyMode
deriving Inhabited
namespace RuleBuilderOptions
protected def default : RuleBuilderOptions :=
⟨none, none, none, none, none, none⟩
instance : EmptyCollection RuleBuilderOptions :=
⟨.default⟩
end RuleBuilderOptions
structure CoreRuleBuilderOutput where
ruleExprName : Name
builderName : BuilderName
scopeName : ScopeName
tac : RuleTacDescr
indexingMode : IndexingMode
pattern? : Option RulePattern
inductive PhaseSpec
| safe (info : SafeRuleInfo)
| norm (info : NormRuleInfo)
| «unsafe» (info : UnsafeRuleInfo)
deriving Inhabited
namespace PhaseSpec
def phase : PhaseSpec → PhaseName
| safe .. => .safe
| «unsafe» .. => .unsafe
| norm .. => .norm
def toRule (phase : PhaseSpec) (ruleExprName : Name) (builder : BuilderName)
(scope : ScopeName) (tac : RuleTacDescr) (indexingMode : IndexingMode)
(pattern? : Option RulePattern) : BaseRuleSetMember :=
let name := {
name := ruleExprName
phase := phase.phase
builder, scope
}
match phase with
| .safe info => .safeRule {
extra := info
name, indexingMode, pattern?, tac
}
| .unsafe info => .unsafeRule {
extra := info
name, indexingMode, pattern?, tac
}
| .norm info => .normRule {
extra := info
name, indexingMode, pattern?, tac
}
end PhaseSpec
structure RuleBuilderInput where
term : Term
options : RuleBuilderOptions
phase : PhaseSpec
deriving Inhabited
namespace RuleBuilderInput
def phaseName (input : RuleBuilderInput) : PhaseName :=
input.phase.phase
end RuleBuilderInput
abbrev RuleBuilder := RuleBuilderInput → ElabM LocalRuleSetMember
def elabGlobalRuleIdent (builderName : BuilderName) (term : Term) :
TermElabM Name := do
if let some decl ← elabGlobalRuleIdent? term then
return decl
else
throwError "aesop: {builderName} builder: expected '{term}' to be an unambiguous global constant"
def elabInductiveRuleIdent (builderName : BuilderName) (term : Term) (md : TransparencyMode) :
TermElabM (Name × InductiveVal) := do
if let some info ← elabInductiveRuleIdent? term md then
return info
else
throwError "aesop: {builderName} builder: expected '{term}' to be an inductive type or structure (or to reduce to one at the given transparency)"
end Aesop |
.lake/packages/aesop/Aesop/Builder/Tactic.lean | module
public import Aesop.Builder.Basic
public section
open Lean Lean.Meta
open Lean.Elab.Tactic (TacticM)
open Lean.Parser.Tactic (tacticSeq)
namespace Aesop
def matchByTactic? : Term → Option (TSyntax ``tacticSeq)
| `(by $ts:tacticSeq) => some ts
| _ => none
namespace RuleBuilder
def tacticIMode (imode? : Option IndexingMode) : IndexingMode :=
imode?.getD .unindexed
def tacticCore (t : Sum Name (TSyntax ``tacticSeq)) (imode? : Option IndexingMode) (phase : PhaseSpec) :
MetaM LocalRuleSetMember := do
let imode := imode?.getD .unindexed
match t with
| .inl decl =>
let type := (← getConstInfo decl).type
let tac ←
if ← isDefEq (mkApp (mkConst ``TacticM) (mkConst ``Unit)) type then
pure $ .tacticM decl
else if ← isDefEq (mkConst ``SingleRuleTac) type then
pure $ .singleRuleTac decl
else if ← isDefEq (mkConst ``RuleTac) type then
pure $ .ruleTac decl
else if ← isDefEq (mkConst ``TacGen) type then
pure $ .tacGen decl
else
throwError "aesop: tactic builder: expected {decl} to be a tactic, i.e. to have one of these types:\n TacticM Unit\n SimpleRuleTac\n RuleTac\n TacGen\nHowever, it has type{indentExpr type}"
return .global $ .base $ phase.toRule decl .tactic .global tac imode none
| .inr tacticSeq =>
let name ← mkFreshId
let tac := .tacticStx tacticSeq
return .global $ .base $ phase.toRule name .tactic .global tac imode none
def tactic : RuleBuilder := λ input => do
let opts := input.options
let t ←
if input.term.raw.isIdent then
.inl <$> elabGlobalRuleIdent .tactic input.term
else if let some stx := matchByTactic? input.term then
pure $ .inr stx
else
throwError "aesop: tactic builder: expected '{input.term}' to be a tactic"
tacticCore t opts.indexingMode? input.phase
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Constructors.lean | module
public import Aesop.Builder.Basic
public section
open Lean
open Lean.Meta
namespace Aesop.RuleBuilderOptions
def constructorsTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.transparency?.getD .default
def constructorsIndexTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.indexTransparency?.getD .reducible
end RuleBuilderOptions
namespace RuleBuilder
def getConstructorsIndexingMode (indexMd : TransparencyMode)
(info : InductiveVal) : MetaM IndexingMode := do
if indexMd != .reducible then
return .unindexed
else
let mut imodes := Array.mkEmpty info.numCtors
for ctor in info.ctors do
let ctorInfo ← getConstInfo ctor
let imode ← IndexingMode.targetMatchingConclusion ctorInfo.type
imodes := imodes.push imode
return .or imodes
def constructorsCore (info : InductiveVal) (imode? : Option IndexingMode)
(md indexMd : TransparencyMode) (phase : PhaseSpec) :
MetaM LocalRuleSetMember := do
let tac := .constructors info.ctors.toArray md
let imode ← imode?.getDM $ getConstructorsIndexingMode indexMd info
return .global $ .base $
phase.toRule info.name .constructors .global tac imode none
def constructors : RuleBuilder := λ input => do
let (_, info) ← elabInductiveRuleIdent .constructors input.term .default
let opts := input.options
constructorsCore info opts.indexingMode? opts.constructorsTransparency
opts.constructorsIndexTransparency input.phase
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Builder/Forward.lean | module
public import Aesop.Builder.Basic
import Aesop.Index.DiscrTreeConfig
import Aesop.RuleTac.ElabRuleTerm
import Batteries.Data.Array.Basic
public section
open Lean
open Lean.Meta
namespace Aesop
namespace RuleBuilderOptions
def forwardTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.transparency?.getD .reducible
def forwardIndexTransparency (opts : RuleBuilderOptions) : TransparencyMode :=
opts.indexTransparency?.getD .reducible
end RuleBuilderOptions
namespace RuleBuilder
def getForwardIndexingMode (type : Expr)
(immediate : UnorderedArraySet PremiseIndex) : MetaM IndexingMode := do
let immediate := immediate.toArray.map (·.toNat)
match immediate.max? with
| some i =>
withoutModifyingState do
let (args, _, _) ← withReducible $ forallMetaTelescopeReducing type
match args[i]? with
| some arg =>
let argT := (← arg.mvarId!.getDecl).type
let keys ← mkDiscrTreePath argT
return .hyps keys
| none => throwError
"aesop: internal error: immediate arg for forward rule is out of range"
| none => return .unindexed
def getImmediatePremises (type : Expr) (pat? : Option RulePattern) :
Option (Array Name) → MetaM (UnorderedArraySet PremiseIndex)
| none =>
-- If no immediate names are given, every argument becomes immediate,
-- except instance args, dependent args and args determined by a rule
-- pattern.
withReducible $ forallTelescopeReducing type λ args _ => do
let mut result := #[]
for h : i in [:args.size] do
if isPatternInstantiated i then
continue
let fvarId := args[i].fvarId!
let ldecl ← fvarId.getDecl
let isNondep : MetaM Bool :=
args.allM (start := i + 1) λ arg => do
let type ← instantiateMVars (← arg.fvarId!.getDecl).type
return ! type.containsFVar fvarId
if ← pure ! ldecl.binderInfo.isInstImplicit <&&> isNondep then
result := result.push ⟨i⟩
return UnorderedArraySet.ofDeduplicatedArray result
| some immediate =>
-- If immediate names are given, we check that corresponding arguments
-- exists and record these arguments' positions.
withReducible $ forallTelescopeReducing type λ args _ => do
let mut unseen := immediate.sortDedup (ord := ⟨Name.quickCmp⟩)
let mut result := #[]
for h : i in [:args.size] do
let argName := (← args[i].fvarId!.getDecl).userName
if immediate.contains argName then
if isPatternInstantiated i then
throwError "{errPrefix}argument '{argName}' cannot be immediate since it is already determined by a pattern"
else
result := result.push ⟨i⟩
unseen := unseen.erase argName
if ! unseen.isEmpty then throwError
"{errPrefix}function does not have arguments with these names: '{unseen}'"
return UnorderedArraySet.ofDeduplicatedArray result
where
isPatternInstantiated (i : Nat) : Bool :=
let idx? : Option Nat := do ← (← pat?).argMap[i]?
idx?.isSome
errPrefix : MessageData :=
m!"aesop: forward builder: "
def forwardCore₂ (t : ElabRuleTerm) (immediate? : Option (Array Name))
(pat? : Option RulePattern) (phase : PhaseSpec) (isDestruct : Bool) :
MetaM ForwardRule := do
let expr ← t.expr
let name ← t.name
let immediate ← getImmediatePremises (← inferType expr) pat? immediate?
let info ← ForwardRuleInfo.ofExpr expr pat? immediate
aesop_trace[forward] "rule type:{indentExpr $ ← inferType expr}"
withConstAesopTraceNode .forward (return m!"slot clusters") do
aesop_trace[forward] do
for h : i in [:info.slotClusters.size] do
let cluster := info.slotClusters[i]
withConstAesopTraceNode .forward (return m!"cluster {i}") do
for s in cluster do
aesop_trace![forward] "slot {s.index} (premise {s.premiseIndex}, deps {s.deps.toArray.qsortOrd}, common {s.common.toArray.qsortOrd}, forward deps {s.forwardDeps.qsortOrd})"
aesop_trace[forward] "conclusion deps: {info.conclusionDeps}"
let prio :=
match phase with
| .safe info => .normSafe info.penalty
| .norm info => .normSafe info.penalty
| .unsafe info => .unsafe info.successProbability
let builder := if isDestruct then .destruct else .forward
let name := { phase := phase.phase, name, scope := t.scope, builder }
return {
toForwardRuleInfo := info
term := t.toRuleTerm
name, prio
}
def forwardCore (t : ElabRuleTerm) (immediate? : Option (Array Name))
(pat? : Option RulePattern) (phase : PhaseSpec) (isDestruct : Bool) :
MetaM LocalRuleSetMember := do
let builderName : BuilderName := if isDestruct then .destruct else .forward
let type ← inferType (← t.expr)
aesop_trace[debug] "decl type: {type}"
let immediate ← getImmediatePremises type pat? immediate?
aesop_trace[debug] "immediate premises: {immediate}"
let imode ← getForwardIndexingMode type immediate
aesop_trace[debug] "imode: {imode}"
let tac := .forward t.toRuleTerm immediate isDestruct
let member := phase.toRule (← t.name) builderName t.scope tac imode pat?
-- HACK we currently add two rule set members for each forward rule; one
-- normal, tactic-based rule and one `ForwardRule`. Eventually, only the
-- `ForwardRule` will remain.
let forwardRule ← forwardCore₂ t immediate? pat? phase isDestruct
let member :=
match member with
| .normRule r => .normForwardRule forwardRule r
| .safeRule r => .safeForwardRule forwardRule r
| .unsafeRule r => .unsafeForwardRule forwardRule r
| _ => unreachable!
return .global $ .base member
def forward (isDestruct : Bool) : RuleBuilder := λ input => do
withConstAesopTraceNode .debug (return "forward builder") do
let opts := input.options
let e ← elabRuleTermForApplyLike input.term
let t := ElabRuleTerm.ofElaboratedTerm input.term e
let pat? ← opts.pattern?.mapM (RulePattern.elab · e)
forwardCore t opts.immediatePremises? pat? input.phase
(isDestruct := isDestruct)
end Aesop.RuleBuilder |
.lake/packages/aesop/Aesop/Stats/Extension.lean | module
public import Aesop.Stats.Basic
public section
open Lean
namespace Aesop
structure StatsExtensionEntry where
/--
The Aesop call for which stats were collected.
-/
aesopStx : Syntax
/-
The file in which Aesop was called.
-/
fileName : String
/-
The position in the file where Aesop was called.
-/
position? : Option Position
/--
The collected stats.
-/
stats : Stats
namespace StatsExtensionEntry
def forCurrentFile [Monad m] [MonadLog m] (stx : Syntax) (stats : Stats) :
m StatsExtensionEntry := do
let fileName ← getFileName
let fileMap ← getFileMap
let position? := stx.getPos?.map fileMap.toPosition
return { aesopStx := stx, stats, fileName, position? }
end StatsExtensionEntry
abbrev StatsExtension := SimplePersistentEnvExtension StatsExtensionEntry Unit
def StatsExtension.importedEntries (env : Environment) (ext : StatsExtension) :
Array (Array StatsExtensionEntry) :=
ext.toEnvExtension.getState env |>.importedEntries
initialize statsExtension : StatsExtension ←
registerSimplePersistentEnvExtension {
addEntryFn := λ _ _ => ()
addImportedFn := λ _ => ()
asyncMode := .sync -- Maybe we could use a less restrictive mode, but (a) it's not clear to me and (b) this extension is unused by default.
}
def recordStatsIfEnabled [Monad m] [MonadEnv m] [MonadOptions m]
(s : StatsExtensionEntry) : m Unit := do
if ← isStatsCollectionEnabled then
modifyEnv λ env => statsExtension.addEntry env s
def recordStatsForCurrentFileIfEnabled [Monad m] [MonadEnv m] [MonadOptions m]
[MonadLog m] (aesopStx : Syntax) (stats : Stats) : m Unit := do
if ← isStatsCollectionEnabled then
let entry ← StatsExtensionEntry.forCurrentFile aesopStx stats
modifyEnv λ env => statsExtension.addEntry env entry
abbrev StatsArray := Array StatsExtensionEntry
def mkStatsArray (localEntries : List StatsExtensionEntry)
(importedEntries : Array (Array StatsExtensionEntry)) :
StatsArray := Id.run do
let mut result := #[]
for entry in localEntries do
result := result.push entry
for entries in importedEntries do
result := result ++ entries
return result
def getStatsArray [Monad m] [MonadEnv m] : m StatsArray := do
let env ← getEnv
let current := statsExtension.getEntries env
let imported := statsExtension.importedEntries env
return mkStatsArray current imported
end Aesop |
.lake/packages/aesop/Aesop/Stats/Basic.lean | module
public import Aesop.Rule.Name
public import Aesop.Tracing
public import Aesop.Nanos
import Aesop.Util.Basic
public section
open Lean
namespace Aesop
initialize collectStatsOption : Lean.Option Bool ←
Lean.Option.register `aesop.collectStats {
defValue := false
group := "aesop"
descr := "(aesop) collect statistics about Aesop invocations. Use #aesop_stats to display the collected statistics."
}
-- All times are in nanoseconds.
structure RuleStats where
rule : DisplayRuleName
elapsed : Nanos
successful : Bool
deriving Inhabited
namespace RuleStats
instance : ToString RuleStats where
toString rp :=
let success := if rp.successful then "successful" else "failed"
s!"[{rp.elapsed.printAsMillis}] apply rule {rp.rule} ({success})"
end RuleStats
inductive ScriptGenerated
| none
| staticallyStructured (perfect : Bool) (hasMVar : Bool)
| dynamicallyStructured (perfect : Bool) (hasMVar : Bool)
deriving Inhabited
namespace ScriptGenerated
protected def toString : ScriptGenerated → String
| none => "no"
| staticallyStructured perfect _ => s!"with {go perfect} static structuring"
| dynamicallyStructured perfect _ => s!"with {go perfect} dynamic structuring"
where
go b := if b then "perfect" else "imperfect"
def isNontrivial : ScriptGenerated → Bool
| none => false
| staticallyStructured (hasMVar := hasMVar) ..
| dynamicallyStructured (hasMVar := hasMVar) .. => hasMVar
end ScriptGenerated
structure Stats where
total : Nanos
configParsing : Nanos
ruleSetConstruction : Nanos
search : Nanos
ruleSelection : Nanos
script : Nanos
scriptGenerated : ScriptGenerated
ruleStats : Array RuleStats
deriving Inhabited
namespace Stats
protected def empty : Stats where
total := 0
configParsing := 0
ruleSetConstruction := 0
search := 0
ruleSelection := 0
script := 0
scriptGenerated := .none
ruleStats := #[]
instance : EmptyCollection Stats :=
⟨Stats.empty⟩
end Stats
structure RuleStatsTotals where
/--
Number of successful applications of a rule.
-/
numSuccessful : Nat
/--
Number of failed applications of a rule.
-/
numFailed : Nat
/--
Total elapsed time of successful applications of a rule.
-/
elapsedSuccessful : Nanos
/--
Total elapsed time of failed applications of a rule.
-/
elapsedFailed : Nanos
namespace RuleStatsTotals
protected def empty : RuleStatsTotals where
numSuccessful := 0
numFailed := 0
elapsedSuccessful := 0
elapsedFailed := 0
instance : EmptyCollection RuleStatsTotals :=
⟨.empty⟩
def compareByTotalElapsed : (x y : RuleStatsTotals) → Ordering :=
compareOn λ totals => totals.elapsedSuccessful + totals.elapsedFailed
end RuleStatsTotals
namespace Stats
def ruleStatsTotals (p : Stats)
(init : Std.HashMap DisplayRuleName RuleStatsTotals := ∅) :
Std.HashMap DisplayRuleName RuleStatsTotals :=
p.ruleStats.foldl (init := init) λ m rp => Id.run do
let mut stats := m.getD rp.rule ∅
if rp.successful then
stats := { stats with
numSuccessful := stats.numSuccessful + 1
elapsedSuccessful := stats.elapsedSuccessful + rp.elapsed
}
else
stats := { stats with
numFailed := stats.numFailed + 1
elapsedFailed := stats.elapsedFailed + rp.elapsed
}
m.insert rp.rule stats
def _root_.Aesop.sortRuleStatsTotals
(ts : Array (DisplayRuleName × RuleStatsTotals)) :
Array (DisplayRuleName × RuleStatsTotals) :=
let lt := λ (n₁, t₁) (n₂, t₂) =>
RuleStatsTotals.compareByTotalElapsed t₁ t₂ |>.swap.then
(compare n₁ n₂)
|>.isLT
ts.qsort lt
def trace (p : Stats) (opt : TraceOption) : CoreM Unit := do
if ! (← opt.isEnabled) then
return
let totalRuleApplications :=
p.ruleStats.foldl (init := 0) λ total rp =>
total + rp.elapsed
aesop_trace![opt] "Total: {p.total.printAsMillis}"
aesop_trace![opt] "Configuration parsing: {p.configParsing.printAsMillis}"
aesop_trace![opt] "Rule set construction: {p.ruleSetConstruction.printAsMillis}"
aesop_trace![opt] "Script generation: {p.script.printAsMillis}"
aesop_trace![opt] "Script generated: {p.scriptGenerated.toString}"
withConstAesopTraceNode opt (collapsed := false)
(return m!"Search: {p.search.printAsMillis}") do
aesop_trace![opt] "Rule selection: {p.ruleSelection.printAsMillis}"
withConstAesopTraceNode opt (collapsed := false)
(return m!"Rule applications: {totalRuleApplications.printAsMillis}") do
let timings := sortRuleStatsTotals p.ruleStatsTotals.toArray
for (n, t) in timings do
aesop_trace![opt] "[{(t.elapsedSuccessful + t.elapsedFailed).printAsMillis} / {t.elapsedSuccessful.printAsMillis} / {t.elapsedFailed.printAsMillis}] {n}"
end Stats
abbrev StatsRef := IO.Ref Stats
class MonadStats (m) extends MonadOptions m where
modifyGetStats : (Stats → α × Stats) → m α
getStats : m Stats :=
modifyGetStats λ s => (s, s)
modifyStats : (Stats → Stats) → m Unit :=
λ f => modifyGetStats λ s => ((), f s)
export MonadStats (modifyGetStats getStats modifyStats)
instance [MonadStats m] : MonadStats (StateRefT' ω σ m) where
modifyGetStats f := (modifyGetStats f : m _)
getStats := (getStats : m _)
modifyStats f := (modifyStats f : m _)
instance [MonadStats m] : MonadStats (ReaderT α m) where
modifyGetStats f := (modifyGetStats f : m _)
getStats := (getStats : m _)
modifyStats f := (modifyStats f : m _)
instance [MonadOptions m] [MonadStateOf Stats m] : MonadStats m where
modifyGetStats f := modifyGetThe Stats f
getStats := getThe Stats
modifyStats := modifyThe Stats
variable [Monad m]
@[inline, always_inline]
def isStatsCollectionEnabled [MonadOptions m] : m Bool :=
collectStatsOption.get <$> getOptions
@[inline, always_inline]
def isStatsTracingEnabled [MonadOptions m] : m Bool :=
TraceOption.stats.isEnabled
@[inline, always_inline]
def isStatsCollectionOrTracingEnabled [MonadOptions m] : m Bool :=
isStatsCollectionEnabled <||> isStatsTracingEnabled
variable [MonadStats m] [MonadLiftT BaseIO m]
@[inline, always_inline]
def profiling (recordStats : Stats → α → Nanos → Stats) (x : m α) : m α := do
if ← isStatsCollectionOrTracingEnabled then
let (result, elapsed) ← time x
modifyStats (recordStats · result elapsed)
return result
else
x
@[inline, always_inline]
def profilingRuleSelection : m α → m α :=
profiling λ stats _ elapsed =>
{ stats with ruleSelection := stats.ruleSelection + elapsed }
@[inline, always_inline]
def profilingRule (rule : DisplayRuleName) (wasSuccessful : α → Bool) :
m α → m α :=
profiling λ stats a elapsed =>
let rp := { successful := wasSuccessful a, rule, elapsed }
{ stats with ruleStats := stats.ruleStats.push rp }
def modifyCurrentStats (f : Stats → Stats) : m Unit := do
if ← isStatsCollectionEnabled then
modifyStats f
def recordScriptGenerated (x : ScriptGenerated) : m Unit := do
modifyCurrentStats ({ · with scriptGenerated := x })
end Aesop |
.lake/packages/aesop/Aesop/Stats/Report.lean | module
public import Aesop.Percent
public import Aesop.Stats.Extension
public section
open Lean
namespace Aesop
/-- Assumes that `xs` is ascending. We use a simple nearest-rank definition of
percentiles. -/
def sortedPercentileD (p : Percent) (dflt : α) (xs : Array α) : α :=
if xs.size == 0 then
dflt
else
let rank := xs.size.toFloat * p.toFloat |>.ceil.toUInt64.toNat |>.min (xs.size - 1)
xs[rank]?.getD dflt
def sortedMedianD (dflt : α) (xs : Array α) : α :=
sortedPercentileD ⟨0.5⟩ dflt xs
abbrev StatsReport := StatsArray → Format
namespace StatsReport
local instance : ToString Nanos :=
⟨Nanos.printAsMillis⟩
def default : StatsReport := λ statsArray => Id.run do
let mut total := 0
let mut configParsing := 0
let mut ruleSetConstruction := 0
let mut search := 0
let mut ruleSelection := 0
let mut script := 0
let mut ruleStats : Std.HashMap DisplayRuleName RuleStatsTotals := ∅
for stats in statsArray do
let stats := stats.stats
total := total + stats.total
configParsing := configParsing + stats.configParsing
ruleSetConstruction := ruleSetConstruction + stats.ruleSetConstruction
search := search + stats.search
ruleSelection := ruleSelection + stats.ruleSelection
script := script + stats.script
ruleStats := stats.ruleStatsTotals (init := ruleStats)
let samples := statsArray.size
f!"Statistics for {statsArray.size} Aesop calls in current and imported modules\n\
Displaying totals and [averages]\n\
Total Aesop time: {fmtTime total samples}\n\
Config parsing: {fmtTime configParsing samples}\n\
Rule set construction: {fmtTime ruleSetConstruction samples}\n\
Rule selection: {fmtTime ruleSelection samples}\n\
Script generation: {fmtTime script samples}\n\
Search: {fmtTime search samples}\n\
Rules:{Std.Format.indentD $ fmtRuleStats $ sortRuleStatsTotals $ ruleStats.toArray}"
where
fmtTime (n : Nanos) (samples : Nat) : Format :=
f!"{n} [{if samples == 0 then 0 else n / samples}]"
fmtRuleStats (stats : Array (DisplayRuleName × RuleStatsTotals)) :
Format := Id.run do
let fmtSection (n : Nanos) (samples : Nat) : Format :=
f!"{samples} in {fmtTime n samples}"
let mut fmt := f!""
for (name, totals) in stats do
fmt := fmt ++
f!"{name}:\n\
{" "}total: {fmtSection (totals.elapsedSuccessful + totals.elapsedFailed) (totals.numSuccessful + totals.numFailed)}\n\
{" "}successful: {fmtSection totals.elapsedSuccessful totals.numSuccessful}\n\
{" "}failed: {fmtSection totals.elapsedFailed totals.numFailed}\n"
return fmt
def scriptsCore (nSlowest := 30) (nontrivialOnly := false) :
StatsReport := λ statsArray => Id.run do
let statsArray :=
if nontrivialOnly then
statsArray.filter (·.stats.scriptGenerated.isNontrivial)
else
statsArray
let mut staticallyStructured := 0
let mut perfectlyStaticallyStructured := 0
let mut dynamicallyStructured := 0
let mut perfectlyDynamicallyStructured := 0
let mut totalTimes := Array.mkEmpty statsArray.size
let mut scriptTimes := Array.mkEmpty statsArray.size
for stats in statsArray do
let stats := stats.stats
totalTimes := totalTimes.push stats.total
match stats.scriptGenerated with
| .none => pure ()
| .staticallyStructured perfect .. =>
scriptTimes := scriptTimes.push stats.script
staticallyStructured := staticallyStructured + 1
if perfect then
perfectlyStaticallyStructured := perfectlyStaticallyStructured + 1
| .dynamicallyStructured perfect .. =>
scriptTimes := scriptTimes.push stats.script
dynamicallyStructured := dynamicallyStructured + 1
if perfect then
perfectlyDynamicallyStructured := perfectlyDynamicallyStructured + 1
let slowest := statsArray.qsort (λ s₁ s₂ => s₁.stats.script > s₂.stats.script)
let slowest := slowest[:nSlowest].toArray
let nSlowest := min slowest.size nSlowest
let slowestFmt := slowest.map λ e =>
let pos :=
match e.position? with
| some pos => f!"{pos.line}:{pos.column}"
| none => f!"?:?"
f!"{e.fileName}:{pos}: script {e.stats.script}, total {e.stats.total}, type {fmtScriptGenerated e.stats.scriptGenerated}"
f!"Statistics for {statsArray.size} Aesop calls{if nontrivialOnly then f!" with nontrivial script generation" else ""} in current and imported modules\n\
Total Aesop time: {fmtTimes totalTimes}\n\
Script generation time: {fmtTimes scriptTimes}\n\
Scripts generated: {scriptTimes.size}\n\
- Statically structured: {staticallyStructured}\n" ++
f!" - perfectly: {perfectlyStaticallyStructured}\n\
- Dynamically structured: {dynamicallyStructured}\n" ++
f!" - perfectly: {perfectlyDynamicallyStructured}\n\
\n\
{nSlowest} Aesop calls with slowest script generation:\n\
{Format.joinSep slowestFmt.toList "\n"}"
where
fmtScriptGenerated : ScriptGenerated → Format
| .none => "<none>"
| .staticallyStructured perfect _ => f!"static (perfect: {perfect})"
| .dynamicallyStructured perfect _ => f!"dynamic (perfect: {perfect})"
fmtTimes (ns : Array Nanos) : Format :=
let ns := ns.qsortOrd
let total : Nanos := ns.foldl (init := 0) (· + ·)
let average := if ns.size == 0 then 0 else total / ns.size
let min := ns[0]?.getD 0
let max := ns[ns.size - 1]?.getD 0
let median := sortedMedianD 0 ns
let pct80 := sortedPercentileD ⟨0.80⟩ 0 ns
let pct95 := sortedPercentileD ⟨0.95⟩ 0 ns
let pct99 := sortedPercentileD ⟨0.99⟩ 0 ns
f!"{total} (min = {min}, avg = {average}, median = {median}, 80pct = {pct80}, 95pct = {pct95}, 99pct = {pct99}, max = {max})"
def scripts := scriptsCore
def scriptsNontrivial := scriptsCore (nontrivialOnly := true)
end Aesop.StatsReport |
.lake/packages/aesop/Aesop/Forward/Substitution.lean | module
public import Aesop.Forward.LevelIndex
public import Aesop.Forward.PremiseIndex
public import Aesop.RPINF.Basic
public import Aesop.Util.Basic
public section
namespace Aesop
open Lean Lean.Meta
set_option linter.missingDocs true
/-- A substitution for the premises of a rule. Given a rule with type
`∀ (x₁ : T₁) ... (xₙ : Tₙ), U` a substitution is a finite partial map with
domain `{1, ..., n}` that associates an expression with some or all of the
premises. -/
structure Substitution where
/-- The substitution. -/
premises : Array (Option RPINF)
/-- The level substitution implied by the premise substitution. If `e` is the
elaborated rule expression (with level params replaced by level mvars), and
`collectLevelMVars (← instantiateMVars e) = [?m₁, ..., ?mₙ]`, then `levels[i]`
is the level assigned to `?mᵢ`. -/
levels : Array (Option Level)
deriving Inhabited
namespace Substitution
instance : BEq Substitution where
beq s₁ s₂ := s₁.premises == s₂.premises
instance : Hashable Substitution where
hash s := hash s.premises
instance : Ord Substitution where
compare s₁ s₂ :=
compare s₁.premises.size s₂.premises.size |>.then $
compareArrayLex compare s₁.premises s₂.premises
/-- The empty substitution for a rule with the given number of premise
indexes. -/
def empty (numPremises numLevels : Nat) : Substitution where
premises := .replicate numPremises none
levels := .replicate numLevels none
/-- Insert the mapping `pi ↦ inst` into the substitution `s`. Precondition: `pi`
is in the domain of `s`. -/
def insert (pi : PremiseIndex) (inst : RPINF) (s : Substitution) :
Substitution :=
{ s with premises := s.premises.set! pi.toNat inst }
/-- Get the instantiation associated with premise `pi` in `s`. Precondition:
`pi` is in the domain of `s`. -/
def find? (pi : PremiseIndex) (s : Substitution) : Option RPINF :=
s.premises[pi.toNat]!
/-- Insert the mapping `li ↦ inst` into the substitution `s`. Precondition: `li`
is in the domain of `s` and `inst` is normalised. -/
def insertLevel (li : LevelIndex) (inst : Level) (s : Substitution) :
Substitution :=
{ s with levels := s.levels.set! li.toNat inst }
/-- Get the instantiation associated with level `li` in `s`. Precondition:
`li` is in the domain of `s`. -/
def findLevel? (li : PremiseIndex) (s : Substitution) : Option Level :=
s.levels[li.toNat]!
instance : ToMessageData Substitution where
toMessageData s :=
let ps := s.premises.filterMap id |>.mapIdx (λ i e => m!"{i} ↦ {e}") |>.toList
let ls := s.levels.filterMap id |>.mapIdx (λ i l => m!"{i} ↦ {l}") |>.toList
.bracket "{" (.joinSep ps ", " ++ " | " ++ .joinSep ls ", ") "}"
/-- Merge two substitutions. Precondition: the substitutions are compatible, so
they must have the same size and if `s₁[x]` and `s₂[x]` are both defined, they
must be the same value. -/
def mergeCompatible (s₁ s₂ : Substitution) : Substitution := Id.run do
assert! s₁.premises.size == s₂.premises.size
assert! s₁.levels.size == s₂.levels.size
let mut result := s₁
for h : i in [:s₂.premises.size] do
if let some e := s₂.premises[i] then
assert! let r := s₁.find? ⟨i⟩; r.isNone || r == some e
if s₁.premises[i]!.isNone then
result := result.insert ⟨i⟩ e
for h : i in [:s₂.levels.size] do
if let some l := s₂.levels[i] then
if s₁.levels[i]!.isNone then
result := result.insertLevel ⟨i⟩ l
return result
/-- Returns `true` if any expression in the codomain of `s` contains `hyp`. -/
def containsHyp (hyp : FVarId) (s : Substitution) : Bool :=
s.premises.any λ
| none => false
| some e => e.toExpr.containsFVar hyp
/-- Given `e` with type `∀ (x₁ : T₁) ... (xₙ : Tₙ), U` and a substitution `σ`
for the arguments `xᵢ`, replace occurrences of `xᵢ` in the body `U` with fresh
metavariables (like `forallMetaTelescope`). Then, for each mapping `xᵢ ↦ tᵢ` in
`σ`, assign `tᵢ` to the metavariable corresponding to `xᵢ`. Returns the newly
created metavariables (which may be assigned!), their binder infos and the
updated body. -/
def openRuleType (e : Expr) (subst : Substitution) :
MetaM (Array MVarId × Array BinderInfo × Expr) := do
let lmvarIds := collectLevelMVars {} (← instantiateMVars e) |>.result
if subst.levels.size != lmvarIds.size then
throwError "openRuleType: substitution contains incorrect number of levels. Rule:{indentExpr e}\nSubstitution:{indentD $ toMessageData subst}"
let type ← inferType e
let (mvars, binfos, body) ← forallMetaTelescopeReducing type
let mvarIds := mvars.map (·.mvarId!)
if subst.premises.size != mvars.size then
throwError "openRuleType: substitution has incorrect size. Rule:{indentExpr e}\nRule type:{indentExpr type}\nSubstitution:{indentD $ toMessageData subst}"
for h : i in [:lmvarIds.size] do
if let some inst := subst.findLevel? ⟨i⟩ then
assignLevelMVar lmvarIds[i] inst
for h : i in [:mvarIds.size] do
if let some inst := subst.find? ⟨i⟩ then
mvarIds[i].assign inst.toExpr
return (mvarIds, binfos, body)
/-- Given `rule` of type `∀ (x₁ : T₁) ... (xₙ : Tₙ), U` and a substitution `σ` for
the arguments `xᵢ`, specialise `rule` with the arguments given by `σ`. That is,
construct `U t₁ ... tₙ` where `tⱼ` is `σ(xⱼ)` if `xⱼ ∈ dom(σ)` and is otherwise
a fresh fvar, then λ-abstract the fresh fvars. -/
def specializeRule (rule : Expr) (subst : Substitution) : MetaM Expr :=
withNewMCtxDepth do
let lmvarIds := collectLevelMVars {} (← instantiateMVars rule) |>.result
for h : i in [:lmvarIds.size] do
if let some l := subst.findLevel? ⟨i⟩ then
assignLevelMVar lmvarIds[i] l
forallTelescopeReducing (← inferType rule) λ fvarIds _ => do
let mut args := Array.mkEmpty fvarIds.size
let mut remainingFVarIds := Array.mkEmpty fvarIds.size
for h : i in [:fvarIds.size] do
if let some inst := subst.find? ⟨i⟩ then
args := args.push $ some inst.toExpr
else
let fvarId := fvarIds[i]
args := args.push $ some fvarId
remainingFVarIds := remainingFVarIds.push fvarId
let result ← mkLambdaFVars remainingFVarIds (← mkAppOptM' rule args)
return result
end Substitution
/-- Open the type of a rule `e`. If a substitution `σ` is given, this function
acts like `Substitution.openRuleType σ`. Otherwise it acts like
`forallMetaTelescope`. -/
def openRuleType (subst? : Option Substitution) (e : Expr) :
MetaM (Array MVarId × Array BinderInfo × Expr) := do
match subst? with
| some subst => do
subst.openRuleType e
| none =>
let (premises, binfos, conclusion) ←
forallMetaTelescopeReducing (← inferType e)
return (premises.map (·.mvarId!), binfos, conclusion)
end Aesop |
.lake/packages/aesop/Aesop/Forward/SlotIndex.lean | module
public section
namespace Aesop
structure SlotIndex where
toNat : Nat
deriving Inhabited, BEq, Hashable, DecidableEq, Ord
instance : LT SlotIndex where
lt i j := i.toNat < j.toNat
instance : DecidableRel (α := SlotIndex) (· < ·) :=
λ i j => inferInstanceAs $ Decidable (i.toNat < j.toNat)
instance : LE SlotIndex where
le i j := i.toNat ≤ j.toNat
instance : DecidableRel (α := SlotIndex) (· ≤ ·) :=
λ i j => inferInstanceAs $ Decidable (i.toNat ≤ j.toNat)
instance : HAdd SlotIndex Nat SlotIndex where
hAdd i j := ⟨i.toNat + j⟩
instance : HSub SlotIndex Nat SlotIndex where
hSub i j := ⟨i.toNat - j⟩
instance : ToString SlotIndex where
toString i := toString i.toNat
end Aesop |
.lake/packages/aesop/Aesop/Forward/State.lean | module
public import Aesop.Forward.Match
import Aesop.RPINF
public section
open Lean Lean.Meta
open ExceptToEmoji (toEmoji)
set_option linter.missingDocs true
namespace Aesop
private def ppPHashMap [BEq α] [Hashable α] [ToMessageData α]
[ToMessageData β] (indent : Bool) (m : PHashMap α β) : MessageData :=
flip MessageData.joinSep "\n" $
m.foldl (init := []) λ xs a b =>
let x :=
if indent then
m!"{a} =>{indentD $ toMessageData b}"
else
m!"{a} => {b}"
x :: xs
private def ppPHashSet [BEq α] [Hashable α] [ToMessageData α] (s : PHashSet α) :
MessageData :=
toMessageData $ s.fold (init := #[]) λ as a => as.push a
/-- A hypothesis that has not yet been matched against a premise, or a rule
pattern substitution. -/
inductive RawHyp where
/-- The hypothesis. -/
| fvarId (fvarId : FVarId)
/-- The rule pattern substitution. -/
| patSubst (subst : Substitution)
deriving Inhabited, BEq, Hashable
/-- A hypothesis that was matched against a premise, or a rule pattern
substitution. -/
structure Hyp where
/-- The hypothesis, or `none` if this is a rule pattern substitution. -/
fvarId? : Option FVarId
/-- The substitution that results from matching the hypothesis against a
premise or that was derived from the pattern. -/
subst : Substitution
deriving Inhabited
namespace Hyp
instance : BEq Hyp where
beq h₁ h₂ :=
match h₁.fvarId?, h₂.fvarId? with
| some h₁, some h₂ => h₁ == h₂
| none, none => h₁.subst == h₂.subst
| _, _ => false
instance : Hashable Hyp where
hash h :=
match h.fvarId? with
| some h => hash h
| none => hash h.subst
/-- Returns `true` if `h` is the hyp `fvarId` or is a pattern substitution
containing `fvarId`. -/
def containsHyp (fvarId : FVarId) (h : Hyp) : Bool :=
h.fvarId? == some fvarId || h.subst.containsHyp fvarId
/-- Does this `Hyp` represent a pattern substitution? -/
def isPatSubst (h : Hyp) : Bool :=
h.fvarId?.isSome
end Hyp
set_option linter.missingDocs false in
/-- Partial matches associated with a particular slot instantiation. An entry
`s ↦ e ↦ (ms, hs)` indicates that for the instantiation `e` of slot `s`, we have
partial matches `ms` and hypotheses `hs`. -/
structure InstMap where
map : PHashMap SlotIndex (PHashMap RPINF (PHashSet Match × PHashSet Hyp))
deriving Inhabited
namespace InstMap
instance : EmptyCollection InstMap := ⟨⟨.empty⟩⟩
instance : ToMessageData InstMap where
toMessageData m := private
ppPHashMap (indent := true) $
m.map.map λ instMap =>
ppPHashMap (indent := false) $
instMap.map λ (ms, hs) =>
let hs : Array MessageData :=
hs.fold (init := #[]) λ hs (h : Hyp) =>
match h.fvarId? with
| none => hs.push m!"{h.subst}"
| some fvarId => hs.push m!"{Expr.fvar fvarId}"
m!"{(ppPHashSet ms, hs)}"
/-- Returns the set of matches and hypotheses associated with a slot `slot`
with instantiation `inst`. -/
@[inline]
def find? (imap : InstMap) (slot : SlotIndex) (inst : RPINF) :
Option (PHashSet Match × PHashSet Hyp) :=
imap.map.find? slot |>.bind λ slotMap => slotMap.find? inst
/-- Returns the set of matches and hypotheses associated with a slot `slot`
with instantiation `inst`, or `(∅, ∅)` if `slot` and `inst` do not have any
associated matches. -/
@[inline]
def findD (imap : InstMap) (slot : SlotIndex) (inst : RPINF) :
PHashSet Match × PHashSet Hyp :=
imap.find? slot inst |>.getD (∅, ∅)
/-- Applies a transfomation to the data associated to `slot` and `inst`.
If there is no such data, the transformation is applied to `(∅, ∅)`. Returns the
new instantiation map and the result of `f`. -/
def modify (imap : InstMap) (slot : SlotIndex) (inst : RPINF)
(f : PHashSet Match → PHashSet Hyp → PHashSet Match × PHashSet Hyp × α) :
InstMap × α :=
let (ms, hyps) := imap.findD slot inst
let (ms, hyps, a) := f ms hyps
let slotMap := imap.map.findD slot .empty |>.insert inst (ms, hyps)
(⟨imap.map.insert slot slotMap⟩, a)
/-- Inserts a hyp associated with slot `slot` and instantiation `inst`.
The hyp must be a valid assignment for the slot's premise. Returns `true` if
the hyp was not previously associated with `slot` and `inst`. -/
def insertHyp (imap : InstMap) (slot : SlotIndex) (inst : RPINF) (hyp : Hyp) :
InstMap × Bool :=
imap.modify slot inst λ ms hs =>
if hs.contains hyp then
(ms, hs, false)
else
(ms, hs.insert hyp, true)
/-- Inserts a match associated with slot `slot` and instantiation `inst`.
The match's level must be `slot`. Returns `true` if the match was not previously
associated with `slot` and `inst`. -/
def insertMatchCore (imap : InstMap) (slot : SlotIndex) (inst : RPINF)
(m : Match) : InstMap × Bool :=
imap.modify slot inst λ ms hs =>
if ms.contains m then
(ms, hs, false)
else
(ms.insert m, hs, true)
/-- Inserts a match. The match `m` is associated with the slot given by its
level (i.e., the maximal slot for which `m` contains a hypothesis) and the
instantiation of `var` given by the map's substitution. Returns `true` if the
match was not previously associated with this slot and instantiation. -/
def insertMatch (imap : InstMap) (var : PremiseIndex) (m : Match) :
InstMap × Bool := Id.run do
let some inst := m.subst.find? var
| panic! s!"variable {var} is not assigned in substitution"
imap.insertMatchCore m.level inst m
/-- Modify the maps for slot `slot` and all later slots. -/
def modifyMapsForSlotsFrom (imap : InstMap) (slot : SlotIndex)
(f : PHashSet Match → PHashSet Hyp → (PHashSet Match × PHashSet Hyp)) :
InstMap := Id.run do
let mut imaps := imap.map
-- TODO Could remove this fold by passing the number of slots to this function.
let nextSlots : Array SlotIndex :=
imap.map.foldl (init := #[]) λ acc slot' _ =>
if slot ≤ slot' then acc.push slot' else acc
for i in nextSlots do
let maps := imap.map.find! i |>.map λ (ms, hs) => f ms hs
imaps := imaps.insert i maps
return { map := imaps }
/-- Remove `hyp` from `slot` and all later slots. For each mapping
`s ↦ e ↦ (ms, hs)` in `imap`, if `s ≥ slot`, then `hyp` is removed from `hs` and
any matches containing `hyp` are removed from `ms`. -/
def eraseHyp (imap : InstMap) (hyp : FVarId) (slot : SlotIndex) :
InstMap :=
imap.modifyMapsForSlotsFrom slot λ ms hs =>
let ms := PersistentHashSet.filter (! ·.containsHyp hyp) ms
let hs := hs.erase { fvarId? := hyp, subst := default }
(ms, hs)
/-- Remove the pattern substitution `subst` from `slot` and all later slots.
For each mapping `s ↦ e ↦ (ms, hs)` in `imap`, if `s ≥ slot`, then `subst` is
removed from `hs` and any matches containing `subst` are removed from `ms`. -/
def erasePatSubst (imap : InstMap) (subst : Substitution) (slot : SlotIndex) :
InstMap :=
imap.modifyMapsForSlotsFrom slot λ ms hs =>
let ms := PersistentHashSet.filter (! ·.containsPatSubst subst) ms
let hs := hs.erase { fvarId? := none, subst }
(ms, hs)
end InstMap
set_option linter.missingDocs false in
/-- Map from variables to the matches and hypotheses of slots whose types
contain the variables. -/
structure VariableMap where
map : PHashMap PremiseIndex InstMap
deriving Inhabited
namespace VariableMap
instance : EmptyCollection VariableMap :=
⟨⟨.empty⟩⟩
instance : ToMessageData VariableMap where
toMessageData m := private ppPHashMap (indent := true) m.map
/-- Get the `InstMap` associated with a variable. -/
def find? (vmap : VariableMap) (var : PremiseIndex) : Option InstMap :=
vmap.map.find? var
/-- Get the `InstMap` associated with a variable, or an empty `InstMap`. -/
def find (vmap : VariableMap) (var : PremiseIndex) : InstMap :=
vmap.find? var |>.getD ∅
/-- Modify the `InstMap` associated to variable `var`. If no such `InstMap`
exists, the function `f` is applied to the empty `InstMap` and the result is
associated with `var`. Returns the new variable map and the result of `f`. -/
def modify (vmap : VariableMap) (var : PremiseIndex) (f : InstMap → InstMap × α) :
VariableMap × α :=
match vmap.map.find? var with
| none =>
let (m, a) := f ∅
(⟨vmap.map.insert var m⟩, a)
| some m =>
let (m, a) := f m
(⟨vmap.map.insert var m⟩, a)
/-- Add a hypothesis `hyp`. Precondition: `hyp` matches the premise of slot
`slot` with substitution `hyp.subst` (and hence `hyp.subst` contains a mapping
for each variable in `slot.common`). Returns `true` if the variable map
changed. -/
def addHyp (vmap : VariableMap) (slot : Slot) (hyp : Hyp) : VariableMap × Bool :=
slot.common.fold (init := (vmap, false)) λ (vmap, changed) var =>
if let some inst := hyp.subst.find? var then
let (vmap, changed') := vmap.modify var (·.insertHyp slot.index inst hyp)
(vmap, changed || changed')
else
panic! s!"substitution contains no instantiation for variable {var}"
/-- Add a match `m`. Precondition: `nextSlot` is the slot with index
`m.level + 1`. Returns `true` if the variable map changed. -/
def addMatch (vmap : VariableMap) (nextSlot : Slot) (m : Match) :
VariableMap × Bool :=
nextSlot.common.fold (init := (vmap, false)) λ (vmap, changed) var =>
let (vmap, changed') := vmap.modify var (·.insertMatch var m)
(vmap, changed || changed')
/-- Remove a hyp from `slot` and all later slots. -/
def eraseHyp (vmap : VariableMap) (hyp : FVarId) (slot : SlotIndex) :
VariableMap :=
⟨vmap.map.map (·.eraseHyp hyp slot)⟩
/-- Remove the pattern substitution `subst` from `slot` and all later slots. -/
def erasePatSubst (vmap : VariableMap) (subst : Substitution) (slot : SlotIndex) :
VariableMap :=
⟨vmap.map.map (·.erasePatSubst subst slot)⟩
/-- Find matches in slot `slot - 1` whose substitutions are compatible with
`subst`. Preconditions: `slot.index` is nonzero, `slot.common` is nonempty and
each variable contained in `slot.common` is also contained in `subst`. -/
def findMatches (vmap : VariableMap) (slot : Slot) (subst : Substitution) :
Std.HashSet Match := Id.run do
if slot.index == ⟨0⟩ then
panic! "slot has index 0"
let common := slot.common.toArray
if h : 0 < common.size then
let firstVar := common[0]
let mut ms := prevSlotMatches firstVar |> PersistentHashSet.toHashSet
for var in common[1:] do
if ms.isEmpty then
break
let ms' := prevSlotMatches var
ms := ms.filter (ms'.contains ·)
return ms
else
panic! "no common variables"
where
prevSlotMatches (var : PremiseIndex) : PHashSet Match :=
if let some inst := subst.find? var then
vmap.find var |>.findD (slot.index - 1) inst |>.1
else
panic! s!"substitution contains no instantiation for variable {var}"
/-- Find hyps in `slot` whose substitutions are compatible with `subst`.
Precondition: `slot.common` is nonempty and each variable contained in it is
also contained in `subst`. -/
def findHyps (vmap : VariableMap) (slot : Slot) (subst : Substitution) :
Std.HashSet Hyp := Id.run do
let common := slot.common.toArray
if h : 0 < common.size then
let mut hyps := slotHyps common[0] |> PersistentHashSet.toHashSet
for var in common[1:] do
if hyps.isEmpty then
break
let hyps' := slotHyps var
hyps := hyps.filter (hyps'.contains ·)
return hyps
else
panic! "no common variables"
where
slotHyps (var : PremiseIndex) : PHashSet Hyp :=
if let some inst := subst.find? var then
vmap.find var |>.findD slot.index inst |>.2
else
panic! s!"substitution contains no instantiation for variable {var}"
end VariableMap
/-- Structure representing the state of a slot cluster. -/
structure ClusterState where
/-- The cluster's slots. -/
slots : Array Slot
/-- The premises that appear in the rule's conclusion. These are the same for
all cluster states of a rule, but are stored here for convenience. -/
conclusionDeps : Array PremiseIndex
/-- The variable map for this cluster. -/
variableMap : VariableMap
/-- Complete matches for this cluster. -/
completeMatches : PHashSet Match
/-- When this flag is `true`, hyps are added to the `slotQueues` rather than
the `variableMap`. This is an optimisation that avoids performing unifications
until a rule can potentially generate a complete match. More precisely:
- `addHypsLazily` is initially set to `true`.
- While `addHypsLazily` is `true`, hyps are added to (and deleted from) the
`slotQueues` and are not added to the `variableMap`.
Once an addition causes all slot queues to have at least one element,
`addHypsLazily` is permanently set to `false` and hyps for slot 0 are added
to the `variableMap`.
- While `addHypsLazily` is `false`:
- Hyps for slot `i` are added directly to the variable maps if `i = 0` or
the slot `i - 1` has matches. Otherwise they are added to the slot queue
for `i`. (More precisely, we only track whether slot `i - 1` has had
matches at some point. This allows us to ignore deletions.)
- The insertion of a match into slot `i` causes all hyps at slot `i + 1`
to be moved from the slot queue into the `variableMap`.
-/
addHypsLazily : Bool
/-- Hypotheses or pattern substitutions that have been added to the cluster
state, but have not yet been added to the `variableMap`. -/
slotQueues : Array (Array RawHyp)
/-- There is exactly one queue for each slot. -/
slotQueues_size : slotQueues.size = slots.size
/-- The `i`th element of this array is `true` if a match was at some point
added to slot `i`. -/
slotMaybeHasMatches : Array Bool
/-- There is exactly one boolean for each slot. -/
slotMaybeHasMatches_size : slotMaybeHasMatches.size = slots.size
namespace ClusterState
instance : Inhabited ClusterState where
default := by refine' {
slots := #[]
slotQueues := #[]
slotQueues_size := by simp
slotMaybeHasMatches := #[]
slotMaybeHasMatches_size := by simp
..
} <;> exact default
instance : ToMessageData ClusterState where
toMessageData cs :=
m!"variables:{indentD $ toMessageData cs.variableMap}\n\
complete matches:{indentD $ .joinSep (PersistentHashSet.toList cs.completeMatches |>.map toMessageData) "\n"}"
/-- Get the slot with the given index. Panic if the index is invalid. -/
@[macro_inline, always_inline, expose]
def slot! (cs : ClusterState) (slot : SlotIndex) : Slot :=
cs.slots[slot.toNat]!
/-- Get the slot with the given premise index. -/
def findSlot? (cs : ClusterState) (i : PremiseIndex) : Option Slot :=
cs.slots.find? (·.premiseIndex == i)
/-- Match hypothesis `hyp` against the slot with index `slot` in `cs` (which
must be a valid index). -/
def matchPremise? (premises : Array MVarId) (lmvarIds : Array LMVarId)
(cs : ClusterState) (slot : SlotIndex) (hyp : FVarId) :
BaseM (Option Substitution) := do
let some slot := cs.slots[slot.toNat]?
| throwError "aesop: internal error: matchPremise?: no slot with index {slot}"
let premiseIdx := slot.premiseIndex.toNat
let some slotPremise := premises[premiseIdx]?
| throwError "aesop: internal error: matchPremise?: slot with premise index {premiseIdx}, but only {premises.size} premises"
let premiseType ← slotPremise.getType
let hypType ← hyp.getType
withAesopTraceNodeBefore .forward (return m!"match against premise {premiseIdx}: {hypType} ≟ {premiseType}") do
withoutModifyingState do
let isDefEq ←
withConstAesopTraceNode .forwardDebug (return m!"defeq check") do
withReducible do
isDefEq premiseType hypType
if isDefEq then
let mut subst := .empty premises.size lmvarIds.size
for var in slot.deps do
subst ← updateSubst premises var subst
subst := subst.insert slot.premiseIndex $ ← rpinf (.fvar hyp)
for h : i in [:lmvarIds.size] do
if let some l ← getLevelMVarAssignment? lmvarIds[i] then
subst := subst.insertLevel ⟨i⟩ (← instantiateLevelMVars l)
aesop_trace[forward] "substitution: {subst}"
return subst
else
return none
where
updateSubst (premises : Array MVarId) (var : PremiseIndex)
(subst : Substitution) : BaseM Substitution :=
withConstAesopTraceNode .forwardDebug (return m!"update var {var}") do
let some varMVarId := premises[var.toNat]?
| throwError "aesop: internal error: matchPremise?: dependency with index {var}, but only {premises.size} premises"
let mvar := .mvar varMVarId
let assignment ← instantiateMVars mvar
if assignment == mvar then
throwError "aesop: internal error: matchPremise?: while matching hyp {hyp.name}: no assignment for variable {var}"
if ← hasAssignableMVar assignment then
throwError "aesop: internal error: matchPremise?: assignment has mvar:{indentExpr assignment}"
let assignment ← rpinf assignment
return subst.insert var assignment
/-- Context for the `AddM` monad. -/
structure AddM.Context where
/-- Metavariables for the premises of the rule for which a hyp or match is
being added. When adding hyps, they are unified with these metavariables. -/
premiseMVars : Array MVarId
/-- Metavariables for level parameters appearing in the rule's premises. -/
premiseLMVars : Array LMVarId
/-- A monad for operations that add hyps or matches to a cluster state. The
monad's state is an array of complete matches discovered while adding
hyps/matches. -/
abbrev AddM := ReaderT AddM.Context $ StateRefT (Array Match) $ BaseM
/-- Run an `AddM` action. -/
def AddM.run (premiseMVars : Array MVarId) (premiseLMVars : Array LMVarId)
(x : AddM α) : BaseM (α × Array Match) :=
ReaderT.run x { premiseMVars, premiseLMVars } |>.run #[]
mutual
/-- Add a match to the cluster state. Returns the new cluster state and any new
complete matches for this cluster. -/
partial def addMatch (cs : ClusterState) (m : Match) : AddM ClusterState := do
let mut cs := cs
let slotIdx := m.level
if slotIdx.toNat == cs.slots.size - 1 then
if cs.completeMatches.contains m then
aesop_trace[forward] "complete match {m} already present"
return cs
else
cs := { cs with completeMatches := cs.completeMatches.insert m }
modify (·.push m)
return cs
else
let nextSlot := cs.slot! $ slotIdx + 1
aesop_trace[forward] "add match {m} for slot {slotIdx}"
let (vmap, changed) := cs.variableMap.addMatch nextSlot m -- This is correct; VariableMap.addMatch needs the next slot.
if ! changed then
aesop_trace[forward] "match already present"
return cs
cs := {
cs with
variableMap := vmap
slotMaybeHasMatches := cs.slotMaybeHasMatches.set! slotIdx.toNat true
slotMaybeHasMatches_size := by simp [cs.slotMaybeHasMatches_size]
}
cs ← cs.addQueuedRawHyps nextSlot
for hyp in cs.variableMap.findHyps nextSlot m.subst do
let m := m.addHypOrPatSubst hyp.subst hyp.isPatSubst nextSlot.forwardDeps
cs ← cs.addMatch m
return cs
/-- Add a hypothesis to the cluster state. `hyp.subst` must be the substitution
that results from applying `h` to `slot`. -/
partial def addHyp (cs : ClusterState) (slot : Slot) (h : Hyp) :
AddM ClusterState := do
withConstAesopTraceNode .forward (return m!"add hyp or pattern inst for slot {slot.index} with substitution {h.subst}") do
if slot.index.toNat == 0 then
let m :=
Match.initial h.subst h.isPatSubst (forwardDeps := slot.forwardDeps)
(conclusionDeps := cs.conclusionDeps)
cs.addMatch m
else
let (vmap, changed) := cs.variableMap.addHyp slot h
if ! changed then
aesop_trace[forward] "hyp already present"
return cs
let mut cs := { cs with variableMap := vmap }
for pm in cs.variableMap.findMatches slot h.subst do
let m := pm.addHypOrPatSubst h.subst h.isPatSubst slot.forwardDeps
cs ← cs.addMatch m
return cs
/-- Add a hypothesis or pattern substitution to the cluster state. -/
partial def addRawHypCore (h : RawHyp) (slot : Slot) (cs : ClusterState) :
AddM ClusterState :=
match h with
| .fvarId fvarId =>
withConstAesopTraceNode .forwardDebug (return m!"add hyp {Expr.fvar fvarId} ({fvarId.name}) to slot {slot.index}") do
let some subst ←
cs.matchPremise? (← read).premiseMVars (← read).premiseLMVars
slot.index fvarId
| return cs
cs.addHyp slot { fvarId? := fvarId, subst }
| .patSubst subst =>
withConstAesopTraceNode .forwardDebug (return m!"add pattern subst {subst} to slot {slot.index}") do
cs.addHyp slot { fvarId? := none, subst }
/-- Insert the raw hyps from `slot`'s queue into the variable map. -/
partial def addQueuedRawHyps (slot : Slot) (cs : ClusterState) :
AddM ClusterState :=
withConstAesopTraceNode .forward (return m!"add queued hyps for slot {slot.index}") do
let cs ← cs.slotQueues[slot.index.toNat]!.foldlM (init := cs) λ cs h =>
cs.addRawHypCore h slot
return {
cs with
slotQueues := cs.slotQueues.set! slot.index.toNat #[]
slotQueues_size := by simp [cs.slotQueues_size]
}
end
/-- Add a hypothesis or pattern substitution to the queue for its slot. If
afterwards each slot queue contains at least one element, then the returned
cluster state `cs` has `cs.addHypsLazily = false`. -/
def enqueueRawHyp (h : RawHyp) (slot : Slot) (cs : ClusterState) :
ClusterState := Id.run do
let mut cs := {
cs with
slotQueues := cs.slotQueues.modify slot.index.toNat (·.push h)
slotQueues_size := by simp [cs.slotQueues_size]
}
if cs.slotQueues.all (·.size > 0) then
cs := { cs with addHypsLazily := false }
return cs
/-- Add a hypothesis or pattern substitution to the cluster state. If a
hypothesis is given and its type does not match the premise corresponding to
`slot`, it is not added. -/
def addRawHyp (cs : ClusterState) (i : PremiseIndex) (h : RawHyp) :
AddM ClusterState := do
let some slot := cs.findSlot? i
| return cs
if cs.addHypsLazily then
let cs := cs.enqueueRawHyp h slot
if ! cs.addHypsLazily then
cs.addQueuedRawHyps (cs.slot! ⟨0⟩)
else
return cs
else if slot.index.toNat == 0 || cs.slotMaybeHasMatches[slot.index.toNat - 1]! then
cs.addRawHypCore h slot
else
return cs.enqueueRawHyp h slot
/-- Erase a `RawHyp` from the slot queue of the given slot. -/
def eraseEnqueuedRawHyp (h : RawHyp) (slot : Slot) (cs : ClusterState) :
ClusterState := {
cs with
slotQueues := cs.slotQueues.modify slot.index.toNat λ q => q.erase h
slotQueues_size := by simp [cs.slotQueues_size]
}
private def filterPHashSet [BEq α] [Hashable α] (p : α → Bool)
(s : PHashSet α) : PHashSet α :=
let toDelete := s.fold (init := #[]) λ toDelete a =>
if p a then toDelete else toDelete.push a
toDelete.foldl (init := s) λ s a => s.erase a
/-- Erase a hypothesis from the cluster state's variable map. -/
def eraseHyp (h : FVarId) (pi : PremiseIndex) (cs : ClusterState) :
ClusterState := Id.run do
let some slot := cs.findSlot? pi
| return cs
if cs.addHypsLazily then
return cs.eraseEnqueuedRawHyp (.fvarId h) slot
else
return {
cs with
variableMap := cs.variableMap.eraseHyp h slot.index
completeMatches := filterPHashSet (! ·.containsHyp h) cs.completeMatches
-- TODO inefficient: complete matches should only be filtered once
}
/-- Erase a pattern substitution from the cluster state. -/
def erasePatSubst (subst : Substitution) (pi : PremiseIndex) (cs : ClusterState) :
ClusterState := Id.run do
let some slot := cs.findSlot? pi
| return cs
if cs.addHypsLazily then
return cs.eraseEnqueuedRawHyp (.patSubst subst) slot
else
return {
cs with
variableMap := cs.variableMap.erasePatSubst subst slot.index
completeMatches := filterPHashSet (! ·.containsPatSubst subst) cs.completeMatches
}
end ClusterState
/-- The source of a pattern substitution. The same substitution can have
multiple sources. -/
inductive PatSubstSource
/-- The pattern substitution came from the given hypothesis. -/
| hyp (fvarId : FVarId)
/-- The pattern substitution came from the goal's target. -/
| target
deriving Inhabited, Hashable, BEq
/-- Forward state for one rule. -/
structure RuleState where
/-- The rule to which this state belongs. -/
rule : ForwardRule
/-- States for each of the rule's slot clusters. -/
clusterStates : Array ClusterState
/-- The sources of all pattern substitutions present in the
`clusterStates`. Invariant: each pattern substitution in the cluster states
is associated with a nonempty set. -/
patSubstSources : PHashMap Substitution (PHashSet PatSubstSource)
deriving Inhabited
instance : ToMessageData RuleState where
toMessageData rs :=
flip MessageData.joinSep "\n" $
rs.clusterStates.toList.mapIdx λ i cs =>
m!"cluster {i}:{indentD $ toMessageData cs}"
/-- The initial (empty) rule state for a given forward rule. -/
def ForwardRule.initialRuleState (r : ForwardRule) : RuleState :=
let clusterStates := r.slotClusters.map λ slots => {
variableMap := ∅
completeMatches := {}
conclusionDeps := r.conclusionDeps
slotQueues := .replicate slots.size #[]
slotQueues_size := by simp
slotMaybeHasMatches := .replicate slots.size false
slotMaybeHasMatches_size := by simp
addHypsLazily := true
slots
}
{ rule := r, clusterStates, patSubstSources := {} }
namespace RuleState
/-- Add a hypothesis or pattern substitution to the rule state. Returns the new
rule state and any newly completed matches. If a hypothesis is given and it does
not match premise `pi`, nothing happens. -/
def addRawHyp (goal : MVarId) (h : RawHyp) (pi : PremiseIndex) (rs : RuleState) :
BaseM (RuleState × Array CompleteMatch) :=
withNewMCtxDepth do
-- TODO We currently open the rule expression also if `h` is a pattern
-- substitution, which is unnecessary.
let some ruleExpr ←
withConstAesopTraceNode .forwardDebug (return m!"elab rule term") do
show MetaM _ from observing? $ elabForwardRuleTerm goal rs.rule.term
| return (rs, #[])
let lmvars := collectLevelMVars {} ruleExpr |>.result
if lmvars.size != rs.rule.numLevelParams then
aesop_trace[forward] "failed to add hyp or pat inst: rule term{indentD $ toMessageData rs.rule.term}\ndoes not have expected number of level mvars {rs.rule.numLevelParams}"
return (rs, #[])
let ruleType ← instantiateMVars (← inferType ruleExpr)
let (premises, _, _) ←
withConstAesopTraceNode .forwardDebug (return m!"open rule term") do
withReducible do
forallMetaTelescope ruleType
if premises.size != rs.rule.numPremises then
aesop_trace[forward] "failed to add hyp or pat inst: rule term{indentD $ toMessageData rs.rule.term}\ndoes not have expected number of premises {rs.rule.numPremises}"
return (rs, #[])
let premises := premises.map (·.mvarId!)
let mut rs := rs
let mut clusterStates := rs.clusterStates
let mut completeMatches := #[]
for i in [:clusterStates.size] do
let cs := clusterStates[i]!
let (cs, newCompleteMatches) ← cs.addRawHyp pi h |>.run premises lmvars
clusterStates := clusterStates.set! i cs
completeMatches ←
withConstAesopTraceNode .forwardDebug (return m!"construct new complete matches") do
return completeMatches ++
getCompleteMatches clusterStates i newCompleteMatches
return ({ rs with clusterStates }, completeMatches)
where
getCompleteMatches (clusterStates : Array ClusterState) (clusterIdx : Nat)
(newCompleteMatches : Array Match) :
Array CompleteMatch := Id.run do
if newCompleteMatches.isEmpty ||
clusterStates.any (·.completeMatches.isEmpty) then
return #[]
else
let mut completeMatches := #[]
for h : i in [:clusterStates.size] do
completeMatches :=
if i == clusterIdx then
addMatches completeMatches newCompleteMatches
else
addMatches completeMatches $
PersistentHashSet.toArray clusterStates[i].completeMatches
return completeMatches
addMatches (completeMatches : Array CompleteMatch)
(clusterMatches : Array Match) : Array CompleteMatch := Id.run do
if completeMatches.isEmpty then
return clusterMatches.map ({ clusterMatches := #[·] })
else
let mut newCompleteMatches :=
Array.mkEmpty (completeMatches.size * clusterMatches.size)
for completeMatch in completeMatches do
for clusterMatch in clusterMatches do
newCompleteMatches := newCompleteMatches.push
{ clusterMatches := completeMatch.clusterMatches.push clusterMatch }
return newCompleteMatches
/-- Erase a pattern substitution that was obtained from the given source. -/
def erasePatSubst (subst : Substitution) (source : PatSubstSource)
(rs : RuleState) : RuleState := Id.run do
let some sources := rs.patSubstSources[subst]
| panic! s!"unknown pattern substitution {subst.premises} for rule {rs.rule.name}"
let sources := sources.erase source
if sources.isEmpty then
let some (pat, patPremiseIdx) := rs.rule.rulePatternInfo?
| panic! s!"rule {rs.rule.name} does not have a pattern"
let some csIdx := rs.clusterStates.findIdx? λ cs =>
cs.findSlot? patPremiseIdx |>.isSome
| panic! s!"pattern slot {patPremiseIdx} not found for rule {rs.rule.name}"
return {
rs with
clusterStates := rs.clusterStates.modify csIdx λ cs =>
cs.erasePatSubst subst patPremiseIdx
patSubstSources := rs.patSubstSources.erase subst
}
else
return { rs with patSubstSources := rs.patSubstSources.insert subst sources }
/-- Erase a hypothesis from the rule state. -/
def eraseHyp (h : FVarId) (pi : PremiseIndex) (rs : RuleState) : RuleState :=
let clusterStates := rs.clusterStates.map (·.eraseHyp h pi)
{ rs with clusterStates }
end RuleState
/-- State representing the non-complete matches of a given set of forward rules
in a given local context. -/
structure ForwardState where
/-- Map from each rule's name to its `RuleState`-/
ruleStates : PHashMap RuleName RuleState
/-- A map from hypotheses to the rules and premises that they matched against
when they were initially added to the rule state. Invariant: the rule states
in which a hypothesis `h` appear are exactly those identified by the rule
names in `hyps[h]`. Furthermore, `h` only appears in slots with premise
indices greater than or equal to those in `hyps[h]`. -/
hyps : PHashMap FVarId (PArray (RuleName × PremiseIndex))
/-- The pattern substitutions present in the rule states. Invariant:
`patSubsts` maps the source `s` to a rule name `r` and pattern substitution `i`
iff the rule state of `r` contains `i` with source `s`. -/
patSubsts : PHashMap PatSubstSource (PArray (RuleName × Substitution))
/-- Normalised types of all non-implementation detail hypotheses in the
local context. -/
hypTypes : PHashSet RPINF
deriving Inhabited
namespace ForwardState
instance : EmptyCollection ForwardState where
emptyCollection := by refine' {..} <;> exact .empty
instance : ToMessageData ForwardState where
toMessageData fs :=
flip MessageData.joinSep "\n" $
fs.ruleStates.foldl (init := []) λ result r rs =>
m!"{r}:{indentD $ toMessageData rs}" :: result
private def addForwardRuleMatches (acc : Array ForwardRuleMatch)
(r : ForwardRule) (completeMatches : Array CompleteMatch) :
MetaM (Array ForwardRuleMatch) := do
let ruleMatches :=
completeMatches.foldl (init := acc) λ ruleMatches «match» =>
ruleMatches.push { rule := r, «match» }
aesop_trace[forward] do
for m in ruleMatches do
aesop_trace![forward] "new complete match for {m.rule.name}:{indentD $ toMessageData m}"
return ruleMatches
/-- Add a hypothesis to the forward state. If `fs` represents a local context
`lctx`, then `fs.addHyp h ms` represents `lctx` with `h` added. `ms` must
overapproximate the rules for which `h` may unify with a maximal premise. -/
def addHypCore (ruleMatches : Array ForwardRuleMatch) (goal : MVarId)
(h : FVarId) (ms : Array (ForwardRule × PremiseIndex))
(fs : ForwardState) : BaseM (ForwardState × Array ForwardRuleMatch) := do
goal.withContext do
withConstAesopTraceNode .forward (return m!"add hyp {Expr.fvar h} ({h.name})") do
let hTypeRPINF ← rpinf (← h.getType)
if (← isProp hTypeRPINF.toExpr) && fs.hypTypes.contains hTypeRPINF then
aesop_trace[forward] "a hyp with the same (propositional) type was already added"
return (fs,ruleMatches)
let fs := { fs with hypTypes := fs.hypTypes.insert hTypeRPINF }
ms.foldlM (init := (fs, ruleMatches)) λ (fs, ruleMatches) (r, i) => do
withConstAesopTraceNode .forward (return m!"rule {r.name}, premise {i}") do
let rs := fs.ruleStates.find? r.name |>.getD r.initialRuleState
let (rs, newRuleMatches) ← rs.addRawHyp goal (.fvarId h) i
let ruleStates := fs.ruleStates.insert r.name rs
let hyps := fs.hyps.insert h $
ms.map (λ (r, i) => (r.name, i)) |>.toPArray'
let fs := { fs with ruleStates, hyps }
let ms ← addForwardRuleMatches ruleMatches r newRuleMatches
return (fs, ms)
@[inherit_doc addHypCore]
def addHyp (goal : MVarId) (h : FVarId)
(ms : Array (ForwardRule × PremiseIndex)) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) :=
fs.addHypCore #[] goal h ms
/-- Add a pattern substitution to the forward state. -/
def addPatSubstCore (ruleMatches : Array ForwardRuleMatch) (goal : MVarId)
(r : ForwardRule) (patSubst : Substitution) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) :=
goal.withContext do
withConstAesopTraceNode .forward (return m!"add pat inst {patSubst} to rule {r.name}") do
let rs := fs.ruleStates.find? r.name |>.getD r.initialRuleState
let some (_, patSlotPremiseIdx) := r.rulePatternInfo?
| throwError "aesop: internal error: addPatSubstCore: rule {r.name} does not have a rule pattern"
let (rs, newRuleMatches) ←
rs.addRawHyp goal (.patSubst patSubst) patSlotPremiseIdx
let fs := { fs with ruleStates := fs.ruleStates.insert r.name rs }
let ms ← addForwardRuleMatches ruleMatches r newRuleMatches
return (fs, ms)
@[inherit_doc addPatSubstCore]
def addPatSubst (goal : MVarId) (r : ForwardRule) (patSubst : Substitution)
(fs : ForwardState) : BaseM (ForwardState × Array ForwardRuleMatch) :=
fs.addPatSubstCore #[] goal r patSubst
/-- Add multiple pattern substitutions to the forward state. -/
def addPatSubstsCore (ruleMatches : Array ForwardRuleMatch) (goal : MVarId)
(patSubsts : Array (ForwardRule × Substitution)) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) := do
patSubsts.foldlM (init := (fs, ruleMatches))
λ (fs, ruleMatches) (r, patSubst) =>
fs.addPatSubstCore ruleMatches goal r patSubst
@[inherit_doc addPatSubstsCore]
def addPatSubsts (goal : MVarId) (patSubsts : Array (ForwardRule × Substitution))
(fs : ForwardState) : BaseM (ForwardState × Array ForwardRuleMatch) :=
fs.addPatSubstsCore #[] goal patSubsts
/-- Add a hypothesis and to the forward state, along with any rule pattern
substitutions obtained from it. -/
def addHypWithPatSubstsCore (ruleMatches : Array ForwardRuleMatch) (goal : MVarId)
(h : FVarId) (ms : Array (ForwardRule × PremiseIndex))
(patSubsts : Array (ForwardRule × Substitution)) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) := do
let (fs, ruleMatches) ← fs.addHypCore ruleMatches goal h ms
fs.addPatSubstsCore ruleMatches goal patSubsts
@[inherit_doc addHypWithPatSubstsCore]
def addHypWithPatSubsts (goal : MVarId) (h : FVarId)
(ms : Array (ForwardRule × PremiseIndex))
(patSubsts : Array (ForwardRule × Substitution)) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) :=
fs.addHypWithPatSubstsCore #[] goal h ms patSubsts
/-- Erase pattern substitutions with the given source. -/
def erasePatSubsts (source : PatSubstSource) (fs : ForwardState) :
ForwardState := Id.run do
let mut ruleStates := fs.ruleStates
for (r, inst) in fs.patSubsts[source].getD {} do
let some rs := ruleStates.find? r
| panic! s!"patSubsts entry for rule {r}, but no rule state"
let rs := rs.erasePatSubst inst source
ruleStates := ruleStates.insert r rs
return { fs with patSubsts := fs.patSubsts.erase source, ruleStates }
/-- Remove a hypothesis from the forward state. If `fs` represents a local
context `lctx`, then `fs.eraseHyp h ms` represents `lctx` with `h` removed.
`type` must be the normalised type of `h`. `ms` must contain all rules for which
`h` may unify with a maximal premise. -/
def eraseHyp (h : FVarId) (type : RPINF) (fs : ForwardState) :
ForwardState := Id.run do
let mut ruleStates := fs.ruleStates
for (r, i) in fs.hyps[h].getD {} do
let some rs := ruleStates.find? r
| panic! s!"hyps entry for rule {r}, but no rule state"
let rs := rs.eraseHyp h i
ruleStates := ruleStates.insert r rs
let fs := {
fs with
hyps := fs.hyps.erase h, ruleStates
hypTypes := fs.hypTypes.erase type
}
fs.erasePatSubsts (.hyp h)
/-- Erase all pattern substitutions whose source is the target. -/
def eraseTargetPatSubsts (fs : ForwardState) : ForwardState :=
fs.erasePatSubsts .target
/-- Update the pattern substitutions after the goal's target changed.
`goal` is the new goal. `newPatSubsts` are the new target's pattern
substitutions. -/
def updateTargetPatSubstsCore (ruleMatches : Array ForwardRuleMatch)
(goal : MVarId)
(newPatSubsts : Array (ForwardRule × Substitution)) (fs : ForwardState) :
BaseM (ForwardState × Array ForwardRuleMatch) :=
-- TODO Instead of erasing all target pattern substitutions, erase only those
-- not present in the new target.
let fs := fs.eraseTargetPatSubsts
fs.addPatSubstsCore ruleMatches goal newPatSubsts
@[inherit_doc updateTargetPatSubstsCore]
def updateTargetPatSubsts (goal : MVarId)
(newPatSubsts : Array (ForwardRule × Substitution))
(fs : ForwardState) : BaseM (ForwardState × Array ForwardRuleMatch) :=
fs.updateTargetPatSubstsCore #[] goal newPatSubsts
end Aesop.ForwardState |
.lake/packages/aesop/Aesop/Forward/LevelIndex.lean | module
public section
namespace Aesop
structure LevelIndex where
toNat : Nat
deriving Inhabited, BEq, Hashable, DecidableEq, Ord
instance : LT LevelIndex where
lt i j := i.toNat < j.toNat
instance : DecidableRel (α := LevelIndex) (· < ·) :=
λ i j => inferInstanceAs $ Decidable (i.toNat < j.toNat)
instance : LE LevelIndex where
le i j := i.toNat ≤ j.toNat
instance : DecidableRel (α := LevelIndex) (· ≤ ·) :=
λ i j => inferInstanceAs $ Decidable (i.toNat ≤ j.toNat)
instance : ToString LevelIndex where
toString i := toString i.toNat
end Aesop |
.lake/packages/aesop/Aesop/Forward/Match.lean | module
public import Aesop.Forward.Match.Types
public import Aesop.Rule
public import Aesop.Script.ScriptM
import Aesop.RPINF
import Aesop.RuleTac.ElabRuleTerm
import Aesop.Script.SpecificTactics
import Aesop.RuleTac.Forward.Basic
import Batteries.Lean.Meta.UnusedNames
import Lean.Meta.Tactic.Apply
public section
set_option linter.missingDocs true
open Lean Lean.Meta
namespace Aesop
/-- Elaborate the term of a forward rule in the current goal. -/
def elabForwardRuleTerm (goal : MVarId) : RuleTerm → MetaM Expr
| .const n => mkConstWithFreshMVarLevels n
| .term stx =>
(withFullElaboration $ elabRuleTermForApplyLikeMetaM goal stx).run'
namespace Match
/-- Create a one-element match. `subst` is the substitution that results from
matching a hypothesis against slot 0, or from a pattern substitution.
`isPatSubst` is `true` if the substitution resulted from a rule pattern.
`forwardDeps` are the forward dependencies of slot 0. `conclusionDeps` are the
conclusion dependencies of the rule to which this match belongs. -/
def initial (subst : Substitution) (isPatSubst : Bool)
(forwardDeps conclusionDeps : Array PremiseIndex) : Match where
subst := subst
patInstSubsts := if isPatSubst then #[subst] else #[]
level := ⟨0⟩
forwardDeps := forwardDeps
conclusionDeps := conclusionDeps
/-- Add a hyp or pattern substitution to the match. `subst` is the substitution
that results from matching a hypothesis against slot `m.level + 1`, or from the
pattern. `isPatSubst` is `true` if the substitution resulted from a pattern
substitution. `forwardDeps` are the forward dependencies of slot
`m.level + 1`. -/
def addHypOrPatSubst (subst : Substitution) (isPatSubst : Bool)
(forwardDeps : Array PremiseIndex) (m : Match) : Match where
subst := m.subst.mergeCompatible subst
patInstSubsts :=
if isPatSubst then m.patInstSubsts.push subst else m.patInstSubsts
level := m.level + 1
forwardDeps := forwardDeps
conclusionDeps := m.conclusionDeps
/-- Returns `true` if the match contains the given hyp. -/
def containsHyp (hyp : FVarId) (m : Match) : Bool :=
m.subst.premises.any (·.any (·.toExpr.containsFVar hyp))
/-- Returns `true` if the match contains the given pattern substitution. -/
def containsPatSubst (subst : Substitution) (m : Match) : Bool :=
m.patInstSubsts.any (· == subst)
end Match
namespace CompleteMatch
/-- Given a complete match `m` for `r`, get arguments to `r` contained in the
match's slots and substitution. For non-immediate arguments, we return `none`.
The returned levels are suitable assignments for the level mvars of `r`. -/
def reconstructArgs (r : ForwardRule) (m : CompleteMatch) :
Array (Option RPINF) × Array (Option Level) := Id.run do
assert! m.clusterMatches.size == r.slotClusters.size
let mut subst : Substitution := .empty r.numPremises r.numLevelParams
for m in m.clusterMatches do
subst := m.subst.mergeCompatible subst
let mut args := Array.mkEmpty r.numPremises
for i in [:r.numPremises] do
args := args.push $ subst.find? ⟨i⟩
let mut levels := Array.mkEmpty r.numLevelParams
for i in [:r.numLevelParams] do
levels := levels.push $ subst.findLevel? ⟨i⟩
return (args, levels)
set_option linter.missingDocs false in
protected def toMessageData (r : ForwardRule) (m : CompleteMatch) :
MessageData :=
m!"{m.reconstructArgs r |>.1.map λ | none => m!"_" | some e => m!"{e}"}"
end CompleteMatch
namespace ForwardRuleMatch
instance : ToMessageData ForwardRuleMatch where
toMessageData m := m!"{m.rule.name} {m.match.toMessageData m.rule}"
/-- Fold over the hypotheses contained in a match. -/
def foldHypsM [Monad M] (f : σ → FVarId → M σ) (init : σ)
(m : ForwardRuleMatch) : M σ :=
m.match.clusterMatches.foldlM (init := init) λ s cm =>
cm.subst.premises.foldlM (init := s) λ
| s, some { toExpr := e, .. } =>
if let .fvar hyp := e.consumeMData then f s hyp else pure s
| s, _ => pure s
/-- Fold over the hypotheses contained in a match. -/
def foldHyps (f : σ → FVarId → σ) (init : σ) (m : ForwardRuleMatch) : σ :=
m.foldHypsM (M := Id) f init
/-- Returns `true` if any hypothesis contained in `m` satisfies `f`. -/
def anyHyp (m : ForwardRuleMatch) (f : FVarId → Bool) : Bool :=
m.match.clusterMatches.any λ m =>
m.subst.premises.any λ
| some { toExpr := e, .. } =>
if let .fvar hyp := e.consumeMData then f hyp else false
| _ => false
/-- Get the hypotheses from the match whose types are propositions. -/
def getPropHyps (m : ForwardRuleMatch) : MetaM (Array FVarId) :=
m.foldHypsM (init := Array.mkEmpty m.rule.numPremises) λ hs h => do
if ← isProof (.fvar h) then return hs.push h else return hs
/-- Construct the proof of the new hypothesis represented by `m`. -/
def getProof (goal : MVarId) (m : ForwardRuleMatch) : MetaM (Option Expr) :=
withExceptionPrefix s!"while constructing a new hyp for forward rule {m.rule.name}:\n" do
withConstAesopTraceNode .forward (return m!"proof construction for forward rule match") do
goal.withContext do
withNewMCtxDepth do
aesop_trace[forward] "rule: {m.rule.name}"
let e ← elabForwardRuleTerm goal m.rule.term
let lmvars := collectLevelMVars {} e |>.result
let eType ← instantiateMVars (← inferType e)
aesop_trace[forward] "term: {e} : {eType}"
let (argMVars, binderInfos, _) ← withReducible do
forallMetaTelescope (← inferType e)
if argMVars.size != m.rule.numPremises then
throwError "rule term{indentExpr e}\nwith type{indentExpr eType}\n was expected to have {m.rule.numPremises} arguments, but has {argMVars.size}"
if lmvars.size != m.rule.numLevelParams then
throwError "rule term{indentExpr e}\nwith type{indentExpr eType}\n was expected to have {m.rule.numLevelParams} level metavariables, but has {lmvars.size}"
let (args, levels) := m.match.reconstructArgs m.rule
aesop_trace[forward] "args: {args.map λ | none => m!"_" | some e => m!"{e}"}"
aesop_trace[forward] "levels: {levels.map λ | none => m!"_" | some l => m!"{l}"}"
for level? in levels, lmvarId in lmvars do
if let some level := level? then
assignLevelMVar lmvarId level
for arg? in args, mvar in argMVars do
if let some arg := arg? then
mvar.mvarId!.assign arg.toExpr
try
synthAppInstances `aesop goal argMVars binderInfos
(synthAssignedInstances := false) (allowSynthFailures := false)
catch _ =>
aesop_trace[forward] "instance synthesis failed"
return none
let result := (← abstractMVars $ mkAppN e argMVars).expr
aesop_trace[forward] "result: {result}"
return result
/-- Apply a forward rule match to a goal. This adds the hypothesis corresponding
to the match to the local context. Returns the new goal, the added hypothesis
and the hypotheses that were removed (if any). Hypotheses may be removed if the
match is for a `destruct` rule. If the `skip` function, when applied to the
normalised type of the new hypothesis, returns true, then the hypothesis is not
added to the local context. -/
def apply (goal : MVarId) (m : ForwardRuleMatch) (skip? : Option (RPINF → Bool)) :
ScriptT BaseM (Option (MVarId × FVarId × Array FVarId)) :=
withConstAesopTraceNode .forward (return m!"apply complete match") do
goal.withContext do
let name ← getUnusedUserName forwardHypPrefix
let some prf ← m.getProof goal
| return none
let type ← inferType prf
if let some skip := skip? then
let doSkip ← withConstAesopTraceNode .forwardDebug (return m!"check whether hyp already exists") do
let result := skip (← rpinf type)
aesop_trace[forwardDebug] "already exists: {result}"
pure result
if doSkip then
return none
let hyp := { userName := name, value := prf, type }
let (goal, #[hyp]) ← assertHypothesisS goal hyp (md := .default)
| unreachable!
if ! m.rule.destruct then
return some (goal, hyp, #[])
let usedPropHyps ← goal.withContext $ m.getPropHyps
let (goal, _) ← tryClearManyS goal usedPropHyps
return some (goal, hyp, usedPropHyps)
end ForwardRuleMatch
private def forwardRuleMatchesToRules? (ms : Array ForwardRuleMatch)
(mkExtra? : ForwardRuleMatch → Option α) :
Option (Array (Rule α)) := Id.run do
let mut ruleMap : Std.HashMap RuleName (Array ForwardRuleMatch) := ∅
for m in ms do
let name := m.rule.name
if let some ms := ruleMap[name]? then
ruleMap := ruleMap.insert name (ms.push m)
else
ruleMap := ruleMap.insert name #[m]
let mut result := Array.mkEmpty ruleMap.size
for (name, ms) in ruleMap do
let some extra := mkExtra? ms[0]!
| return none
result := result.push {
indexingMode := .unindexed
pattern? := none
tac := .forwardMatches ms
name, extra
}
return some result
/-- Convert forward rule matches to norm rules. Fails if any of the matches is
not a norm rule match. -/
def forwardRuleMatchesToNormRules? (ms : Array ForwardRuleMatch) :
Option (Array NormRule) :=
forwardRuleMatchesToRules? ms
(·.rule.prio.penalty?.map ({ penalty := · }))
/-- Convert forward rule matches to safe rules. Fails if any of the matches is
not a safe rule match. -/
def forwardRuleMatchesToSafeRules? (ms : Array ForwardRuleMatch) :
Option (Array SafeRule) :=
forwardRuleMatchesToRules? ms
(·.rule.prio.penalty?.map ({ penalty := ·, safety := .safe }))
/-- Convert forward rule matches to unsafe rules. Fails if any of the matches
is not an unsafe rule match. -/
def forwardRuleMatchesToUnsafeRules? (ms : Array ForwardRuleMatch) :
Option (Array UnsafeRule) :=
forwardRuleMatchesToRules? ms
(·.rule.prio.successProbability?.map ({ successProbability := · }))
end Aesop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.