blob: a08afa262e985779f2a094fddf1082225bf373c6 [file]
/-
Copyright (c) 2026 Lean FRO LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Graf
-/
module
prelude
public import Lean.Meta.Tactic.Grind.Main
public import Lean.Elab.Tactic.VCGen.Context
public import Lean.Elab.Tactic.VCGen.Reduce
public import Lean.Meta.Sym.AlphaShareBuilder
public import Lean.Meta.Sym.InstantiateMVarsS
public import Lean.Meta.Sym.Intro
public import Lean.Meta.Sym.Simp.Goal
public import Lean.Meta.Sym.Simp.Telescope
public import Lean.Meta.Sym.Util
open Lean Meta Sym Lean.Order
/-!
Generic `VCGenM` helpers: checked backward-rule application, telescope-aware `simp` driver,
hygienic binder introduction, hypothesis-internalization for grind, and the emission-time cleanup
`cleanupVC`. None of these know anything about the entailment shapes `solve` decomposes.
-/
namespace Lean.Elab.Tactic.VCGen
/-- Completes the class application `@cls x₁ … xₙ` to an instance. The array `xs` works as in
`mkAppOptM`: `some x` fixes an argument and `none` leaves it to instance search. The result holds
all arguments of `cls` in order and the instance. Example: for `cls := ToEStack` and
`xs := #[some E]`, the result is `(#[E, T, instE, instT], inst)`. -/
public def synthInstanceOpt? (cls : Name) (xs : Array (Option Expr)) :
MetaM (Option (Array Expr × Expr)) :=
withNewMCtxDepth do
let c ← mkConstWithFreshMVarLevels cls
let (args, _, _) ← forallMetaTelescopeReducing (← inferType c)
if xs.size > args.size then
throwError "synthInstanceOpt?: too many arguments for `{cls}`"
for arg in args, x? in xs do
if let some x := x? then
unless ← isDefEq arg x do return none
let some inst ← synthInstance? (mkAppN c args) | return none
let args ← args.mapM instantiateMVars
let inst ← instantiateMVars inst
if inst.hasExprMVar || args.any (·.hasExprMVar) then return none
return some (args, inst)
/-- Change `goal`'s `Prop`-typed target to the definitionally-equal `targetNew`, assigning `goal` a
fresh synthetic-opaque goal for `targetNew`, so the kernel checks the two types against each other.
Unlike `MVarId.replaceTargetDefEq` it skips the `instantiateMVars`/`Expr.equal` round-trip, so it
neither detects a no-op change nor supports a non-`Prop` target; the caller must pass a genuinely
different `targetNew` definitionally equal to the current target. -/
public def _root_.Lean.MVarId.replaceTargetDefEqFast (goal : MVarId) (targetNew : Expr) :
MetaM MVarId := goal.withContext do
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew (← goal.getTag)
goal.assign mvarNew
return mvarNew.mvarId!
/-- Internalize a backward rule's pattern into the current `SymM` share table. See
`Pattern.shareCommon`. Designed for dot notation: `rule.shareCommon`. -/
public def _root_.Lean.Meta.Sym.BackwardRule.shareCommon (rule : BackwardRule) : SymM BackwardRule :=
return { rule with pattern := ← rule.pattern.shareCommon }
/--
`VCGenM` wrapper around `BackwardRule.apply`. Behaves identically to
`rule.apply goal` unless the application fails and `Context.debug` is on.
In that case it retries on a fresh metavariable whose type is the
`unfoldReducible`-normalized goal type. If the retry succeeds, an earlier
step forgot a normalization; we throw a hard error pointing at the rule and
the missing reduction.
`ruleDesc?` describes the rule for debug output. When `none`, the description
is reconstructed from `rule.expr.getAppFn` — works for the common case of a
constant rule. Pass a custom message for dynamically-built rules.
Designed for dot notation: `rule.applyChecked goal`. Requires
`open Lean.Elab.Tactic.VCGen` in scope so that the dot lookup resolves.
-/
public def Lean.Meta.Sym.BackwardRule.applyChecked (rule : BackwardRule) (goal : MVarId)
(ruleDesc? : Option MessageData := none) : VCGenM ApplyResult := do
let r ← rule.apply goal
match r with
| .goals _ => return r
| .failed =>
unless (← read).debug do return r
let originalType ← goal.getType
let normalized ← unfoldReducible originalType
if normalized == originalType then return r
let succeeded ← Lean.Meta.withoutModifyingMCtx do
let goal' ← Meta.mkFreshExprSyntheticOpaqueMVar normalized
match ← rule.apply goal'.mvarId! with
| .goals _ => return true
| .failed => return false
if succeeded then
let ruleDesc := ruleDesc?.getD <|
match rule.expr.getAppFn with
| .const declName _ => m!"`{.ofConstName declName}`"
| _ => m!"<rule constructed from expression>"
throwError m!"[vcgen +debug] BackwardRule {ruleDesc} failed to \
apply to:{indentExpr originalType}\nbut succeeded after `unfoldReducible`-\
normalization to:{indentExpr normalized}\nAn earlier step is missing a normalization. \
Re-run with `set_option pp.all true` to see the structural difference."
return r
open Sym Sym.Internal
open Lean.Elab.Tactic.VCGen
/-- `Grind.processHypotheses` if `Context.internalize` is `true`, otherwise a no-op. -/
public def processHypotheses (goal : Grind.Goal) : VCGenM Grind.Goal := do
if (← read).internalize then Grind.processHypotheses goal else return goal
/-- Whether `n` is a program variable's own name: no macro scopes and no implementation-detail
`__` prefix. Such a name stays accessible in a verification condition. -/
public def isProgramName (n : Name) : Bool :=
!n.hasMacroScopes && !n.isImplementationDetail
/-- The number of leading `∀` and `let` binders of `type`. -/
public def numBindersToIntro : Expr → Nat
| .forallE _ _ b _ => numBindersToIntro b + 1
| .letE _ _ _ b _ => numBindersToIntro b + 1
| _ => 0
/-- Introduce the first `n` binders of `goal`, named by `mkFreshBinderNameForTactic`, which
`tactic.hygienic` makes inaccessible: `∀ acc, acc % 2 = 0` introduces `acc✝`. -/
public def introsHygienicN (goal : MVarId) (n : Nat) : VCGenM MVarId :=
goal.withContext do
let rec collectBinders : Nat → Expr → Array Name → Array Name
| 0, _, acc => acc
| n+1, .forallE nm _ b _, acc => collectBinders n b (acc.push nm)
| n+1, .letE nm _ _ b _, acc => collectBinders n b (acc.push nm)
| _, _, acc => acc
let binderNames := collectBinders n (← goal.getType) #[]
if binderNames.isEmpty then return goal
let mut names := #[]
for nm in binderNames do
names := names.push (← Meta.mkFreshBinderNameForTactic nm)
let .goal _ goal ← Sym.intros goal names | return goal
return goal
public def instantiateBinderDomains (goal : MVarId) : VCGenM MVarId := do
let target ← goal.getType
let target' ← go target
if isSameExpr target' target then return goal else goal.replaceTargetDefEqFast target'
where
go : Expr → SymM Expr
| e@(.forallE _ d b _) => do e.updateForallS! (← instantiateMVarsS d) (← go b)
| e@(.letE _ t v b _) => do e.updateLetS! (← instantiateMVarsS t) v (← go b)
| e => return e
/-- `introsHygienicN` for every non-`Prod` binder the goal leads with. -/
public def introsHygienic (goal : MVarId) : VCGenM MVarId := do
let goal ← instantiateBinderDomains goal
introsHygienicN goal (numBindersToIntro (← goal.getType))
/--
Simplify the hypotheses of the goal's target `h₁ → … → hₙ → G` with `Context.simpMethods`, leaving
`G` untouched, and thread the persistent simp cache through `VCGenM`'s state. `.noProgress` is
forwarded to the caller.
-/
public def simpGoalTelescope (goal : MVarId) : VCGenM Sym.SimpGoalResult := do
let some methods := (← read).simpMethods | return .noProgress
let target ← goal.getType
(← runSimp methods (Sym.Simp.simpTelescope target)).toSimpGoalResult goal
/--
Introduce the excess state arguments of an entailment goal `pre ⊑ rhs` whose lattice type is a
function type `σ₁ → … → σₙ → α`: repeatedly apply `stateArgIntro` (a backward rule for
`Lean.Order.le_of_forall_le`) and introduce the new state binder, until the lattice type is
no longer a function type. A state binder that a `@[vcgen_rintro]` rule matches stays in the
target for `solve` to destructure. Returns `none` when the carrier is not a function type (nothing
to introduce); throws when the carrier is a function type that `le_of_forall_le` cannot peel, such
as a dependent function lattice `(a : α) → β a → …`.
-/
public partial def introsExcessArgs (goal : MVarId) :
VCGenM (Option MVarId) := goal.withContext do
let type ← goal.getType
let_expr PartialOrder.rel α _inst _pre _rhs := type | return none
unless α.isForall do return none
let .goals [goal] ← (← read).backwardRules.stateArgIntro.applyChecked goal
| throwError "failed to apply {.ofConstName ``Lean.Order.le_of_forall_le} to goal{indentExpr type}"
unless (Sym.getMatch (← getMCtx) (← read).rintros (← goal.getType)).isEmpty do return some goal
let goal ← introsHygienic goal
return (← introsExcessArgs goal) <|> some goal
/--
Solves conjunctions whose leaves are `True` or `e₁ = e₂`, and returns a residual goal containing
exactly the conjuncts that could not be solved.
The goal is head-reduced first, so a conjunction that a `match` on a constructor or a projection
of a tuple leaves behind a redex is still recognized.
This procedure may assign metavariables in `e₁`/`e₂`, for example for `e = ?m` it will assign
`?m := e`.
-/
public partial def cleanupVC (goal : MVarId) : VCGenM (Option MVarId) :=
goal.withContext do
let ctx ← read
let ty ← instantiateMVarsIfMVarAppS (← goal.getType)
let (goal, ty) ← match ← reduceHead? ty with
| some ty' => pure (← goal.replaceTargetDefEqFast ty', ty')
| none => pure (goal, ty)
if ty.isAppOf ``True then
goal.assign (mkConst ``True.intro)
return none
else if ty.isAppOf ``And then
let .goals [g₁, g₂] ← ctx.backwardRules.andIntro.applyChecked goal
| throwError "cleanupVC: failed to apply {.ofConstName ``And.intro} to{indentExpr ty}"
match ← cleanupVC g₁, ← cleanupVC g₂ with
| none, none => return none
| some g, none => return some g
| none, some g => return some g
| some g₁', some g₂' =>
let t₁ ← g₁'.getType
let t₂ ← g₂'.getType
let combined ← mkFreshExprSyntheticOpaqueMVar (mkApp2 (mkConst ``And) t₁ t₂)
g₁'.assign (mkApp3 (mkConst ``And.left) t₁ t₂ combined)
g₂'.assign (mkApp3 (mkConst ``And.right) t₁ t₂ combined)
return some combined.mvarId!
else if let some (ty, lhs, rhs) := ty.app3? ``Eq then
let lhs ← reduceHead lhs
let rhs ← reduceHead rhs
let u ← Meta.getLevel ty
let goal ← goal.replaceTargetDefEqFast (mkApp3 (mkConst ``Eq [u]) ty lhs rhs)
-- Synthetic opaque metavariables (e.g. invariant holes) stay rigid; natural
-- metavariables may be assigned (e.g. `?m := e` for `e = ?m` leaves).
if ← isDefEqS lhs rhs then
goal.assign (mkApp2 (mkConst ``Eq.refl [← Meta.getLevel ty]) ty lhs)
return none
else
return some goal
else
return some goal
end Lean.Elab.Tactic.VCGen