blob: 043dd71dddb4d9045eca80274ae3bdc4a7e9bba9 [file]
/-
Copyright (c) 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
module
prelude
public import Lean.Meta.Sym.Simp.Simproc
public import Lean.Meta.Sym.Simp.Theorems
public import Lean.Meta.Sym.Simp.App
public import Lean.Meta.Sym.Simp.Discharger
import Lean.Meta.ACLt
import Lean.Meta.Sym.InstantiateS
import Lean.Meta.Sym.InstantiateMVarsS
import Init.Data.Range.Polymorphic.Iterators
namespace Lean.Meta.Sym.Simp
open Lean.Meta.Grind
/--
Creates proof term for a rewriting step.
Handles both constant expressions (common case, avoids `instantiateLevelParams`)
and general expressions.
-/
def mkValue (expr : Expr) (pattern : Pattern) (us : List Level) (args : Array Expr) : Expr :=
if let .const declName [] := expr then
mkAppN (mkConst declName us) args
else
mkAppN (expr.instantiateLevelParams pattern.levelParams us) args
/--
Tries to rewrite `e` using the given theorem.
-/
public def Theorem.rewrite (thm : Theorem) (e : Expr) (d : Discharger := dischargeNone) : SimpM Result :=
/-
**Note**: We use `withNewMCtxDepth` to ensure auxiliary metavariables used during the `match?`
do not pollute the metavariable context.
Thus, we must ensure that all assigned variables have be instantiate.
-/
withNewMCtxDepth do
let mvarCounterSaved := (← getMCtx).mvarCounter
if let some result ← thm.pattern.match? e then
-- **Note**: Potential optimization: check whether pattern covers all variables.
let mut args := result.args.toVector
let us ← result.us.mapM instantiateLevelMVars
-- Track whether any discharger used context-dependent information.
-- If so, the result is context-dependent: in another context, the discharger
-- might succeed/fail differently, changing whether the rewrite applies.
let mut isCD := false
for h : i in *...args.size do
let arg := args[i]
if let .mvar mvarId := arg then
if (← mvarId.isAssigned) then
let arg ← instantiateMVarsS arg
args := args.set i arg
else
let decl ← mvarId.getDecl
-- Metavariables created by `match?` (index ≥ `mvarCounterSaved`) stand for
-- hypotheses/instances not covered by the pattern and must be discharged.
-- Metavariables occurring in `e` itself are opaque atoms; leave them as-is.
if decl.index ≥ mvarCounterSaved then
match (← d decl.type) with
| .failed cd =>
isCD := isCD || cd
-- Failed to discharge hypothesis.
return mkRflResultCD isCD
| .solved val cd =>
isCD := isCD || cd
-- Dischargers are not required to return maximally shared proofs. Sharing is
-- needed only when the hypothesis occurs in `rhs`, and the proof consequently
-- becomes part of the resulting term.
let val ← if thm.rhsVarMask.testBit i then
shareCommon (← instantiateMVars val)
else
instantiateMVars val
mvarId.assign val
args := args.set i val
else if arg.hasMVar then
let arg ← instantiateMVarsS arg
args := args.set i arg
let proof := mkValue thm.expr thm.pattern us args.toArray
let rhs := thm.rhs.instantiateLevelParams thm.pattern.levelParams us
let rhs ← share rhs
let expr ← instantiateRevBetaS rhs args.toArray
if isSameExpr e expr then
return mkRflResultCD isCD
else if !(← checkPerm thm.perm e expr) then
return mkRflResultCD isCD
else
return .step expr proof (contextDependent := isCD)
else
return .rfl
where
checkPerm (perm : Bool) (e result : Expr) : MetaM Bool := do
if !perm then return true
acLt result e
/--
Tries to rewrite `e` using the given `candidates`. `anyCD` is the context-dependency flag
accumulated by previous attempts. Returns the result and the updated flag.
-/
def rewriteUsing (candidates : Array (Theorem × Nat)) (e : Expr) (d : Discharger) (anyCD : Bool) : SimpM (Result × Bool) := do
-- Track `cd` across all attempted theorems. If theorem A fails with cd=true
-- and theorem B succeeds with cd=false, the result is still cd=true: in another
-- context A might succeed (with higher priority) and produce a different result.
let mut anyCD := anyCD
for (thm, numExtra) in candidates do
let result ← if numExtra == 0 then
thm.rewrite e d
else
simpOverApplied e numExtra (thm.rewrite · d)
anyCD := anyCD || result.isContextDependent
if !result.isRfl then
return (if anyCD && !result.isContextDependent then result.withContextDependent else result, anyCD)
return (mkRflResultCD anyCD, anyCD)
/--
Rewrites `e` using the first applicable theorem in `thms`. The fallback theorems
(`Theorem.fallback`) are tried only when no other theorem rewrites `e`.
-/
public def Theorems.rewrite (thms : Theorems) (d : Discharger := dischargeNone) : Simproc := fun e => do
let mctx ← getMCtx
let (result, anyCD) ← rewriteUsing (thms.getMatchWithExtra mctx e) e d false
if result.isRfl && !thms.fallback.root.isEmpty then
return (← rewriteUsing (thms.getFallbackMatchWithExtra mctx e) e d anyCD).1
return result
end Lean.Meta.Sym.Simp