|
| 1 | +/- |
| 2 | +Copyright (c) 2023 Scott Morrison. All rights reserved. |
| 3 | +Released under Apache 2.0 license as described in the file LICENSE. |
| 4 | +Authors: Scott Morrison |
| 5 | +-/ |
| 6 | +import Mathlib.Data.ListM.Heartbeats |
| 7 | +import Mathlib.Lean.Meta.DiscrTree |
| 8 | +import Mathlib.Tactic.Cache |
| 9 | +import Mathlib.Tactic.SolveByElim |
| 10 | +import Mathlib.Tactic.TryThis |
| 11 | +import Mathlib.Control.Basic |
| 12 | + |
| 13 | +/-! |
| 14 | +# The `rewrites` tactic. |
| 15 | +
|
| 16 | +`rewrites` tries to find a lemma which can rewrite the goal. |
| 17 | +
|
| 18 | +`rewrites` should not be left in proofs; it is a search tool, like `library_search`. |
| 19 | +
|
| 20 | +Suggestions are printed as `rw [h]` or `rw [←h]`. |
| 21 | +
|
| 22 | +## Future work |
| 23 | +It would be nice to have `rewrites at h`. |
| 24 | +
|
| 25 | +We could also try discharging side goals via `assumption` or `solve_by_elim`. |
| 26 | +
|
| 27 | +-/ |
| 28 | + |
| 29 | +namespace Mathlib.Tactic.Rewrites |
| 30 | + |
| 31 | +open Lean Meta Std.Tactic.TryThis |
| 32 | + |
| 33 | +initialize registerTraceClass `Tactic.rewrites |
| 34 | + |
| 35 | +initialize rewriteLemmas : DeclCache (DiscrTree (Name × Bool × Nat) true) ← |
| 36 | + DeclCache.mk "rewrites: init cache" {} fun name constInfo lemmas => do |
| 37 | + if constInfo.isUnsafe then return lemmas |
| 38 | + if ← name.isBlackListed then return lemmas |
| 39 | + if name matches .str _ "injEq" then return lemmas |
| 40 | + if name matches .str _ "sizeOf_spec" then return lemmas |
| 41 | + match name with |
| 42 | + | .str _ n => if n.endsWith "_inj" ∨ n.endsWith "_inj'" then return lemmas |
| 43 | + | _ => pure () |
| 44 | + let forwardWeight := 2 |
| 45 | + let backwardWeight := 1 |
| 46 | + withNewMCtxDepth do withReducible do |
| 47 | + let (_, _, type) ← forallMetaTelescopeReducing constInfo.type |
| 48 | + match type.getAppFnArgs with |
| 49 | + | (``Eq, #[_, lhs, rhs]) => do |
| 50 | + let lhsKey ← DiscrTree.mkPath lhs |
| 51 | + let rhsKey ← DiscrTree.mkPath rhs |
| 52 | + pure <| lemmas.insertIfSpecific lhsKey (name, false, forwardWeight * lhsKey.size) |
| 53 | + |>.insertIfSpecific rhsKey (name, true, backwardWeight * rhsKey.size) |
| 54 | + | (``Iff, #[lhs, rhs]) => do |
| 55 | + let lhsKey ← DiscrTree.mkPath lhs |
| 56 | + let rhsKey ← DiscrTree.mkPath rhs |
| 57 | + pure <| lemmas.insertIfSpecific lhsKey (name, false, forwardWeight * lhsKey.size) |
| 58 | + |>.insertIfSpecific rhsKey (name, true, backwardWeight * rhsKey.size) |
| 59 | + | _ => pure lemmas |
| 60 | + |
| 61 | +/-- Data structure recording a potential rewrite to report from the `rewrites` tactic. -/ |
| 62 | +structure RewriteResult where |
| 63 | + name : Name |
| 64 | + symm : Bool |
| 65 | + weight : Nat |
| 66 | + result : Meta.RewriteResult |
| 67 | + /-- Can the new goal in `result` be closed by `with_reducible rfl`? -/ |
| 68 | + -- This is an `Option` so that it can be computed lazily. |
| 69 | + refl? : Option Bool |
| 70 | + |
| 71 | +/-- Update a `RewriteResult` by filling in the `refl?` field if it is currently `none`, |
| 72 | +to reflect whether the remaining goal can be closed by `with_reducible rfl`. -/ |
| 73 | +def RewriteResult.computeRefl (r : RewriteResult) : MetaM RewriteResult := do |
| 74 | + if let some _ := r.refl? then |
| 75 | + return r |
| 76 | + try |
| 77 | + (← mkFreshExprMVar r.result.eNew).mvarId!.refl |
| 78 | + pure { r with refl? := some true } |
| 79 | + catch _ => |
| 80 | + pure { r with refl? := some false } |
| 81 | + |
| 82 | +/-- |
| 83 | +Find lemmas which can rewrite the goal. |
| 84 | +
|
| 85 | +This core function returns a monadic list, to allow the caller to decide how long to search. |
| 86 | +See also `rewrites` for a more convenient interface. |
| 87 | +-/ |
| 88 | +def rewritesCore (lemmas : DiscrTree (Name × Bool × Nat) s) (goal : MVarId) : |
| 89 | + ListM MetaM RewriteResult := ListM.squash do |
| 90 | + let type ← instantiateMVars (← goal.getType) |
| 91 | + -- Get all lemmas which could match some subexpression |
| 92 | + let candidates ← lemmas.getSubexpressionMatches type |
| 93 | + -- Sort them by our preferring weighting |
| 94 | + -- (length of discriminant key, doubled for the forward implication) |
| 95 | + let candidates := candidates.insertionSort fun r s => r.2.2 > s.2.2 |
| 96 | + -- Lift to a monadic list, so the caller can decide how much of the computation to run. |
| 97 | + let candidates := ListM.ofList candidates.toList |
| 98 | + pure <| candidates.filterMapM fun ⟨lem, symm, weight⟩ => do |
| 99 | + trace[Tactic.rewrites] "considering {if symm then "←" else ""}{lem}" |
| 100 | + let some result ← try? <| goal.rewrite type (← mkConstWithFreshMVarLevels lem) symm |
| 101 | + | return none |
| 102 | + return if result.mvarIds.isEmpty then |
| 103 | + some ⟨lem, symm, weight, result, none⟩ |
| 104 | + else |
| 105 | + -- TODO Perhaps allow new goals? Try closing them with solveByElim? |
| 106 | + none |
| 107 | + |
| 108 | +/-- Find lemmas which can rewrite the goal. -/ |
| 109 | +def rewrites (lemmas : DiscrTree (Name × Bool × Nat) s) (goal : MVarId) |
| 110 | + (max : Nat := 10) (leavePercentHeartbeats : Nat := 10) : MetaM (List RewriteResult) := |
| 111 | +rewritesCore lemmas goal |
| 112 | + -- Don't use too many heartbeats. |
| 113 | + |>.whileAtLeastHeartbeatsPercent leavePercentHeartbeats |
| 114 | + -- Stop if we find a rewrite after which `with_reducible rfl` would succeed. |
| 115 | + |>.mapM RewriteResult.computeRefl |
| 116 | + |>.takeUpToFirst (fun r => r.refl? = some true) |
| 117 | + -- Bound the number of results. |
| 118 | + |>.takeAsList max |
| 119 | + |
| 120 | +open Lean.Parser.Tactic |
| 121 | + |
| 122 | +/-- |
| 123 | +`rewrites` tries to find a lemma which can rewrite the goal. |
| 124 | +
|
| 125 | +`rewrites` should not be left in proofs; it is a search tool, like `library_search`. |
| 126 | +
|
| 127 | +Suggestions are printed as `rw [h]` or `rw [←h]`. |
| 128 | +`rewrites!` is the "I'm feeling lucky" mode, and will run the first rewrite it finds. |
| 129 | +-/ |
| 130 | +syntax (name := rewrites') "rewrites" "!"? : tactic |
| 131 | + |
| 132 | +open Elab.Tactic Elab Tactic in |
| 133 | +elab_rules : tactic | |
| 134 | + `(tactic| rewrites%$tk $[!%$lucky]?) => do |
| 135 | + let goal ← getMainGoal |
| 136 | + goal.withContext do |
| 137 | + let results ← rewrites (← rewriteLemmas.get) goal |
| 138 | + reportOutOfHeartbeats `rewrites tk |
| 139 | + if results.isEmpty then |
| 140 | + throwError "rewrites could not find any lemmas which can rewrite the goal" |
| 141 | + for r in results do |
| 142 | + let newGoal := if r.refl? = some true then Expr.lit (.strVal "no goals") else r.result.eNew |
| 143 | + addRewriteSuggestion tk (← mkConstWithFreshMVarLevels r.name) r.symm newGoal |
| 144 | + if lucky.isSome then |
| 145 | + match results[0]? with |
| 146 | + | some r => do |
| 147 | + replaceMainGoal |
| 148 | + ((← goal.replaceTargetEq r.result.eNew r.result.eqProof) :: r.result.mvarIds) |
| 149 | + evalTactic (← `(tactic| rfl)) |
| 150 | + | _ => failure |
| 151 | + |
| 152 | +@[inherit_doc rewrites'] macro "rewrites!" : tactic => |
| 153 | + `(tactic| rewrites !) |
0 commit comments