blob: 868085ebb1baa33bc7afb829f49b804d5d04cbbf [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, Vladimir Gladshtein
-/
module
prelude
public import Lean.Elab.Tactic.Do.VCGen.Split
public import Lean.Elab.Tactic.VCGen.Context
public import Lean.Elab.Tactic.VCGen.Reduce
public import Lean.Elab.Tactic.VCGen.SpecDB
import Lean.Elab.Tactic.VCGen.Util
import Lean.Elab.Tactic.VCGen.ExcessArgsFrame
public import Lean.Meta.Sym.Apply
public import Lean.Meta.Sym.Util
meta import Std.WP.Frame
open Lean Meta Elab Tactic Sym
open Lean.Elab.Tactic.VCGen.SpecAttr
namespace Lean.Elab.Tactic.VCGen
/-!
Construction of `BackwardRule`s from `SpecTheorem`s and split info, with no knowledge of `VCGenM`.
The `VCGenM` cache wrappers live in `VCGen.RuleCache`.
-/
open Std.WP Lean.Order
/-! ## Spec rules -/
/-- Build the explicit pointwise implication premise used to weaken a concrete `post`.
State binders are named positionally from `stateArgNames` (else `s`); their names ride
on the premise and are later introduced with the right user-facing names. -/
def mkPostPointwisePremise (postSpec postTarget postTy : Expr) (ssTypes : Array Expr)
(stateArgNames : Array Name := #[]) : MetaM Expr := do
let .forallE _ α _ _ := postTy
| throwError "expected a postcondition function, got {indentExpr postTy}"
withLocalDeclD `a α fun a => do
let ssNamesTypes := ssTypes.mapIdx fun i ty => (stateArgNames[i]?.getD `s, ty)
withLocalDeclsDND ssNamesTypes fun ss' => do
let lhs := postSpec.betaRev <| ss'.reverse.push a
let rhs := mkAppN (mkApp postTarget a) ss'
mkForallFVars (#[a] ++ ss') (← mkAppM ``PartialOrder.rel #[lhs, rhs])
/-- Reduce a projection of a constructor application, e.g. `(⟨R⟩ : Thrown).onThrow` to `R`.
Return any other term unchanged. -/
def reduceProjOfCtor (e : Expr) : MetaM Expr := do
let .const fn _ := e.getAppFn | return e
let some info ← getProjectionFnInfo? fn | return e
let args := e.getAppArgs
let some s := args[info.numParams]? | return e
let some f ← projectCore? s.consumeMData info.i | return e
return mkAppN f (args.extract (info.numParams + 1)) |>.headBeta
/-- Recursively decompose `epostsSpec ⊑ epostsAbstract` into per-component proofs.
- `(head, tail)` → mvar for `head ⊑ epostsAbstract.fst`, recurse on `tail`
- Otherwise, if `EPosts` is a product, project `epostsSpec.fst`/`.snd` and decompose those
- Otherwise, if `EPosts` is `Unit`, trivial via `Unit.unit_le`
- Otherwise, if `EPosts` is a function type, a pointwise mvar
- Otherwise, if `EPosts` has a `ToEStack` instance, decompose the entailment between the
stacks and reflect it via `ToEStack.le_of_toEStack_le`
- Otherwise → single mvar for `epostsSpec ⊑ epostsAbstract` -/
partial def decomposeProdRel (EPosts epostsSpec epostsAbstract : Expr)
(stateArgNames : Array Name := #[]) : MetaM Expr := do
match_expr epostsSpec with
| Prod.mk ehTy etTy head tail =>
let absHead ← mkAppM ``Prod.fst #[epostsAbstract]
let absTail ← mkAppM ``Prod.snd #[epostsAbstract]
let hTail ← decomposeProdRel etTy tail absTail stateArgNames
-- The components of a `toEStack` image are projections such as `(⟨R⟩ : Thrown).onThrow`.
let head ← reduceProjOfCtor head
/- Sometimes, even though `eposts` is not schematic itself, its components might be schematic.
Think of a triple of a kind `⦃ pre ⦄ x ⦃ post; eposts₁, ⊥, eposts₃, ⊥, ... ⦄`.
In this case we do not want to create new metavariables for `eposts₁`, `eposts₃`, etc.
Instead, we will just assign them to `epostsAbstract.snd.fst` and
`epostsAbstract.snd.snd.fst`, etc. -/
if head.isMVar then
head.mvarId!.assign absHead
mkAppM ``Prod.mk_le_snd #[tail, epostsAbstract, hTail]
else
-- Collect state types: e.g. String → Nat → Prop → skip first (exc type), rest are state types
let ssTypes ← forallTelescope ehTy fun xs _ => xs.drop 1 |>.mapM (Meta.inferType ·)
let headTy ← Meta.inferType head
let hHeadTy ← mkPostPointwisePremise head absHead headTy ssTypes stateArgNames
let hHead ← mkFreshExprMVar (userName := `epostsImpl) hHeadTy
mkAppM ``Prod.mk_le #[head, tail, epostsAbstract, hHead, hTail]
| _ =>
let EPosts := EPosts.consumeMData
match_expr EPosts with
| Prod ehTy etTy =>
let specHead ← mkAppM ``Prod.fst #[epostsSpec]
let specTail ← mkAppM ``Prod.snd #[epostsSpec]
let absHead ← mkAppM ``Prod.fst #[epostsAbstract]
let absTail ← mkAppM ``Prod.snd #[epostsAbstract]
let headTy ← Meta.inferType specHead
-- Collect state types: e.g. String → Nat → Prop → skip first (exc type), rest are state types
let ssTypes ← forallTelescope ehTy fun xs _ => xs.drop 1 |>.mapM (Meta.inferType ·)
let hHeadTy ← mkPostPointwisePremise specHead absHead headTy ssTypes stateArgNames
let hHead ← mkFreshExprMVar (userName := `epostsImpl) hHeadTy
let hTail ← decomposeProdRel etTy specTail absTail stateArgNames
mkAppM ``Prod.mk_le #[specHead, specTail, epostsAbstract, hHead, hTail]
| _ =>
let EPostsR ← whnfR EPosts
-- The terminator is reducibly `PUnit`, under any of its names.
if EPostsR.isConstOf ``PUnit then
mkAppM ``Unit.unit_le #[epostsAbstract]
else if EPostsR.isForall then
-- A bare `ε → σ → Prop`, e.g. of `Except ε`, yields a pointwise VC like a stack component.
let ssTypes ← forallTelescope EPostsR fun xs _ => xs.drop 1 |>.mapM (Meta.inferType ·)
let hTy ← mkPostPointwisePremise epostsSpec epostsAbstract EPostsR ssTypes stateArgNames
let h ← mkFreshExprMVar (userName := `epostsImpl) hTy
mkExpectedTypeHint h (← mkAppM ``PartialOrder.rel #[epostsSpec, epostsAbstract])
else if let some (args, inst) ← synthInstanceOpt? ``ToEStack #[some EPosts] then
let args := args.push inst
let toEStack ← mkAppOptM ``ToEStack.toEStack (args.map some)
-- `unfoldProjInst?` turns the image of a spec literal into a stack literal.
let stackSpec := mkApp toEStack epostsSpec
let stackAbstract := mkApp toEStack epostsAbstract
let h ← decomposeProdRel args[1]! ((← unfoldProjInst? stackSpec).getD stackSpec)
stackAbstract stateArgNames
withDefault <| mkAppOptM ``ToEStack.le_of_toEStack_le <|
(args.map some) ++ #[some epostsSpec, some epostsAbstract, some h]
else
let hTy ← mkAppM ``PartialOrder.rel #[epostsSpec, epostsAbstract]
mkFreshExprMVar (userName := `epostsImpl) hTy
/--
Create the proof term for the backward rule built from an instantiated spec theorem.
In order for the backward rule to apply, the concrete precondition, postcondition and exception
postcondition appearing in the spec may need to be generalized into rule parameters, emitting
verification conditions for the generalization.
### General idea
Consider the spec theorem `WPMonad.bind_le_wp_bind`:
```
WPMonad.bind_le_wp_bind :
wp x (fun a => wp (f a) post eposts) eposts ⊑ wp (x >>= f) post eposts
```
This theorem is already in WP-form, so `post` and `eposts` are schematic. However, its precondition
`wp x (fun a => wp (f a) post eposts) eposts` is not. Hence we must emit a VC for the precondition:
```
prf : ∀ {α β} (x : m α) (f : α → m β) (post : β → Pred) (eposts : EPosts)
(pre : Pred) (hpre : pre ⊑ wp x (fun a => wp (f a) post eposts) eposts),
pre ⊑ wp (x >>= f) post eposts
```
The proof term is constructed with `PartialOrder.rel_trans hpre WPMonad.bind_le_wp_bind`.
#### Postcondition VCs
Similarly, a VC is generated for the postcondition if it is not schematic. For example, a
hypothetical restrictive spec for `pure` could be:
```
myPure.spec (n : Nat) : (⊤ : Prop) ⊑ wp (myPure n) (fun r => r = n) eposts
```
This yields a backward rule of the form:
```
prf : ∀ (n : Nat) (pre : Prop) (hpre : pre ⊑ True)
(post : Nat → Prop) (hpost : ∀ r, r = n ⊑ post r) (eposts : Unit),
pre ⊑ wp (myPure n) post eposts
```
The postcondition VC is pointwise over the return value and over any excess state arguments. The
proof is generalized with `WP.wp_monotone_post_le`.
#### Exception postcondition VCs
A VC is also generated for the exception postcondition if it is not schematic. For a product
value, the relation `epostsSpec ⊑ eposts` is decomposed component by component:
```
∀ e s₁ ... sₙ, epostsSpec.fst e s₁ ... sₙ ⊑ eposts.fst e s₁ ... sₙ
```
and recursively for the tail. `decomposeProdRel` assembles these component VCs using
`Prod.mk_le` and `Unit.unit_le`. A bare function value such as the one of `Except ε` yields the
same pointwise VC. A value of a type with a `ToEStack` instance is first converted to a stack.
The proof is then generalized with `WP.wp_monotone_epost_le`. When the spec exception
postcondition is `⊥`, no VC is needed and `WP.wp_monotone_bot_le` is used instead.
#### Excess state arguments
Furthermore, when there are excess state arguments `[s₁, ..., sₙ]` involved, the proof is
specialized to those arguments:
```
... :
pre ⊑ wp x (fun a => wp (f a) post eposts) eposts s₁ ... sₙ →
pre ⊑ wp (x >>= f) post eposts s₁ ... sₙ
```
The precondition and all generated pointwise postcondition premises are applied to these same state
arguments.
### Caching
It turns out we can cache backward rules for the cache key
`(specThm.proof.key, instWP, excessArgs.size)`. This is important for performance and helps avoid
rebuilding the same rule for every goal that uses the same spec theorem, `WPMonad` instance and
number of excess state arguments. We do that in the `VCGenM` wrapper
`mkBackwardRuleFromSpecCached`.
The rule is built from the abstracted proof returned here via `mkBackwardRuleFromExpr`. This keeps
the proof construction reusable even when the proof still contains free variables from the goal
context, such as generic monad or WP instance parameters.
### Specialization
It is unnecessary to use the `bind` rule in full generality. It is much more efficient to specialize
it for the particular predicate type, exception postcondition type and `WPMonad` instance.
`tryMkBackwardRuleFromSpec` does that by instantiating the spec theorem and checking that its
`Pred` and `WPMonad` arguments match the ones from the use site.
For `StateM Nat` and one excess state arg `s`, the type produced for `WPMonad.bind_le_wp_bind` becomes
```
prf : ∀ (pre : Prop) (α : Type) (x : StateT Nat Id α) (β : Type)
(f : α → StateT Nat Id β) (post : β → Nat → Prop) (eposts : Unit) (s : Nat),
pre ⊑ wp x (fun a => wp (f a) post eposts) eposts s →
pre ⊑ wp (x >>= f) post eposts s
```
-/
def mkSpecBackwardProof (info : WPApp)
(pre prog postSpec epostsSpec specProof : Expr) (ss ssTypes : Array Expr)
(stateArgNames : Array Name := #[]) : MetaM AbstractMVarsResult := do
/- we start with `pre ⊑ wp prog post eposts` where
1. `pre` represents the Lean expression for `pre`
2. `prog`, `postSpec`, and `epostsSpec` are the selected arguments of the spec's `wp` RHS
3. `specProof` is the proof of the spec `pre ⊑ wp prog postSpec epostsSpec`
4. `ss` represents the Lean expressions for the state variables `s1`, `s2`, ..., `sn`
5. `ssTypes` represents the Lean types for the state variables `s1`, `s2`, ..., `sn` -/
let wpArgs := info.args.take 7
let wpLemma (n : Name) := mkAppN (mkConst n info.head.constLevels!) wpArgs
let mut postAbstract := postSpec.consumeMData
let mut epostsAbstract := epostsSpec.consumeMData
let mut specApplied := specProof
/- abstract concrete `post` if it is not already abstract -/
unless postAbstract.isMVar do
/- `α → Pred`: type of `post` -/
let postTy ← Meta.inferType postSpec
/- mvar `postAbstract` for new abstract `post` -/
postAbstract ← mkFreshExprMVar (userName := `Post) postTy
/- premise type `∀ (a : α) (s₁ : σ₁) ... (sₙ : σₙ), postSpec a s₁ ... sₙ → postAbstract a s₁ ... sₙ` -/
let hpostTy ← mkPostPointwisePremise postSpec postAbstract postTy ssTypes stateArgNames
/- mvar `?postImpl` for the proof of the premise -/
let hpost ← mkFreshExprMVar (userName := `postImpl) hpostTy
/- `wp_monotone_post_le` expects its premise at the *function-lattice* order `postSpec ⊑ postAbstract`,
whereas `hpost` is stated pointwise (`∀ a s…, postSpec a s… ⊑ postAbstract a s…`). The two are
defeq, but unfolding the function-lattice `⊑` instance is blocked when the post's domain is a
metavariable (e.g. the accumulator `β` of a `forIn` loop spec). Cast `hpost` to the function
order here so the defeq is forced at this depth, keeping the user-facing VC pointwise. -/
let relTy ← mkAppM ``PartialOrder.rel #[postSpec, postAbstract]
let hpostRel ← mkExpectedTypeHint hpost relTy
/- get the proof of `pre ⊑ wp prog postAbstract epostsSpec`, where `post` is abstracted.
Uses wp_monotone_post_le: post ⊑ post' → pre ⊑ wp x post eposts → pre ⊑ wp x post' eposts -/
specApplied := mkAppN (wpLemma ``WP.wp_monotone_post_le)
#[prog, postSpec, postAbstract, epostsSpec, hpostRel, pre, specApplied]
/- abstract concrete `eposts` if it is not already abstract -/
unless epostsAbstract.isMVar do
/- `EStack⟨t₁, t₂, ..., tₙ⟩`: type of `eposts` -/
let epostsTy ← Meta.inferType epostsSpec
/- mvar `epostsAbstract` for new abstract `eposts` -/
epostsAbstract ← mkFreshExprMVar (userName := `EPosts) epostsTy
/- if `eposts` is `⊥`, then `eposts ⊑ epostsAbstract` holds trivially and
abstracting `eposts` can be simply done by `WP.wp_monotone_bot_le` without
introducing a new premise. This case is quite common, that's why we handle
it specially.
The test runs at a fresh metavariable depth, where a schematic component of
`eposts` such as `E` in `estack⟨E⟩` is read-only. `decomposeProdRel` below
assigns `E` the matching component of `epostsAbstract`. -/
let isBot ← withNewMCtxDepth do
try
let botEPred ← mkAppOptM ``Lean.Order.bot #[epostsTy, none]
isDefEqGuarded epostsSpec botEPred
catch _ => pure false
if isBot then
/- get the proof of `pre ⊑ wp prog postAbstract epostsAbstract`, where `eposts (= ⊥)` is abstracted.
This proof DOES NOT have a `?epostsImpl` premise -/
specApplied := mkAppN (wpLemma ``WP.wp_monotone_bot_le)
#[prog, postAbstract, epostsAbstract, pre, specApplied]
else
/- Decompose `epostsSpec ⊑ epostsAbstract` into per-component proofs
using `Prod.mk_le` and `Unit.unit_le` -/
let heposts ← decomposeProdRel info.EPosts epostsSpec epostsAbstract stateArgNames
specApplied := mkAppN (wpLemma ``WP.wp_monotone_epost_le)
#[prog, postAbstract, epostsSpec, epostsAbstract, heposts, pre, specApplied]
/- By default we always abstract `pre`, since in most of the specifications
`pre` is not schematic. In exceptional cases, where `pre` is schematic, it
is redundant, but we still do that to keep the code simple.
Here we also apply the excess state arguments to `pre` and `wp prog postAbstract epostsAbstract` -/
/- use `beta` to create `pre s₁ ... sₙ` to avoid creating beta redexes when `pre` is a lambda -/
let preApplied := pre.beta ss
/- proof of the original theorem with abstracted `post` and `eposts` specialized to the excess state arguments -/
specApplied := mkAppN specApplied ss
/- `wp prog postAbstract epostsAbstract s₁ ... sₙ` -/
let wpTy := mkAppN info.head <| wpArgs ++ #[prog, postAbstract, epostsAbstract] ++ ss
let specAppliedTy ← mkAppM ``PartialOrder.rel #[preApplied, wpTy]
/- later when the whole proof is type checked, we want to help the kernel by providing the expected type -/
specApplied ← mkExpectedTypeHint specApplied specAppliedTy
let preAppliedTy ← Meta.inferType preApplied
/- create a new mvar for the abstracted `pre` -/
let preAbstract ← mkFreshExprMVar (userName := `Pre) preAppliedTy
let specAbstractTy ← mkAppM ``PartialOrder.rel #[preAbstract, preApplied]
/- create a new mvar for the proof of the abstracted `pre` -/
let specAbstract ← mkFreshExprMVar (userName := `vc) specAbstractTy
/- use `PartialOrder.rel_trans` to compose the abstracted `pre` and the proof of the original theorem -/
specApplied ← mkAppM ``PartialOrder.rel_trans #[specAbstract, specApplied]
abstractMVars specApplied
/--
Normalize an instantiated equality spec `lhs = rhs` (both of type `info.M α`) to the `⊑ wp` form
`wp rhs Q E ⊑ wp lhs Q E` by instantiating `wp_le_wp_of_eq` with fresh schematic `Q`/`E`.
The schematic `Q`/`E` make the postcondition and exception-postcondition VCs collapse in
`mkSpecBackwardProof`, so the resulting rule rewrites a `wp lhs` goal to a `wp rhs` premise, matching
the equational behaviour of a simp spec. Only the monad, the value type and the `WP` instance are
pinned from the goal, mirroring how `tryMkBackwardRuleFromSpec` treats `⊑ wp` specs; the equation's
remaining variables, including instance binders, stay schematic and become rule parameters that
applying the rule binds against the concrete goal program. Dictionary projections this substitution
exposes in the premise program (e.g. for class projection unfold equations like
`MonadState.modifyGet.eq_1`) are reduced by `wpHeadReduce?` before the next spec lookup.
-/
def eqSpecToWp? (info : WPApp) (eqPrf eqType : Expr) :
OptionT MetaM (Expr × Expr) := do
let_expr Eq eqα _lhs _rhs := eqType
| throwError "simp spec is not an equation: {eqType}"
-- Unify the equation's type with the goal's program type. First-order approximation decomposes
-- flex-headed equation types (e.g. class projection unfold equations quantified over the monad,
-- like `MonadState.modifyGet.eq_1`, where `eqα = ?m ?β`). The unification must happen at the
-- current metavariable depth: `mkAppOptM` raises the depth, so the equation's type metavariables
-- are read-only there.
guard <| ← withReducible <| approxDefEq <| isDefEqGuarded eqα info.Prog
-- `post`/`eposts` are schematic metavariables (their VCs collapse downstream).
let post ← mkFreshExprMVar (userName := `Q) (← mkArrow info.Value info.Pred)
let eposts ← mkFreshExprMVar (userName := `E) info.EPosts
-- The goal's leading `wp` arguments `#[Prog, Value, Pred, EPosts, instAL, instEAL, instWP]` are
-- exactly the leading arguments of `wp_le_wp_of_eq`.
let specProof ← mkAppOptM ``Std.WP.wp_le_wp_of_eq <|
(info.args.take 7).map some ++ #[none, none, some eqPrf, some post, some eposts]
return (specProof, ← instantiateMVars (← Meta.inferType specProof))
/--
Try to build a backward rule from a single spec theorem.
For a spec already in `⊑ wp` form (`pre ⊑ wp prog post eposts`, where the lattice type is
`info.Pred = σ1 → ... → σn → Prop`), produces an auxiliary lemma directly. An equality spec
`lhs = rhs` is first normalized to `wp rhs Q E ⊑ wp lhs Q E` via `eqSpecToWp?` and then handled the
same way.
- `info.Pred`: the goal's lattice type (e.g. `Nat → Prop`)
- `info.instWP`: the `WP` instance of the goal's `wp` application
- `info.excessArgs`: free variables representing state args from
`info.Pred = σ1 → ... → σn → Prop`
-/
public def tryMkBackwardRuleFromSpec (specThm : SpecTheorem) (info : WPApp)
(stateArgNames : Array Name := #[]) : OptionT MetaM BackwardRule := do
-- Instantiate the spec theorem, creating metavars for all universally quantified params
let (_xs, _bs, specProof, specType) ← specThm.instantiate
-- Equality specs (the simp side of `@[spec]`) are normalized to `⊑ wp` form, then handled like
-- any ordinary `⊑ wp` spec.
let (specProof, specType) ←
if specType.isAppOfArity ``Eq 3 then eqSpecToWp? info specProof specType
else pure (specProof, specType)
let_expr PartialOrder.rel Pred' _cl' pre rhs := specType
| throwError "target not a partial order ⊑ application {specType}"
guard <| ← isDefEqGuarded info.Pred Pred'
let_expr Std.WP.wp _Prog' _Value' _Pred' _EPred' _instAL' _instEAL' instWP' prog postSpec epostsSpec := rhs
| throwError "target not a wp application {rhs}"
-- `withDefault`: the goal can carry a registered `WP` instance (e.g. `Id.wpInst`) while the
-- spec spells `WPMonad.toWP ?inst`; default transparency unfolds both after `?inst` synthesis.
guard <| ← withDefault <| isDefEqGuarded info.instWP instWP'
-- Use local excess-state binders so explicit post premises can be re-lifted to `⊑`.
-- Name them positionally from `stateArgNames` (else `s`) so the rule's binders carry good names.
let mut ss := #[]
let mut ssTypes := #[]
for h : i in [0:info.excessArgs.size] do
let ty ← Meta.inferType info.excessArgs[i]
ssTypes := ssTypes.push ty
ss := ss.push <| ← mkFreshExprMVar (userName := stateArgNames[i]?.getD `s) ty
let res ← mkSpecBackwardProof info pre prog postSpec epostsSpec specProof ss ssTypes stateArgNames
mkBackwardRuleFromExpr res.expr res.paramNames.toList
/-! ## Split rules -/
open Lean.Elab.Tactic.Do in
/-- Creates a reusable backward rule for splitting `ite`, `dite`, `cond`, or matchers.
Uses `SplitInfo.withAbstract` to introduce abstract fvars for the split components,
then `SplitInfo.splitWith` to build the splitting proof. Hypothesis types are
discovered via `rwIfOrMatcher` inside the splitter telescope. -/
public def mkBackwardRuleForSplit
(splitInfo : SplitInfo) (info : WPApp) : MetaM BackwardRule := do
-- The split value type is the goal's, so reuse the goal's program type and `WP` instance directly.
let a := info.Value
let ma := info.Prog
let prf ←
splitInfo.withAbstract ma fun abstractInfo splitFVars => do
-- Eta-reduce matcher alts for the backward rule pattern to avoid expensive
-- higher-order unification. The alts are eta-expanded by `withAbstract` so that
-- `splitWith`/`matcherApp.transform` can `instantiateLambda` them directly.
let abstractProg := match abstractInfo with
| .ite e | .dite e | .cond e => e
| .matcher matcherApp =>
{ matcherApp with alts := matcherApp.alts.map Expr.eta }.toExpr
let excessArgNamesTypes ← info.excessArgs.mapM fun arg =>
return (`s, ← Meta.inferType arg)
withLocalDeclsDND excessArgNamesTypes fun ss => do
withLocalDeclD `Post (← mkArrow a info.Pred) fun post => do
withLocalDeclD `EPosts info.EPosts fun eposts => do
let mkWP (prog : Expr) : Expr :=
let args := info.args.take 7 ++ #[prog, post, eposts]
mkAppN (mkAppN info.head args) ss
let Pred' ← Meta.inferType (mkWP abstractProg)
withLocalDeclD `Pre Pred' fun pre => do
let sampleGoal ← mkAppM ``PartialOrder.rel #[pre, mkWP abstractProg]
let relArgs := sampleGoal.getAppArgs
let relHead := mkAppN sampleGoal.getAppFn (relArgs.extract 0 3)
let mkGoal (prog : Expr) : Expr := mkApp relHead (mkWP prog)
-- Use synthetic opaque mvars so that `rwIfOrMatcher`'s `assumption` cannot
-- accidentally assign our subgoal metavariables.
let subgoals ← splitInfo.altInfos.mapM fun _ =>
mkFreshExprSyntheticOpaqueMVar (mkSort 0)
let namedSubgoals := subgoals.mapIdx fun i mv => ((`h).appendIndexAfter (i+1), mv)
withLocalDeclsDND namedSubgoals fun subgoalHyps => do
let prf ←
abstractInfo.splitWith
(useSplitter := true)
(mkGoal abstractProg)
(fun _name bodyType idx altFVars => do
-- Extract the program from `bodyType` (the substituted alt goal type).
-- For matchers, `bodyType` has the discriminant replaced by the constructor
-- pattern (e.g., `Nat.zero` instead of `discr`), which is required for
-- `rwMatcher` to discharge the equality hypotheses of congr equation theorems.
-- For ite/dite, `bodyType` equals `mkGoal abstractProg` so this is equivalent.
let prog := bodyType.getArg! 3 |>.getArg! 7
let res ← rwIfOrMatcher idx prog
if res.proof?.isNone then
throwError "mkBackwardRuleForSplit: rwIfOrMatcher failed for alt {idx}"
let altParams := altFVars.all
subgoals[idx]!.mvarId!.assign (← mkForallFVars altParams (mkGoal res.expr))
let context ← withLocalDecl `x .default ma fun x =>
mkLambdaFVars #[x] (mkGoal x)
let eqProof ← mkAppM ``congrArg #[context, res.proof?.get!]
mkEqMPR eqProof (mkAppN subgoalHyps[idx]! altParams))
let prf ← instantiateMVars prf
mkLambdaFVars (splitFVars ++ ss ++ #[post, eposts, pre] ++ subgoalHyps) prf
let prf ← instantiateMVars prf
let res ← abstractMVars prf
mkBackwardRuleFromExpr res.expr res.paramNames.toList
/-! ## Frame rules -/
/-- Locate the assignable subgoal positions of a frame backward rule: the split VC (the premise
`pre ⊑ (op F W) s⃗`, found by `opHead`) and the frame `F` read off its right-hand side. -/
def analyzeFrameRule (rule : BackwardRule) (opHead : Name) (numExcess : Nat) :
MetaM FrameBackwardRule := do
-- The binder telescope of the rule type is the pattern telescope, so `xs` is indexed by the
-- entries of `resultPos`, which reorders the subgoal binders (non-dependent first) into the
-- applied rule's goal list.
let resultPos := rule.resultPos.toArray
forallTelescope (← Meta.inferType rule.expr) fun xs _ => do
let premiseType (listIdx : Nat) : MetaM Expr :=
Meta.inferType xs[resultPos[listIdx]!]!
let mut found := none
-- Find the opApp `op F W` in the split VC that looks like `pre ⊑ (op F W) s`
for i in [0:resultPos.size] do
let_expr Lean.Order.PartialOrder.rel _ _ _ rhs := (← premiseType i) | continue
let opApp := rhs.stripArgsN numExcess
if opApp.isAppOf opHead then
found := some (i, opApp)
break
let some (splitVCIdx, opApp) := found
| throwError "frame: could not locate the split VC in the frame rule for `{opHead}`"
let frameIdx := resultPos.idxOf (xs.idxOf opApp.appFn!.appArg!)
return { rule, splitVCIdx, frameIdx }
/--
The frame backward rule for a frame operator `op : R → Pred → Pred`, built from the frame rule
`meet_op_wp_upperAdjoint_le_wp`.
The rule concludes `pre ⊑ wp prog Q E s⃗` from the split VC `pre ⊑ (op F W) s⃗` and the frame
condition `WP.Frames op prog F G`, with the frame `F` left schematic, the guard `G` the frame of
`pre` for the excess state arguments `fun u⃗ => ⌜u⃗ = s⃗⌝ ⊓ pre`, and the weakest footprint
`W = wp prog (fun a => upperAdjoint (op F) (Q a)) (upperAdjoint (opE F) E)` baked in, so a single
rule serves every inferred frame. When `FrameProc.framesThm?` applies to the frame condition, the
rule proves it, and the rule has no frame condition premise. `analyzeFrameRule` records the
positions of the schematic slots.
-/
public def mkFrameBackwardRule (fp : FrameProc) (info : WPApp) :
MetaM FrameBackwardRule := do
let op ← fp.mkOpAppM info
let thm ← mkAppOptM ``Std.WP.meet_op_wp_upperAdjoint_le_wp
((info.args.take 7).map some ++ #[none, some op, none, none])
let (xs, _, concl) ← forallMetaTelescope (← instantiateMVars (← Meta.inferType thm))
let_expr PartialOrder.rel _ _ lhs wp := concl
| throwError "frame: unexpected frame rule conclusion{indentExpr concl}"
let_expr Lean.Order.meet _ _ guard opApp := lhs
| throwError "frame: unexpected frame rule precondition{indentExpr lhs}"
let ss ← info.excessArgs.mapM fun s => do mkFreshExprMVar (← Meta.inferType s) (userName := `s)
let pre ← mkFreshExprMVar (← Meta.inferType info.expr) (userName := `Pre)
let hsplit ← mkFreshExprMVar (← mkAppM ``PartialOrder.rel #[pre, mkAppN opApp ss])
(userName := `vc)
let ssFrame ← ExcessArgsFrameInfo.new pre ss
guard.mvarId!.assign ssFrame.frame
if let some declName := fp.framesThm? then
let hframes := xs.back!.mvarId!
discard <| commitWhen do
try return (← hframes.apply (← mkConstWithFreshMVarLevels declName)).isEmpty
catch _ => return false
let hop ← ssFrame.abstract opApp ss hsplit
let G := ssFrame.frame
let hmeet ← mkAppM ``le_meet
#[G, G, opApp, ← mkAppOptM ``PartialOrder.rel_refl #[none, none, G], hop]
let prf ← ssFrame.instantiate wp ss (← mkAppM ``PartialOrder.rel_trans #[hmeet, mkAppN thm xs])
let res ← abstractMVars (← instantiateMVars prf)
let rule ← mkBackwardRuleFromExpr res.expr res.paramNames.toList
analyzeFrameRule rule fp.opHead info.excessArgs.size
end Lean.Elab.Tactic.VCGen