path stringlengths 11 71 | content stringlengths 75 124k |
|---|---|
Tactic\AdaptationNote.lean | /-
Copyright (c) 2024 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Lean
/-!
# Adaptation notes
This file defines a `#adaptation_note` command.
Adaptation notes are comments that are used to indicate that a piece of code
has been changed to accomodate a change in Lean core.
They typically require further action/maintenance to be taken in the future.
-/
open Lean
initialize registerTraceClass `adaptationNote
/-- General function implementing adaptation notes. -/
def reportAdaptationNote (f : Syntax β Meta.Tactic.TryThis.Suggestion) : MetaM Unit := do
let stx β getRef
if let some doc := stx[1].getOptional? then
trace[adaptationNote] (Lean.TSyntax.getDocString β¨docβ©)
else
logError "Adaptation notes must be followed by a /-- comment -/"
let trailing := if let .original (trailing := s) .. := stx[0].getTailInfo then s else default
let doc : Syntax :=
Syntax.node2 .none ``Parser.Command.docComment (mkAtom "/--") (mkAtom "comment -/")
-- Optional: copy the original whitespace after the `#adaptation_note` token
-- to after the docstring comment
let doc := doc.updateTrailing trailing
let stx' := (β getRef)
let stx' := stx'.setArg 0 stx'[0].unsetTrailing
let stx' := stx'.setArg 1 (mkNullNode #[doc])
Meta.Tactic.TryThis.addSuggestion (β getRef) (f stx') (origSpan? := β getRef)
/-- Adaptation notes are comments that are used to indicate that a piece of code
has been changed to accomodate a change in Lean core.
They typically require further action/maintenance to be taken in the future. -/
elab (name := adaptationNoteCmd) "#adaptation_note " (docComment)? : command => do
Elab.Command.liftTermElabM <| reportAdaptationNote (fun s => (β¨sβ© : TSyntax `tactic))
@[inherit_doc adaptationNoteCmd]
elab "#adaptation_note " (docComment)? : tactic =>
reportAdaptationNote (fun s => (β¨sβ© : TSyntax `tactic))
@[inherit_doc adaptationNoteCmd]
syntax (name := adaptationNoteTermStx) "#adaptation_note " (docComment)? term : term
/-- Elaborator for adaptation notes. -/
@[term_elab adaptationNoteTermStx]
def adaptationNoteTermElab : Elab.Term.TermElab
| `(#adaptation_note $[$_]? $t) => fun expectedType? => do
reportAdaptationNote (fun s => (β¨sβ© : Term))
Elab.Term.elabTerm t expectedType?
| _ => fun _ => Elab.throwUnsupportedSyntax
#adaptation_note /-- This is a test -/
example : True := by
#adaptation_note /-- This is a test -/
trivial
example : True :=
#adaptation_note /-- This is a test -/
trivial
|
Tactic\ApplyAt.lean | /-
Copyright (c) 2023 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import Lean.Elab.Tactic.ElabTerm
import Mathlib.Lean.Meta.Basic
/-!
# Apply at
A tactic for applying functions at hypotheses.
-/
open Lean Meta Elab Tactic Term
namespace Mathlib.Tactic
/--
`apply t at i` will use forward reasoning with `t` at the hypothesis `i`.
Explicitly, if `t : Ξ±β β β― β Ξ±α΅’ β β― β Ξ±β` and `i` has type `Ξ±α΅’`, then this tactic will add
metavariables/goals for any terms of `Ξ±β±Ό` for `j = 1, β¦, i-1`,
then replace the type of `i` with `Ξ±α΅’ββ β β― β Ξ±β` by applying those metavariables and the
original `i`.
-/
elab "apply" t:term "at" i:ident : tactic => withSynthesize <| withMainContext do
let f β elabTermForApply t
let some ldecl := (β getLCtx).findFromUserName? i.getId
| throwErrorAt i m!"Identifier {i} not found"
let (mvs, bis, tp) β forallMetaTelescopeReducingUntilDefEq (β inferType f) ldecl.type
let mainGoal β getMainGoal
let mainGoal β mainGoal.tryClear ldecl.fvarId
for (m, b) in mvs.zip bis do
if b.isInstImplicit && !(β m.mvarId!.isAssigned) then
try m.mvarId!.inferInstance
catch _ => continue
let mainGoal β mainGoal.assert ldecl.userName tp
(β mkAppOptM' f (mvs.pop.push ldecl.toExpr |>.map fun e => some e))
let (_, mainGoal) β mainGoal.intro1P
replaceMainGoal <| [mainGoal] ++ mvs.pop.toList.map fun e => e.mvarId!
|
Tactic\ApplyCongr.lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lucas Allen, Scott Morrison
-/
import Mathlib.Tactic.Conv
/-!
## Introduce the `apply_congr` conv mode tactic.
`apply_congr` will apply congruence lemmas inside `conv` mode.
It is particularly useful when the automatically generated congruence lemmas
are not of the optimal shape. An example, described in the doc-string is
rewriting inside the operand of a `Finset.sum`.
-/
open Lean Expr Parser.Tactic Elab Command Elab.Tactic Meta Conv
/--
Apply a congruence lemma inside `conv` mode.
When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`.
Otherwise `apply_congr e` will apply the lemma `e`.
Recall that a goal that appears as `β£ X` in `conv` mode
represents a goal of `β’ X = ?m`,
i.e. an equation with a metavariable for the right hand side.
To successfully use `apply_congr e`, `e` will need to be an equation
(possibly after function arguments),
which can be unified with a goal of the form `X = ?m`.
The right hand side of `e` will then determine the metavariable,
and `conv` will subsequently replace `X` with that right hand side.
As usual, `apply_congr` can create new goals;
any of these which are _not_ equations with a metavariable on the right hand side
will be hard to deal with in `conv` mode.
Thus `apply_congr` automatically calls `intros` on any new goals,
and fails if they are not then equations.
In particular it is useful for rewriting inside the operand of a `Finset.sum`,
as it provides an extra hypothesis asserting we are inside the domain.
For example:
```lean
example (f g : β€ β β€) (S : Finset β€) (h : β m β S, f m = g m) :
Finset.sum S f = Finset.sum S g := by
conv_lhs =>
-- If we just call `congr` here, in the second goal we're helpless,
-- because we are only given the opportunity to rewrite `f`.
-- However `apply_congr` uses the appropriate `@[congr]` lemma,
-- so we get to rewrite `f x`, in the presence of the crucial `H : x β S` hypothesis.
apply_congr
Β· skip
Β· simp [*]
```
In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x β S`
which is then used to rewrite the `f x` to `g x`.
-/
def Lean.Elab.Tactic.applyCongr (q : Option Expr) : TacticM Unit := do
let const lhsFun _ β (getAppFn β cleanupAnnotations) <$> instantiateMVars (β getLhs) |
throwError "Left-hand side must be an application of a constant."
let congrTheoremExprs β
match q with
-- If the user specified a lemma, use that one,
| some e =>
pure [e]
-- otherwise, look up everything tagged `@[congr]`
| none =>
let congrTheorems β
(fun congrTheoremMap => congrTheoremMap.get lhsFun) <$> getSimpCongrTheorems
congrTheorems.mapM (fun congrTheorem =>
liftM <| mkConstWithFreshMVarLevels congrTheorem.theoremName)
if congrTheoremExprs == [] then
throwError "No matching congr lemmas found"
-- For every lemma:
liftMetaTactic fun mainGoal => congrTheoremExprs.firstM (fun congrTheoremExpr => do
let newGoals β mainGoal.apply congrTheoremExpr { newGoals := .nonDependentOnly }
newGoals.mapM fun newGoal => Prod.snd <$> newGoal.intros)
syntax (name := Lean.Parser.Tactic.applyCongr) "apply_congr" (ppSpace colGt term)? : conv
-- TODO: add `apply_congr with h` to specify hypothesis name
-- https://github.com/leanprover-community/mathlib/issues/2882
elab_rules : conv
| `(conv| apply_congr$[ $t?]?) => do
let e? β t?.mapM (fun t => elabTerm t.raw none)
applyCongr e?
|
Tactic\ApplyFun.lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Patrick Massot, Scott Morrison
-/
import Mathlib.Lean.Expr.Basic
import Mathlib.Order.Monotone.Basic
import Mathlib.Order.Hom.Basic
/-!
# The `apply_fun` tactic.
Apply a function to an equality or inequality in either a local hypothesis or the goal.
## Porting notes
When the `mono` tactic has been ported we can attempt to automatically discharge `Monotone f` goals.
-/
namespace Mathlib.Tactic
open Lean Parser Tactic Elab Tactic Meta
initialize registerTraceClass `apply_fun
/-- Apply a function to a hypothesis. -/
def applyFunHyp (f : Term) (using? : Option Term) (h : FVarId) (g : MVarId) :
TacticM (List MVarId) := do
let using? β using?.mapM (elabTerm Β· none)
let d β h.getDecl
let (prf, newGoals) β match (β whnfR (β instantiateMVars d.type)).getAppFnArgs with
| (``Eq, #[_, lhs, rhs]) => do
let (eq', gs) β withCollectingNewGoalsFrom (tagSuffix := `apply_fun) <|
withoutRecover <| runTermElab <| do
let f β Term.elabTerm f none
let lhs' β Term.elabAppArgs f #[] #[.expr lhs] none false false
let rhs' β Term.elabAppArgs f #[] #[.expr rhs] none false false
unless β isDefEq (β inferType lhs') (β inferType rhs') do
let msg β mkHasTypeButIsExpectedMsg (β inferType rhs') (β inferType lhs')
throwError "In generated equality, right-hand side {msg}"
let eq β mkEq lhs'.headBeta rhs'.headBeta
Term.synthesizeSyntheticMVarsUsingDefault
instantiateMVars eq
let mvar β mkFreshExprMVar eq'
let [] β mvar.mvarId!.congrN! | throwError "`apply_fun` could not construct congruence"
pure (mvar, gs)
| (``Not, #[P]) =>
match (β whnfR P).getAppFnArgs with
| (``Eq, _) =>
let (injective_f, newGoals) β match using? with
-- Use the expression passed with `using`
| some r => pure (r, [])
-- Create a new `Injective f` goal
| none => do
let f β elabTermForApply f
let ng β mkFreshExprMVar (β mkAppM ``Function.Injective #[f])
-- TODO attempt to solve this goal using `mono` when it has been ported,
-- via `synthesizeUsing`.
pure (ng, [ng.mvarId!])
pure (β mkAppM' (β mkAppM ``Function.Injective.ne #[injective_f]) #[d.toExpr], newGoals)
| _ => throwError
"apply_fun can only handle negations of equality."
| (``LT.lt, _) =>
let (strict_monotone_f, newGoals) β match using? with
-- Use the expression passed with `using`
| some r => pure (r, [])
-- Create a new `StrictMono f` goal
| none => do
let f β elabTermForApply f
let ng β mkFreshExprMVar (β mkAppM ``StrictMono #[f])
-- TODO attempt to solve this goal using `mono` when it has been ported,
-- via `synthesizeUsing`.
pure (ng, [ng.mvarId!])
pure (β mkAppM' strict_monotone_f #[d.toExpr], newGoals)
| (``LE.le, _) =>
let (monotone_f, newGoals) β match using? with
-- Use the expression passed with `using`
| some r => pure (r, [])
-- Create a new `Monotone f` goal
| none => do
let f β elabTermForApply f
let ng β mkFreshExprMVar (β mkAppM ``Monotone #[f])
-- TODO attempt to solve this goal using `mono` when it has been ported,
-- via `synthesizeUsing`.
pure (ng, [ng.mvarId!])
pure (β mkAppM' monotone_f #[d.toExpr], newGoals)
| _ => throwError
"apply_fun can only handle hypotheses of the form `a = b`, `a β b`, `a β€ b`, `a < b`."
let g β g.clear h
let (_, g) β g.note d.userName prf
return g :: newGoals
/-- Failure message for `applyFunTarget`. -/
def applyFunTargetFailure (f : Term) : MetaM (List MVarId) := do
throwError "`apply_fun` could not apply `{f}` to the main goal."
/-- Given a metavariable `ginj` of type `Injective f`, try to prove it.
Returns whether it was successful. -/
def maybeProveInjective (ginj : Expr) (using? : Option Expr) : MetaM Bool := do
-- Try the `using` clause
if let some u := using? then
if β isDefEq ginj u then
ginj.mvarId!.assign u
return true
else
let err β mkHasTypeButIsExpectedMsg (β inferType u) (β inferType ginj)
throwError "Using clause {err}"
-- Try an assumption
if β ginj.mvarId!.assumptionCore then
return true
-- Try using that this is an equivalence
-- Note: if `f` is itself a metavariable, this can cause it to become an equivalence;
-- perhaps making sure `f` is an equivalence would be correct, but maybe users
-- shouldn't do `apply_fun _`.
let ok β observing? do
let [] β ginj.mvarId!.apply (β mkConstWithFreshMVarLevels ``Equiv.injective) | failure
if ok.isSome then return true
return false
-- for simplicity of the implementation below it is helpful
-- to have the forward direction of these lemmas
alias β¨ApplyFun.le_of_le, _β© := OrderIso.le_iff_le
alias β¨ApplyFun.lt_of_lt, _β© := OrderIso.lt_iff_lt
/-- Apply a function to the main goal. -/
def applyFunTarget (f : Term) (using? : Option Term) (g : MVarId) : TacticM (List MVarId) := do
-- handle applying a two-argument theorem whose first argument is f
let handle (thm : Name) : TacticM (List MVarId) := do
let ng β mkFreshExprMVar none
let (pf, gs) β withCollectingNewGoalsFrom (tagSuffix := `apply_fun) <|
withoutRecover <| runTermElab do
-- This coerces `f` to be a function as necessary:
let pf β Term.elabTermEnsuringType (β `($(mkIdent thm) $f $(β Term.exprToSyntax ng)))
(β g.getType)
Term.synthesizeSyntheticMVarsUsingDefault
return pf
g.assign pf
return ng.mvarId! :: gs
let gty β whnfR (β instantiateMVars (β g.getType))
match gty.getAppFnArgs with
| (``Not, #[p]) => match p.getAppFnArgs with
| (``Eq, #[_, _, _]) => handle ``ne_of_apply_ne
| _ => applyFunTargetFailure f
| (``LE.le, _)
| (``GE.ge, _) => handle ``ApplyFun.le_of_le
| (``LT.lt, _)
| (``GT.gt, _) => handle ``ApplyFun.lt_of_lt
| (``Eq, #[_, _, _]) => do
-- g' is for the `f lhs = f rhs` goal
let g' β mkFreshExprSyntheticOpaqueMVar (β mkFreshTypeMVar) (β g.getTag)
-- ginj is for the `Injective f` goal
let ginj β mkFreshExprSyntheticOpaqueMVar (β mkFreshTypeMVar) (appendTag (β g.getTag) `inj)
-- `withCollectingNewGoalsFrom` does not expect the goal to be closed, so here is "the goal"
let gDefer β mkFreshExprMVar (β g.getType)
let (_, gs) β withCollectingNewGoalsFrom (tagSuffix := `apply_fun) <|
withoutRecover <| runTermElab do
let inj β Term.elabTerm (β ``(Function.Injective $f)) none
_ β isDefEq (β inferType ginj) inj
let pf β Term.elabAppArgs ginj #[] #[.expr g'] (β g.getType) false false
let pf β Term.ensureHasType (β g.getType) pf
-- In the current context, let's try proving injectivity since it might fill in some holes
let using? β using?.mapM (Term.elabTerm Β· (some inj))
_ β withAssignableSyntheticOpaque <| maybeProveInjective ginj using?
Term.synthesizeSyntheticMVarsUsingDefault
gDefer.mvarId!.assign pf
-- Return `inj` so that `withCollectingNewGoalsFrom` detects holes in `f`.
return inj
g.assign gDefer
-- Perhaps ginj was assigned by `proveInjective`, but it's OK putting `ginj` in the list.
return [g'.mvarId!, ginj.mvarId!] ++ gs
| _ => applyFunTargetFailure f
/--
Apply a function to an equality or inequality in either a local hypothesis or the goal.
* If we have `h : a = b`, then `apply_fun f at h` will replace this with `h : f a = f b`.
* If we have `h : a β€ b`, then `apply_fun f at h` will replace this with `h : f a β€ f b`,
and create a subsidiary goal `Monotone f`.
`apply_fun` will automatically attempt to discharge this subsidiary goal using `mono`,
or an explicit solution can be provided with `apply_fun f at h using P`, where `P : Monotone f`.
* If we have `h : a < b`, then `apply_fun f at h` will replace this with `h : f a < f b`,
and create a subsidiary goal `StrictMono f` and behaves as in the previous case.
* If we have `h : a β b`, then `apply_fun f at h` will replace this with `h : f a β f b`,
and create a subsidiary goal `Injective f` and behaves as in the previous two cases.
* If the goal is `a β b`, `apply_fun f` will replace this with `f a β f b`.
* If the goal is `a = b`, `apply_fun f` will replace this with `f a = f b`,
and create a subsidiary goal `injective f`.
`apply_fun` will automatically attempt to discharge this subsidiary goal using local hypotheses,
or if `f` is actually an `Equiv`,
or an explicit solution can be provided with `apply_fun f using P`, where `P : Injective f`.
* If the goal is `a β€ b` (or similarly for `a < b`), and `f` is actually an `OrderIso`,
`apply_fun f` will replace the goal with `f a β€ f b`.
If `f` is anything else (e.g. just a function, or an `Equiv`), `apply_fun` will fail.
Typical usage is:
```lean
open Function
example (X Y Z : Type) (f : X β Y) (g : Y β Z) (H : Injective <| g β f) :
Injective f := by
intros x x' h
apply_fun g at h
exact H h
```
The function `f` is handled similarly to how it would be handled by `refine` in that `f` can contain
placeholders. Named placeholders (like `?a` or `?_`) will produce new goals.
-/
syntax (name := applyFun) "apply_fun " term (location)? (" using " term)? : tactic
elab_rules : tactic | `(tactic| apply_fun $f $[$loc]? $[using $P]?) => do
withLocation (expandOptLocation (Lean.mkOptionalNode loc))
(atLocal := fun h β¦ do replaceMainGoal <| β applyFunHyp f P h (β getMainGoal))
(atTarget := withMainContext do
replaceMainGoal <| β applyFunTarget f P (β getMainGoal))
(failed := fun _ β¦ throwError "apply_fun failed")
|
Tactic\ApplyWith.lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Elab.Eval
import Lean.Elab.Tactic.ElabTerm
/-!
# The `applyWith` tactic
The `applyWith` tactic is like `apply`, but allows passing a custom configuration to the underlying
`apply` operation.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic Term
/--
`apply (config := cfg) e` is like `apply e` but allows you to provide a configuration
`cfg : ApplyConfig` to pass to the underlying `apply` operation.
-/
elab (name := applyWith) "apply" " (" &"config" " := " cfg:term ") " e:term : tactic => do
let cfg β unsafe evalTerm ApplyConfig (mkConst ``ApplyConfig) cfg
evalApplyLikeTactic (Β·.apply Β· cfg) e
|
Tactic\ArithMult.lean | /-
Copyright (c) 2023 Arend Mellendijk. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arend Mellendijk
-/
import Mathlib.Tactic.Basic
import Mathlib.Tactic.ArithMult.Init
/-!
# Multiplicativity
We define the arith_mult tactic using aesop
-/
namespace ArithmeticFunction
/--
The `arith_mult` attribute used to tag `IsMultiplicative` statements for the
`arith_mult` tactic. -/
macro "arith_mult" : attr =>
`(attr|aesop safe apply (rule_sets := [$(Lean.mkIdent `IsMultiplicative):ident]))
/--
`arith_mult` solves goals of the form `IsMultiplicative f` for `f : ArithmeticFunction R`
by applying lemmas tagged with the user attribute `arith_mult`. -/
macro (name := arith_mult) "arith_mult" c:Aesop.tactic_clause* : tactic =>
`(tactic|
{ aesop $c* (config :=
{ destructProductsTransparency := .reducible,
applyHypsTransparency := .default,
introsTransparency? := some .reducible,
enableSimp := false } )
(rule_sets := [$(Lean.mkIdent `IsMultiplicative):ident])})
/--
`arith_mult` solves goals of the form `IsMultiplicative f` for `f : ArithmeticFunction R`
by applying lemmas tagged with the user attribute `arith_mult`, and prints out the generated
proof term. -/
macro (name := arith_mult?) "arith_mult?" c:Aesop.tactic_clause* : tactic =>
`(tactic|
{ show_term { arith_mult $c* } })
|
Tactic\Basic.lean | /-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kyle Miller
-/
import Lean
import Mathlib.Tactic.PPWithUniv
import Mathlib.Tactic.ExtendDoc
import Mathlib.Tactic.Lemma
import Mathlib.Tactic.TypeStar
import Mathlib.Tactic.Linter.OldObtain
/-!
# Basic tactics and utilities for tactic writing
This file defines some basic utilities for tactic writing, and also
- the `introv` tactic, which allows the user to automatically introduce the variables of a theorem
and explicitly name the non-dependent hypotheses,
- an `assumption` macro, calling the `assumption` tactic on all goals
- the tactics `match_target`, `clear_aux_decl` (clearing all auxiliary declarations from the
context) and `clear_value` (which clears the bodies of given local definitions,
changing them into regular hypotheses).
-/
namespace Mathlib.Tactic
open Lean Parser.Tactic Elab Command Elab.Tactic Meta
syntax (name := Β«variablesΒ») "variables" (ppSpace bracketedBinder)* : command
@[command_elab Β«variablesΒ»] def elabVariables : CommandElab
| `(variables%$pos $binders*) => do
logWarningAt pos "'variables' has been replaced by 'variable' in lean 4"
elabVariable (β `(variable%$pos $binders*))
| _ => throwUnsupportedSyntax
/-- Given two arrays of `FVarId`s, one from an old local context and the other from a new local
context, pushes `FVarAliasInfo`s into the info tree for corresponding pairs of `FVarId`s.
Recall that variables linked this way should be considered to be semantically identical.
The effect of this is, for example, the unused variable linter will see that variables
from the first array are used if corresponding variables in the second array are used. -/
def pushFVarAliasInfo {m : Type β Type} [Monad m] [MonadInfoTree m]
(oldFVars newFVars : Array FVarId) (newLCtx : LocalContext) : m Unit := do
for old in oldFVars, new in newFVars do
if old != new then
let decl := newLCtx.get! new
pushInfoLeaf (.ofFVarAliasInfo { id := new, baseId := old, userName := decl.userName })
/--
The tactic `introv` allows the user to automatically introduce the variables of a theorem and
explicitly name the non-dependent hypotheses.
Any dependent hypotheses are assigned their default names.
Examples:
```
example : β a b : Nat, a = b β b = a := by
introv h,
exact h.symm
```
The state after `introv h` is
```
a b : β,
h : a = b
β’ b = a
```
```
example : β a b : Nat, a = b β β c, b = c β a = c := by
introv hβ hβ,
exact hβ.trans hβ
```
The state after `introv hβ hβ` is
```
a b : β,
hβ : a = b,
c : β,
hβ : b = c
β’ a = c
```
-/
syntax (name := introv) "introv " (ppSpace colGt binderIdent)* : tactic
@[tactic introv] partial def evalIntrov : Tactic := fun stx β¦ do
match stx with
| `(tactic| introv) => introsDep
| `(tactic| introv $h:ident $hs:binderIdent*) =>
evalTactic (β `(tactic| introv; intro $h:ident; introv $hs:binderIdent*))
| `(tactic| introv _%$tk $hs:binderIdent*) =>
evalTactic (β `(tactic| introv; intro _%$tk; introv $hs:binderIdent*))
| _ => throwUnsupportedSyntax
where
introsDep : TacticM Unit := do
let t β getMainTarget
match t with
| Expr.forallE _ _ e _ =>
if e.hasLooseBVars then
intro1PStep
introsDep
| _ => pure ()
intro1PStep : TacticM Unit :=
liftMetaTactic fun goal β¦ do
let (_, goal) β goal.intro1P
pure [goal]
/-- Try calling `assumption` on all goals; succeeds if it closes at least one goal. -/
macro "assumption'" : tactic => `(tactic| any_goals assumption)
elab "match_target " t:term : tactic => do
withMainContext do
let (val) β elabTerm t (β inferType (β getMainTarget))
if not (β isDefEq val (β getMainTarget)) then
throwError "failed"
/-- This tactic clears all auxiliary declarations from the context. -/
elab (name := clearAuxDecl) "clear_aux_decl" : tactic => withMainContext do
let mut g β getMainGoal
for ldec in β getLCtx do
if ldec.isAuxDecl then
g β g.tryClear ldec.fvarId
replaceMainGoal [g]
/-- Clears the value of the local definition `fvarId`. Ensures that the resulting goal state
is still type correct. Throws an error if it is a local hypothesis without a value. -/
def _root_.Lean.MVarId.clearValue (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId := do
mvarId.checkNotAssigned `clear_value
let tag β mvarId.getTag
let (_, mvarId) β mvarId.withReverted #[fvarId] fun mvarId' fvars => mvarId'.withContext do
let tgt β mvarId'.getType
unless tgt.isLet do
mvarId.withContext <|
throwTacticEx `clear_value mvarId m!"{Expr.fvar fvarId} is not a local definition"
let tgt' := Expr.forallE tgt.letName! tgt.letType! tgt.letBody! .default
unless β isTypeCorrect tgt' do
mvarId.withContext <|
throwTacticEx `clear_value mvarId
m!"cannot clear {Expr.fvar fvarId}, the resulting context is not type correct"
let mvarId'' β mkFreshExprSyntheticOpaqueMVar tgt' tag
mvarId'.assign <| .app mvarId'' tgt.letValue!
return ((), fvars.map .some, mvarId''.mvarId!)
return mvarId
/-- `clear_value nβ nβ ...` clears the bodies of the local definitions `nβ, nβ ...`, changing them
into regular hypotheses. A hypothesis `n : Ξ± := t` is changed to `n : Ξ±`.
The order of `nβ nβ ...` does not matter, and values will be cleared in reverse order of
where they appear in the context. -/
elab (name := clearValue) "clear_value" hs:(ppSpace colGt term:max)+ : tactic => do
let fvarIds β getFVarIds hs
let fvarIds β withMainContext <| sortFVarIds fvarIds
for fvarId in fvarIds.reverse do
withMainContext do
let mvarId β (β getMainGoal).clearValue fvarId
replaceMainGoal [mvarId]
attribute [pp_with_univ] ULift PUnit PEmpty
|
Tactic\Bound.lean | /-
Copyright (c) 2024 Geoffrey Irving. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Geoffrey Irving
-/
import Aesop
import Mathlib.Tactic.Bound.Attribute
import Mathlib.Tactic.Lemma
import Mathlib.Tactic.Linarith.Frontend
import Mathlib.Tactic.NormNum.Core
/-!
## The `bound` tactic
`bound` is an `aesop` wrapper that proves inequalities by straightforward recursion on structure,
assuming that intermediate terms are nonnegative or positive as needed. It also has some support
for guessing where it is unclear where to recurse, such as which side of a `min` or `max` to use
as the bound or whether to assume a power is less than or greater than one.
The functionality of `bound` overlaps with `positivity` and `gcongr`, but can jump back and forth
between `0 β€ x` and `x β€ y`-type inequalities. For example, `bound` proves
`0 β€ c β b β€ a β 0 β€ a * c - b * c`
by turning the goal into `b * c β€ a * c`, then using `mul_le_mul_of_nonneg_right`. `bound` also
uses specialized lemmas for goals of the form `1 β€ x, 1 < x, x β€ 1, x < 1`.
Additional hypotheses can be passed as `bound [h0, h1 n, ...]`. This is equivalent to declaring
them via `have` before calling `bound`.
See `test/Bound.lean` for tests.
### Calc usage
Since `bound` requires the inequality proof to exactly match the structure of the expression, it is
often useful to iterate between `bound` and `rw / simp` using `calc`. Here is an example:
```
-- Calc example: A weak lower bound for `z β¦ z^2 + c`
lemma le_sqr_add {c z : β} (cz : abs c β€ abs z) (z3 : 3 β€ abs z) :
2 * abs z β€ abs (z^2 + c) := by
calc abs (z^2 + c)
_ β₯ abs (z^2) - abs c := by bound
_ β₯ abs (z^2) - abs z := by bound
_ β₯ (abs z - 1) * abs z := by rw [mul_comm, mul_sub_one, β pow_two, β abs.map_pow]
_ β₯ 2 * abs z := by bound
```
### Aesop rules
`bound` uses threes types of aesop rules: `apply`, `forward`, and closing `tactic`s. To register a
lemma as an `apply` rule, tag it with `@[bound]`. It will be automatically converted into either a
`norm apply` or `safe apply` rule depending on the number and type of its hypotheses:
1. Nonnegativity/positivity/nonpositivity/negativity hypotheses get score 1 (those involving `0`).
2. Other inequalities get score 10.
3. Disjunctions `a β¨ b` get score 100, plus the score of `a` and `b`.
Score `0` lemmas turn into `norm apply` rules, and score `0 < s` lemmas turn into `safe apply s`
rules. The score is roughly lexicographic ordering on the counts of the three type (guessing,
general, involving-zero), and tries to minimize the complexity of hypotheses we have to prove.
See `Mathlib.Tactic.Bound.Attribute` for the full algorithm.
To register a lemma as a `forward` rule, tag it with `@[bound_forward]`. The most important
builtin forward rule is `le_of_lt`, so that strict inequalities can be used to prove weak
inequalities. Another example is `HasFPowerSeriesOnBall.r_pos`, so that `bound` knows that any
power series present in the context have positive radius of convergence. Custom `@[bound_forward]`
rules that similarly expose inequalities inside structures are often useful.
### Guessing apply rules
There are several cases where there are two standard ways to recurse down an inequality, and it is
not obvious which is correct without more information. For example, `a β€ min b c` is registered as
a `safe apply 4` rule, since we always need to prove `a β€ b β§ a β€ c`. But if we see `min a b β€ c`,
either `a β€ c` or `b β€ c` suffices, and we don't know which.
In these cases we declare a new lemma with an `β¨` hypotheses that covers the two cases. Tagging
it as `@[bound]` will add a +100 penalty to the score, so that it will be used only if necessary.
Aesop will then try both ways by splitting on the resulting `β¨` hypothesis.
Currently the two types of guessing rules are
1. `min` and `max` rules, for both `β€` and `<`
2. `pow` and `rpow` monotonicity rules which branch on `1 β€ a` or `a β€ 1`.
### Closing tactics
We close numerical goals with `norm_num` and `linarith`.
-/
open Lean Elab Meta Term Mathlib.Tactic Syntax
open Lean.Elab.Tactic (liftMetaTactic liftMetaTactic' TacticM getMainGoal)
namespace Mathlib.Tactic.Bound
/-!
### `.mpr` lemmas of iff statements for use as Aesop apply rules
Once Aesop can do general terms directly, we can remove these:
https://github.com/leanprover-community/aesop/issues/107
-/
lemma mul_lt_mul_left_of_pos_of_lt {Ξ± : Type} {a b c : Ξ±} [Mul Ξ±] [Zero Ξ±] [Preorder Ξ±]
[PosMulStrictMono Ξ±] [PosMulReflectLT Ξ±] (a0 : 0 < a) : b < c β a * b < a * c :=
(mul_lt_mul_left a0).mpr
lemma mul_lt_mul_right_of_pos_of_lt {Ξ± : Type} {a b c : Ξ±} [Mul Ξ±] [Zero Ξ±] [Preorder Ξ±]
[MulPosStrictMono Ξ±] [MulPosReflectLT Ξ±] (c0 : 0 < c) : a < b β a * c < b * c :=
(mul_lt_mul_right c0).mpr
lemma Nat.cast_pos_of_pos {R : Type} [OrderedSemiring R] [Nontrivial R] {n : β} :
0 < n β 0 < (n : R) :=
Nat.cast_pos.mpr
lemma Nat.one_le_cast_of_le {Ξ± : Type} [AddCommMonoidWithOne Ξ±] [PartialOrder Ξ±]
[CovariantClass Ξ± Ξ± (fun (x y : Ξ±) => x + y) fun (x y : Ξ±) => x β€ y] [ZeroLEOneClass Ξ±]
[CharZero Ξ±] {n : β} : 1 β€ n β 1 β€ (n : Ξ±) :=
Nat.one_le_cast.mpr
/-!
### Apply rules for `bound`
Most `bound` lemmas are registered in-place where the lemma is declared. These are only the lemmas
that do not require additional imports within this file.
-/
-- Reflexivity
attribute [bound] le_refl
-- 0 β€, 0 <
attribute [bound] sq_nonneg Nat.cast_nonneg abs_nonneg Nat.zero_lt_succ pow_pos pow_nonneg
sub_nonneg_of_le sub_pos_of_lt inv_nonneg_of_nonneg inv_pos_of_pos tsub_pos_of_lt mul_pos
mul_nonneg div_pos div_nonneg add_nonneg
-- 1 β€, β€ 1
attribute [bound] Nat.one_le_cast_of_le one_le_mul_of_one_le_of_one_le
-- β€
attribute [bound] le_abs_self neg_abs_le neg_le_neg tsub_le_tsub_right mul_le_mul_of_nonneg_left
mul_le_mul_of_nonneg_right le_add_of_nonneg_right le_add_of_nonneg_left le_mul_of_one_le_right
mul_le_of_le_one_right sub_le_sub add_le_add mul_le_mul
-- <
attribute [bound] Nat.cast_pos_of_pos neg_lt_neg sub_lt_sub_left sub_lt_sub_right add_lt_add_left
add_lt_add_right mul_lt_mul_left_of_pos_of_lt mul_lt_mul_right_of_pos_of_lt
-- min and max
attribute [bound] min_le_right min_le_left le_max_left le_max_right le_min max_le lt_min max_lt
-- Memorize a few constants to avoid going to `norm_num`
attribute [bound] zero_le_one zero_lt_one zero_le_two zero_lt_two
/-!
### Forward rules for `bound`
-/
-- Bound applies `le_of_lt` to all hypotheses
attribute [bound_forward] le_of_lt
/-!
### Guessing rules: when we don't know how to recurse
-/
section Guessing
variable {Ξ± : Type} [LinearOrder Ξ±] {a b c : Ξ±}
-- `min` and `max` guessing lemmas
lemma le_max_of_le_left_or_le_right : a β€ b β¨ a β€ c β a β€ max b c := le_max_iff.mpr
lemma lt_max_of_lt_left_or_lt_right : a < b β¨ a < c β a < max b c := lt_max_iff.mpr
lemma min_le_of_left_le_or_right_le : a β€ c β¨ b β€ c β min a b β€ c := min_le_iff.mpr
lemma min_lt_of_left_lt_or_right_lt : a < c β¨ b < c β min a b < c := min_lt_iff.mpr
-- Register guessing rules
attribute [bound]
-- Which side of the `max` should we use as the lower bound?
le_max_of_le_left_or_le_right
lt_max_of_lt_left_or_lt_right
-- Which side of the `min` should we use as the upper bound?
min_le_of_left_le_or_right_le
min_lt_of_left_lt_or_right_lt
end Guessing
/-!
### Closing tactics
TODO: Kim Morrison noted that we could check for `β` or `β€` and try `omega` as well.
-/
/-- Close numerical goals with `norm_num` -/
def boundNormNum : Aesop.RuleTac :=
Aesop.SingleRuleTac.toRuleTac fun i => do
let tac := do Mathlib.Meta.NormNum.elabNormNum .missing .missing .missing
let goals β Lean.Elab.Tactic.run i.goal tac |>.run'
if !goals.isEmpty then failure
return (#[], none, some .hundred)
attribute [aesop unsafe 10% tactic (rule_sets := [Bound])] boundNormNum
/-- Close numerical and other goals with `linarith` -/
def boundLinarith : Aesop.RuleTac :=
Aesop.SingleRuleTac.toRuleTac fun i => do
Linarith.linarith false [] {} i.goal
return (#[], none, some .hundred)
attribute [aesop unsafe 5% tactic (rule_sets := [Bound])] boundLinarith
/-!
### `bound` tactic implementation
-/
/-- Aesop configuration for `bound` -/
def boundConfig : Aesop.Options := {
enableSimp := false
}
end Mathlib.Tactic.Bound
/-- `bound` tactic for proving inequalities via straightforward recursion on expression structure.
An example use case is
```
-- Calc example: A weak lower bound for `z β¦ z^2 + c`
lemma le_sqr_add {c z : β} (cz : abs c β€ abs z) (z3 : 3 β€ abs z) :
2 * abs z β€ abs (z^2 + c) := by
calc abs (z^2 + c)
_ β₯ abs (z^2) - abs c := by bound
_ β₯ abs (z^2) - abs z := by bound
_ β₯ (abs z - 1) * abs z := by rw [mul_comm, mul_sub_one, β pow_two, β abs.map_pow]
_ β₯ 2 * abs z := by bound
```
`bound` is built on top of `aesop`, and uses
1. Apply lemmas registered via the `@[bound]` attribute
2. Forward lemmas registered via the `@[bound_forward]` attribute
3. Local hypotheses from the context
4. Optionally: additional hypotheses provided as `bound [hβ, hβ]` or similar. These are added to the
context as if by `have := hα΅’`.
The functionality of `bound` overlaps with `positivity` and `gcongr`, but can jump back and forth
between `0 β€ x` and `x β€ y`-type inequalities. For example, `bound` proves
`0 β€ c β b β€ a β 0 β€ a * c - b * c`
by turning the goal into `b * c β€ a * c`, then using `mul_le_mul_of_nonneg_right`. `bound` also
contains lemmas for goals of the form `1 β€ x, 1 < x, x β€ 1, x < 1`. Conversely, `gcongr` can prove
inequalities for more types of relations, supports all `positivity` functionality, and is likely
faster since it is more specialized (not built atop `aesop`). -/
syntax "bound " (" [" term,* "]")? : tactic
-- Plain `bound` elaboration, with no hypotheses
elab_rules : tactic
| `(tactic| bound) => do
let tac β `(tactic| aesop (rule_sets := [Bound, -default]) (config := Bound.boundConfig))
liftMetaTactic fun g β¦ do return (β Lean.Elab.runTactic g tac.raw).1
-- Rewrite `bound [hβ, hβ]` into `have := hβ, have := hβ, bound`, and similar
macro_rules
| `(tactic| bound%$tk [$[$ts],*]) => do
let haves β ts.mapM fun (t : Term) => withRef t `(tactic| have := $t)
`(tactic| ($haves;*; bound%$tk))
|
Tactic\ByContra.lean | /-
Copyright (c) 2022 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard
-/
import Mathlib.Tactic.PushNeg
/-!
# The `by_contra` tactic
The `by_contra!` tactic is a variant of the `by_contra` tactic, for proofs of contradiction.
-/
open Lean Lean.Parser Parser.Tactic Elab Command Elab.Tactic Meta
/--
If the target of the main goal is a proposition `p`,
`by_contra!` reduces the goal to proving `False` using the additional hypothesis `this : Β¬ p`.
`by_contra! h` can be used to name the hypothesis `h : Β¬ p`.
The hypothesis `Β¬ p` will be negation normalized using `push_neg`.
For instance, `Β¬ a < b` will be changed to `b β€ a`.
`by_contra! h : q` will normalize negations in `Β¬ p`, normalize negations in `q`,
and then check that the two normalized forms are equal.
The resulting hypothesis is the pre-normalized form, `q`.
If the name `h` is not explicitly provided, then `this` will be used as name.
This tactic uses classical reasoning.
It is a variant on the tactic `by_contra`.
Examples:
```lean
example : 1 < 2 := by
by_contra! h
-- h : 2 β€ 1 β’ False
example : 1 < 2 := by
by_contra! h : Β¬ 1 < 2
-- h : Β¬ 1 < 2 β’ False
```
-/
syntax (name := byContra!) "by_contra!" (ppSpace colGt binderIdent)? Term.optType : tactic
macro_rules
| `(tactic| by_contra!%$tk $[_%$under]? $[: $ty]?) =>
`(tactic| by_contra! $(mkIdentFrom (under.getD tk) `this (canonical := true)):ident $[: $ty]?)
| `(tactic| by_contra! $e:ident) => `(tactic| (by_contra $e:ident; try push_neg at $e:ident))
| `(tactic| by_contra! $e:ident : $y) => `(tactic|
(by_contra! h
-- if the below `exact` call fails then this tactic should fail with the message
-- tactic failed: <goal type> and <type of h> are not definitionally equal
have $e:ident : $y := by { (try push_neg); exact h }
clear h))
|
Tactic\CancelDenoms.lean | import Mathlib.Tactic.CancelDenoms.Core
import Mathlib.Tactic.NormNum.Ineq
|
Tactic\Cases.lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Elab.Tactic.Induction
import Batteries.Tactic.OpenPrivate
import Mathlib.Lean.Expr.Basic
/-!
# Backward compatible implementation of lean 3 `cases` tactic
This tactic is similar to the `cases` tactic in lean 4 core, but the syntax for giving
names is different:
```
example (h : p β¨ q) : q β¨ p := by
cases h with
| inl hp => exact Or.inr hp
| inr hq => exact Or.inl hq
example (h : p β¨ q) : q β¨ p := by
cases' h with hp hq
Β· exact Or.inr hp
Β· exact Or.inl hq
example (h : p β¨ q) : q β¨ p := by
rcases h with hp | hq
Β· exact Or.inr hp
Β· exact Or.inl hq
```
Prefer `cases` or `rcases` when possible, because these tactics promote structured proofs.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Elab.Tactic
private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do
for altInfo in elimInfo.altsInfo do
if altInfo.name == altName then
return altInfo.numFields
throwError "unknown alternative name '{altName}'"
def ElimApp.evalNames (elimInfo : ElimInfo) (alts : Array ElimApp.Alt) (withArg : Syntax)
(numEqs := 0) (generalized : Array FVarId := #[]) (toClear : Array FVarId := #[])
(toTag : Array (Ident Γ FVarId) := #[]) :
TermElabM (Array MVarId) := do
let mut names : List Syntax := withArg[1].getArgs |>.toList
let mut subgoals := #[]
for { name := altName, mvarId := g, .. } in alts do
let numFields β getAltNumFields elimInfo altName
let (altVarNames, names') := names.splitAtD numFields (Unhygienic.run `(_))
names := names'
let (fvars, g) β g.introN numFields <| altVarNames.map (getNameOfIdent' Β·[0])
let some (g, subst) β Cases.unifyEqs? numEqs g {} | pure ()
let (introduced, g) β g.introNP generalized.size
let subst := (generalized.zip introduced).foldl (init := subst) fun subst (a, b) =>
subst.insert a (.fvar b)
let g β liftM $ toClear.foldlM (Β·.tryClear) g
g.withContext do
for (stx, fvar) in toTag do
Term.addLocalVarInfo stx (subst.get fvar)
for fvar in fvars, stx in altVarNames do
(subst.get fvar).addLocalVarInfoForBinderIdent β¨stxβ©
subgoals := subgoals.push g
pure subgoals
open private getElimNameInfo generalizeTargets generalizeVars from Lean.Elab.Tactic.Induction
elab (name := induction') "induction' " tgts:(Parser.Tactic.casesTarget,+)
usingArg:((" using " ident)?)
withArg:((" with" (ppSpace colGt binderIdent)+)?)
genArg:((" generalizing" (ppSpace colGt ident)+)?) : tactic => do
let (targets, toTag) β elabCasesTargets tgts.1.getSepArgs
let g :: gs β getUnsolvedGoals | throwNoGoalsToBeSolved
g.withContext do
let elimInfo β getElimNameInfo usingArg targets (induction := true)
let targets β addImplicitTargets elimInfo targets
evalInduction.checkTargets targets
let targetFVarIds := targets.map (Β·.fvarId!)
g.withContext do
let genArgs β if genArg.1.isNone then pure #[] else getFVarIds genArg.1[1].getArgs
let forbidden β mkGeneralizationForbiddenSet targets
let mut s β getFVarSetToGeneralize targets forbidden
for v in genArgs do
if forbidden.contains v then
throwError "variable cannot be generalized \
because target depends on it{indentExpr (mkFVar v)}"
if s.contains v then
throwError "unnecessary 'generalizing' argument, \
variable '{mkFVar v}' is generalized automatically"
s := s.insert v
let (fvarIds, g) β g.revert (β sortFVarIds s.toArray)
g.withContext do
let result β withRef tgts <| ElimApp.mkElimApp elimInfo targets (β g.getTag)
let elimArgs := result.elimApp.getAppArgs
ElimApp.setMotiveArg g elimArgs[elimInfo.motivePos]!.mvarId! targetFVarIds
g.assign result.elimApp
let subgoals β ElimApp.evalNames elimInfo result.alts withArg
(generalized := fvarIds) (toClear := targetFVarIds) (toTag := toTag)
setGoals <| (subgoals ++ result.others).toList ++ gs
elab (name := cases') "cases' " tgts:(Parser.Tactic.casesTarget,+) usingArg:((" using " ident)?)
withArg:((" with" (ppSpace colGt binderIdent)+)?) : tactic => do
let (targets, toTag) β elabCasesTargets tgts.1.getSepArgs
let g :: gs β getUnsolvedGoals | throwNoGoalsToBeSolved
g.withContext do
let elimInfo β getElimNameInfo usingArg targets (induction := false)
let targets β addImplicitTargets elimInfo targets
let result β withRef tgts <| ElimApp.mkElimApp elimInfo targets (β g.getTag)
let elimArgs := result.elimApp.getAppArgs
let targets β elimInfo.targetsPos.mapM (instantiateMVars elimArgs[Β·]!)
let motive := elimArgs[elimInfo.motivePos]!
let g β generalizeTargetsEq g (β inferType motive) targets
let (targetsNew, g) β g.introN targets.size
g.withContext do
ElimApp.setMotiveArg g motive.mvarId! targetsNew
g.assign result.elimApp
let subgoals β ElimApp.evalNames elimInfo result.alts withArg
(numEqs := targets.size) (toClear := targetsNew) (toTag := toTag)
setGoals <| subgoals.toList ++ gs
|
Tactic\CasesM.lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Elab.Tactic.Conv.Pattern
/-!
# `casesm`, `cases_type`, `constructorm` tactics
These tactics implement repeated `cases` / `constructor` on anything satisfying a predicate.
-/
namespace Lean.MVarId
/--
Core tactic for `casesm` and `cases_type`. Calls `cases` on all fvars in `g` for which
`matcher ldecl.type` returns true.
* `recursive`: if true, it calls itself repeatedly on the resulting subgoals
* `allowSplit`: if false, it will skip any hypotheses where `cases` returns more than one subgoal.
* `throwOnNoMatch`: if true, then throws an error if no match is found
-/
partial def casesMatching (matcher : Expr β MetaM Bool) (recursive := false) (allowSplit := true)
(throwOnNoMatch := true) (g : MVarId) : MetaM (List MVarId) := do
let result := (β go g).toList
if throwOnNoMatch && result == [g] then
throwError "no match"
else
return result
where
/-- Auxiliary for `casesMatching`. Accumulates generated subgoals in `acc`. -/
go (g : MVarId) (acc : Array MVarId := #[]) : MetaM (Array MVarId) :=
g.withContext do
for ldecl in β getLCtx do
if ldecl.isImplementationDetail then continue
if β matcher ldecl.type then
let mut acc := acc
let subgoals β if allowSplit then
g.cases ldecl.fvarId
else
let s β saveState
let subgoals β g.cases ldecl.fvarId
if subgoals.size > 1 then
s.restore
continue
else
pure subgoals
for subgoal in subgoals do
if recursive then
acc β go subgoal.mvarId acc
else
acc := acc.push subgoal.mvarId
return acc
return (acc.push g)
def casesType (heads : Array Name) (recursive := false) (allowSplit := true) :
MVarId β MetaM (List MVarId) :=
let matcher ty := pure <|
if let .const n .. := ty.headBeta.getAppFn then heads.contains n else false
casesMatching matcher recursive allowSplit
end Lean.MVarId
namespace Mathlib.Tactic
open Lean Meta Elab Tactic MVarId
/-- Elaborate a list of terms with holes into a list of patterns. -/
def elabPatterns (pats : Array Term) : TermElabM (Array AbstractMVarsResult) :=
withTheReader Term.Context (fun ctx β¦ { ctx with ignoreTCFailures := true }) <|
Term.withoutErrToSorry <|
pats.mapM fun p β¦ Term.withoutModifyingElabMetaStateWithInfo do
withRef p <| abstractMVars (β Term.elabTerm p none)
/-- Returns true if any of the patterns match the expression. -/
def matchPatterns (pats : Array AbstractMVarsResult) (e : Expr) : MetaM Bool := do
let e β instantiateMVars e
pats.anyM fun p β¦ return (β Conv.matchPattern? p e) matches some (_, #[])
/--
* `casesm p` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches the pattern `p`.
* `casesm p_1, ..., p_n` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches one of the given patterns.
* `casesm* p` is a more efficient and compact version of `Β· repeat casesm p`.
It is more efficient because the pattern is compiled once.
Example: The following tactic destructs all conjunctions and disjunctions in the current context.
```
casesm* _ β¨ _, _ β§ _
```
-/
elab (name := casesM) "casesm" recursive:"*"? ppSpace pats:term,+ : tactic => do
let pats β elabPatterns pats.getElems
liftMetaTactic (casesMatching (matchPatterns pats) recursive.isSome)
/-- Common implementation of `cases_type` and `cases_type!`. -/
def elabCasesType (heads : Array Ident)
(recursive := false) (allowSplit := true) : TacticM Unit := do
let heads β heads.mapM (fun stx => realizeGlobalConstNoOverloadWithInfo stx)
liftMetaTactic (casesType heads recursive allowSplit)
/--
* `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
* `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis
`h : (I_1 ...)` or ... or `h : (I_n ...)`
* `cases_type* I` is shorthand for `Β· repeat cases_type I`
* `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_type* Or And
```
-/
elab (name := casesType) "cases_type" recursive:"*"? heads:(ppSpace colGt ident)+ : tactic =>
elabCasesType heads recursive.isSome true
@[inherit_doc casesType]
elab (name := casesType!) "cases_type!" recursive:"*"? heads:(ppSpace colGt ident)+ : tactic =>
elabCasesType heads recursive.isSome false
/--
Core tactic for `constructorm`. Calls `constructor` on all subgoals for which
`matcher ldecl.type` returns true.
* `recursive`: if true, it calls itself repeatedly on the resulting subgoals
* `throwOnNoMatch`: if true, throws an error if no match is found
-/
partial def constructorMatching (g : MVarId) (matcher : Expr β MetaM Bool)
(recursive := false) (throwOnNoMatch := true) : MetaM (List MVarId) := do
let result β
(if recursive then (do
let result β go g
pure result.toList)
else
(g.withContext do
if β matcher (β g.getType) then g.constructor else pure [g]))
if throwOnNoMatch && [g] == result then
throwError "no match"
else
return result
where
/-- Auxiliary for `constructorMatching`. Accumulates generated subgoals in `acc`. -/
go (g : MVarId) (acc : Array MVarId := #[]) : MetaM (Array MVarId) :=
g.withContext do
if β matcher (β g.getType) then
let mut acc := acc
for g' in β g.constructor do
acc β go g' acc
return acc
return (acc.push g)
/--
* `constructorm p_1, ..., p_n` applies the `constructor` tactic to the main goal
if `type` matches one of the given patterns.
* `constructorm* p` is a more efficient and compact version of `Β· repeat constructorm p`.
It is more efficient because the pattern is compiled once.
Example: The following tactic proves any theorem like `True β§ (True β¨ True)` consisting of
and/or/true:
```
constructorm* _ β¨ _, _ β§ _, True
```
-/
elab (name := constructorM) "constructorm" recursive:"*"? ppSpace pats:term,+ : tactic => do
let pats β elabPatterns pats.getElems
liftMetaTactic (constructorMatching Β· (matchPatterns pats) recursive.isSome)
|
Tactic\CC.lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Miyahara KΕ
-/
import Mathlib.Tactic.CC.Addition
/-!
# Congruence closure
The congruence closure tactic `cc` tries to solve the goal by chaining
equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).
It is a finishing tactic, i.e. it is meant to close
the current goal, not to make some inconclusive progress.
A mostly trivial example would be:
```lean
example (a b c : β) (f : β β β) (h: a = b) (h' : b = c) : f a = f c := by
cc
```
As an example requiring some thinking to do by hand, consider:
```lean
example (f : β β β) (x : β)
(H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :
f x = x := by
cc
```
The tactic works by building an equality matching graph. It's a graph where
the vertices are terms and they are linked by edges if they are known to
be equal. Once you've added all the equalities in your context, you take
the transitive closure of the graph and, for each connected component
(i.e. equivalence class) you can elect a term that will represent the
whole class and store proofs that the other elements are equal to it.
You then take the transitive closure of these equalities under the
congruence lemmas.
The `cc` implementation in Lean does a few more tricks: for example it
derives `a = b` from `Nat.succ a = Nat.succ b`, and `Nat.succ a != Nat.zero` for any `a`.
* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence
closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),
Journal of the ACM (1980)
* The congruence lemmas for dependent type theory as used in Lean are described in
[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)
(de Moura, Selsam IJCAR 2016).
-/
universe u
open Lean Meta Elab Tactic Std
namespace Mathlib.Tactic.CC
namespace CCState
open CCM
/-- Make an new `CCState` from the given `config`. -/
def mkCore (config : CCConfig) : CCState :=
let s : CCState := { config with }
s.mkEntryCore (.const ``True []) true false |>.mkEntryCore (.const ``False []) true false
/-- Create a congruence closure state object from the given `config` using the hypotheses in the
current goal. -/
def mkUsingHsCore (config : CCConfig) : MetaM CCState := do
let ctx β getLCtx
let ctx β instantiateLCtxMVars ctx
let (_, c) β CCM.run (ctx.forM fun dcl => do
unless dcl.isImplementationDetail do
if β isProp dcl.type then
add dcl.type dcl.toExpr) { mkCore config with }
return c.toCCState
/-- Returns the root expression for each equivalence class in the graph.
If the `Bool` argument is set to `true` then it only returns roots of non-singleton classes. -/
def rootsCore (ccs : CCState) (nonsingleton : Bool) : List Expr :=
ccs.getRoots #[] nonsingleton |>.toList
/-- Increment the Global Modification time. -/
def incGMT (ccs : CCState) : CCState :=
{ ccs with gmt := ccs.gmt + 1 }
/-- Add the given expression to the graph. -/
def internalize (ccs : CCState) (e : Expr) : MetaM CCState := do
let (_, c) β CCM.run (CCM.internalize e) { ccs with }
return c.toCCState
/-- Add the given proof term as a new rule.
The proof term `H` must be an `Eq _ _`, `HEq _ _`, `Iff _ _`, or a negation of these. -/
def add (ccs : CCState) (H : Expr) : MetaM CCState := do
let type β inferType H
unless β isProp type do
throwError "CCState.add failed, given expression is not a proof term"
let (_, c) β CCM.run (CCM.add type H) { ccs with }
return c.toCCState
/-- Check whether two expressions are in the same equivalence class. -/
def isEqv (ccs : CCState) (eβ eβ : Expr) : MetaM Bool := do
let (b, _) β CCM.run (CCM.isEqv eβ eβ) { ccs with }
return b
/-- Check whether two expressions are not in the same equivalence class. -/
def isNotEqv (ccs : CCState) (eβ eβ : Expr) : MetaM Bool := do
let (b, _) β CCM.run (CCM.isNotEqv eβ eβ) { ccs with }
return b
/-- Returns a proof term that the given terms are equivalent in the given `CCState` -/
def eqvProof (ccs : CCState) (eβ eβ : Expr) : MetaM Expr := do
let (some r, _) β CCM.run (CCM.getEqProof eβ eβ) { ccs with }
| throwError "CCState.eqvProof failed to build proof"
return r
/-- `proofFor cc e` constructs a proof for e if it is equivalent to true in `CCState` -/
def proofFor (ccs : CCState) (e : Expr) : MetaM Expr := do
let (some r, _) β CCM.run (CCM.getEqProof e (.const ``True [])) { ccs with }
| throwError "CCState.proofFor failed to build proof"
mkAppM ``of_eq_true #[r]
/-- `refutationFor cc e` constructs a proof for `Not e` if it is equivalent to `False` in `CCState`
-/
def refutationFor (ccs : CCState) (e : Expr) : MetaM Expr := do
let (some r, _) β CCM.run (CCM.getEqProof e (.const ``False [])) { ccs with }
| throwError "CCState.refutationFor failed to build proof"
mkAppM ``not_of_eq_false #[r]
/-- If the given state is inconsistent, return a proof for `False`. Otherwise fail. -/
def proofForFalse (ccs : CCState) : MetaM Expr := do
let (some pr, _) β CCM.run CCM.getInconsistencyProof { ccs with }
| throwError "CCState.proofForFalse failed, state is not inconsistent"
return pr
/-- Create a congruence closure state object using the hypotheses in the current goal. -/
def mkUsingHs : MetaM CCState :=
CCState.mkUsingHsCore {}
/-- The root expressions for each equivalence class in the graph. -/
def roots (s : CCState) : List Expr :=
CCState.rootsCore s true
instance : ToMessageData CCState :=
β¨fun s => CCState.ppEqcs s trueβ©
/-- Continue to append following expressions in the equivalence class of `e` to `r` until `f` is
found. -/
partial def eqcOfCore (s : CCState) (e : Expr) (f : Expr) (r : List Expr) : List Expr :=
let n := s.next e
if n == f then e :: r else eqcOfCore s n f (e :: r)
/-- The equivalence class of `e`. -/
def eqcOf (s : CCState) (e : Expr) : List Expr :=
s.eqcOfCore e e []
/-- The size of the equivalence class of `e`. -/
def eqcSize (s : CCState) (e : Expr) : Nat :=
s.eqcOf e |>.length
/-- Fold `f` over the equivalence class of `c`, accumulating the result in `a`.
Loops until the element `first` is encountered.
See `foldEqc` for folding `f` over all elements of the equivalence class. -/
partial def foldEqcCore {Ξ±} (s : CCState) (f : Ξ± β Expr β Ξ±) (first : Expr) (c : Expr) (a : Ξ±) :
Ξ± :=
let new_a := f a c
let next := s.next c
if next == first then new_a else foldEqcCore s f first next new_a
/-- Fold the function of `f` over the equivalence class of `e`. -/
def foldEqc {Ξ±} (s : CCState) (e : Expr) (a : Ξ±) (f : Ξ± β Expr β Ξ±) : Ξ± :=
foldEqcCore s f e e a
/-- Fold the monadic function of `f` over the equivalence class of `e`. -/
def foldEqcM {Ξ±} {m : Type β Type} [Monad m] (s : CCState) (e : Expr) (a : Ξ±)
(f : Ξ± β Expr β m Ξ±) : m Ξ± :=
foldEqc s e (return a) fun act e => do
let a β act
f a e
end CCState
/--
Applies congruence closure to solve the given metavariable.
This procedure tries to solve the goal by chaining
equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).
The tactic works by building an equality matching graph. It's a graph where
the vertices are terms and they are linked by edges if they are known to
be equal. Once you've added all the equalities in your context, you take
the transitive closure of the graph and, for each connected component
(i.e. equivalence class) you can elect a term that will represent the
whole class and store proofs that the other elements are equal to it.
You then take the transitive closure of these equalities under the
congruence lemmas.
The `cc` implementation in Lean does a few more tricks: for example it
derives `a = b` from `Nat.succ a = Nat.succ b`, and `Nat.succ a != Nat.zero` for any `a`.
* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence
closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),
Journal of the ACM (1980)
* The congruence lemmas for dependent type theory as used in Lean are described in
[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)
(de Moura, Selsam IJCAR 2016).
-/
def _root_.Lean.MVarId.cc (m : MVarId) (cfg : CCConfig := {}) : MetaM Unit := do
let (_, m) β m.intros
m.withContext do
let s β CCState.mkUsingHsCore cfg
let t β m.getType >>= instantiateMVars
let s β s.internalize t
if s.inconsistent then
let pr β s.proofForFalse
mkAppOptM ``False.elim #[t, pr] >>= m.assign
else
let tr := Expr.const ``True []
let b β s.isEqv t tr
if b then
let pr β s.eqvProof t tr
mkAppM ``of_eq_true #[pr] >>= m.assign
else
let dbg β getBoolOption `trace.Meta.Tactic.cc.failure false
if dbg then
throwError m!"cc tactic failed, equivalence classes: {s}"
else
throwError "cc tactic failed"
/--
Allow elaboration of `CCConfig` arguments to tactics.
-/
declare_config_elab elabCCConfig CCConfig
open Parser.Tactic in
/--
The congruence closure tactic `cc` tries to solve the goal by chaining
equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).
It is a finishing tactic, i.e. it is meant to close
the current goal, not to make some inconclusive progress.
A mostly trivial example would be:
```lean
example (a b c : β) (f : β β β) (h: a = b) (h' : b = c) : f a = f c := by
cc
```
As an example requiring some thinking to do by hand, consider:
```lean
example (f : β β β) (x : β)
(H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :
f x = x := by
cc
``` -/
elab (name := _root_.Mathlib.Tactic.cc) "cc" cfg:(config)? : tactic => do
let cfg β elabCCConfig (mkOptionalNode cfg)
withMainContext <| liftMetaFinishingTactic (Β·.cc cfg)
end Mathlib.Tactic.CC
|
Tactic\Change.lean | /-
Copyright (c) 2023 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import Lean.Elab.Tactic.ElabTerm
import Lean.Meta.Tactic.TryThis
/-!
# Tactic `change? term`
This tactic is used to suggest a replacement of the goal by a definitionally equal term.
`term` is intended to contain holes which get unified with the main goal and filled in explicitly
in the suggestion.
`term` can also be omitted, in which case `change?` simply suggests `change` with the main goal.
This is helpful after tactics like `dsimp`, which can then be deleted.
-/
/-- `change? term` unifies `term` with the current goal, then suggests explicit `change` syntax
that uses the resulting unified term.
If `term` is not present, `change?` suggests the current goal itself. This is useful after tactics
which transform the goal while maintaining definitional equality, such as `dsimp`; those preceding
tactic calls can then be deleted.
```lean
example : (fun x : Nat => x) 0 = 1 := by
change? 0 = _ -- `Try this: change 0 = 1`
```
-/
syntax (name := change?) "change?" (ppSpace colGt term)? : tactic
open Lean Meta Elab.Tactic Meta.Tactic.TryThis in
elab_rules : tactic
| `(tactic|change?%$tk $[$sop:term]?) => withMainContext do
let stx β getRef
let expr β match sop with
| none => getMainTarget
| some sop => do
let tgt β getMainTarget
let ex β withRef sop <| elabTermEnsuringType sop (β inferType tgt)
if !(β isDefEq ex tgt) then throwErrorAt sop "\
The term{indentD ex}\n\
is not defeq to the goal:{indentD tgt}"
instantiateMVars ex
let dstx β delabToRefinableSyntax expr
addSuggestion tk (β `(tactic| change $dstx)) (origSpan? := stx)
|
Tactic\Check.lean | /-
Copyright (c) 2024 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Lean.Elab.Tactic.Basic
import Lean.PrettyPrinter
import Lean.Elab.SyntheticMVars
/-!
# `#check` tactic
This module defines a tactic version of the `#check` command.
While `#check t` is similar to `have := t`, it is a little more convenient
since it elaborates `t` in a more tolerant way and so it can be possible to get a result.
For example, `#check` allows metavariables.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic
/--
Tactic version of `Lean.Elab.Command.elabCheck`.
Elaborates `term` without modifying tactic/elab/meta state.
Info messages are placed at `tk`.
-/
def elabCheckTactic (tk : Syntax) (ignoreStuckTC : Bool) (term : Term) : TacticM Unit :=
withoutModifyingStateWithInfoAndMessages <| withMainContext do
if let `($_:ident) := term then
-- show signature for `#check ident`
try
for c in (β realizeGlobalConstWithInfos term) do
addCompletionInfo <| .id term c (danglingDot := false) {} none
logInfoAt tk <| MessageData.signature c
return
catch _ => pure () -- identifier might not be a constant but constant + projection
let e β Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := ignoreStuckTC)
let e β Term.levelMVarToParam (β instantiateMVars e)
let type β inferType e
if e.isSyntheticSorry then
return
logInfoAt tk m!"{e} : {type}"
/--
The `#check t` tactic elaborates the term `t` and then pretty prints it with its type as `e : ty`.
If `t` is an identifier, then it pretty prints a type declaration form
for the global constant `t` instead.
Use `#check (t)` to pretty print it as an elaborated expression.
Like the `#check` command, the `#check` tactic allows stuck typeclass instance problems.
These become metavariables in the output.
-/
elab tk:"#check " colGt term:term : tactic => elabCheckTactic tk true term
|
Tactic\Choose.lean | /-
Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Floris van Doorn, Mario Carneiro, Reid Barton, Johan Commelin
-/
import Mathlib.Util.Tactic
import Mathlib.Logic.Function.Basic
/-!
# `choose` tactic
Performs Skolemization, that is, given `h : β a:Ξ±, β b:Ξ², p a b |- G` produces
`f : Ξ± β Ξ², hf: β a, p a (f a) |- G`.
TODO: switch to `rcases` syntax: `choose β¨i, j, hβ -β© := expr`.
-/
open Lean Meta Elab Tactic
namespace Mathlib.Tactic.Choose
/-- Given `Ξ± : Sort u`, `nonemp : Nonempty Ξ±`, `p : Ξ± β Prop`, a context of free variables
`ctx`, and a pair of an element `val : Ξ±` and `spec : p val`,
`mk_sometimes u Ξ± nonemp p ctx (val, spec)` produces another pair `val', spec'`
such that `val'` does not have any free variables from elements of `ctx` whose types are
propositions. This is done by applying `Function.sometimes` to abstract over all the propositional
arguments. -/
def mk_sometimes (u : Level) (Ξ± nonemp p : Expr) :
List Expr β Expr Γ Expr β MetaM (Expr Γ Expr)
| [], (val, spec) => pure (val, spec)
| (e :: ctx), (val, spec) => do
let (val, spec) β mk_sometimes u Ξ± nonemp p ctx (val, spec)
let t β inferType e
let b β isProp t
if b then do
let val' β mkLambdaFVars #[e] val
pure
(mkApp4 (Expr.const ``Function.sometimes [Level.zero, u]) t Ξ± nonemp val',
mkApp7 (Expr.const ``Function.sometimes_spec [u]) t Ξ± nonemp p val' e spec)
else pure (val, spec)
/-- Results of searching for nonempty instances,
to eliminate dependencies on propositions (`choose!`).
`success` means we found at least one instance;
`failure ts` means we didn't find instances for any `t β ts`.
(`failure []` means we didn't look for instances at all.)
Rationale:
`choose!` means we are expected to succeed at least once
in eliminating dependencies on propositions.
-/
inductive ElimStatus
| success
| failure (ts : List Expr)
/-- Combine two statuses, keeping a success from either side
or merging the failures. -/
def ElimStatus.merge : ElimStatus β ElimStatus β ElimStatus
| success, _ => success
| _, success => success
| failure tsβ, failure tsβ => failure (tsβ ++ tsβ)
/-- `mkFreshNameFrom orig base` returns `mkFreshUserName base` if ``orig = `_``
and `orig` otherwise. -/
def mkFreshNameFrom (orig base : Name) : CoreM Name :=
if orig = `_ then mkFreshUserName base else pure orig
/-- Changes `(h : βxs, βa:Ξ±, p a) β’ g` to `(d : βxs, a) β’ (s : βxs, p (d xs)) β g` and
`(h : βxs, p xs β§ q xs) β’ g` to `(d : βxs, p xs) β’ (s : βxs, q xs) β g`.
`choose1` returns a tuple of
- the error result (see `ElimStatus`)
- the data new free variable that was "chosen"
- the new goal (which contains the spec of the data as domain of an arrow type)
If `nondep` is true and `Ξ±` is inhabited, then it will remove the dependency of `d` on
all propositional assumptions in `xs`. For example if `ys` are propositions then
`(h : βxs ys, βa:Ξ±, p a) β’ g` becomes `(d : βxs, a) (s : βxs ys, p (d xs)) β’ g`. -/
def choose1 (g : MVarId) (nondep : Bool) (h : Option Expr) (data : Name) :
MetaM (ElimStatus Γ Expr Γ MVarId) := do
let (g, h) β match h with
| some e => pure (g, e)
| none => do
let (e, g) β g.intro1P
pure (g, .fvar e)
g.withContext do
let h β instantiateMVars h
let t β inferType h
forallTelescopeReducing t fun ctx t β¦ do
(β withTransparency .all (whnf t)).withApp fun
| .const ``Exists [u], #[Ξ±, p] => do
let data β mkFreshNameFrom data ((β p.getBinderName).getD `h)
let ((neFail : ElimStatus), (nonemp : Option Expr)) β if nondep then
let ne := (Expr.const ``Nonempty [u]).app Ξ±
let m β mkFreshExprMVar ne
let mut g' := m.mvarId!
for e in ctx do
if (β isProof e) then continue
let ty β whnf (β inferType e)
let nety := (Expr.const ``Nonempty [u]).app ty
let neval := mkApp2 (Expr.const ``Nonempty.intro [u]) ty e
g' β g'.assert .anonymous nety neval
(_, g') β g'.intros
g'.withContext do
match β synthInstance? (β g'.getType) with
| some e => do
g'.assign e
let m β instantiateMVars m
pure (.success, some m)
| none => pure (.failure [ne], none)
else pure (.failure [], none)
let ctx' β if nonemp.isSome then ctx.filterM (not <$> isProof Β·) else pure ctx
let dataTy β mkForallFVars ctx' Ξ±
let mut dataVal := mkApp3 (.const ``Classical.choose [u]) Ξ± p (mkAppN h ctx)
let mut specVal := mkApp3 (.const ``Classical.choose_spec [u]) Ξ± p (mkAppN h ctx)
if let some nonemp := nonemp then
(dataVal, specVal) β mk_sometimes u Ξ± nonemp p ctx.toList (dataVal, specVal)
dataVal β mkLambdaFVars ctx' dataVal
specVal β mkLambdaFVars ctx specVal
let (fvar, g) β withLocalDeclD .anonymous dataTy fun d β¦ do
let specTy β mkForallFVars ctx (p.app (mkAppN d ctx')).headBeta
g.withContext <| withLocalDeclD data dataTy fun d' β¦ do
let mvarTy β mkArrow (specTy.replaceFVar d d') (β g.getType)
let newMVar β mkFreshExprSyntheticOpaqueMVar mvarTy (β g.getTag)
g.assign <| mkApp2 (β mkLambdaFVars #[d'] newMVar) dataVal specVal
pure (d', newMVar.mvarId!)
let g β match h with
| .fvar v => g.clear v
| _ => pure g
return (neFail, fvar, g)
| .const ``And _, #[p, q] => do
let data β mkFreshNameFrom data `h
let e1 β mkLambdaFVars ctx <| mkApp3 (.const ``And.left []) p q (mkAppN h ctx)
let e2 β mkLambdaFVars ctx <| mkApp3 (.const ``And.right []) p q (mkAppN h ctx)
let t1 β inferType e1
let t2 β inferType e2
let (fvar, g) β (β (β g.assert .anonymous t2 e2).assert data t1 e1).intro1P
let g β match h with
| .fvar v => g.clear v
| _ => pure g
return (.success, .fvar fvar, g)
-- TODO: support Ξ£, Γ, or even any inductive type with 1 constructor ?
| _, _ => throwError "expected a term of the shape `βxs, βa, p xs a` or `βxs, p xs β§ q xs`"
/-- A wrapper around `choose1` that parses identifiers and adds variable info to new variables. -/
def choose1WithInfo (g : MVarId) (nondep : Bool) (h : Option Expr) (data : TSyntax ``binderIdent) :
MetaM (ElimStatus Γ MVarId) := do
let n := if let `(binderIdent| $n:ident) := data then n.getId else `_
let (status, fvar, g) β choose1 g nondep h n
g.withContext <| fvar.addLocalVarInfoForBinderIdent data
pure (status, g)
/-- A loop around `choose1`. The main entry point for the `choose` tactic. -/
def elabChoose (nondep : Bool) (h : Option Expr) :
List (TSyntax ``binderIdent) β ElimStatus β MVarId β MetaM MVarId
| [], _, _ => throwError "expect list of variables"
| [n], status, g =>
match nondep, status with
| true, .failure tys => do -- We expected some elimination, but it didn't happen.
let mut msg := m!"choose!: failed to synthesize any nonempty instances"
for ty in tys do
msg := msg ++ m!"{(β mkFreshExprMVar ty).mvarId!}"
throwError msg
| _, _ => do
let (fvar, g) β match n with
| `(binderIdent| $n:ident) => g.intro n.getId
| _ => g.intro1
g.withContext <| (Expr.fvar fvar).addLocalVarInfoForBinderIdent n
return g
| n::ns, status, g => do
let (status', g) β choose1WithInfo g nondep h n
elabChoose nondep none ns (status.merge status') g
/--
* `choose a b h h' using hyp` takes a hypothesis `hyp` of the form
`β (x : X) (y : Y), β (a : A) (b : B), P x y a b β§ Q x y a b`
for some `P Q : X β Y β A β B β Prop` and outputs
into context a function `a : X β Y β A`, `b : X β Y β B` and two assumptions:
`h : β (x : X) (y : Y), P x y (a x y) (b x y)` and
`h' : β (x : X) (y : Y), Q x y (a x y) (b x y)`. It also works with dependent versions.
* `choose! a b h h' using hyp` does the same, except that it will remove dependency of
the functions on propositional arguments if possible. For example if `Y` is a proposition
and `A` and `B` are nonempty in the above example then we will instead get
`a : X β A`, `b : X β B`, and the assumptions
`h : β (x : X) (y : Y), P x y (a x) (b x)` and
`h' : β (x : X) (y : Y), Q x y (a x) (b x)`.
The `using hyp` part can be omitted,
which will effectively cause `choose` to start with an `intro hyp`.
Examples:
```
example (h : β n m : β, β i j, m = n + i β¨ m + j = n) : True := by
choose i j h using h
guard_hyp i : β β β β β
guard_hyp j : β β β β β
guard_hyp h : β (n m : β), m = n + i n m β¨ m + j n m = n
trivial
```
```
example (h : β i : β, i < 7 β β j, i < j β§ j < i+i) : True := by
choose! f h h' using h
guard_hyp f : β β β
guard_hyp h : β (i : β), i < 7 β i < f i
guard_hyp h' : β (i : β), i < 7 β f i < i + i
trivial
```
-/
syntax (name := choose) "choose" "!"? (ppSpace colGt binderIdent)+ (" using " term)? : tactic
elab_rules : tactic
| `(tactic| choose $[!%$b]? $[$ids]* $[using $h]?) => withMainContext do
let h β h.mapM (Elab.Tactic.elabTerm Β· none)
let g β elabChoose b.isSome h ids.toList (.failure []) (β getMainGoal)
replaceMainGoal [g]
@[inherit_doc choose]
syntax "choose!" (ppSpace colGt binderIdent)+ (" using " term)? : tactic
macro_rules
| `(tactic| choose! $[$ids]* $[using $h]?) => `(tactic| choose ! $[$ids]* $[using $h]?)
|
Tactic\Clean.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Michail Karatarakis, Kyle Miller
-/
import Lean.Elab.SyntheticMVars
/-!
# `clean%` term elaborator
Remove identity functions from a term.
-/
open Lean Meta Elab
namespace Lean.Expr
/-- List of names removed by the `clean` tactic.
All of these names must resolve to functions defeq `id`. -/
-- Note: one could also add `hidden`, but this doesn't arise from type hints.
def cleanConsts : List Name :=
[``id]
/-- Clean an expression by eliminating identify functions listed in `cleanConsts`.
Also eliminates `fun x => x` applications and tautological `let_fun` bindings. -/
def clean (e : Expr) : Expr :=
e.replace fun
| .app (.app (.const n _) _) e' => if n β cleanConsts then some e' else none
| .app (.lam _ _ (.bvar 0) _) e' => some e'
| e =>
match e.letFun? with
| some (_n, _t, v, .bvar 0) => some v
| _ => none
end Lean.Expr
namespace Mathlib.Tactic
/--
`clean% t` fully elaborates `t` and then eliminates all identity functions from it.
Identity functions are normally generated with terms like `show t from p`,
which translate to some variant on `@id t p` in order to retain the type.
These are also generated by tactics such as `dsimp` to insert type hints.
Example:
```lean
def x : Id Nat := by dsimp [Id]; exact 1
#print x
-- def x : Id Nat := id 1
def x' : Id Nat := clean% by dsimp [Id]; exact 1
#print x'
-- def x' : Id Nat := 1
```
-/
syntax (name := cleanStx) "clean% " term : term
@[term_elab cleanStx, inherit_doc cleanStx]
def elabClean : Term.TermElab := fun stx expectedType? =>
match stx with
| `(clean% $t) => do
let e β Term.withSynthesize <| Term.elabTerm t expectedType?
return (β instantiateMVars e).clean
| _ => throwUnsupportedSyntax
/-- (Deprecated) `clean t` is a macro for `exact clean% t`. -/
macro "clean " t:term : tactic => `(tactic| exact clean% $t)
end Mathlib.Tactic
|
Tactic\ClearExcept.lean | /-
Copyright (c) 2022 Joshua Clune. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joshua Clune
-/
import Lean.Elab.Tactic.ElabTerm
/-!
# The `clear*` tactic
This file provides a variant of the `clear` tactic, which clears all hypotheses it can
besides a provided list.
-/
open Lean.Meta
namespace Lean.Elab.Tactic
/-- Clears all hypotheses it can besides those provided -/
syntax (name := clearExcept) "clear " "*" " -" (ppSpace colGt ident)* : tactic
elab_rules : tactic
| `(tactic| clear * - $hs:ident*) => do
let fvarIds β getFVarIds hs
liftMetaTactic1 fun goal β¦ do
let mut toClear : Array FVarId := #[]
for decl in β getLCtx do
unless fvarIds.contains decl.fvarId do
if let none β isClass? decl.type then
toClear := toClear.push decl.fvarId
goal.tryClearMany toClear
|
Tactic\ClearExclamation.lean | /-
Copyright (c) 2022 Joshua Clune. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joshua Clune
-/
import Lean.Elab.Tactic.ElabTerm
/-! # `clear!` tactic -/
namespace Mathlib.Tactic
open Lean Meta Elab.Tactic
/-- A variant of `clear` which clears not only the given hypotheses but also any other hypotheses
depending on them -/
elab (name := clear!) "clear!" hs:(ppSpace colGt ident)* : tactic => do
let fvarIds β getFVarIds hs
liftMetaTactic1 fun goal β¦ do
goal.tryClearMany <| (β collectForwardDeps (fvarIds.map .fvar) true).map (Β·.fvarId!)
|
Tactic\Clear_.lean | /-
Copyright (c) 2022 Joshua Clune. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joshua Clune
-/
import Lean.Meta.Tactic.Clear
import Lean.Elab.Tactic.Basic
/-! # `clear_` tactic -/
namespace Mathlib.Tactic
open Lean Meta Elab.Tactic
/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/
elab (name := clear_) "clear_" : tactic =>
liftMetaTactic1 fun goal β¦ do
let mut toClear := #[]
for decl in β getLCtx do
if let Name.str _ str := decl.userName then
if !str.isEmpty && str.front == '_' then
if let none β isClass? decl.type then
toClear := toClear.push decl.fvarId
goal.tryClearMany toClear
|
Tactic\Coe.lean | /-
Copyright (c) 2021 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Elab.ElabRules
/-!
# Additional coercion notation
Defines notation for coercions.
1. `β t` is defined in core.
2. `(β)` is equivalent to the eta-reduction of `(β Β·)`
3. `β t` is a coercion to a function type.
4. `(β)` is equivalent to the eta-reduction of `(β Β·)`
3. `β₯ t` is a coercion to a type.
6. `(β₯)` is equivalent to the eta-reduction of `(β₯ Β·)`
-/
open Lean Meta
namespace Lean.Elab.Term.CoeImpl
/-- Elaborator for the `(β)`, `(β)`, and `(β₯)` notations. -/
def elabPartiallyAppliedCoe (sym : String) (expectedType : Expr)
(mkCoe : (expectedType x : Expr) β TermElabM Expr) : TermElabM Expr := do
let expectedType β instantiateMVars expectedType
let Expr.forallE _ a b .. := expectedType | do
tryPostpone
throwError "({sym}) must have a function type, not{indentExpr expectedType}"
if b.hasLooseBVars then
tryPostpone
throwError "({sym}) must have a non-dependent function type, not{indentExpr expectedType}"
if a.hasExprMVar then tryPostpone
let f β withLocalDeclD `x a fun x β¦ do
mkLambdaFVars #[x] (β mkCoe b x)
return f.etaExpanded?.getD f
/-- Partially applied coercion. Equivalent to the Ξ·-reduction of `(β Β·)` -/
elab "(" "β" ")" : term <= expectedType =>
elabPartiallyAppliedCoe "β" expectedType fun b x => do
if b.hasExprMVar then tryPostpone
if let .some e β coerce? x b then
return e
else
throwError "cannot coerce{indentExpr x}\nto type{indentExpr b}"
/-- Partially applied function coercion. Equivalent to the Ξ·-reduction of `(β Β·)` -/
elab "(" "β" ")" : term <= expectedType =>
elabPartiallyAppliedCoe "β" expectedType fun b x => do
if let some ty β coerceToFunction? x then
ensureHasType b ty
else
throwError "cannot coerce to function{indentExpr x}"
/-- Partially applied type coercion. Equivalent to the Ξ·-reduction of `(β₯ Β·)` -/
elab "(" "β₯" ")" : term <= expectedType =>
elabPartiallyAppliedCoe "β₯" expectedType fun b x => do
if let some ty β coerceToSort? x then
ensureHasType b ty
else
throwError "cannot coerce to sort{indentExpr x}"
|
Tactic\Common.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
-- First import Aesop and Qq
import Aesop
import Qq
-- Tools for analysing imports, like `#find_home`, `#minimize_imports`, ...
import ImportGraph.Imports
-- Import common Batteries tactics and commands
import Batteries.Tactic.Where
-- Import Mathlib-specific linters.
import Mathlib.Tactic.Linter.Lint
-- Now import all tactics defined in Mathlib that do not require theory files.
import Mathlib.Tactic.ApplyCongr
-- ApplyFun imports `Mathlib.Order.Monotone.Basic`
-- import Mathlib.Tactic.ApplyFun
import Mathlib.Tactic.ApplyAt
import Mathlib.Tactic.ApplyWith
import Mathlib.Tactic.Basic
import Mathlib.Tactic.ByContra
import Mathlib.Tactic.Cases
import Mathlib.Tactic.CasesM
import Mathlib.Tactic.Check
import Mathlib.Tactic.Choose
import Mathlib.Tactic.ClearExclamation
import Mathlib.Tactic.ClearExcept
import Mathlib.Tactic.Clear_
import Mathlib.Tactic.Coe
import Mathlib.Tactic.CongrExclamation
import Mathlib.Tactic.CongrM
import Mathlib.Tactic.Constructor
import Mathlib.Tactic.Contrapose
import Mathlib.Tactic.Conv
import Mathlib.Tactic.Convert
import Mathlib.Tactic.DefEqTransformations
import Mathlib.Tactic.DeprecateMe
import Mathlib.Tactic.DeriveToExpr
import Mathlib.Tactic.Eqns
import Mathlib.Tactic.ExistsI
import Mathlib.Tactic.ExtractGoal
import Mathlib.Tactic.ExtractLets
import Mathlib.Tactic.FailIfNoProgress
import Mathlib.Tactic.Find
-- `gcongr` currently imports `Algebra.Order.Field.Power` and thence `Algebra.CharZero.Lemmas`
-- Hopefully this can be rearranged.
-- import Mathlib.Tactic.GCongr
import Mathlib.Tactic.GeneralizeProofs
import Mathlib.Tactic.GuardGoalNums
import Mathlib.Tactic.GuardHypNums
import Mathlib.Tactic.HelpCmd
import Mathlib.Tactic.HigherOrder
import Mathlib.Tactic.Hint
import Mathlib.Tactic.InferParam
import Mathlib.Tactic.Inhabit
import Mathlib.Tactic.IrreducibleDef
import Mathlib.Tactic.Lift
import Mathlib.Tactic.Linter
import Mathlib.Tactic.MkIffOfInductiveProp
-- NormNum imports `Algebra.Order.Invertible`, `Data.Int.Basic`, `Data.Nat.Cast.Commute`
-- import Mathlib.Tactic.NormNum.Basic
import Mathlib.Tactic.NthRewrite
import Mathlib.Tactic.Observe
-- `positivity` imports `Data.Nat.Factorial.Basic`, but hopefully this can be rearranged.
-- import Mathlib.Tactic.Positivity
import Mathlib.Tactic.ProjectionNotation
import Mathlib.Tactic.Propose
import Mathlib.Tactic.PushNeg
import Mathlib.Tactic.RSuffices
import Mathlib.Tactic.Recover
import Mathlib.Tactic.Relation.Rfl
import Mathlib.Tactic.Relation.Trans
import Mathlib.Tactic.Rename
import Mathlib.Tactic.RenameBVar
import Mathlib.Tactic.Says
import Mathlib.Tactic.ScopedNS
import Mathlib.Tactic.Set
import Mathlib.Tactic.SimpIntro
import Mathlib.Tactic.SimpRw
import Mathlib.Tactic.Simps.Basic
-- SlimCheck has unnecessarily complicated imports, and could be streamlined.
-- `Gen` / `Testable` / `Sampleable` instances for types should be out in the library,
-- rather than the theory for those types being imported into `SlimCheck`.
-- import Mathlib.Tactic.SlimCheck
import Mathlib.Tactic.SplitIfs
import Mathlib.Tactic.Spread
import Mathlib.Tactic.Subsingleton
import Mathlib.Tactic.Substs
import Mathlib.Tactic.SuccessIfFailWithMsg
import Mathlib.Tactic.SudoSetOption
import Mathlib.Tactic.SwapVar
import Mathlib.Tactic.Tauto
import Mathlib.Tactic.TermCongr
-- TFAE imports `Mathlib.Data.List.TFAE` and thence `Mathlib.Data.List.Basic`.
-- import Mathlib.Tactic.TFAE
import Mathlib.Tactic.ToExpr
import Mathlib.Tactic.ToLevel
import Mathlib.Tactic.Trace
import Mathlib.Tactic.TypeCheck
import Mathlib.Tactic.UnsetOption
import Mathlib.Tactic.Use
import Mathlib.Tactic.Variable
import Mathlib.Tactic.Widget.Calc
import Mathlib.Tactic.Widget.CongrM
import Mathlib.Tactic.Widget.Conv
import Mathlib.Tactic.WLOG
import Mathlib.Util.AssertExists
import Mathlib.Util.CountHeartbeats
import Mathlib.Util.WhatsNew
/-!
This file imports all tactics which do not have significant theory imports,
and hence can be imported very low in the theory import hierarchy,
thereby making tactics widely available without needing specific imports.
We include some commented out imports here, with an explanation of their theory requirements,
to save some time for anyone wondering why they are not here.
We also import theory-free linters, commands, and utilities which are useful to have low in the
import hierarchy.
-/
/-!
# Register tactics with `hint`.
-/
section Hint
register_hint split
register_hint intro
register_hint aesop
register_hint simp_all?
register_hint exact?
register_hint decide
register_hint omega
end Hint
|
Tactic\ComputeDegree.lean | /-
Copyright (c) 2023 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import Mathlib.Algebra.Polynomial.Degree.Lemmas
/-!
# `compute_degree` and `monicity`: tactics for explicit polynomials
This file defines two related tactics: `compute_degree` and `monicity`.
Using `compute_degree` when the goal is of one of the five forms
* `natDegree f β€ d`,
* `degree f β€ d`,
* `natDegree f = d`,
* `degree f = d`,
* `coeff f d = r`, if `d` is the degree of `f`,
tries to solve the goal.
It may leave side-goals, in case it is not entirely successful.
Using `monicity` when the goal is of the form `Monic f` tries to solve the goal.
It may leave side-goals, in case it is not entirely successful.
Both tactics admit a `!` modifier (`compute_degree!` and `monicity!`) instructing
Lean to try harder to close the goal.
See the doc-strings for more details.
## Future work
* Currently, `compute_degree` does not deal correctly with some edge cases. For instance,
```lean
example [Semiring R] : natDegree (C 0 : R[X]) = 0 := by
compute_degree
-- β’ 0 β 0
```
Still, it may not be worth to provide special support for `natDegree f = 0`.
* Make sure that numerals in coefficients are treated correctly.
* Make sure that `compute_degree` works with goals of the form `degree f β€ βd`, with an
explicit coercion from `β` on the RHS.
* Add support for proving goals of the from `natDegree f β 0` and `degree f β 0`.
* Make sure that `degree`, `natDegree` and `coeff` are equally supported.
## Implementation details
Assume that `f : R[X]` is a polynomial with coefficients in a semiring `R` and
`d` is either in `β` or in `WithBot β`.
If the goal has the form `natDegree f = d`, then we convert it to three separate goals:
* `natDegree f β€ d`;
* `coeff f d = r`;
* `r β 0`.
Similarly, an initial goal of the form `degree f = d` gives rise to goals of the form
* `degree f β€ d`;
* `coeff f d = r`;
* `r β 0`.
Next, we apply successively lemmas whose side-goals all have the shape
* `natDegree f β€ d`;
* `degree f β€ d`;
* `coeff f d = r`;
plus possibly "numerical" identities and choices of elements in `β`, `WithBot β`, and `R`.
Recursing into `f`, we break apart additions, multiplications, powers, subtractions,...
The leaves of the process are
* numerals, `C a`, `X` and `monomial a n`, to which we assign degree `0`, `1` and `a` respectively;
* `fvar`s `f`, to which we tautologically assign degree `natDegree f`.
-/
open Polynomial
namespace Mathlib.Tactic.ComputeDegree
section recursion_lemmas
/-!
### Simple lemmas about `natDegree`
The lemmas in this section all have the form `natDegree <some form of cast> β€ 0`.
Their proofs are weakenings of the stronger lemmas `natDegree <same> = 0`.
These are the lemmas called by `compute_degree` on (almost) all the leaves of its recursion.
-/
variable {R : Type*}
section semiring
variable [Semiring R]
theorem natDegree_C_le (a : R) : natDegree (C a) β€ 0 := (natDegree_C a).le
theorem natDegree_natCast_le (n : β) : natDegree (n : R[X]) β€ 0 := (natDegree_natCast _).le
theorem natDegree_zero_le : natDegree (0 : R[X]) β€ 0 := natDegree_zero.le
theorem natDegree_one_le : natDegree (1 : R[X]) β€ 0 := natDegree_one.le
@[deprecated (since := "2024-04-17")]
alias natDegree_nat_cast_le := natDegree_natCast_le
theorem coeff_add_of_eq {n : β} {a b : R} {f g : R[X]}
(h_add_left : f.coeff n = a) (h_add_right : g.coeff n = b) :
(f + g).coeff n = a + b := by subst βΉ_βΊ βΉ_βΊ; apply coeff_add
theorem coeff_mul_add_of_le_natDegree_of_eq_ite {d df dg : β} {a b : R} {f g : R[X]}
(h_mul_left : natDegree f β€ df) (h_mul_right : natDegree g β€ dg)
(h_mul_left : f.coeff df = a) (h_mul_right : g.coeff dg = b) (ddf : df + dg β€ d) :
(f * g).coeff d = if d = df + dg then a * b else 0 := by
split_ifs with h
Β· subst h_mul_left h_mul_right h
exact coeff_mul_of_natDegree_le βΉ_βΊ βΉ_βΊ
Β· apply coeff_eq_zero_of_natDegree_lt
apply lt_of_le_of_lt ?_ (lt_of_le_of_ne ddf ?_)
Β· exact natDegree_mul_le_of_le βΉ_βΊ βΉ_βΊ
Β· exact ne_comm.mp h
theorem coeff_pow_of_natDegree_le_of_eq_ite' {m n o : β} {a : R} {p : R[X]}
(h_pow : natDegree p β€ n) (h_exp : m * n β€ o) (h_pow_bas : coeff p n = a) :
coeff (p ^ m) o = if o = m * n then a ^ m else 0 := by
split_ifs with h
Β· subst h h_pow_bas
exact coeff_pow_of_natDegree_le βΉ_βΊ
Β· apply coeff_eq_zero_of_natDegree_lt
apply lt_of_le_of_lt ?_ (lt_of_le_of_ne βΉ_βΊ ?_)
Β· exact natDegree_pow_le_of_le m βΉ_βΊ
Β· exact Iff.mp ne_comm h
theorem natDegree_smul_le_of_le {n : β} {a : R} {f : R[X]} (hf : natDegree f β€ n) :
natDegree (a β’ f) β€ n :=
(natDegree_smul_le a f).trans hf
theorem degree_smul_le_of_le {n : β} {a : R} {f : R[X]} (hf : degree f β€ n) :
degree (a β’ f) β€ n :=
(degree_smul_le a f).trans hf
theorem coeff_smul {n : β} {a : R} {f : R[X]} : (a β’ f).coeff n = a * f.coeff n := rfl
section congr_lemmas
/-- The following two lemmas should be viewed as a hand-made "congr"-lemmas.
They achieve the following goals.
* They introduce *two* fresh metavariables replacing the given one `deg`,
one for the `natDegree β€` computation and one for the `coeff =` computation.
This helps `compute_degree`, since it does not "pre-estimate" the degree,
but it "picks it up along the way".
* They split checking the inequality `coeff p n β 0` into the task of
finding a value `c` for the `coeff` and then
proving that this value is non-zero by `coeff_ne_zero`.
-/
theorem natDegree_eq_of_le_of_coeff_ne_zero' {deg m o : β} {c : R} {p : R[X]}
(h_natDeg_le : natDegree p β€ m) (coeff_eq : coeff p o = c)
(coeff_ne_zero : c β 0) (deg_eq_deg : m = deg) (coeff_eq_deg : o = deg) :
natDegree p = deg := by
subst coeff_eq deg_eq_deg coeff_eq_deg
exact natDegree_eq_of_le_of_coeff_ne_zero βΉ_βΊ βΉ_βΊ
theorem degree_eq_of_le_of_coeff_ne_zero' {deg m o : WithBot β} {c : R} {p : R[X]}
(h_deg_le : degree p β€ m) (coeff_eq : coeff p (WithBot.unbot' 0 deg) = c)
(coeff_ne_zero : c β 0) (deg_eq_deg : m = deg) (coeff_eq_deg : o = deg) :
degree p = deg := by
subst coeff_eq coeff_eq_deg deg_eq_deg
rcases eq_or_ne m β₯ with rfl|hh
Β· exact bot_unique h_deg_le
Β· obtain β¨m, rflβ© := WithBot.ne_bot_iff_exists.mp hh
exact degree_eq_of_le_of_coeff_ne_zero βΉ_βΊ βΉ_βΊ
variable {m n : β} {f : R[X]} {r : R}
theorem coeff_congr_lhs (h : coeff f m = r) (natDeg_eq_coeff : m = n) : coeff f n = r :=
natDeg_eq_coeff βΈ h
theorem coeff_congr (h : coeff f m = r) (natDeg_eq_coeff : m = n) {s : R} (rs : r = s) :
coeff f n = s :=
natDeg_eq_coeff βΈ rs βΈ h
end congr_lemmas
end semiring
section ring
variable [Ring R]
theorem natDegree_intCast_le (n : β€) : natDegree (n : R[X]) β€ 0 := (natDegree_intCast _).le
@[deprecated (since := "2024-04-17")]
alias natDegree_int_cast_le := natDegree_intCast_le
theorem coeff_sub_of_eq {n : β} {a b : R} {f g : R[X]} (hf : f.coeff n = a) (hg : g.coeff n = b) :
(f - g).coeff n = a - b := by subst hf hg; apply coeff_sub
theorem coeff_intCast_ite {n : β} {a : β€} : (Int.cast a : R[X]).coeff n = ite (n = 0) a 0 := by
simp only [β C_eq_intCast, coeff_C, Int.cast_ite, Int.cast_zero]
@[deprecated (since := "2024-04-17")]
alias coeff_int_cast_ite := coeff_intCast_ite
end ring
end recursion_lemmas
section Tactic
open Lean Elab Tactic Meta Expr
/-- `twoHeadsArgs e` takes an `Expr`ession `e` as input and recurses into `e` to make sure
the `e` looks like `lhs β€ rhs` or `lhs = rhs` and that `lhs` is one of
`natDegree f, degree f, coeff f d`.
It returns
* the function being applied on the LHS (`natDegree`, `degree`, or `coeff`),
or else `.anonymous` if it's none of these.
* the name of the relation (`Eq` or `LE.le`), or else `.anonymous` if it's none of these.
* either
* `.inl zero`, `.inl one`, or `.inl many` if the polynomial in a numeral
* or `.inr` of the head symbol of `f`
* or `.inl .anonymous` if inapplicable
* if it exists, whether the `rhs` is a metavariable
* if the LHS is `coeff f d`, whether `d` is a metavariable
This is all the data needed to figure out whether `compute_degree` can make progress on `e`
and, if so, which lemma it should apply.
Sample outputs:
* `natDegree (f + g) β€ d => (natDegree, LE.le, HAdd.hAdd, d.isMVar, none)` (similarly for `=`);
* `degree (f * g) = d => (degree, Eq, HMul.hMul, d.isMVar, none)` (similarly for `β€`);
* `coeff (1 : β[X]) c = x => (coeff, Eq, one, x.isMVar, c.isMVar)` (no `β€` option!).
-/
def twoHeadsArgs (e : Expr) : Name Γ Name Γ (Name β Name) Γ List Bool := Id.run do
let (eq_or_le, lhs, rhs) β match e.getAppFnArgs with
| (na@``Eq, #[_, lhs, rhs]) => pure (na, lhs, rhs)
| (na@``LE.le, #[_, _, lhs, rhs]) => pure (na, lhs, rhs)
| _ => return (.anonymous, .anonymous, .inl .anonymous, [])
let (ndeg_or_deg_or_coeff, pol, and?) β match lhs.getAppFnArgs with
| (na@``Polynomial.natDegree, #[_, _, pol]) => (na, pol, [rhs.isMVar])
| (na@``Polynomial.degree, #[_, _, pol]) => (na, pol, [rhs.isMVar])
| (na@``Polynomial.coeff, #[_, _, pol, c]) => (na, pol, [rhs.isMVar, c.isMVar])
| _ => return (.anonymous, eq_or_le, .inl .anonymous, [])
let head := match pol.numeral? with
-- can I avoid the tri-splitting `n = 0`, `n = 1`, and generic `n`?
| some 0 => .inl `zero
| some 1 => .inl `one
| some _ => .inl `many
| none => match pol.getAppFnArgs with
| (``DFunLike.coe, #[_, _, _, _, polFun, _]) =>
let na := polFun.getAppFn.constName
if na β [``Polynomial.monomial, ``Polynomial.C] then
.inr na
else
.inl .anonymous
| (na, _) => .inr na
(ndeg_or_deg_or_coeff, eq_or_le, head, and?)
/--
`getCongrLemma (lhs_name, rel_name, Mvars?)` returns the name of a lemma that preprocesses
one of the five target
* `natDegree f β€ d`;
* `natDegree f = d`.
* `degree f β€ d`;
* `degree f = d`.
* `coeff f d = r`.
The end goals are of the form
* `natDegree f β€ ?_`, `degree f β€ ?_`, `coeff f ?_ = ?_`, with fresh metavariables;
* `coeff f m β s` with `m, s` not necessarily metavariables;
* several equalities/inequalities between expressions and assignments for metavariables.
`getCongrLemma` gets called at the very beginning of `compute_degree` and whenever an intermediate
goal does not have the right metavariables.
Note that the side-goals of the congruence lemma are neither of the form `natDegree f = d` nor
of the form `degree f = d`.
`getCongrLemma` admits an optional "debug" flag: `getCongrLemma data true` prints the name of
the congruence lemma that it returns.
-/
def getCongrLemma (twoH : Name Γ Name Γ List Bool) (debug : Bool := false) : Name :=
let nam := match twoH with
| (_, ``LE.le, [rhs]) => if rhs then ``id else ``le_trans
| (``natDegree, ``Eq, [rhs]) => if rhs then ``id else ``natDegree_eq_of_le_of_coeff_ne_zero'
| (``degree, ``Eq, [rhs]) => if rhs then ``id else ``degree_eq_of_le_of_coeff_ne_zero'
| (``coeff, ``Eq, [rhs, c]) =>
match rhs, c with
| false, false => ``coeff_congr
| false, true => ``Eq.trans
| true, false => ``coeff_congr_lhs
| true, true => ``id
| _ => ``id
if debug then
let last := nam.lastComponentAsString
let natr := if last == "trans" then nam.toString else last
dbg_trace f!"congr lemma: '{natr}'"
nam
else
nam
/--
`dispatchLemma twoH` takes its input `twoH` from the output of `twoHeadsArgs`.
Using the information contained in `twoH`, it decides which lemma is the most appropriate.
`dispatchLemma` is essentially the main dictionary for `compute_degree`.
-/
-- Internally, `dispatchLemma` produces 3 names: these are the lemmas that are appropriate
-- for goals of the form `natDegree f β€ d`, `degree f β€ d`, `coeff f d = a`, in this order.
def dispatchLemma
(twoH : Name Γ Name Γ (Name β Name) Γ List Bool) (debug : Bool := false) : Name :=
match twoH with
| (.anonymous, _, _) => ``id -- `twoH` gave default value, so we do nothing
| (_, .anonymous, _) => ``id -- `twoH` gave default value, so we do nothing
| (na1, na2, head, bools) =>
let msg := f!"\ndispatchLemma:\n {head}"
-- if there is some non-metavariable on the way, we "congr" it away
if false β bools then getCongrLemma (na1, na2, bools) debug
else
-- otherwise, we select either the first, second or third element of the triple in `nas` below
let Ο (natDegLE : Name) (degLE : Name) (coeff : Name) : Name := Id.run do
let lem := match na1, na2 with
| ``natDegree, ``LE.le => natDegLE
| ``degree, ``LE.le => degLE
| ``coeff, ``Eq => coeff
| _, ``LE.le => ``le_rfl
| _, _ => ``rfl
if debug then
dbg_trace f!"{lem.lastComponentAsString}\n{msg}"
lem
match head with
| .inl `zero => Ο ``natDegree_zero_le ``degree_zero_le ``coeff_zero
| .inl `one => Ο ``natDegree_one_le ``degree_one_le ``coeff_one
| .inl `many => Ο ``natDegree_natCast_le ``degree_natCast_le ``coeff_natCast_ite
| .inl .anonymous => Ο ``le_rfl ``le_rfl ``rfl
| .inr ``HAdd.hAdd =>
Ο ``natDegree_add_le_of_le ``degree_add_le_of_le ``coeff_add_of_eq
| .inr ``HSub.hSub =>
Ο ``natDegree_sub_le_of_le ``degree_sub_le_of_le ``coeff_sub_of_eq
| .inr ``HMul.hMul =>
Ο ``natDegree_mul_le_of_le ``degree_mul_le_of_le ``coeff_mul_add_of_le_natDegree_of_eq_ite
| .inr ``HPow.hPow =>
Ο ``natDegree_pow_le_of_le ``degree_pow_le_of_le ``coeff_pow_of_natDegree_le_of_eq_ite'
| .inr ``Neg.neg =>
Ο ``natDegree_neg_le_of_le ``degree_neg_le_of_le ``coeff_neg
| .inr ``Polynomial.X =>
Ο ``natDegree_X_le ``degree_X_le ``coeff_X
| .inr ``Nat.cast =>
Ο ``natDegree_natCast_le ``degree_natCast_le ``coeff_natCast_ite
| .inr ``NatCast.natCast =>
Ο ``natDegree_natCast_le ``degree_natCast_le ``coeff_natCast_ite
| .inr ``Int.cast =>
Ο ``natDegree_intCast_le ``degree_intCast_le ``coeff_intCast_ite
| .inr ``IntCast.intCast =>
Ο ``natDegree_intCast_le ``degree_intCast_le ``coeff_intCast_ite
| .inr ``Polynomial.monomial =>
Ο ``natDegree_monomial_le ``degree_monomial_le ``coeff_monomial
| .inr ``Polynomial.C =>
Ο ``natDegree_C_le ``degree_C_le ``coeff_C
| .inr ``HSMul.hSMul =>
Ο ``natDegree_smul_le_of_le ``degree_smul_le_of_le ``coeff_smul
| _ => Ο ``le_rfl ``le_rfl ``rfl
/-- `try_rfl mvs` takes as input a list of `MVarId`s, scans them partitioning them into two
lists: the goals containing some metavariables and the goals not containing any metavariable.
If a goal containing a metavariable has the form `?_ = x`, `x = ?_`, where `?_` is a metavariable
and `x` is an expression that does not involve metavariables, then it closes this goal using `rfl`,
effectively assigning the metavariable to `x`.
If a goal does not contain metavariables, it tries `rfl` on it.
It returns the list of `MVarId`s, beginning with the ones that initially involved (`Expr`)
metavariables followed by the rest.
-/
def try_rfl (mvs : List MVarId) : MetaM (List MVarId) := do
let (yesMV, noMV) := β mvs.partitionM fun mv =>
return hasExprMVar (β instantiateMVars (β mv.getDecl).type)
let tried_rfl := β noMV.mapM fun g => g.applyConst ``rfl <|> return [g]
let assignable := β yesMV.mapM fun g => do
let tgt := β instantiateMVars (β g.getDecl).type
match tgt.eq? with
| some (_, lhs, rhs) =>
if (isMVar rhs && (! hasExprMVar lhs)) ||
(isMVar lhs && (! hasExprMVar rhs)) then
g.applyConst ``rfl
else pure [g]
| none =>
return [g]
return (assignable.join ++ tried_rfl.join)
/--
`splitApply mvs static` takes two lists of `MVarId`s. The first list, `mvs`,
corresponds to goals that are potentially within the scope of `compute_degree`:
namely, goals of the form
`natDegree f β€ d`, `degree f β€ d`, `natDegree f = d`, `degree f = d`, `coeff f d = r`.
`splitApply` determines which of these goals are actually within the scope, it applies the relevant
lemma and returns two lists: the left-over goals of all the applications, followed by the
concatenation of the previous `static` list, followed by the newly discovered goals outside of the
scope of `compute_degree`. -/
def splitApply (mvs static : List MVarId) : MetaM ((List MVarId) Γ (List MVarId)) := do
let (can_progress, curr_static) := β mvs.partitionM fun mv => do
return dispatchLemma (twoHeadsArgs (β mv.getType'')) != ``id
let progress := β can_progress.mapM fun mv => do
let lem := dispatchLemma <| twoHeadsArgs (β mv.getType'')
mv.applyConst <| lem
return (progress.join, static ++ curr_static)
/-- `miscomputedDegree? deg false_goals` takes as input
* an `Expr`ession `deg`, representing the degree of a polynomial
(i.e. an `Expr`ession of inferred type either `β` or `WithBot β`);
* a list of `MVarId`s `false_goals`.
Although inconsequential for this function, the list of goals `false_goals` reduces to `False`
if `norm_num`med.
`miscomputedDegree?` extracts error information from goals of the form
* `a β b`, assuming it comes from `β’ coeff_of_given_degree β 0`
-- reducing to `False` means that the coefficient that was supposed to vanish, does not;
* `a β€ b`, assuming it comes from `β’ degree_of_subterm β€ degree_of_polynomial`
-- reducing to `False` means that there is a term of degree that is apparently too large;
* `a = b`, assuming it comes from `β’ computed_degree β€ given_degree`
-- reducing to `False` means that there is a term of degree that is apparently too large.
The cases `a β b` and `a = b` are not a perfect match with the top coefficient:
reducing to `False` is not exactly correlated with a coefficient being non-zero.
It does mean that `compute_degree` reduced the initial goal to an unprovable state
(unless there was already a contradiction in the initial hypotheses!), but it is indicative that
there may be some problem.
-/
def miscomputedDegree? (deg : Expr) : List Expr β List MessageData
| tgt::tgts =>
let rest := miscomputedDegree? deg tgts
if tgt.ne?.isSome then
m!"* the coefficient of degree {deg} may be zero" :: rest
else if let some ((Expr.const ``Nat []), lhs, _) := tgt.le? then
m!"* there is at least one term of naΓ―ve degree {lhs}" :: rest
else if let some (_, lhs, _) := tgt.eq? then
m!"* there may be a term of naΓ―ve degree {lhs}" :: rest
else rest
| [] => []
/--
`compute_degree` is a tactic to solve goals of the form
* `natDegree f = d`,
* `degree f = d`,
* `natDegree f β€ d`,
* `degree f β€ d`,
* `coeff f d = r`, if `d` is the degree of `f`.
The tactic may leave goals of the form `d' = d` `d' β€ d`, or `r β 0`, where `d'` in `β` or
`WithBot β` is the tactic's guess of the degree, and `r` is the coefficient's guess of the
leading coefficient of `f`.
`compute_degree` applies `norm_num` to the left-hand side of all side goals, trying to clos them.
The variant `compute_degree!` first applies `compute_degree`.
Then it uses `norm_num` on all the whole remaining goals and tries `assumption`.
-/
syntax (name := computeDegree) "compute_degree" "!"? : tactic
initialize registerTraceClass `Tactic.compute_degree
@[inherit_doc computeDegree]
macro "compute_degree!" : tactic => `(tactic| compute_degree !)
elab_rules : tactic | `(tactic| compute_degree $[!%$bang]?) => focus <| withMainContext do
let goal β getMainGoal
let gt β goal.getType''
let deg? := match gt.eq? with
| some (_, _, rhs) => some rhs
| _ => none
let twoH := twoHeadsArgs gt
match twoH with
| (_, .anonymous, _) => throwError m!"'compute_degree' inapplicable. \
The goal{indentD gt}\nis expected to be 'β€' or '='."
| (.anonymous, _, _) => throwError m!"'compute_degree' inapplicable. \
The LHS must be an application of 'natDegree', 'degree', or 'coeff'."
| _ =>
let lem := dispatchLemma twoH
trace[Tactic.compute_degree]
f!"'compute_degree' first applies lemma '{lem.lastComponentAsString}'"
let mut (gls, static) := (β goal.applyConst lem, [])
while gls != [] do (gls, static) β splitApply gls static
let rfled β try_rfl static
setGoals rfled
-- simplify the left-hand sides, since this is where the degree computations leave
-- expressions such as `max (0 * 1) (max (1 + 0 + 3 * 4) (7 * 0))`
evalTactic
(β `(tactic| try any_goals conv_lhs =>
(simp (config := {decide := true}) only [Nat.cast_withBot]; norm_num)))
if bang.isSome then
let mut false_goals : Array MVarId := #[]
let mut new_goals : Array MVarId := #[]
for g in β getGoals do
let gs' β run g do evalTactic (β
`(tactic| try (any_goals norm_num <;> norm_cast <;> try assumption)))
new_goals := new_goals ++ gs'.toArray
if β gs'.anyM fun g' => g'.withContext do return (β g'.getType'').isConstOf ``False then
false_goals := false_goals.push g
setGoals new_goals.toList
if let some deg := deg? then
let errors := miscomputedDegree? deg (β false_goals.mapM (MVarId.getType'' Β·)).toList
unless errors.isEmpty do
throwError Lean.MessageData.joinSep
(m!"The given degree is '{deg}'. However,\n" :: errors) "\n"
/-- `monicity` tries to solve a goal of the form `Monic f`.
It converts the goal into a goal of the form `natDegree f β€ n` and one of the form `f.coeff n = 1`
and calls `compute_degree` on those two goals.
The variant `monicity!` starts like `monicity`, but calls `compute_degree!` on the two side-goals.
-/
macro (name := monicityMacro) "monicity" : tactic =>
`(tactic| (apply monic_of_natDegree_le_of_coeff_eq_one <;> compute_degree))
@[inherit_doc monicityMacro]
macro "monicity!" : tactic =>
`(tactic| (apply monic_of_natDegree_le_of_coeff_eq_one <;> compute_degree!))
end Tactic
end Mathlib.Tactic.ComputeDegree
|
Tactic\CongrExclamation.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Lean.Elab.Tactic.Config
import Lean.Elab.Tactic.RCases
import Lean.Meta.Tactic.Assumption
import Lean.Meta.Tactic.Rfl
import Mathlib.Lean.Meta.CongrTheorems
import Mathlib.Logic.Basic
/-!
# The `congr!` tactic
This is a more powerful version of the `congr` tactic that knows about more congruence lemmas and
can apply to more situations. It is similar to the `congr'` tactic from Mathlib 3.
The `congr!` tactic is used by the `convert` and `convert_to` tactics.
See the syntax docstring for more details.
-/
universe u v
open Lean Meta Elab Tactic
initialize registerTraceClass `congr!
initialize registerTraceClass `congr!.synthesize
/-- The configuration for the `congr!` tactic. -/
structure Congr!.Config where
/-- If `closePre := true`, then try to close goals before applying congruence lemmas
using tactics such as `rfl` and `assumption. These tactics are applied with the
transparency level specified by `preTransparency`, which is `.reducible` by default. -/
closePre : Bool := true
/-- If `closePost := true`, then try to close goals that remain after no more congruence
lemmas can be applied, using the same tactics as `closePre`. These tactics are applied
with current tactic transparency level. -/
closePost : Bool := true
/-- The transparency level to use when applying a congruence theorem.
By default this is `.reducible`, which prevents unfolding of most definitions. -/
transparency : TransparencyMode := TransparencyMode.reducible
/-- The transparency level to use when trying to close goals before applying congruence lemmas.
This includes trying to prove the goal by `rfl` and using the `assumption` tactic.
By default this is `.reducible`, which prevents unfolding of most definitions. -/
preTransparency : TransparencyMode := TransparencyMode.reducible
/-- For passes that synthesize a congruence lemma using one side of the equality,
we run the pass both for the left-hand side and the right-hand side. If `preferLHS` is `true`
then we start with the left-hand side.
This can be used to control which side's definitions are expanded when applying the
congruence lemma (if `preferLHS = true` then the RHS can be expanded). -/
preferLHS : Bool := true
/-- Allow both sides to be partial applications.
When false, given an equality `f a b = g x y z` this means we never consider
proving `f a = g x y`.
In this case, we might still consider `f = g x` if a pass generates a congruence lemma using the
left-hand side. Use `sameFun := true` to ensure both sides are applications
of the same function (making it be similar to the `congr` tactic). -/
partialApp : Bool := true
/-- Whether to require that both sides of an equality be applications of defeq functions.
That is, if true, `f a = g x` is only considered if `f` and `g` are defeq (making it be similar
to the `congr` tactic). -/
sameFun : Bool := false
/-- The maximum number of arguments to consider when doing congruence of function applications.
For example, with `f a b c = g w x y z`, setting `maxArgs := some 2` means it will only consider
either `f a b = g w x y` and `c = z` or `f a = g w x`, `b = y`, and `c = z`. Setting
`maxArgs := none` (the default) means no limit.
When the functions are dependent, `maxArgs` can prevent congruence from working at all.
In `Fintype.card Ξ± = Fintype.card Ξ²`, one needs to have `maxArgs` at `2` or higher since
there is a `Fintype` instance argument that depends on the first.
When there aren't such dependency issues, setting `maxArgs := some 1` causes `congr!` to
do congruence on a single argument at a time. This can be used in conjunction with the
iteration limit to control exactly how many arguments are to be processed by congruence. -/
maxArgs : Option Nat := none
/-- For type arguments that are implicit or have forward dependencies, whether or not `congr!`
should generate equalities even if the types do not look plausibly equal.
We have a heuristic in the main congruence generator that types
`Ξ±` and `Ξ²` are *plausibly equal* according to the following algorithm:
- If the types are both propositions, they are plausibly equal (`Iff`s are plausible).
- If the types are from different universes, they are not plausibly equal.
- Suppose in whnf we have `Ξ± = f aβ ... aβ` and `Ξ² = g bβ ... bβ`. If `f` is not definitionally
equal to `g` or `m β n`, then `Ξ±` and `Ξ²` are not plausibly equal.
- If there is some `i` such that `aα΅’` and `bα΅’` are not plausibly equal, then `Ξ±` and `Ξ²` are
not plausibly equal.
- Otherwise, `Ξ±` and `Ξ²` are plausibly equal.
The purpose of this is to prevent considering equalities like `β = β€` while allowing equalities
such as `Fin n = Fin m` or `Subtype p = Subtype q` (so long as these are subtypes of the
same type).
The way this is implemented is that when the congruence generator is comparing arguments when
looking at an equality of function applications, it marks a function parameter as "fixed" if the
provided arguments are types that are not plausibly equal. The effect of this is that congruence
succeeds only if those arguments are defeq at `transparency` transparency. -/
typeEqs : Bool := false
/-- As a last pass, perform eta expansion of both sides of an equality. For example,
this transforms a bare `HAdd.hAdd` into `fun x y => x + y`. -/
etaExpand : Bool := false
/-- Whether to use the congruence generator that is used by `simp` and `congr`. This generator
is more strict, and it does not respect all configuration settings. It does respect
`preferLHS`, `partialApp` and `maxArgs` and transparency settings. It acts as if `sameFun := true`
and it ignores `typeEqs`. -/
useCongrSimp : Bool := false
/-- Whether to use a special congruence lemma for `BEq` instances.
This synthesizes `LawfulBEq` instances to discharge equalities of `BEq` instances. -/
beqEq : Bool := true
/-- A configuration option that makes `congr!` do the sorts of aggressive unfoldings that `congr`
does while also similarly preventing `congr!` from considering partial applications or congruences
between different functions being applied. -/
def Congr!.Config.unfoldSameFun : Congr!.Config where
partialApp := false
sameFun := true
transparency := .default
preTransparency := .default
/-- Whether the given number of arguments is allowed to be considered. -/
def Congr!.Config.numArgsOk (config : Config) (numArgs : Nat) : Bool :=
numArgs β€ config.maxArgs.getD numArgs
/-- According to the configuration, how many of the arguments in `numArgs` should be considered. -/
def Congr!.Config.maxArgsFor (config : Config) (numArgs : Nat) : Nat :=
min numArgs (config.maxArgs.getD numArgs)
/--
Asserts the given congruence theorem as fresh hypothesis, and then applies it.
Return the `fvarId` for the new hypothesis and the new subgoals.
We apply it with transparency settings specified by `Congr!.Config.transparency`.
-/
private def applyCongrThm?
(config : Congr!.Config) (mvarId : MVarId) (congrThmType congrThmProof : Expr) :
MetaM (List MVarId) := do
trace[congr!] "trying to apply congr lemma {congrThmType}"
try
let mvarId β mvarId.assert (β mkFreshUserName `h_congr_thm) congrThmType congrThmProof
let (fvarId, mvarId) β mvarId.intro1P
let mvarIds β withTransparency config.transparency <|
mvarId.apply (mkFVar fvarId) { synthAssignedInstances := false }
mvarIds.mapM fun mvarId => mvarId.tryClear fvarId
catch e =>
withTraceNode `congr! (fun _ => pure m!"failed to apply congr lemma") do
trace[congr!] "{e.toMessageData}"
throw e
/-- Returns whether or not it's reasonable to consider an equality between types `ty1` and `ty2`.
The heuristic is the following:
- If `ty1` and `ty2` are in `Prop`, then yes.
- If in whnf both `ty1` and `ty2` have the same head and if (recursively) it's reasonable to
consider an equality between corresponding type arguments, then yes.
- Otherwise, no.
This helps keep congr from going too far and generating hypotheses like `β = β€`.
To keep things from going out of control, there is a `maxDepth`. Additionally, if we do the check
with `maxDepth = 0` then the heuristic answers "no". -/
def Congr!.plausiblyEqualTypes (ty1 ty2 : Expr) (maxDepth : Nat := 5) : MetaM Bool :=
match maxDepth with
| 0 => return false
| maxDepth + 1 => do
-- Props are plausibly equal
if (β isProp ty1) && (β isProp ty2) then
return true
-- Types from different type universes are not plausibly equal.
-- This is redundant, but it saves carrying out the remaining checks.
unless β withNewMCtxDepth <| isDefEq (β inferType ty1) (β inferType ty2) do
return false
-- Now put the types into whnf, check they have the same head, and then recurse on arguments
let ty1 β whnfD ty1
let ty2 β whnfD ty2
unless β withNewMCtxDepth <| isDefEq ty1.getAppFn ty2.getAppFn do
return false
for arg1 in ty1.getAppArgs, arg2 in ty2.getAppArgs do
if (β isType arg1) && (β isType arg2) then
unless β plausiblyEqualTypes arg1 arg2 maxDepth do
return false
return true
/--
This is like `Lean.MVarId.hcongr?` but (1) looks at both sides when generating the congruence lemma
and (2) inserts additional hypotheses from equalities from previous arguments.
It uses `Lean.Meta.mkRichHCongr` to generate the congruence lemmas.
If the goal is an `Eq`, it uses `eq_of_heq` first.
As a backup strategy, it uses the LHS/RHS method like in `Lean.MVarId.congrSimp?`
(where `Congr!.Config.preferLHS` determines which side to try first). This uses a particular side
of the target, generates the congruence lemma, then tries applying it. This can make progress
with higher transparency settings. To help the unifier, in this mode it assumes both sides have the
exact same function.
-/
partial
def Lean.MVarId.smartHCongr? (config : Congr!.Config) (mvarId : MVarId) :
MetaM (Option (List MVarId)) :=
mvarId.withContext do
mvarId.checkNotAssigned `congr!
commitWhenSome? do
let mvarId β mvarId.eqOfHEq
let some (_, lhs, _, rhs) := (β withReducible mvarId.getType').heq? | return none
if let some mvars β loop mvarId 0 lhs rhs [] [] then
return mvars
-- The "correct" behavior failed. However, it's often useful
-- to apply congruence lemmas while unfolding definitions, which is what the
-- basic `congr` tactic does due to limitations in how congruence lemmas are generated.
-- We simulate this behavior here by generating congruence lemmas for the LHS and RHS and
-- then applying them.
trace[congr!] "Default smartHCongr? failed, trying LHS/RHS method"
let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)
if let some mvars β forSide mvarId fst then
return mvars
else if let some mvars β forSide mvarId snd then
return mvars
else
return none
where
loop (mvarId : MVarId) (numArgs : Nat) (lhs rhs : Expr) (lhsArgs rhsArgs : List Expr) :
MetaM (Option (List MVarId)) :=
match lhs.cleanupAnnotations, rhs.cleanupAnnotations with
| .app f a, .app f' b => do
if not (config.numArgsOk (numArgs + 1)) then
return none
let lhsArgs' := a :: lhsArgs
let rhsArgs' := b :: rhsArgs
-- We try to generate a theorem for the maximal number of arguments
if let some mvars β loop mvarId (numArgs + 1) f f' lhsArgs' rhsArgs' then
return mvars
-- That failing, we now try for the present number of arguments.
if not config.partialApp && f.isApp && f'.isApp then
-- It's a partial application on both sides though.
return none
-- The congruence generator only handles the case where both functions have
-- definitionally equal types.
unless β withNewMCtxDepth <| isDefEq (β inferType f) (β inferType f') do
return none
let funDefEq β withReducible <| withNewMCtxDepth <| isDefEq f f'
if config.sameFun && not funDefEq then
return none
let info β getFunInfoNArgs f (numArgs + 1)
let mut fixed : Array Bool := #[]
for larg in lhsArgs', rarg in rhsArgs', pinfo in info.paramInfo do
if !config.typeEqs && (!pinfo.isExplicit || pinfo.hasFwdDeps) then
-- When `typeEqs = false` then for non-explicit arguments or
-- arguments with forward dependencies, we want type arguments
-- to be plausibly equal.
if β isType larg then
-- ^ since `f` and `f'` have defeq types, this implies `isType rarg`.
unless β Congr!.plausiblyEqualTypes larg rarg do
fixed := fixed.push true
continue
fixed := fixed.push (β withReducible <| withNewMCtxDepth <| isDefEq larg rarg)
let cthm β mkRichHCongr (forceHEq := true) (β inferType f) info
(fixedFun := funDefEq) (fixedParams := fixed)
-- Now see if the congruence theorem actually applies in this situation by applying it!
let (congrThm', congrProof') :=
if funDefEq then
(cthm.type.bindingBody!.instantiate1 f, cthm.proof.beta #[f])
else
(cthm.type.bindingBody!.bindingBody!.instantiateRev #[f, f'],
cthm.proof.beta #[f, f'])
observing? <| applyCongrThm? config mvarId congrThm' congrProof'
| _, _ => return none
forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) := do
let side := side.cleanupAnnotations
if not side.isApp then return none
let numArgs := config.maxArgsFor side.getAppNumArgs
if not config.partialApp && numArgs < side.getAppNumArgs then
return none
let mut f := side
for _ in [:numArgs] do
f := f.appFn!'
let info β getFunInfoNArgs f numArgs
let mut fixed : Array Bool := #[]
if !config.typeEqs then
-- We need some strategy for fixed parameters to keep `forSide` from applying
-- in cases where `Congr!.possiblyEqualTypes` suggested not to in the previous pass.
for pinfo in info.paramInfo, arg in side.getAppArgs do
if pinfo.isProp || !(β isType arg) then
fixed := fixed.push false
else if pinfo.isExplicit && !pinfo.hasFwdDeps then
-- It's fine generating equalities for explicit type arguments without forward
-- dependencies. Only allowing these is a little strict, because an argument
-- might be something like `Fin n`. We might consider being able to generate
-- congruence lemmas that only allow equalities where they can plausibly go,
-- but that would take looking at a whole application tree.
fixed := fixed.push false
else
fixed := fixed.push true
let cthm β mkRichHCongr (forceHEq := true) (β inferType f) info
(fixedFun := true) (fixedParams := fixed)
let congrThm' := cthm.type.bindingBody!.instantiate1 f
let congrProof' := cthm.proof.beta #[f]
observing? <| applyCongrThm? config mvarId congrThm' congrProof'
/--
Like `Lean.MVarId.congr?` but instead of using only the congruence lemma associated to the LHS,
it tries the RHS too, in the order specified by `config.preferLHS`.
It uses `Lean.Meta.mkCongrSimp?` to generate a congruence lemma, like in the `congr` tactic.
Applies the congruence generated congruence lemmas according to `config`.
-/
def Lean.MVarId.congrSimp? (config : Congr!.Config) (mvarId : MVarId) :
MetaM (Option (List MVarId)) :=
mvarId.withContext do
mvarId.checkNotAssigned `congrSimp?
let some (_, lhs, rhs) := (β withReducible mvarId.getType').eq? | return none
let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)
if let some mvars β forSide mvarId fst then
return mvars
else if let some mvars β forSide mvarId snd then
return mvars
else
return none
where
forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) :=
commitWhenSome? do
let side := side.cleanupAnnotations
if not side.isApp then return none
let numArgs := config.maxArgsFor side.getAppNumArgs
if not config.partialApp && numArgs < side.getAppNumArgs then
return none
let mut f := side
for _ in [:numArgs] do
f := f.appFn!'
let some congrThm β mkCongrSimpNArgs f numArgs
| return none
observing? <| applyCongrThm? config mvarId congrThm.type congrThm.proof
/-- Like `mkCongrSimp?` but takes in a specific arity. -/
mkCongrSimpNArgs (f : Expr) (nArgs : Nat) : MetaM (Option CongrTheorem) := do
let f := (β Lean.instantiateMVars f).cleanupAnnotations
let info β getFunInfoNArgs f nArgs
mkCongrSimpCore? f info
(β getCongrSimpKinds f info) (subsingletonInstImplicitRhs := false)
/--
Try applying user-provided congruence lemmas. If any are applicable,
returns a list of new goals.
Tries a congruence lemma associated to the LHS and then, if that failed, the RHS.
-/
def Lean.MVarId.userCongr? (config : Congr!.Config) (mvarId : MVarId) :
MetaM (Option (List MVarId)) :=
mvarId.withContext do
mvarId.checkNotAssigned `userCongr?
let some (lhs, rhs) := (β withReducible mvarId.getType').eqOrIff? | return none
let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)
if let some mvars β forSide fst then
return mvars
else if let some mvars β forSide snd then
return mvars
else
return none
where
forSide (side : Expr) : MetaM (Option (List MVarId)) := do
let side := side.cleanupAnnotations
if not side.isApp then return none
let some name := side.getAppFn.constName? | return none
let congrTheorems := (β getSimpCongrTheorems).get name
-- Note: congruence theorems are provided in decreasing order of priority.
for congrTheorem in congrTheorems do
let res β observing? do
let cinfo β getConstInfo congrTheorem.theoremName
let us β cinfo.levelParams.mapM fun _ => mkFreshLevelMVar
let proof := mkConst congrTheorem.theoremName us
let ptype β instantiateTypeLevelParams cinfo us
applyCongrThm? config mvarId ptype proof
if let some mvars := res then
return mvars
return none
/--
Try to apply `pi_congr`. This is similar to `Lean.MVar.congrImplies?`.
-/
def Lean.MVarId.congrPi? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
observing? do withReducible <| mvarId.apply (β mkConstWithFreshMVarLevels `pi_congr)
/--
Try to apply `funext`, but only if it is an equality of two functions where at least one is
a lambda expression.
One thing this check prevents is accidentally applying `funext` to a set equality, but also when
doing congruence we don't want to apply `funext` unnecessarily.
-/
def Lean.MVarId.obviousFunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
mvarId.withContext <| observing? do
let some (_, lhs, rhs) := (β withReducible mvarId.getType').eq? | failure
if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure
mvarId.apply (β mkConstWithFreshMVarLevels ``funext)
/--
Try to apply `Function.hfunext`, returning the new goals if it succeeds.
Like `Lean.MVarId.obviousFunext?`, we only do so if at least one side of the `HEq` is a lambda.
This prevents unfolding of things like `Set`.
Need to have `Mathlib.Logic.Function.Basic` imported for this to succeed.
-/
def Lean.MVarId.obviousHfunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
mvarId.withContext <| observing? do
let some (_, lhs, _, rhs) := (β withReducible mvarId.getType').heq? | failure
if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure
mvarId.apply (β mkConstWithFreshMVarLevels `Function.hfunext)
/-- Like `implies_congr` but provides an additional assumption to the second hypothesis.
This is a non-dependent version of `pi_congr` that allows the domains to be different. -/
private theorem implies_congr' {Ξ± Ξ±' : Sort u} {Ξ² Ξ²' : Sort v} (h : Ξ± = Ξ±') (h' : Ξ±' β Ξ² = Ξ²') :
(Ξ± β Ξ²) = (Ξ±' β Ξ²') := by
cases h
show (β (x : Ξ±), (fun _ => Ξ²) x) = _
rw [funext h']
/-- A version of `Lean.MVarId.congrImplies?` that uses `implies_congr'`
instead of `implies_congr`. -/
def Lean.MVarId.congrImplies?' (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
observing? do
let [mvarIdβ, mvarIdβ] β mvarId.apply (β mkConstWithFreshMVarLevels ``implies_congr')
| throwError "unexpected number of goals"
return [mvarIdβ, mvarIdβ]
protected theorem FastSubsingleton.helim {Ξ± Ξ² : Sort u} [FastSubsingleton Ξ±]
(hβ : Ξ± = Ξ²) (a : Ξ±) (b : Ξ²) : HEq a b := by
have : Subsingleton Ξ± := FastSubsingleton.inst
exact Subsingleton.helim hβ a b
/--
Try to apply `Subsingleton.helim` if the goal is a `HEq`. Tries synthesizing a `Subsingleton`
instance for both the LHS and the RHS.
If successful, this reduces proving `@HEq Ξ± x Ξ² y` to proving `Ξ± = Ξ²`.
-/
def Lean.MVarId.subsingletonHelim? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
mvarId.withContext <| observing? do
mvarId.checkNotAssigned `subsingletonHelim
let some (Ξ±, lhs, Ξ², rhs) := (β withReducible mvarId.getType').heq? | failure
withSubsingletonAsFast fun elim => do
let eqmvar β mkFreshExprSyntheticOpaqueMVar (β mkEq Ξ± Ξ²) (β mvarId.getTag)
-- First try synthesizing using the left-hand side for the Subsingleton instance
if let some pf β observing? (mkAppM ``FastSubsingleton.helim #[eqmvar, lhs, rhs]) then
mvarId.assign <| elim pf
return [eqmvar.mvarId!]
let eqsymm β mkAppM ``Eq.symm #[eqmvar]
-- Second try synthesizing using the right-hand side for the Subsingleton instance
if let some pf β observing? (mkAppM ``FastSubsingleton.helim #[eqsymm, rhs, lhs]) then
mvarId.assign <| elim (β mkAppM ``HEq.symm #[pf])
return [eqmvar.mvarId!]
failure
/--
Tries to apply `lawful_beq_subsingleton` to prove that two `BEq` instances are equal
by synthesizing `LawfulBEq` instances for both.
-/
def Lean.MVarId.beqInst? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=
observing? do withReducible <| mvarId.applyConst ``lawful_beq_subsingleton
/--
A list of all the congruence strategies used by `Lean.MVarId.congrCore!`.
-/
def Lean.MVarId.congrPasses! :
List (String Γ (Congr!.Config β MVarId β MetaM (Option (List MVarId)))) :=
[("user congr", userCongr?),
("hcongr lemma", smartHCongr?),
("congr simp lemma", when (Β·.useCongrSimp) congrSimp?),
("Subsingleton.helim", fun _ => subsingletonHelim?),
("BEq instances", when (Β·.beqEq) fun _ => beqInst?),
("obvious funext", fun _ => obviousFunext?),
("obvious hfunext", fun _ => obviousHfunext?),
("congr_implies", fun _ => congrImplies?'),
("congr_pi", fun _ => congrPi?)]
where
/--
Conditionally runs a congruence strategy depending on the predicate `b` applied to the config.
-/
when (b : Congr!.Config β Bool) (f : Congr!.Config β MVarId β MetaM (Option (List MVarId)))
(config : Congr!.Config) (mvar : MVarId) : MetaM (Option (List MVarId)) := do
unless b config do return none
f config mvar
structure CongrState where
/-- Accumulated goals that `congr!` could not handle. -/
goals : Array MVarId
/-- Patterns to use when doing intro. -/
patterns : List (TSyntax `rcasesPat)
abbrev CongrMetaM := StateRefT CongrState MetaM
/-- Pop the next pattern from the current state. -/
def CongrMetaM.nextPattern : CongrMetaM (Option (TSyntax `rcasesPat)) := do
modifyGet fun s =>
if let p :: ps := s.patterns then
(p, {s with patterns := ps})
else
(none, s)
private theorem heq_imp_of_eq_imp {Ξ± : Sort*} {x y : Ξ±} {p : HEq x y β Prop}
(h : (he : x = y) β p (heq_of_eq he)) (he : HEq x y) : p he := by
cases he
exact h rfl
private theorem eq_imp_of_iff_imp {x y : Prop} {p : x = y β Prop}
(h : (he : x β y) β p (propext he)) (he : x = y) : p he := by
cases he
exact h Iff.rfl
/--
Does `Lean.MVarId.intros` but then cleans up the introduced hypotheses, removing anything
that is trivial. If there are any patterns in the current `CongrMetaM` state then instead
of `Lean.MVarId.intros` it does `Lean.Elab..Tactic.RCases.rintro`.
Cleaning up includes:
- deleting hypotheses of the form `HEq x x`, `x = x`, and `x β x`.
- deleting Prop hypotheses that are already in the local context.
- converting `HEq x y` to `x = y` if possible.
- converting `x = y` to `x β y` if possible.
-/
partial
def Lean.MVarId.introsClean (mvarId : MVarId) : CongrMetaM (List MVarId) :=
loop mvarId
where
heqImpOfEqImp (mvarId : MVarId) : MetaM (Option MVarId) :=
observing? <| withReducible do
let [mvarId] β mvarId.apply (β mkConstWithFreshMVarLevels ``heq_imp_of_eq_imp) | failure
return mvarId
eqImpOfIffImp (mvarId : MVarId) : MetaM (Option MVarId) :=
observing? <| withReducible do
let [mvarId] β mvarId.apply (β mkConstWithFreshMVarLevels ``eq_imp_of_iff_imp) | failure
return mvarId
loop (mvarId : MVarId) : CongrMetaM (List MVarId) :=
mvarId.withContext do
let ty β withReducible <| mvarId.getType'
if ty.isForall then
let mvarId := (β heqImpOfEqImp mvarId).getD mvarId
let mvarId := (β eqImpOfIffImp mvarId).getD mvarId
let ty β withReducible <| mvarId.getType'
if ty.isArrow then
if β (isTrivialType ty.bindingDomain!
<||> (β getLCtx).anyM (fun decl => do
return (β Lean.instantiateMVars decl.type) == ty.bindingDomain!)) then
-- Don't intro, clear it
let mvar β mkFreshExprSyntheticOpaqueMVar ty.bindingBody! (β mvarId.getTag)
mvarId.assign <| .lam .anonymous ty.bindingDomain! mvar .default
return β loop mvar.mvarId!
if let some patt β CongrMetaM.nextPattern then
let gs β Term.TermElabM.run' <| Lean.Elab.Tactic.RCases.rintro #[patt] none mvarId
List.join <$> gs.mapM loop
else
let (_, mvarId) β mvarId.intro1
loop mvarId
else
return [mvarId]
isTrivialType (ty : Expr) : MetaM Bool := do
unless β Meta.isProp ty do
return false
let ty β Lean.instantiateMVars ty
if let some (lhs, rhs) := ty.eqOrIff? then
if lhs.cleanupAnnotations == rhs.cleanupAnnotations then
return true
if let some (Ξ±, lhs, Ξ², rhs) := ty.heq? then
if Ξ±.cleanupAnnotations == Ξ².cleanupAnnotations
&& lhs.cleanupAnnotations == rhs.cleanupAnnotations then
return true
return false
/-- Convert a goal into an `Eq` goal if possible (since we have a better shot at those).
Also, if `tryClose := true`, then try to close the goal using an assumption, `Subsingleton.Elim`,
or definitional equality. -/
def Lean.MVarId.preCongr! (mvarId : MVarId) (tryClose : Bool) : MetaM (Option MVarId) := do
-- Next, turn `HEq` and `Iff` into `Eq`
let mvarId β mvarId.heqOfEq
if tryClose then
-- This is a good time to check whether we have a relevant hypothesis.
if β mvarId.assumptionCore then return none
let mvarId β mvarId.iffOfEq
if tryClose then
-- Now try definitional equality. No need to try `mvarId.hrefl` since we already did `heqOfEq`.
-- We allow synthetic opaque metavariables to be assigned to fill in `x = _` goals that might
-- appear (for example, due to using `convert` with placeholders).
try withAssignableSyntheticOpaque mvarId.refl; return none catch _ => pure ()
-- Now we go for (heterogenous) equality via subsingleton considerations
if β Lean.Meta.fastSubsingletonElim mvarId then return none
if β mvarId.proofIrrelHeq then return none
return some mvarId
def Lean.MVarId.congrCore! (config : Congr!.Config) (mvarId : MVarId) :
MetaM (Option (List MVarId)) := do
mvarId.checkNotAssigned `congr!
let s β saveState
/- We do `liftReflToEq` here rather than in `preCongr!` since we don't want to commit to it
if there are no relevant congr lemmas. -/
let mvarId β mvarId.liftReflToEq
for (passName, pass) in congrPasses! do
try
if let some mvarIds β pass config mvarId then
trace[congr!] "pass succeeded: {passName}"
return mvarIds
catch e =>
throwTacticEx `congr! mvarId
m!"internal error in congruence pass {passName}, {e.toMessageData}"
if β mvarId.isAssigned then
throwTacticEx `congr! mvarId
s!"congruence pass {passName} assigned metavariable but failed"
restoreState s
trace[congr!] "no passes succeeded"
return none
/-- A pass to clean up after `Lean.MVarId.preCongr!` and `Lean.MVarId.congrCore!`. -/
def Lean.MVarId.postCongr! (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option MVarId) := do
let some mvarId β mvarId.preCongr! config.closePost | return none
-- Convert `p = q` to `p β q`, which is likely the more useful form:
let mvarId β mvarId.propext
if config.closePost then
-- `preCongr` sees `p = q`, but now we've put it back into `p β q` form.
if β mvarId.assumptionCore then return none
if config.etaExpand then
if let some (_, lhs, rhs) := (β withReducible mvarId.getType').eq? then
let lhs' β Meta.etaExpand lhs
let rhs' β Meta.etaExpand rhs
return β mvarId.change (β mkEq lhs' rhs')
return mvarId
/-- A more insistent version of `Lean.MVarId.congrN`.
See the documentation on the `congr!` syntax.
The `depth?` argument controls the depth of the recursion. If `none`, then it uses a reasonably
large bound that is linear in the expression depth. -/
def Lean.MVarId.congrN! (mvarId : MVarId)
(depth? : Option Nat := none) (config : Congr!.Config := {})
(patterns : List (TSyntax `rcasesPat) := []) :
MetaM (List MVarId) := do
let ty β withReducible <| mvarId.getType'
-- A reasonably large yet practically bounded default recursion depth.
let defaultDepth := min 1000000 (8 * (1 + ty.approxDepth.toNat))
let depth := depth?.getD defaultDepth
let (_, s) β go depth depth mvarId |>.run {goals := #[], patterns := patterns}
return s.goals.toList
where
post (mvarId : MVarId) : CongrMetaM Unit := do
for mvarId in β mvarId.introsClean do
if let some mvarId β mvarId.postCongr! config then
modify (fun s => {s with goals := s.goals.push mvarId})
else
trace[congr!] "Dispatched goal by post-processing step."
go (depth : Nat) (n : Nat) (mvarId : MVarId) : CongrMetaM Unit := do
for mvarId in β mvarId.introsClean do
if let some mvarId β withTransparency config.preTransparency <|
mvarId.preCongr! config.closePre then
match n with
| 0 =>
trace[congr!] "At level {depth - n}, doing post-processing. {mvarId}"
post mvarId
| n + 1 =>
trace[congr!] "At level {depth - n}, trying congrCore!. {mvarId}"
if let some mvarIds β mvarId.congrCore! config then
mvarIds.forM (go depth n)
else
post mvarId
namespace Congr!
declare_config_elab elabConfig Config
/--
Equates pieces of the left-hand side of a goal to corresponding pieces of the right-hand side by
recursively applying congruence lemmas. For example, with `β’ f as = g bs` we could get
two goals `β’ f = g` and `β’ as = bs`.
Syntax:
```
congr!
congr! n
congr! with x y z
congr! n with x y z
```
Here, `n` is a natural number and `x`, `y`, `z` are `rintro` patterns (like `h`, `rfl`, `β¨x, yβ©`,
`_`, `-`, `(h | h)`, etc.).
The `congr!` tactic is similar to `congr` but is more insistent in trying to equate left-hand sides
to right-hand sides of goals. Here is a list of things it can try:
- If `R` in `β’ R x y` is a reflexive relation, it will convert the goal to `β’ x = y` if possible.
The list of reflexive relations is maintained using the `@[refl]` attribute.
As a special case, `β’ p β q` is converted to `β’ p = q` during congruence processing and then
returned to `β’ p β q` form at the end.
- If there is a user congruence lemma associated to the goal (for instance, a `@[congr]`-tagged
lemma applying to `β’ List.map f xs = List.map g ys`), then it will use that.
- It uses a congruence lemma generator at least as capable as the one used by `congr` and `simp`.
If there is a subexpression that can be rewritten by `simp`, then `congr!` should be able
to generate an equality for it.
- It can do congruences of pi types using lemmas like `implies_congr` and `pi_congr`.
- Before applying congruences, it will run the `intros` tactic automatically.
The introduced variables can be given names using a `with` clause.
This helps when congruence lemmas provide additional assumptions in hypotheses.
- When there is an equality between functions, so long as at least one is obviously a lambda, we
apply `funext` or `Function.hfunext`, which allows for congruence of lambda bodies.
- It can try to close goals using a few strategies, including checking
definitional equality, trying to apply `Subsingleton.elim` or `proof_irrel_heq`, and using the
`assumption` tactic.
The optional parameter is the depth of the recursive applications.
This is useful when `congr!` is too aggressive in breaking down the goal.
For example, given `β’ f (g (x + y)) = f (g (y + x))`,
`congr!` produces the goals `β’ x = y` and `β’ y = x`,
while `congr! 2` produces the intended `β’ x + y = y + x`.
The `congr!` tactic also takes a configuration option, for example
```lean
congr! (config := {transparency := .default}) 2
```
This overrides the default, which is to apply congruence lemmas at reducible transparency.
The `congr!` tactic is aggressive with equating two sides of everything. There is a predefined
configuration that uses a different strategy:
Try
```lean
congr! (config := .unfoldSameFun)
```
This only allows congruences between functions applications of definitionally equal functions,
and it applies congruence lemmas at default transparency (rather than just reducible).
This is somewhat like `congr`.
See `Congr!.Config` for all options.
-/
syntax (name := congr!) "congr!" (Parser.Tactic.config)? (ppSpace num)?
(" with" (ppSpace colGt rintroPat)*)? : tactic
elab_rules : tactic
| `(tactic| congr! $[$cfg:config]? $[$n]? $[with $ps?*]?) => do
let config β elabConfig (mkOptionalNode cfg)
let patterns := (Lean.Elab.Tactic.RCases.expandRIntroPats (ps?.getD #[])).toList
liftMetaTactic fun g β¦
let depth := n.map (Β·.getNat)
g.congrN! depth config patterns
end Congr!
|
Tactic\CongrM.lean | /-
Copyright (c) 2023 Moritz Doll, Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll, Gabriel Ebner, Damiano Testa, Kyle Miller
-/
import Mathlib.Tactic.TermCongr
/-!
# The `congrm` tactic
The `congrm` tactic ("`congr` with matching")
is a convenient frontend for `congr(...)` congruence quotations.
Roughly, `congrm e` is `refine congr(e')`, where `e'` is `e` with every `?m` placeholder
replaced by `$(?m)`.
-/
namespace Mathlib.Tactic
open Lean Parser Tactic Elab Tactic Meta
initialize registerTraceClass `Tactic.congrm
/--
`congrm e` is a tactic for proving goals of the form `lhs = rhs`, `lhs β rhs`, `HEq lhs rhs`,
or `R lhs rhs` when `R` is a reflexive relation.
The expression `e` is a pattern containing placeholders `?_`,
and this pattern is matched against `lhs` and `rhs` simultaneously.
These placeholders generate new goals that state that corresponding subexpressions
in `lhs` and `rhs` are equal.
If the placeholders have names, such as `?m`, then the new goals are given tags with those names.
Examples:
```lean
example {a b c d : β} :
Nat.pred a.succ * (d + (c + a.pred)) = Nat.pred b.succ * (b + (c + d.pred)) := by
congrm Nat.pred (Nat.succ ?h1) * (?h2 + ?h3)
/- Goals left:
case h1 β’ a = b
case h2 β’ d = b
case h3 β’ c + a.pred = c + d.pred
-/
sorry
sorry
sorry
example {a b : β} (h : a = b) : (fun y : β => β z, a + a = z) = (fun x => β z, b + a = z) := by
congrm fun x => β w, ?_ + a = w
-- β’ a = b
exact h
```
The `congrm` command is a convenient frontend to `congr(...)` congruence quotations.
If the goal is an equality, `congrm e` is equivalent to `refine congr(e')` where `e'` is
built from `e` by replacing each placeholder `?m` by `$(?m)`.
The pattern `e` is allowed to contain `$(...)` expressions to immediately substitute
equality proofs into the congruence, just like for congruence quotations.
-/
syntax (name := congrM) "congrm " term : tactic
elab_rules : tactic
| `(tactic| congrm $expr:term) => do
-- Wrap all synthetic holes `?m` as `c(?m)` to form `congr(...)` pattern
let pattern β expr.raw.replaceM fun stx =>
if stx.isOfKind ``Parser.Term.syntheticHole then
pure <| stx.mkAntiquotNode `term
else if stx.isAntiquots then
-- Don't look into `$(..)` expressions
pure stx
else
pure none
trace[Tactic.congrm] "pattern: {pattern}"
-- Chain together transformations as needed to convert the goal to an Eq if possible.
liftMetaTactic fun g => do
return [β (β g.iffOfEq).liftReflToEq]
-- Apply `congr(...)`
withMainContext do
let gStx β Term.exprToSyntax (β getMainTarget)
-- Gives the expected type to `refine` as a workaround for its elaboration order.
evalTactic <| β `(tactic| refine (congr($(β¨patternβ©)) : $gStx))
|
Tactic\Constructor.lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Newell Jensen
-/
import Lean.Elab.SyntheticMVars
import Lean.Meta.Tactic.Constructor
/-!
# The `fconstructor` and `econstructor` tactics
The `fconstructor` and `econstructor` tactics are variants of the `constructor` tactic in Lean core,
except that
- `fconstructor` does not reorder goals
- `econstructor` adds only non-dependent premises as new goals.
-/
open Lean Elab Tactic
/--
`fconstructor` is like `constructor`
(it calls `apply` using the first matching constructor of an inductive datatype)
except that it does not reorder goals.
-/
elab "fconstructor" : tactic => withMainContext do
let mvarIds' β (β getMainGoal).constructor {newGoals := .all}
Term.synthesizeSyntheticMVarsNoPostponing
replaceMainGoal mvarIds'
/--
`econstructor` is like `constructor`
(it calls `apply` using the first matching constructor of an inductive datatype)
except only non-dependent premises are added as new goals.
-/
elab "econstructor" : tactic => withMainContext do
let mvarIds' β (β getMainGoal).constructor {newGoals := .nonDependentOnly}
Term.synthesizeSyntheticMVarsNoPostponing
replaceMainGoal mvarIds'
|
Tactic\Continuity.lean | /-
Copyright (c) 2023 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import Mathlib.Tactic.Continuity.Init
/-!
# Continuity
We define the `continuity` tactic using `aesop`. -/
attribute [aesop (rule_sets := [Continuous]) unfold norm] Function.comp
/--
The `continuity` attribute used to tag continuity statements for the `continuity` tactic. -/
macro "continuity" : attr =>
`(attr|aesop safe apply (rule_sets := [$(Lean.mkIdent `Continuous):ident]))
/--
The tactic `continuity` solves goals of the form `Continuous f` by applying lemmas tagged with the
`continuity` user attribute. -/
macro "continuity" : tactic =>
`(tactic| aesop (config := { terminal := true })
(rule_sets := [$(Lean.mkIdent `Continuous):ident]))
/--
The tactic `continuity` solves goals of the form `Continuous f` by applying lemmas tagged with the
`continuity` user attribute. -/
macro "continuity?" : tactic =>
`(tactic| aesop? (config := { terminal := true })
(rule_sets := [$(Lean.mkIdent `Continuous):ident]))
-- Todo: implement `continuity!` and `continuity!?` and add configuration, original
-- syntax was (same for the missing `continuity` variants):
-- syntax (name := continuity) "continuity" (config)? : tactic
|
Tactic\ContinuousFunctionalCalculus.lean | /-
Copyright (c) 2024 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import Mathlib.Tactic.Core
import Mathlib.Tactic.FunProp
import Aesop
/-!
# Tactics for the continuous functional calculus
At the moment, these tactics are just wrappers, but potentially they could be more sophisticated.
-/
/-- A tactic used to automatically discharge goals relating to the continuous functional calculus,
specifically whether the element satisfies the predicate. -/
syntax (name := cfcTac) "cfc_tac" : tactic
macro_rules
| `(tactic| cfc_tac) => `(tactic| (try (first | assumption | infer_instance | aesop)))
-- we may want to try using `fun_prop` directly in the future.
/-- A tactic used to automatically discharge goals relating to the continuous functional calculus,
specifically concerning continuity of the functions involved. -/
syntax (name := cfcContTac) "cfc_cont_tac" : tactic
macro_rules
| `(tactic| cfc_cont_tac) => `(tactic| try (first | fun_prop (disch := aesop) | assumption))
/-- A tactic used to automatically discharge goals relating to the non-unital continuous functional
calculus, specifically concerning whether `f 0 = 0`. -/
syntax (name := cfcZeroTac) "cfc_zero_tac" : tactic
macro_rules
| `(tactic| cfc_zero_tac) => `(tactic| try (first | aesop | assumption))
|
Tactic\Contrapose.lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import Mathlib.Tactic.PushNeg
/-! # Contrapose
The `contrapose` tactic transforms the goal into its contrapositive when that goal is an
implication.
* `contrapose` turns a goal `P β Q` into `Β¬ Q β Β¬ P`
* `contrapose!` turns a goal `P β Q` into `Β¬ Q β Β¬ P` and pushes negations inside `P` and `Q`
using `push_neg`
* `contrapose h` first reverts the local assumption `h`, and then uses `contrapose` and `intro h`
* `contrapose! h` first reverts the local assumption `h`, and then uses `contrapose!` and `intro h`
* `contrapose h with new_h` uses the name `new_h` for the introduced hypothesis
-/
namespace Mathlib.Tactic.Contrapose
lemma mtr {p q : Prop} : (Β¬ q β Β¬ p) β (p β q) := fun h hp β¦ by_contra (fun h' β¦ h h' hp)
/--
Transforms the goal into its contrapositive.
* `contrapose` turns a goal `P β Q` into `Β¬ Q β Β¬ P`
* `contrapose h` first reverts the local assumption `h`, and then uses `contrapose` and `intro h`
* `contrapose h with new_h` uses the name `new_h` for the introduced hypothesis
-/
syntax (name := contrapose) "contrapose" (ppSpace colGt ident (" with " ident)?)? : tactic
macro_rules
| `(tactic| contrapose) => `(tactic| (refine mtr ?_))
| `(tactic| contrapose $e) => `(tactic| (revert $e:ident; contrapose; intro $e:ident))
| `(tactic| contrapose $e with $e') => `(tactic| (revert $e:ident; contrapose; intro $e':ident))
/--
Transforms the goal into its contrapositive and uses pushes negations inside `P` and `Q`.
Usage matches `contrapose`
-/
syntax (name := contrapose!) "contrapose!" (ppSpace colGt ident (" with " ident)?)? : tactic
macro_rules
| `(tactic| contrapose!) => `(tactic| (contrapose; try push_neg))
| `(tactic| contrapose! $e) => `(tactic| (revert $e:ident; contrapose!; intro $e:ident))
| `(tactic| contrapose! $e with $e') => `(tactic| (revert $e:ident; contrapose!; intro $e':ident))
end Mathlib.Tactic.Contrapose
|
Tactic\Conv.lean | /-
Copyright (c) 2021 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Elab.Tactic.Conv.Basic
import Lean.Elab.Command
/-!
Additional `conv` tactics.
-/
namespace Mathlib.Tactic.Conv
open Lean Parser.Tactic Parser.Tactic.Conv Elab.Tactic Meta
syntax (name := convLHS) "conv_lhs" (" at " ident)? (" in " (occs)? term)? " => " convSeq : tactic
macro_rules
| `(tactic| conv_lhs $[at $id]? $[in $[$occs]? $pat]? => $seq) =>
`(tactic| conv $[at $id]? $[in $[$occs]? $pat]? => lhs; ($seq:convSeq))
syntax (name := convRHS) "conv_rhs" (" at " ident)? (" in " (occs)? term)? " => " convSeq : tactic
macro_rules
| `(tactic| conv_rhs $[at $id]? $[in $[$occs]? $pat]? => $seq) =>
`(tactic| conv $[at $id]? $[in $[$occs]? $pat]? => rhs; ($seq:convSeq))
macro "run_conv" e:doSeq : conv => `(conv| tactic' => run_tac $e)
/--
`conv in pat => cs` runs the `conv` tactic sequence `cs`
on the first subexpression matching the pattern `pat` in the target.
The converted expression becomes the new target subgoal, like `conv => cs`.
The arguments `in` are the same as those as the in `pattern`.
In fact, `conv in pat => cs` is a macro for `conv => pattern pat; cs`.
The syntax also supports the `occs` clause. Example:
```lean
conv in (occs := *) x + y => rw [add_comm]
```
-/
macro "conv" " in " occs?:(occs)? p:term " => " code:convSeq : conv =>
`(conv| conv => pattern $[$occs?]? $p; ($code:convSeq))
/--
* `discharge => tac` is a conv tactic which rewrites target `p` to `True` if `tac` is a tactic
which proves the goal `β’ p`.
* `discharge` without argument returns `β’ p` as a subgoal.
-/
syntax (name := dischargeConv) "discharge" (" => " tacticSeq)? : conv
/-- Elaborator for the `discharge` tactic. -/
@[tactic dischargeConv] def elabDischargeConv : Tactic := fun
| `(conv| discharge $[=> $tac]?) => do
let g :: gs β getGoals | throwNoGoalsToBeSolved
let (theLhs, theRhs) β Conv.getLhsRhsCore g
let .true β isProp theLhs | throwError "target is not a proposition"
theRhs.mvarId!.assign (mkConst ``True)
let m β mkFreshExprMVar theLhs
g.assign (β mkEqTrue m)
if let some tac := tac then
setGoals [m.mvarId!]
evalTactic tac; done
setGoals gs
else
setGoals (m.mvarId! :: gs)
| _ => Elab.throwUnsupportedSyntax
/-- Use `refine` in `conv` mode. -/
macro "refine " e:term : conv => `(conv| tactic => refine $e)
open Elab Tactic
/--
The command `#conv tac => e` will run a conv tactic `tac` on `e`, and display the resulting
expression (discarding the proof).
For example, `#conv rw [true_and_iff] => True β§ False` displays `False`.
There are also shorthand commands for several common conv tactics:
* `#whnf e` is short for `#conv whnf => e`
* `#simp e` is short for `#conv simp => e`
* `#norm_num e` is short for `#conv norm_num => e`
* `#push_neg e` is short for `#conv push_neg => e`
-/
elab tk:"#conv " conv:conv " => " e:term : command =>
Command.runTermElabM fun _ β¦ do
let e β Elab.Term.elabTermAndSynthesize e none
let (rhs, g) β Conv.mkConvGoalFor e
_ β Tactic.run g.mvarId! do
evalTactic conv
for mvarId in (β getGoals) do
liftM <| mvarId.refl <|> mvarId.inferInstance <|> pure ()
pruneSolvedGoals
let e' β instantiateMVars rhs
logInfoAt tk e'
@[inherit_doc Parser.Tactic.withReducible]
macro (name := withReducible) tk:"with_reducible " s:convSeq : conv =>
`(conv| tactic' => with_reducible%$tk conv' => $s)
/--
The command `#whnf e` evaluates `e` to Weak Head Normal Form, which means that the "head"
of the expression is reduced to a primitive - a lambda or forall, or an axiom or inductive type.
It is similar to `#reduce e`, but it does not reduce the expression completely,
only until the first constructor is exposed. For example:
```
open Nat List
set_option pp.notation false
#whnf [1, 2, 3].map succ
-- cons (succ 1) (map succ (cons 2 (cons 3 nil)))
#reduce [1, 2, 3].map succ
-- cons 2 (cons 3 (cons 4 nil))
```
The head of this expression is the `List.cons` constructor,
so we can see from this much that the list is not empty,
but the subterms `Nat.succ 1` and `List.map Nat.succ (List.cons 2 (List.cons 3 List.nil))` are
still unevaluated. `#reduce` is equivalent to using `#whnf` on every subexpression.
-/
macro tk:"#whnf " e:term : command => `(command| #conv%$tk whnf => $e)
/--
The command `#whnfR e` evaluates `e` to Weak Head Normal Form with Reducible transparency,
that is, it uses `whnf` but only unfolding reducible definitions.
-/
macro tk:"#whnfR " e:term : command => `(command| #conv%$tk with_reducible whnf => $e)
/--
* `#simp => e` runs `simp` on the expression `e` and displays the resulting expression after
simplification.
* `#simp only [lems] => e` runs `simp only [lems]` on `e`.
* The `=>` is optional, so `#simp e` and `#simp only [lems] e` have the same behavior.
It is mostly useful for disambiguating the expression `e` from the lemmas.
-/
syntax "#simp" (&" only")? (simpArgs)? " =>"? ppSpace term : command
macro_rules
| `(#simp%$tk $[only%$o]? $[[$args,*]]? $[=>]? $e) =>
`(#conv%$tk simp $[only%$o]? $[[$args,*]]? => $e)
|
Tactic\Convert.lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Kyle Miller
-/
import Mathlib.Tactic.CongrExclamation
/-!
# The `convert` tactic.
-/
open Lean Meta Elab Tactic
/--
Close the goal `g` using `Eq.mp v e`,
where `v` is a metavariable asserting that the type of `g` and `e` are equal.
Then call `MVarId.congrN!` (also using local hypotheses and reflexivity) on `v`,
and return the resulting goals.
With `symm = true`, reverses the equality in `v`, and uses `Eq.mpr v e` instead.
With `depth = some n`, calls `MVarId.congrN! n` instead, with `n` as the max recursion depth.
-/
def Lean.MVarId.convert (e : Expr) (symm : Bool)
(depth : Option Nat := none) (config : Congr!.Config := {})
(patterns : List (TSyntax `rcasesPat) := []) (g : MVarId) :
MetaM (List MVarId) := g.withContext do
let src β inferType e
let tgt β g.getType
let v β mkFreshExprMVar (β mkAppM ``Eq (if symm then #[src, tgt] else #[tgt, src]))
g.assign (β mkAppM (if symm then ``Eq.mp else ``Eq.mpr) #[v, e])
let m := v.mvarId!
m.congrN! depth config patterns
/--
Replaces the type of the local declaration `fvarId` with `typeNew`,
using `Lean.MVarId.congrN!` to prove that the old type of `fvarId` is equal to `typeNew`.
Uses `Lean.MVarId.replaceLocalDecl` to replace the type.
Returns the new goal along with the side goals generated by `congrN!`.
With `symm = true`, reverses the equality,
changing the goal to prove `typeNew` is equal to `typeOld`.
With `depth = some n`, calls `MVarId.congrN! n` instead, with `n` as the max recursion depth.
-/
def Lean.MVarId.convertLocalDecl (g : MVarId) (fvarId : FVarId) (typeNew : Expr) (symm : Bool)
(depth : Option Nat := none) (config : Congr!.Config := {})
(patterns : List (TSyntax `rcasesPat) := []) :
MetaM (MVarId Γ List MVarId) := g.withContext do
let typeOld β fvarId.getType
let v β mkFreshExprMVar (β mkAppM ``Eq (if symm then #[typeNew, typeOld] else #[typeOld, typeNew]))
let pf β if symm then mkEqSymm v else pure v
let res β g.replaceLocalDecl fvarId typeNew pf
let gs β v.mvarId!.congrN! depth config patterns
return (res.mvarId, gs)
namespace Mathlib.Tactic
/--
The `exact e` and `refine e` tactics require a term `e` whose type is
definitionally equal to the goal. `convert e` is similar to `refine e`,
but the type of `e` is not required to exactly match the
goal. Instead, new goals are created for differences between the type
of `e` and the goal using the same strategies as the `congr!` tactic.
For example, in the proof state
```lean
n : β,
e : Prime (2 * n + 1)
β’ Prime (n + n + 1)
```
the tactic `convert e using 2` will change the goal to
```lean
β’ n + n = 2 * n
```
In this example, the new goal can be solved using `ring`.
The `using 2` indicates it should iterate the congruence algorithm up to two times,
where `convert e` would use an unrestricted number of iterations and lead to two
impossible goals: `β’ HAdd.hAdd = HMul.hMul` and `β’ n = 2`.
A variant configuration is `convert (config := .unfoldSameFun) e`, which only equates function
applications for the same function (while doing so at the higher `default` transparency).
This gives the same goal of `β’ n + n = 2 * n` without needing `using 2`.
The `convert` tactic applies congruence lemmas eagerly before reducing,
therefore it can fail in cases where `exact` succeeds:
```lean
def p (n : β) := True
example (h : p 0) : p 1 := by exact h -- succeeds
example (h : p 0) : p 1 := by convert h -- fails, with leftover goal `1 = 0`
```
Limiting the depth of recursion can help with this. For example, `convert h using 1` will work
in this case.
The syntax `convert β e` will reverse the direction of the new goals
(producing `β’ 2 * n = n + n` in this example).
Internally, `convert e` works by creating a new goal asserting that
the goal equals the type of `e`, then simplifying it using
`congr!`. The syntax `convert e using n` can be used to control the
depth of matching (like `congr! n`). In the example, `convert e using 1`
would produce a new goal `β’ n + n + 1 = 2 * n + 1`.
Refer to the `congr!` tactic to understand the congruence operations. One of its many
features is that if `x y : t` and an instance `Subsingleton t` is in scope,
then any goals of the form `x = y` are solved automatically.
Like `congr!`, `convert` takes an optional `with` clause of `rintro` patterns,
for example `convert e using n with x y z`.
The `convert` tactic also takes a configuration option, for example
```lean
convert (config := {transparency := .default}) h
```
These are passed to `congr!`. See `Congr!.Config` for options.
-/
syntax (name := convert) "convert" (Parser.Tactic.config)? " β"? ppSpace term (" using " num)?
(" with" (ppSpace colGt rintroPat)*)? : tactic
/--
Elaborates `term` ensuring the expected type, allowing stuck metavariables.
Returns stuck metavariables as additional goals.
-/
def elabTermForConvert (term : Syntax) (expectedType? : Option Expr) :
TacticM (Expr Γ List MVarId) := do
withCollectingNewGoalsFrom (allowNaturalHoles := true) (tagSuffix := `convert) do
-- Allow typeclass inference failures since these will be inferred by unification
-- or else become new goals
withTheReader Term.Context (fun ctx => { ctx with ignoreTCFailures := true }) do
let t β elabTermEnsuringType (mayPostpone := true) term expectedType?
-- Process everything so that tactics get run, but again allow TC failures
Term.synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true)
return t
elab_rules : tactic
| `(tactic| convert $[$cfg:config]? $[β%$sym]? $term $[using $n]? $[with $ps?*]?) =>
withMainContext do
let config β Congr!.elabConfig (mkOptionalNode cfg)
let patterns := (Lean.Elab.Tactic.RCases.expandRIntroPats (ps?.getD #[])).toList
let expectedType β mkFreshExprMVar (mkSort (β getLevel (β getMainTarget)))
let (e, gs) β elabTermForConvert term expectedType
liftMetaTactic fun g β¦
return (β g.convert e sym.isSome (n.map (Β·.getNat)) config patterns) ++ gs
-- FIXME restore when `add_tactic_doc` is ported.
-- add_tactic_doc
-- { name := "convert",
-- category := doc_category.tactic,
-- decl_names := [`tactic.interactive.convert],
-- tags := ["congruence"] }
/--
The `convert_to` tactic is for changing the type of the target or a local hypothesis,
but unlike the `change` tactic it will generate equality proof obligations using `congr!`
to resolve discrepancies.
* `convert_to ty` changes the target to `ty`
* `convert_to ty using n` uses `congr! n` instead of `congr! 1`
* `convert_to ty at h` changes the type of the local hypothesis `h` to `ty`.
Any remaining `congr!` goals come first.
Operating on the target, the tactic `convert_to ty using n`
is the same as `convert (?_ : ty) using n`.
The difference is that `convert_to` takes a type but `convert` takes a proof term.
Except for it also being able to operate on local hypotheses,
the syntax for `convert_to` is the same as for `convert`, and it has variations such as
`convert_to β g` and `convert_to (config := {transparency := .default}) g`.
Note that `convert_to ty at h` may leave a copy of `h` if a later local hypotheses or the target
depends on it, just like in `rw` or `simp`.
-/
syntax (name := convertTo) "convert_to" (Parser.Tactic.config)? " β"? ppSpace term (" using " num)?
(" with" (ppSpace colGt rintroPat)*)? (Parser.Tactic.location)? : tactic
elab_rules : tactic
| `(tactic| convert_to $[$cfg:config]? $[β%$sym]? $newType $[using $n]?
$[with $ps?*]? $[$loc?:location]?) => do
let n : β := n |>.map (Β·.getNat) |>.getD 1
let config β Congr!.elabConfig (mkOptionalNode cfg)
let patterns := (Lean.Elab.Tactic.RCases.expandRIntroPats (ps?.getD #[])).toList
withLocation (expandOptLocation (mkOptionalNode loc?))
(atLocal := fun fvarId β¦ do
let (e, gs) β elabTermForConvert newType (β inferType (β fvarId.getType))
liftMetaTactic fun g β¦ do
let (g', gs') β g.convertLocalDecl fvarId e sym.isSome n config patterns
return (gs' ++ (g' :: gs)))
(atTarget := do
let expectedType β mkFreshExprMVar (mkSort (β getLevel (β getMainTarget)))
let (e, gs) β elabTermForConvert (β `((id ?_ : $newType))) expectedType
liftMetaTactic fun g β¦
return (β g.convert e sym.isSome n config patterns) ++ gs)
(failed := fun _ β¦ throwError "convert_to failed")
/--
`ac_change g using n` is `convert_to g using n` followed by `ac_rfl`. It is useful for
rearranging/reassociating e.g. sums:
```lean
example (a b c d e f g N : β) : (a + b) + (c + d) + (e + f) + g β€ N := by
ac_change a + d + e + f + c + g + b β€ _
-- β’ a + d + e + f + c + g + b β€ N
```
-/
syntax (name := acChange) "ac_change " term (" using " num)? : tactic
macro_rules
| `(tactic| ac_change $t $[using $n]?) => `(tactic| convert_to $t:term $[using $n]? <;> try ac_rfl)
end Mathlib.Tactic
|
Tactic\Core.lean | /-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, AurΓ©lien Saue, Mario Carneiro
-/
import Lean.Elab.PreDefinition.Basic
import Lean.Util.Paths
import Mathlib.Lean.Expr.Basic
import Batteries.Tactic.OpenPrivate
/-!
# Generally useful tactics.
-/
open Lean.Elab.Tactic
namespace Lean
open Elab
/--
Return the modifiers of declaration `nm` with (optional) docstring `newDoc`.
Currently, recursive or partial definitions are not supported, and no attributes are provided.
-/
def toModifiers (nm : Name) (newDoc : Option String := none) :
CoreM Modifiers := do
let env β getEnv
let d β getConstInfo nm
let mods : Modifiers :=
{ docString? := newDoc
visibility :=
if isPrivateNameExport nm then
Visibility.private
else if isProtected env nm then
Visibility.regular
else
Visibility.protected
isNoncomputable := if (env.find? <| nm.mkStr "_cstage1").isSome then false else true
recKind := RecKind.default -- nonrec only matters for name resolution, so is irrelevant (?)
isUnsafe := d.isUnsafe
attrs := #[] }
return mods
/--
Make a PreDefinition taking some metadata from declaration `nm`.
You can provide a new type, value and (optional) docstring, but the remaining information is taken
from `nm`.
Currently only implemented for definitions and theorems. Also see docstring of `toModifiers`
-/
def toPreDefinition (nm newNm : Name) (newType newValue : Expr) (newDoc : Option String := none) :
CoreM PreDefinition := do
let d β getConstInfo nm
let mods β toModifiers nm newDoc
let predef : PreDefinition :=
{ ref := Syntax.missing
kind := if d.isDef then DefKind.def else DefKind.theorem
levelParams := d.levelParams
modifiers := mods
declName := newNm
type := newType
value := newValue
termination := .none }
return predef
/-- Make `nm` protected. -/
def setProtected {m : Type β Type} [MonadEnv m] (nm : Name) : m Unit :=
modifyEnv (addProtected Β· nm)
open private getIntrosSize from Lean.Meta.Tactic.Intro in
/-- Introduce variables, giving them names from a specified list. -/
def MVarId.introsWithBinderIdents
(g : MVarId) (ids : List (TSyntax ``binderIdent)) :
MetaM (List (TSyntax ``binderIdent) Γ Array FVarId Γ MVarId) := do
let type β g.getType
let type β instantiateMVars type
let n := getIntrosSize type
if n == 0 then
return (ids, #[], g)
let mut ids := ids
let mut names := #[]
for _ in [0:n] do
names := names.push (ids.headD (Unhygienic.run `(binderIdent| _)))
ids := ids.tail
let (xs, g) β g.introN n <| names.toList.map fun stx =>
match stx.raw with
| `(binderIdent| $n:ident) => n.getId
| _ => `_
g.withContext do
for n in names, fvar in xs do
(Expr.fvar fvar).addLocalVarInfoForBinderIdent n
return (ids, xs, g)
end Lean
namespace Mathlib.Tactic
-- FIXME: we cannot write this line when `Lean.Parser.Tactic` is open,
-- or it will get an extra `group`
syntax withArgs := " with" (ppSpace colGt ident)+
syntax usingArg := " using " term
open Lean Parser.Tactic
/-- Extract the arguments from a `simpArgs` syntax as an array of syntaxes -/
def getSimpArgs : Syntax β TacticM (Array Syntax)
| `(simpArgs| [$args,*]) => pure args.getElems
| _ => Elab.throwUnsupportedSyntax
/-- Extract the arguments from a `dsimpArgs` syntax as an array of syntaxes -/
def getDSimpArgs : Syntax β TacticM (Array Syntax)
| `(dsimpArgs| [$args,*]) => pure args.getElems
| _ => Elab.throwUnsupportedSyntax
/-- Extract the arguments from a `withArgs` syntax as an array of syntaxes -/
def getWithArgs : Syntax β TacticM (Array Syntax)
| `(withArgs| with $args*) => pure args
| _ => Elab.throwUnsupportedSyntax
/-- Extract the argument from a `usingArg` syntax as a syntax term -/
def getUsingArg : Syntax β TacticM Syntax
| `(usingArg| using $e) => pure e
| _ => Elab.throwUnsupportedSyntax
/--
`repeat1 tac` applies `tac` to main goal at least once. If the application succeeds,
the tactic is applied recursively to the generated subgoals until it eventually fails.
-/
macro "repeat1 " seq:tacticSeq : tactic => `(tactic| (($seq); repeat $seq))
end Mathlib.Tactic
namespace Lean.Elab.Tactic
/-- Given a local context and an array of `FVarIds` assumed to be in that local context, remove all
implementation details. -/
def filterOutImplementationDetails (lctx : LocalContext) (fvarIds : Array FVarId) : Array FVarId :=
fvarIds.filter (fun fvar => ! (lctx.fvarIdToDecl.find! fvar).isImplementationDetail)
/-- Elaborate syntax for an `FVarId` in the local context of the given goal. -/
def getFVarIdAt (goal : MVarId) (id : Syntax) : TacticM FVarId := withRef id do
-- use apply-like elaboration to suppress insertion of implicit arguments
let e β goal.withContext do
elabTermForApply id (mayPostpone := false)
match e with
| Expr.fvar fvarId => return fvarId
| _ => throwError "unexpected term '{e}'; expected single reference to variable"
/-- Get the array of `FVarId`s in the local context of the given `goal`.
If `ids` is specified, elaborate them in the local context of the given goal to obtain the array of
`FVarId`s.
If `includeImplementationDetails` is `false` (the default), we filter out implementation details
(`implDecl`s and `auxDecl`s) from the resulting list of `FVarId`s. -/
def getFVarIdsAt (goal : MVarId) (ids : Option (Array Syntax) := none)
(includeImplementationDetails : Bool := false) : TacticM (Array FVarId) :=
goal.withContext do
let lctx := (β goal.getDecl).lctx
let fvarIds β match ids with
| none => pure lctx.getFVarIds
| some ids => ids.mapM <| getFVarIdAt goal
if includeImplementationDetails then
return fvarIds
else
return filterOutImplementationDetails lctx fvarIds
/--
Run a tactic on all goals, and always succeeds.
(This is parallel to `Lean.Elab.Tactic.evalAllGoals` in core,
which takes a `Syntax` rather than `TacticM Unit`.
This function could be moved to core and `evalAllGoals` refactored to use it.)
-/
def allGoals (tac : TacticM Unit) : TacticM Unit := do
let mvarIds β getGoals
let mut mvarIdsNew := #[]
for mvarId in mvarIds do
unless (β mvarId.isAssigned) do
setGoals [mvarId]
try
tac
mvarIdsNew := mvarIdsNew ++ (β getUnsolvedGoals)
catch ex =>
if (β read).recover then
logException ex
mvarIdsNew := mvarIdsNew.push mvarId
else
throw ex
setGoals mvarIdsNew.toList
/-- Simulates the `<;>` tactic combinator. First runs `tac1` and then runs
`tac2` on all newly-generated subgoals.
-/
def andThenOnSubgoals (tac1 : TacticM Unit) (tac2 : TacticM Unit) : TacticM Unit :=
focus do tac1; allGoals tac2
universe u
variable {m : Type β Type u} [Monad m] [MonadExcept Exception m]
/-- Repeats a tactic at most `n` times, stopping sooner if the
tactic fails. Always succeeds. -/
def iterateAtMost : Nat β m Unit β m Unit
| 0, _ => pure ()
| n + 1, tac => try tac; iterateAtMost n tac catch _ => pure ()
/-- `iterateExactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails.
-/
def iterateExactly' : Nat β m Unit β m Unit
| 0, _ => pure ()
| n+1, tac => tac *> iterateExactly' n tac
/--
`iterateRange m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times.
-/
def iterateRange : Nat β Nat β m Unit β m Unit
| 0, 0, _ => pure ()
| 0, b, tac => iterateAtMost b tac
| (a+1), n, tac => do tac; iterateRange a (n-1) tac
/-- Repeats a tactic until it fails. Always succeeds. -/
partial def iterateUntilFailure (tac : m Unit) : m Unit :=
try tac; iterateUntilFailure tac catch _ => pure ()
/-- `iterateUntilFailureWithResults` is a helper tactic which accumulates the list of results
obtained from iterating `tac` until it fails. Always succeeds.
-/
partial def iterateUntilFailureWithResults {Ξ± : Type} (tac : m Ξ±) : m (List Ξ±) := do
try
let a β tac
let l β iterateUntilFailureWithResults tac
pure (a :: l)
catch _ => pure []
/-- `iterateUntilFailureCount` is similar to `iterateUntilFailure` except it counts
the number of successful calls to `tac`. Always succeeds.
-/
def iterateUntilFailureCount {Ξ± : Type} (tac : m Ξ±) : m Nat := do
let r β iterateUntilFailureWithResults tac
return r.length
end Lean.Elab.Tactic
namespace Mathlib
open Lean
/-- Returns the root directory which contains the package root file, e.g. `Mathlib.lean`. -/
def getPackageDir (pkg : String) : IO System.FilePath := do
let sp β initSrcSearchPath
let root? β sp.findM? fun p =>
(p / pkg).isDir <||> ((p / pkg).withExtension "lean").pathExists
if let some root := root? then return root
throw <| IO.userError s!"Could not find {pkg} directory. \
Make sure the LEAN_SRC_PATH environment variable is set correctly."
/-- Returns the mathlib root directory. -/
def getMathlibDir := getPackageDir "Mathlib"
|
Tactic\DefEqTransformations.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Tactic.Basic
/-! # Tactics that transform types into definitionally equal types
This module defines a standard wrapper that can be used to create tactics that
change hypotheses and the goal to things that are definitionally equal.
It then provides a number of tactics that transform local hypotheses and/or the target.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Elab.Tactic
/--
This is `Lean.MVarId.changeLocalDecl` but makes sure to preserve local variable order.
-/
def _root_.Lean.MVarId.changeLocalDecl' (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr)
(checkDefEq := true) : MetaM MVarId := do
mvarId.checkNotAssigned `changeLocalDecl
let lctx := (β mvarId.getDecl).lctx
let some decl := lctx.find? fvarId | throwTacticEx `changeLocalDecl mvarId m!"\
local variable {Expr.fvar fvarId} is not present in local context{mvarId}"
let toRevert := lctx.foldl (init := #[]) fun arr decl' =>
if decl.index β€ decl'.index then arr.push decl'.fvarId else arr
let (_, mvarId) β mvarId.withReverted toRevert fun mvarId fvars => mvarId.withContext do
let check (typeOld : Expr) : MetaM Unit := do
if checkDefEq then
unless β isDefEq typeNew typeOld do
throwTacticEx `changeLocalDecl mvarId
m!"given type{indentExpr typeNew}\nis not definitionally equal to{indentExpr typeOld}"
let finalize (targetNew : Expr) := do
return ((), fvars.map .some, β mvarId.replaceTargetDefEq targetNew)
match β mvarId.getType with
| .forallE n d b bi => do check d; finalize (.forallE n typeNew b bi)
| .letE n t v b ndep => do check t; finalize (.letE n typeNew v b ndep)
| _ => throwTacticEx `changeLocalDecl mvarId "unexpected auxiliary target"
return mvarId
/-- For the main goal, use `m` to transform the types of locations specified by `loc?`.
If `loc?` is none, then transforms the type of target. `m` is provided with an expression
with instantiated metavariables as well as, if the location is a local hypothesis, the fvar.
`m` *must* transform expressions to defeq expressions.
If `checkDefEq = true` (the default) then `runDefEqTactic` will throw an error
if the resulting expression is not definitionally equal to the original expression. -/
def runDefEqTactic (m : Option FVarId β Expr β MetaM Expr)
(loc? : Option (TSyntax ``Parser.Tactic.location))
(tacticName : String)
(checkDefEq : Bool := true) :
TacticM Unit := withMainContext do
withLocation (expandOptLocation (Lean.mkOptionalNode loc?))
(atLocal := fun h => liftMetaTactic1 fun mvarId => do
let ty β h.getType
let ty' β m h (β instantiateMVars ty)
if Expr.equal ty ty' then
return mvarId
else
mvarId.changeLocalDecl' (checkDefEq := checkDefEq) h ty')
(atTarget := liftMetaTactic1 fun mvarId => do
let ty β instantiateMVars (β mvarId.getType)
mvarId.change (checkDefEq := checkDefEq) (β m none ty))
(failed := fun _ => throwError "{tacticName} failed")
/-- Like `Mathlib.Tactic.runDefEqTactic` but for `conv` mode. -/
def runDefEqConvTactic (m : Expr β MetaM Expr) : TacticM Unit := withMainContext do
Conv.changeLhs <| β m (β instantiateMVars <| β Conv.getLhs)
/-! ### `whnf` -/
/--
`whnf at loc` puts the given location into weak-head normal form.
This also exists as a `conv`-mode tactic.
Weak-head normal form is when the outer-most expression has been fully reduced, the expression
may contain subexpressions which have not been reduced.
-/
elab "whnf" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (checkDefEq := false) (fun _ => whnf) loc? "whnf"
/-! ### `beta_reduce` -/
/--
`beta_reduce at loc` completely beta reduces the given location.
This also exists as a `conv`-mode tactic.
This means that whenever there is an applied lambda expression such as
`(fun x => f x) y` then the argument is substituted into the lambda expression
yielding an expression such as `f y`.
-/
elab (name := betaReduceStx) "beta_reduce" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (checkDefEq := false) (fun _ e => Core.betaReduce e) loc? "beta_reduce"
@[inherit_doc betaReduceStx]
elab "beta_reduce" : conv => runDefEqConvTactic (Core.betaReduce Β·)
/-! ### `reduce` -/
/--
`reduce at loc` completely reduces the given location.
This also exists as a `conv`-mode tactic.
This does the same transformation as the `#reduce` command.
-/
elab "reduce" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (fun _ e => reduce e (skipTypes := false) (skipProofs := false)) loc? "reduce"
/-! ### `unfold_let` -/
/-- Unfold all the fvars from `fvars` in `e` that have local definitions (are "let-bound"). -/
def unfoldFVars (fvars : Array FVarId) (e : Expr) : MetaM Expr := do
transform (usedLetOnly := true) e fun node => do
match node with
| .fvar fvarId =>
if fvars.contains fvarId then
if let some val β fvarId.getValue? then
return .visit (β instantiateMVars val)
else
return .continue
else
return .continue
| _ => return .continue
/--
`unfold_let x y z at loc` unfolds the local definitions `x`, `y`, and `z` at the given
location, which is known as "zeta reduction."
This also exists as a `conv`-mode tactic.
If no local definitions are given, then all local definitions are unfolded.
This variant also exists as the `conv`-mode tactic `zeta`.
This is similar to the `unfold` tactic, which instead is for unfolding global definitions.
-/
syntax (name := unfoldLetStx) "unfold_let" (ppSpace colGt term:max)*
(ppSpace Parser.Tactic.location)? : tactic
elab_rules : tactic
| `(tactic| unfold_let $[$loc?]?) =>
runDefEqTactic (fun _ => zetaReduce) loc? "unfold_let"
| `(tactic| unfold_let $hs:term* $[$loc?]?) => do
let fvars β getFVarIds hs
runDefEqTactic (fun _ => unfoldFVars fvars) loc? "unfold_let"
@[inherit_doc unfoldLetStx]
syntax "unfold_let" (ppSpace colGt term:max)* : conv
elab_rules : conv
| `(conv| unfold_let) => runDefEqConvTactic zetaReduce
| `(conv| unfold_let $hs:term*) => do
runDefEqConvTactic (unfoldFVars (β getFVarIds hs))
/-! ### `refold_let` -/
/-- For each fvar, looks for its body in `e` and replaces it with the fvar. -/
def refoldFVars (fvars : Array FVarId) (loc? : Option FVarId) (e : Expr) : MetaM Expr := do
-- Filter the fvars, only taking those that are from earlier in the local context.
let fvars β
if let some loc := loc? then
let locIndex := (β loc.getDecl).index
fvars.filterM fun fvar => do
let some decl β fvar.findDecl? | return false
return decl.index < locIndex
else
pure fvars
let mut e := e
for fvar in fvars do
let some val β fvar.getValue?
| throwError "local variable {Expr.fvar fvar} has no value to refold"
e := (β kabstract e val).instantiate1 (Expr.fvar fvar)
return e
/--
`refold_let x y z at loc` looks for the bodies of local definitions `x`, `y`, and `z` at the given
location and replaces them with `x`, `y`, or `z`. This is the inverse of "zeta reduction."
This also exists as a `conv`-mode tactic.
-/
syntax (name := refoldLetStx) "refold_let" (ppSpace colGt term:max)*
(ppSpace Parser.Tactic.location)? : tactic
elab_rules : tactic
| `(tactic| refold_let $hs:term* $[$loc?]?) => do
let fvars β getFVarIds hs
runDefEqTactic (refoldFVars fvars) loc? "refold_let"
@[inherit_doc refoldLetStx]
syntax "refold_let" (ppSpace colGt term:max)* : conv
elab_rules : conv
| `(conv| refold_let $hs:term*) => do
runDefEqConvTactic (refoldFVars (β getFVarIds hs) none)
/-! ### `unfold_projs` -/
/-- Recursively unfold all the projection applications for class instances. -/
def unfoldProjs (e : Expr) : MetaM Expr := do
transform e fun node => do
if let some node' β unfoldProjInst? node then
return .visit (β instantiateMVars node')
else
return .continue
/--
`unfold_projs at loc` unfolds projections of class instances at the given location.
This also exists as a `conv`-mode tactic.
-/
elab (name := unfoldProjsStx) "unfold_projs" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (fun _ => unfoldProjs) loc? "unfold_projs"
@[inherit_doc unfoldProjsStx]
elab "unfold_projs" : conv => runDefEqConvTactic unfoldProjs
/-! ### `eta_reduce` -/
/-- Eta reduce everything -/
def etaReduceAll (e : Expr) : MetaM Expr := do
transform e fun node =>
match node.etaExpandedStrict? with
| some e' => return .visit e'
| none => return .continue
/--
`eta_reduce at loc` eta reduces all sub-expressions at the given location.
This also exists as a `conv`-mode tactic.
For example, `fun x y => f x y` becomes `f` after eta reduction.
-/
elab (name := etaReduceStx) "eta_reduce" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (fun _ => etaReduceAll) loc? "eta_reduce"
@[inherit_doc etaReduceStx]
elab "eta_reduce" : conv => runDefEqConvTactic etaReduceAll
/-! ### `eta_expand` -/
/-- Eta expand every sub-expression in the given expression.
As a side-effect, beta reduces any pre-existing instances of eta expanded terms. -/
partial def etaExpandAll (e : Expr) : MetaM Expr := do
let betaOrApp (f : Expr) (args : Array Expr) : Expr :=
if f.etaExpanded?.isSome then f.beta args else mkAppN f args
let expand (e : Expr) : MetaM Expr := do
if e.isLambda then
return e
else
forallTelescopeReducing (β inferType e) fun xs _ => do
mkLambdaFVars xs (betaOrApp e xs)
transform e
(pre := fun node => do
if node.isApp then
let f β etaExpandAll node.getAppFn
let args β node.getAppArgs.mapM etaExpandAll
.done <$> expand (betaOrApp f args)
else
pure .continue)
(post := (.done <$> expand Β·))
/--
`eta_expand at loc` eta expands all sub-expressions at the given location.
It also beta reduces any applications of eta expanded terms, so it puts it
into an eta-expanded "normal form."
This also exists as a `conv`-mode tactic.
For example, if `f` takes two arguments, then `f` becomes `fun x y => f x y`
and `f x` becomes `fun y => f x y`.
This can be useful to turn, for example, a raw `HAdd.hAdd` into `fun x y => x + y`.
-/
elab (name := etaExpandStx) "eta_expand" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (fun _ => etaExpandAll) loc? "eta_expand"
@[inherit_doc etaExpandStx]
elab "eta_expand" : conv => runDefEqConvTactic etaExpandAll
/-! ### `eta_struct` -/
/-- Given an expression that's either a native projection or a registered projection
function, gives (1) the name of the structure type, (2) the index of the projection, and
(3) the object being projected. -/
def getProjectedExpr (e : Expr) : MetaM (Option (Name Γ Nat Γ Expr)) := do
if let .proj S i x := e then
return (S, i, x)
if let .const fn _ := e.getAppFn then
if let some info β getProjectionFnInfo? fn then
if e.getAppNumArgs == info.numParams + 1 then
if let some (ConstantInfo.ctorInfo fVal) := (β getEnv).find? info.ctorName then
return (fVal.induct, info.i, e.appArg!)
return none
/-- Checks if the expression is of the form `S.mk x.1 ... x.n` with `n` nonzero
and `S.mk` a structure constructor and returns `x`.
Each projection `x.i` can be either a native projection or from a projection function.
`tryWhnfR` controls whether to try applying `whnfR` to arguments when none of them
are obviously projections.
Once an obviously correct projection is found, relies on the structure eta rule in `isDefEq`. -/
def etaStruct? (e : Expr) (tryWhnfR : Bool := true) : MetaM (Option Expr) := do
let .const f _ := e.getAppFn | return none
let some (ConstantInfo.ctorInfo fVal) := (β getEnv).find? f | return none
unless 0 < fVal.numFields && e.getAppNumArgs == fVal.numParams + fVal.numFields do return none
unless isStructureLike (β getEnv) fVal.induct do return none
let args := e.getAppArgs
let mut x? β findProj fVal args pure
if tryWhnfR then
if let .undef := x? then
x? β findProj fVal args whnfR
if let .some x := x? then
-- Rely on eta for structures to make the check:
if β isDefEq x e then
return x
return none
where
/-- Check to see if there's an argument at some index `i`
such that it's the `i`th projection of a some expression.
Returns the expression. -/
findProj (fVal : ConstructorVal) (args : Array Expr) (m : Expr β MetaM Expr) :
MetaM (LOption Expr) := do
for i in [0 : fVal.numFields] do
let arg β m args[fVal.numParams + i]!
let some (S, j, x) β getProjectedExpr arg | continue
if S == fVal.induct && i == j then
return .some x
else
-- Then the eta rule can't apply since there's an obviously wrong projection
return .none
return .undef
/-- Finds all occurrences of expressions of the form `S.mk x.1 ... x.n` where `S.mk`
is a structure constructor and replaces them by `x`. -/
def etaStructAll (e : Expr) : MetaM Expr :=
transform e fun node => do
if let some node' β etaStruct? node then
return .visit node'
else
return .continue
/--
`eta_struct at loc` transforms structure constructor applications such as `S.mk x.1 ... x.n`
(pretty printed as, for example, `{a := x.a, b := x.b, ...}`) into `x`.
This also exists as a `conv`-mode tactic.
The transformation is known as eta reduction for structures, and it yields definitionally
equal expressions.
For example, given `x : Ξ± Γ Ξ²`, then `(x.1, x.2)` becomes `x` after this transformation.
-/
elab (name := etaStructStx) "eta_struct" loc?:(ppSpace Parser.Tactic.location)? : tactic =>
runDefEqTactic (fun _ => etaStructAll) loc? "eta_struct"
@[inherit_doc etaStructStx]
elab "eta_struct" : conv => runDefEqConvTactic etaStructAll
end Mathlib.Tactic
|
Tactic\DeprecateMe.lean | /-
Copyright (c) 2024 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import Mathlib.Lean.Expr.Basic
import Mathlib.Tactic.Lemma
/-!
# `deprecate to` -- a deprecation tool
Writing
```lean
deprecate to new_name new_nameβ ... new_nameβ
theorem old_name : True := .intro
```
where `new_name new_nameβ ... new_nameβ` is a sequence of identifiers produces the
`Try this` suggestion:
```lean
theorem new_name : True := .intro
@[deprecated (since := "YYYY-MM-DD")] alias old_name := new_name
@[deprecated (since := "YYYY-MM-DD")] alias old_nameβ := new_nameβ
...
@[deprecated (since := "YYYY-MM-DD")] alias old_nameβ := new_nameβ
```
where `old_name old_nameβ ... old_nameβ` are the non-blacklisted declarations
(auto)generated by the initial command.
TODO:
* the "new" names come fully qualified with their namespace -- if the deprecation is happening
inside a `namespace X`, it would be better to remove the `X` prefix from them;
* preserve formatting of existing command?
-/
namespace Mathlib.Tactic.DeprecateMe
open Lean Elab Term Command
/-- Produce the syntax for the command `@[deprecated (since := "YYYY-MM-DD")] alias n := id`. -/
def mkDeprecationStx (id : TSyntax `ident) (n : Name) (dat : Option String := none) :
CommandElabM (TSyntax `command) := do
let dat := β match dat with
| none => IO.Process.run { cmd := "date", args := #["-I"] }
| some s => return s
let nd := mkNode `str #[mkAtom ("\"" ++ dat.trimRight ++ "\"")]
`(command| @[deprecated (since := $nd)] alias $(mkIdent n) := $id)
/-- Returns the array of names that are in `new` but not in `old`. -/
def newNames (old new : Environment) : Array Name := Id.run do
let mut diffs := #[]
for (c, _) in new.constants.mapβ.toList do
unless old.constants.mapβ.contains c do
diffs := diffs.push c
pure <| diffs.qsort (Β·.toString < Β·.toString)
variable (newName : TSyntax `ident) in
/--
If the input command is a `theorem` or a `lemma`, then it replaces the name of the
resulting declaration with `newName` and it returns the old declaration name and the
command with the new name.
If the input command is neither a `theorem` nor a `lemma`, then it returns
`.missing` and the unchanged command.
-/
def renameTheorem : TSyntax `command β TSyntax `Lean.Parser.Command.declId Γ TSyntax `command
| `(command| $dm:declModifiers theorem $id:declId $d:declSig $v:declVal) => Unhygienic.run do
return (id, β `($dm:declModifiers theorem $newName:declId $d:declSig $v:declVal))
| `(command| $dm:declModifiers lemma $id:declId $d:declSig $v:declVal) => Unhygienic.run do
return (id, β `($dm:declModifiers lemma $newName:declId $d:declSig $v:declVal))
| a => (default, a)
open Meta.Tactic.TryThis in
/--
Writing
```lean
deprecate to new_name new_nameβ ... new_nameβ
theorem old_name : True := .intro
```
where `new_name new_nameβ ... new_nameβ` is a sequence of identifiers produces the
`Try this` suggestion:
```lean
theorem new_name : True := .intro
@[deprecated (since := "YYYY-MM-DD")] alias old_name := new_name
@[deprecated (since := "YYYY-MM-DD")] alias old_nameβ := new_nameβ
...
@[deprecated (since := "YYYY-MM-DD")] alias old_nameβ := new_nameβ
```
where `old_name old_nameβ ... old_nameβ` are the non-blacklisted declarations
(auto)generated by the initial command.
The "YYYY-MM-DD" entry is today's date and it is automatically filled in.
`deprecate to` makes an effort to match `old_name`, the "visible" name, with
`new_name`, the first identifier produced by the user.
The "old", autogenerated declarations `old_nameβ ... old_nameβ` are retrieved in alphabetical order.
In the case in which the initial declaration produces at most 1 non-blacklisted
declarations besides itself, the alphabetical sorting is irrelevant.
Technically, the command also take an optional `String` argument to fill in the date in `since`.
However, its use is mostly intended for debugging purposes, where having a variable date would
make tests time-dependent.
-/
elab tk:"deprecate to " id:ident* dat:(str)? ppLine cmd:command : command => do
let oldEnv β getEnv
try
elabCommand cmd
finally
let newEnv β getEnv
let allNew := newNames oldEnv newEnv
let skip β allNew.filterM (Β·.isBlackListed)
let mut news := allNew.filter (! Β· β skip)
let mut warn := #[]
if id.size < news.size then
warn := warn.push s!"Un-deprecated declarations: {news.toList.drop id.size}"
if news.size < id.size then
for i in id.toList.drop news.size do logErrorAt i ""
warn := warn.push s!"Unused names: {id.toList.drop news.size}"
let (oldId, newCmd) := renameTheorem id[0]! cmd
let oldNames := β resolveGlobalName (oldId.raw.getArg 0).getId.eraseMacroScopes
let fil := news.filter fun n => n.toString.endsWith oldNames[0]!.1.toString
if fil.size != 1 && oldId != default then
logError m!"Expected to find one declaration called {oldNames[0]!.1}, found {fil.size}"
if oldId != default then
news := #[fil[0]!] ++ (news.erase fil[0]!)
let pairs := id.zip news
let msg := s!"* Pairings:\n{pairs.map fun (l, r) => (l.getId, r)}" ++
if skip.size != 0 then s!"\n\n* Ignoring: {skip}" else ""
let dat := if dat.isSome then some dat.get!.getString else none
let stxs β pairs.mapM fun (id, n) => mkDeprecationStx id n dat
if newCmd == cmd then
logWarningAt cmd m!"New declaration uses the old name {oldId.raw.getArg 0}!"
let stxs := #[newCmd] ++ stxs
if warn != #[] then
logWarningAt tk m!"{warn.foldl (Β· ++ "\n" ++ Β·) "Warnings:\n"}"
liftTermElabM do
let prettyStxs β stxs.mapM (SuggestionText.prettyExtra <|.tsyntax Β·)
let toMessageData := (prettyStxs.toList.drop 1).foldl
(fun x y => x ++ "\n\n" ++ y) prettyStxs[0]!
addSuggestion (header := msg ++ "\n\nTry this:\n") (β getRef)
toMessageData
end Mathlib.Tactic.DeprecateMe
|
Tactic\DeriveFintype.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Tactic.ProxyType
import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Fintype.Sigma
import Mathlib.Data.Fintype.Sum
/-!
# The `Fintype` derive handler
This file defines a derive handler to automatically generate `Fintype` instances
for structures and inductive types.
The following is a prototypical example of what this can handle:
```
inductive MyOption (Ξ± : Type*)
| none
| some (x : Ξ±)
deriving Fintype
```
This deriving handler does not attempt to process inductive types that are either
recursive or that have indices.
To get debugging information, do `set_option trace.Elab.Deriving.fintype true`
and `set_option Elab.ProxyType true`.
There is a term elaborator `derive_fintype%` implementing the derivation of `Fintype` instances.
This can be useful in cases when there are necessary additional assumptions (like `DecidableEq`).
This is implemented using `Fintype.ofEquiv` and `proxy_equiv%`, which is a term elaborator
that creates an equivalence from a "proxy type" composed of basic type constructors. If Lean
can synthesize a `Fintype` instance for the proxy type, then `derive_fintype%` succeeds.
## Implementation notes
There are two kinds of `Fintype` instances that we generate, depending on the inductive type.
If it is an enum (an inductive type with only 0-ary constructors), then we generate the
complete `List` of all constructors; see `Mathlib.Deriving.Fintype.mkFintypeEnum` for more
details. The proof has $O(n)$ complexity in the number of constructors.
Otherwise, the strategy we take is to generate a "proxy type", define an equivalence between
our type and the proxy type (see `proxy_equiv%`), and then use `Fintype.ofEquiv` to pull a
`Fintype` instance on the proxy type (if one exists) to our inductive type. For example, with
the `MyOption Ξ±` type above, we generate `Unit β Ξ±`. While the proxy type is not a finite type
in general, we add `Fintype` instances for every type parameter of our inductive type (and
`Decidable` instances for every `Prop` parameter). Hence, in our example we get
`Fintype (MyOption Ξ±)` assuming `Fintype Ξ±`.
There is a source of quadratic complexity in this `Fintype` instance from the fact that an
inductive type with `n` constructors has a proxy type of the form `Cβ β (Cβ β (β― β Cβ))`,
so mapping to and from `Cα΅’` requires looking through `i` levels of `Sum` constructors.
Ignoring time spent looking through these constructors, the construction of `Finset.univ`
contributes just linear time with respect to the cardinality of the type since the instances
involved compute the underlying `List` for the `Finset` as `lβ ++ (lβ ++ (β― ++ lβ))` with
right associativity.
Note that an alternative design could be that instead of using `Sum` we could create a
function `C : Fin n β Type*` with `C i = ULift Cα΅’` and then use `(i : Fin n) Γ C i` for
the proxy type, which would save us from the nested `Sum` constructors.
This implementation takes some inspiration from the one by Mario Carneiro for Mathlib 3.
A difference is that the Mathlib 3 version does not explicitly construct the total proxy type,
and instead it opts to construct the underlying `Finset` as a disjoint union of the `Finset.univ`
for each individual constructor's proxy type.
-/
namespace Mathlib.Deriving.Fintype
open Lean Elab Lean.Parser.Term
open Meta Command
/--
The term elaborator `derive_fintype% Ξ±` tries to synthesize a `Fintype Ξ±` instance
using all the assumptions in the local context; this can be useful, for example, if one
needs an extra `DecidableEq` instance. It works only if `Ξ±` is an inductive
type that `proxy_equiv% Ξ±` can handle. The elaborator makes use of the
expected type, so `(derive_fintype% _ : Fintype Ξ±)` works.
This uses `proxy_equiv% Ξ±`, so as a side effect it defines `proxyType` and `proxyTypeEquiv` in
the namespace associated to the inductive type `Ξ±`.
-/
macro "derive_fintype% " t:term : term => `(term| Fintype.ofEquiv _ (proxy_equiv% $t))
/-
Creates a `Fintype` instance by adding additional `Fintype` and `Decidable` instance arguments
for every type and prop parameter of the type, then use the `derive_fintype%` elaborator.
-/
def mkFintype (declName : Name) : CommandElabM Bool := do
let indVal β getConstInfoInduct declName
let cmd β liftTermElabM do
let header β Deriving.mkHeader `Fintype 0 indVal
let binders' β Deriving.mkInstImplicitBinders `Decidable indVal header.argNames
let instCmd β `(command|
instance $header.binders:bracketedBinder* $(binders'.map TSyntax.mk):bracketedBinder* :
Fintype $header.targetType := derive_fintype% _)
return instCmd
trace[Elab.Deriving.fintype] "instance command:\n{cmd}"
elabCommand cmd
return true
/-- Derive a `Fintype` instance for enum types. These come with a `toCtorIdx` function.
We generate a more optimized instance than the one produced by `mkFintype`.
The strategy is to (1) create a list `enumList` of all the constructors, (2) prove that this
is in `toCtorIdx` order, (3) show that `toCtorIdx` maps `enumList` to `List.range numCtors` to show
the list has no duplicates, and (4) give the `Fintype` instance, using 2 for completeness.
The proofs are all linear complexity, and the main computation is that
`enumList.map toCtorIdx = List.range numCtors`, which is true by `refl`. -/
def mkFintypeEnum (declName : Name) : CommandElabM Unit := do
let indVal β getConstInfoInduct declName
let levels := indVal.levelParams.map Level.param
let toCtorIdxName := declName.mkStr "toCtorIdx"
let enumListName := declName.mkStr "enumList"
let toCtorThmName := declName.mkStr "enumList_get?_to_CtorIdx_eq"
let enumListNodupName := declName.mkStr "enumList_nodup"
liftTermElabM <| Term.withoutErrToSorry do
do -- Define `enumList` enumerating all constructors
trace[Elab.Deriving.fintype] "defining {enumListName}"
let type := mkConst declName levels
let listType β mkAppM ``List #[type]
let listNil β mkAppOptM ``List.nil #[some type]
let listCons name xs := mkAppM ``List.cons #[mkConst name levels, xs]
let enumList β indVal.ctors.foldrM (listCons Β· Β·) listNil
addAndCompile <| Declaration.defnDecl
{ name := enumListName
levelParams := indVal.levelParams
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
type := listType
value := enumList }
setProtected enumListName
addDocString enumListName s!"A list enumerating every element of the type, \
which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)"
do -- Prove that this list is in `toCtorIdx` order
trace[Elab.Deriving.fintype] "proving {toCtorThmName}"
let goalStx β `(term| β (x : $(β Term.exprToSyntax <| mkConst declName levels)),
List.get? $(mkIdent enumListName) ($(mkIdent toCtorIdxName) x) = some x)
let goal β Term.elabTerm goalStx (mkSort .zero)
let pf β Term.elabTerm (β `(term| by intro x; cases x <;> rfl)) goal
Term.synthesizeSyntheticMVarsNoPostponing
addAndCompile <| Declaration.thmDecl
{ name := toCtorThmName
levelParams := indVal.levelParams
type := β instantiateMVars goal
value := β instantiateMVars pf }
setProtected toCtorThmName
do -- Use this theorem to prove `enumList` has no duplicates
trace[Elab.Deriving.fintype] "proving {enumListNodupName}"
let enum β Term.exprToSyntax <| mkConst enumListName levels
let goal β Term.elabTerm (β `(term| List.Nodup $enum)) (mkSort .zero)
let n : TSyntax `term := quote indVal.numCtors
let pf β Term.elabTerm (β `(term| by
apply List.Nodup.of_map $(mkIdent toCtorIdxName)
have h : List.map $(mkIdent toCtorIdxName) $(mkIdent enumListName)
= List.range $n := rfl
exact h βΈ List.nodup_range $n)) goal
Term.synthesizeSyntheticMVarsNoPostponing
addAndCompile <| Declaration.thmDecl
{ name := enumListNodupName
levelParams := indVal.levelParams
type := β instantiateMVars goal
value := β instantiateMVars pf }
setProtected enumListNodupName
-- Make the Fintype instance
trace[Elab.Deriving.fintype] "defining fintype instance"
let cmd β `(command|
instance : Fintype $(mkIdent declName) where
elems := Finset.mk $(mkIdent enumListName) $(mkIdent enumListNodupName)
complete := by
intro x
rw [Finset.mem_mk, Multiset.mem_coe, List.mem_iff_get?]
exact β¨$(mkIdent toCtorIdxName) x, $(mkIdent toCtorThmName) xβ©)
trace[Elab.Deriving.fintype] "instance command:\n{cmd}"
elabCommand cmd
def mkFintypeInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if declNames.size != 1 then
return false -- mutually inductive types are not supported
let declName := declNames[0]!
if β isEnumType declName then
mkFintypeEnum declName
return true
else
mkFintype declName
initialize
registerDerivingHandler `Fintype mkFintypeInstanceHandler
registerTraceClass `Elab.Deriving.fintype
end Mathlib.Deriving.Fintype
|
Tactic\DeriveToExpr.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Tactic.ToLevel
/-!
# A `ToExpr` derive handler
This module defines a `ToExpr` derive handler for inductive types. It supports mutually inductive
types as well.
The `ToExpr` derive handlers support universe level polymorphism. This is implemented using the
`Lean.ToLevel` class. To use `ToExpr` in places where there is universe polymorphism, make sure
to have a `[ToLevel.{u}]` instance available.
**Warning:** Import `Mathlib.Tactic.ToExpr` instead of this one. This ensures that you are using
the universe polymorphic `ToExpr` instances that override the ones from Lean 4 core.
Implementation note: this derive handler was originally modeled after the `Repr` derive handler.
-/
namespace Mathlib.Deriving.ToExpr
open Lean Elab Lean.Parser.Term
open Meta Command Deriving
/-- Specialization of `Lean.Elab.Deriving.mkHeader` for `ToExpr`. -/
def mkToExprHeader (indVal : InductiveVal) : TermElabM Header := do
-- The auxiliary functions we produce are `indtype -> Expr`.
let header β mkHeader ``ToExpr 1 indVal
return header
/-- Give a term that is equivalent to `(term| mkAppN $f #[$args,*])`.
As an optimization, `mkAppN` is pre-expanded out to use `Expr.app` directly. -/
def mkAppNTerm (f : Term) (args : Array Term) : MetaM Term :=
args.foldlM (fun a b => `(Expr.app $a $b)) f
/-- Create the body of the `toExpr` function
for the `ToExpr` instance, which is a `match` expression
that calls `toExpr` and `toTypeExpr` to assemble an expression for a given term.
For recursive inductive types, `auxFunName` refers to the `ToExpr` instance
for the current type.
For mutually recursive types, we rely on the local instances set up by `mkLocalInstanceLetDecls`. -/
def mkToExprBody (header : Header) (indVal : InductiveVal) (auxFunName : Name) :
TermElabM Term := do
let discrs β mkDiscrs header indVal
let alts β mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
/-- Create the `match` cases, one per constructor. -/
mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let ctorInfo β getConstInfoCtor ctorName
let alt β forallTelescopeReducing ctorInfo.type fun xs _ => do
let mut patterns := #[]
-- add `_` pattern for indices
for _ in [:indVal.numIndices] do
patterns := patterns.push (β `(_))
let mut ctorArgs := #[]
let mut rhsArgs : Array Term := #[]
let mkArg (x : Expr) (a : Term) : TermElabM Term := do
if (β inferType x).isAppOf indVal.name then
`($(mkIdent auxFunName) $a)
else if β Meta.isType x then
`(toTypeExpr $a)
else
`(toExpr $a)
-- add `_` pattern for inductive parameters, which are inaccessible
for i in [:ctorInfo.numParams] do
let a := mkIdent header.argNames[i]!
ctorArgs := ctorArgs.push (β `(_))
rhsArgs := rhsArgs.push <| β mkArg xs[i]! a
for i in [:ctorInfo.numFields] do
let a := mkIdent (β mkFreshUserName `a)
ctorArgs := ctorArgs.push a
rhsArgs := rhsArgs.push <| β mkArg xs[ctorInfo.numParams + i]! a
patterns := patterns.push (β `(@$(mkIdent ctorName):ident $ctorArgs:term*))
let levels β indVal.levelParams.toArray.mapM (fun u => `(toLevel.{$(mkIdent u)}))
let rhs : Term β
mkAppNTerm (β `(Expr.const $(quote ctorInfo.name) [$levels,*])) rhsArgs
`(matchAltExpr| | $[$patterns:term],* => $rhs)
alts := alts.push alt
return alts
/-- Create the body of the `toTypeExpr` function for the `ToExpr` instance.
Calls `toExpr` and `toTypeExpr` to the arguments to the type constructor. -/
def mkToTypeExpr (argNames : Array Name) (indVal : InductiveVal) : TermElabM Term := do
let levels β indVal.levelParams.toArray.mapM (fun u => `(toLevel.{$(mkIdent u)}))
forallTelescopeReducing indVal.type fun xs _ => do
let mut args : Array Term := #[]
for i in [:xs.size] do
let x := xs[i]!
let a := mkIdent argNames[i]!
if β Meta.isType x then
args := args.push <| β `(toTypeExpr $a)
else
args := args.push <| β `(toExpr $a)
mkAppNTerm (β `((Expr.const $(quote indVal.name) [$levels,*]))) args
/--
For mutually recursive inductive types, the strategy is to have local `ToExpr` instances in scope
for each of the inductives when defining each instance.
This way, each instance can freely use `toExpr` and `toTypeExpr` for each of the other types.
Note that each instance gets its own definition of each of the others' `toTypeExpr` fields.
(This is working around the fact that the `Deriving.Context` API assumes
that each instance in mutual recursion only has a single auxiliary definition.
There are other ways to work around it, but `toTypeExpr` implementations
are very simple, so duplicating them seemed to be OK.) -/
def mkLocalInstanceLetDecls (ctx : Deriving.Context) (argNames : Array Name) :
TermElabM (Array (TSyntax ``Parser.Term.letDecl)) := do
let mut letDecls := #[]
for i in [:ctx.typeInfos.size] do
let indVal := ctx.typeInfos[i]!
let auxFunName := ctx.auxFunNames[i]!
let currArgNames β mkInductArgNames indVal
let numParams := indVal.numParams
let currIndices := currArgNames[numParams:]
let binders β mkImplicitBinders currIndices
let argNamesNew := argNames[:numParams] ++ currIndices
let indType β mkInductiveApp indVal argNamesNew
let instName β mkFreshUserName `localinst
let toTypeExpr β mkToTypeExpr argNames indVal
let letDecl β `(Parser.Term.letDecl| $(mkIdent instName):ident $binders:implicitBinder* :
ToExpr $indType :=
{ toExpr := $(mkIdent auxFunName), toTypeExpr := $toTypeExpr })
letDecls := letDecls.push letDecl
return letDecls
/-- Fix the output of `mkInductiveApp` to explicitly reference universe levels. -/
def fixIndType (indVal : InductiveVal) (t : Term) : TermElabM Term :=
match t with
| `(@$f $args*) =>
let levels := indVal.levelParams.toArray.map mkIdent
`(@$f.{$levels,*} $args*)
| _ => throwError "(internal error) expecting output of `mkInductiveApp`"
/-- Make `ToLevel` instance binders for all the level variables. -/
def mkToLevelBinders (indVal : InductiveVal) : TermElabM (TSyntaxArray ``instBinderF) := do
indVal.levelParams.toArray.mapM (fun u => `(instBinderF| [ToLevel.{$(mkIdent u)}]))
open TSyntax.Compat in
/-- Make a `toExpr` function for the given inductive type.
The implementations of each `toExpr` function for a (mutual) inductive type
are given as top-level private definitions.
These end up being assembled into `ToExpr` instances in `mkInstanceCmds`.
For mutual inductive types,
then each of the other types' `ToExpr` instances are provided as local instances,
to wire together the recursion (this necessitates these auxiliary definitions being `partial`). -/
def mkAuxFunction (ctx : Deriving.Context) (i : Nat) : TermElabM Command := do
let auxFunName := ctx.auxFunNames[i]!
let indVal := ctx.typeInfos[i]!
let header β mkToExprHeader indVal
let mut body β mkToExprBody header indVal auxFunName
if ctx.usePartial then
let letDecls β mkLocalInstanceLetDecls ctx header.argNames
body β mkLet letDecls body
-- We need to alter the last binder (the one for the "target") to have explicit universe levels
-- so that the `ToLevel` instance arguments can use them.
let addLevels binder :=
match binder with
| `(bracketedBinderF| ($a : $ty)) => do `(bracketedBinderF| ($a : $(β fixIndType indVal ty)))
| _ => throwError "(internal error) expecting inst binder"
let binders := header.binders.pop
++ (β mkToLevelBinders indVal)
++ #[β addLevels header.binders.back]
let levels := indVal.levelParams.toArray.map mkIdent
if ctx.usePartial then
`(private partial def $(mkIdent auxFunName):ident.{$levels,*} $binders:bracketedBinder* :
Expr := $body:term)
else
`(private def $(mkIdent auxFunName):ident.{$levels,*} $binders:bracketedBinder* :
Expr := $body:term)
/-- Create all the auxiliary functions using `mkAuxFunction` for the (mutual) inductive type(s).
Wraps the resulting definition commands in `mutual ... end`. -/
def mkMutualBlock (ctx : Deriving.Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (β mkAuxFunction ctx i)
`(mutual $auxDefs:command* end)
open TSyntax.Compat in
/-- Assuming all of the auxiliary definitions exist, create all the `instance` commands
for the `ToExpr` instances for the (mutual) inductive type(s). -/
def mkInstanceCmds (ctx : Deriving.Context) (typeNames : Array Name) :
TermElabM (Array Command) := do
let mut instances := #[]
for i in [:ctx.typeInfos.size] do
let indVal := ctx.typeInfos[i]!
if typeNames.contains indVal.name then
let auxFunName := ctx.auxFunNames[i]!
let argNames β mkInductArgNames indVal
let binders β mkImplicitBinders argNames
let binders := binders ++ (β mkInstImplicitBinders ``ToExpr indVal argNames)
let binders := binders ++ (β mkToLevelBinders indVal)
let indType β fixIndType indVal (β mkInductiveApp indVal argNames)
let toTypeExpr β mkToTypeExpr argNames indVal
let levels := indVal.levelParams.toArray.map mkIdent
let instCmd β `(instance $binders:implicitBinder* : ToExpr $indType where
toExpr := $(mkIdent auxFunName).{$levels,*}
toTypeExpr := $toTypeExpr)
instances := instances.push instCmd
return instances
/-- Returns all the commands generated by `mkMutualBlock` and `mkInstanceCmds`. -/
def mkToExprInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do
let ctx β mkContext "toExpr" declNames[0]!
let cmds := #[β mkMutualBlock ctx] ++ (β mkInstanceCmds ctx declNames)
trace[Elab.Deriving.toExpr] "\n{cmds}"
return cmds
/-- The main entry point to the `ToExpr` derive handler. -/
def mkToExprInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if (β declNames.allM isInductive) && declNames.size > 0 then
let cmds β liftTermElabM <| mkToExprInstanceCmds declNames
cmds.forM elabCommand
return true
else
return false
initialize
registerDerivingHandler `Lean.ToExpr mkToExprInstanceHandler
registerTraceClass `Elab.Deriving.toExpr
end Mathlib.Deriving.ToExpr
|
Tactic\DeriveTraversable.lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import Mathlib.Control.Traversable.Lemmas
import Lean.Elab.Match
import Lean.Elab.Deriving.Basic
import Lean.Elab.PreDefinition.Main
/-!
# Deriving handler for `Traversable` instances
This module gives deriving handlers for `Functor`, `LawfulFunctor`, `Traversable`, and
`LawfulTraversable`. These deriving handlers automatically derive their dependencies, for
example `deriving LawfulTraversable` all by itself gives all four.
-/
namespace Mathlib.Deriving.Traversable
open Lean Meta Elab Term Command Tactic Match List Monad Functor
/-- `nestedMap f Ξ± (List (Array (List Ξ±)))` synthesizes the expression
`Functor.map (Functor.map (Functor.map f))`. `nestedMap` assumes that `Ξ±` appears in
`(List (Array (List Ξ±)))`.
(Similar to `nestedTraverse` but for `Functor`.) -/
partial def nestedMap (f v t : Expr) : TermElabM Expr := do
let t β instantiateMVars t
if β withNewMCtxDepth <| isDefEq t v then
return f
else if !v.occurs t.appFn! then
let cl β mkAppM ``Functor #[t.appFn!]
let inst β synthInstance cl
let f' β nestedMap f v t.appArg!
mkAppOptM ``Functor.map #[t.appFn!, inst, none, none, f']
else throwError "type {t} is not a functor with respect to variable {v}"
/-- similar to `traverseField` but for `Functor` -/
def mapField (n : Name) (cl f Ξ± Ξ² e : Expr) : TermElabM Expr := do
let t β whnf (β inferType e)
if t.getAppFn.constName = some n then
throwError "recursive types not supported"
else if Ξ±.eqv e then
return Ξ²
else if Ξ±.occurs t then
let f' β nestedMap f Ξ± t
return f'.app e
else if β
(match t with
| .app t' _ => withNewMCtxDepth <| isDefEq t' cl
| _ => return false) then
mkAppM ``Comp.mk #[e]
else
return e
/-- Get the auxiliary local declaration corresponding to the current declaration. If there are
multiple declaraions it will throw. -/
def getAuxDefOfDeclName : TermElabM FVarId := do
let some declName β getDeclName? | throwError "no 'declName?'"
let auxDeclMap := (β read).auxDeclToFullName
let fvars := auxDeclMap.fold (init := []) fun fvars fvar fullName =>
if fullName = declName then fvars.concat fvar else fvars
match fvars with
| [] => throwError "no auxiliary local declaration corresponding to the current declaration"
| [fvar] => return fvar
| _ => throwError "multiple local declarations corresponding to the current declaration"
/-- similar to `traverseConstructor` but for `Functor` -/
def mapConstructor (c n : Name) (f Ξ± Ξ² : Expr) (argsβ : List Expr)
(argsβ : List (Bool Γ Expr)) (m : MVarId) : TermElabM Unit := do
let ad β getAuxDefOfDeclName
let g β m.getType >>= instantiateMVars
let args' β argsβ.mapM (fun (y : Bool Γ Expr) =>
if y.1 then return mkAppN (.fvar ad) #[Ξ±, Ξ², f, y.2]
else mapField n g.appFn! f Ξ± Ξ² y.2)
mkAppOptM c ((argsβ ++ args').map some).toArray >>= m.assign
/-- Makes a `match` expression corresponding to the application of `casesOn` like:
```lean
match (motive := motive) indicesβ, indicesβ, .., (val : type.{univs} paramsβ paramsβ ..) with
| _, _, .., ctorβ fieldsββ fieldsββ .. => rhss ctorβ [fieldsββ, fieldsββ, ..]
| _, _, .., ctorβ fieldsββ fieldsββ .. => rhss ctorβ [fieldsββ, fieldsββ, ..]
```
This is convenient to make a definition with equation lemmas. -/
def mkCasesOnMatch (type : Name) (levels : List Level) (params : List Expr) (motive : Expr)
(indices : List Expr) (val : Expr)
(rhss : (ctor : Name) β (fields : List FVarId) β TermElabM Expr) : TermElabM Expr := do
let matcherName β getDeclName? >>= (fun n? => Lean.mkAuxName (.mkStr (n?.getD type) "match") 1)
let matchType β generalizeTelescope (indices.concat val).toArray fun iargs =>
mkForallFVars iargs (motive.beta iargs)
let iinfo β getConstInfoInduct type
let lhss β iinfo.ctors.mapM fun ctor => do
let cinfo β getConstInfoCtor ctor
let catype β
instantiateForall (cinfo.type.instantiateLevelParams cinfo.levelParams levels) params.toArray
forallBoundedTelescope catype cinfo.numFields fun cargs _ => do
let fvarDecls β cargs.toList.mapM fun carg => getFVarLocalDecl carg
let fieldPats := cargs.toList.map fun carg => Pattern.var carg.fvarId!
let patterns := [Pattern.ctor cinfo.name levels params fieldPats]
return { ref := .missing
fvarDecls
patterns }
let mres β Term.mkMatcher { matcherName
matchType
discrInfos := mkArray (indices.length + 1) {}
lhss }
mres.addMatcher
let rhss β lhss.mapM fun altLHS => do
let [.ctor ctor _ _ cpats] := altLHS.patterns | unreachable!
withExistingLocalDecls altLHS.fvarDecls do
let fields := altLHS.fvarDecls.map LocalDecl.fvarId
let rhsBody β rhss ctor fields
if cpats.isEmpty then
mkFunUnit rhsBody
else
mkLambdaFVars (fields.map Expr.fvar).toArray rhsBody
return mkAppN mres.matcher (motive :: indices ++ [val] ++ rhss).toArray
/-- Get `FVarId`s which is not implementation details in the current context. -/
def getFVarIdsNotImplementationDetails : MetaM (List FVarId) := do
let lctx β getLCtx
return lctx.decls.foldl (init := []) fun r decl? => match decl? with
| some decl => if decl.isImplementationDetail then r else r.concat decl.fvarId
| none => r
/-- Get `Expr`s of `FVarId`s which is not implementation details in the current context. -/
def getFVarsNotImplementationDetails : MetaM (List Expr) :=
List.map Expr.fvar <$> getFVarIdsNotImplementationDetails
/-- derive the `map` definition of a `Functor` -/
def mkMap (type : Name) (m : MVarId) : TermElabM Unit := do
let levels β getLevelNames
let vars β getFVarsNotImplementationDetails
let (#[Ξ±, Ξ², f, x], m) β m.introN 4 [`Ξ±, `Ξ², `f, `x] | failure
m.withContext do
let xtype β x.getType
let target β m.getType >>= instantiateMVars
let motive β mkLambdaFVars #[.fvar x] target
let e β
mkCasesOnMatch type (levels.map Level.param) (vars.concat (.fvar Ξ±)) motive [] (.fvar x)
fun ctor fields => do
let m β mkFreshExprSyntheticOpaqueMVar target
let args := fields.map Expr.fvar
let argsβ β args.mapM fun a => do
let b := xtype.occurs (β inferType a)
return (b, a)
mapConstructor
ctor type (.fvar f) (.fvar Ξ±) (.fvar Ξ²) (vars.concat (.fvar Ξ²)) argsβ m.mvarId!
instantiateMVars m
m.assign e
/-- derive the `map` definition and declare `Functor` using this. -/
def deriveFunctor (m : MVarId) : TermElabM Unit := do
let levels β getLevelNames
let vars β getFVarsNotImplementationDetails
let .app (.const ``Functor _) F β m.getType >>= instantiateMVars | failure
let some n := F.getAppFn.constName? | failure
let d β getConstInfo n
let [m] β run m <| evalTactic (β `(tactic| refine { map := @(?_) })) | failure
let t β m.getType >>= instantiateMVars
let n' := .mkStr n "map"
withDeclName n' <| withAuxDecl (.mkSimple "map") t n' fun ad => do
let m' := (β mkFreshExprSyntheticOpaqueMVar t).mvarId!
mkMap n m'
let e β instantiateMVars (mkMVar m')
let e := e.replaceFVar ad (mkAppN (.const n' (levels.map Level.param)) vars.toArray)
let e' β mkLambdaFVars vars.toArray e
let t' β mkForallFVars vars.toArray t
addPreDefinitions
#[{ ref := .missing
kind := .def
levelParams := levels
modifiers :=
{ isUnsafe := d.isUnsafe
attrs :=
#[{ kind := .global
name := `specialize
stx := β `(attr| specialize) }] }
declName := n'
type := t'
value := e'
termination := .none }] {}
m.assign (mkAppN (mkConst n' (levels.map Level.param)) vars.toArray)
/-- Similar to `mkInstanceName`, but for a `Expr` type. -/
def mkInstanceNameForTypeExpr (type : Expr) : TermElabM Name := do
let result β do
let ref β IO.mkRef ""
Meta.forEachExpr type fun e => do
if e.isForall then ref.modify (Β· ++ "ForAll")
else if e.isProp then ref.modify (Β· ++ "Prop")
else if e.isType then ref.modify (Β· ++ "Type")
else if e.isSort then ref.modify (Β· ++ "Sort")
else if e.isConst then
match e.constName!.eraseMacroScopes with
| .str _ str =>
if str.front.isLower then
ref.modify (Β· ++ str.capitalize)
else
ref.modify (Β· ++ str)
| _ => pure ()
ref.get
liftMacroM <| mkUnusedBaseName <| Name.mkSimple ("inst" ++ result)
/-- Derive the `cls` instance for the inductive type constructor `n` using the `tac` tactic. -/
def mkOneInstance (n cls : Name) (tac : MVarId β TermElabM Unit)
(mkInst : Name β Expr β TermElabM Expr := fun n arg => mkAppM n #[arg]) : TermElabM Unit := do
let .inductInfo decl β getConstInfo n |
throwError m!"failed to derive '{cls}', '{n}' is not an inductive type"
let clsDecl β getConstInfo cls
let ls := decl.levelParams.map Level.param
-- incrementally build up target expression `(hp : p) β [cls hp] β ... cls (n.{ls} hp ...)`
-- where `p ...` are the inductive parameter types of `n`
let tgt := Lean.mkConst n ls
let tgt β forallTelescope decl.type fun params _ => do
let params := params.pop
let tgt := mkAppN tgt params
let tgt β mkInst cls tgt
params.zipWithIndex.foldrM (fun (param, i) tgt => do
-- add typeclass hypothesis for each inductive parameter
let tgt β (do
guard (i < decl.numParams)
let paramCls β mkAppM cls #[param]
return mkForall `a .instImplicit paramCls tgt) <|> return tgt
mkForallFVars #[param] tgt) tgt
(discard <| liftM (synthInstance tgt)) <|> do
let m := (β mkFreshExprSyntheticOpaqueMVar tgt).mvarId!
let (_, m') β m.intros
withLevelNames decl.levelParams <| m'.withContext <| tac m'
let val β instantiateMVars (mkMVar m)
let isUnsafe := decl.isUnsafe || clsDecl.isUnsafe
let instN β m'.withContext do
let type β m'.getType >>= instantiateMVars
mkInstanceNameForTypeExpr type
addPreDefinitions
#[{ ref := .missing
kind := .def
levelParams := decl.levelParams
modifiers :=
{ isUnsafe
attrs :=
#[{ kind := .global
name := `instance
stx := β `(attr| instance) }] }
declName := instN
type := tgt
value := val
termination := .none }] {}
/-- Make the new deriving handler depends on other deriving handlers. -/
def higherOrderDeriveHandler (cls : Name) (tac : MVarId β TermElabM Unit)
(deps : List DerivingHandlerNoArgs := [])
(mkInst : Name β Expr β TermElabM Expr := fun n arg => mkAppM n #[arg]) :
DerivingHandlerNoArgs := fun a => do
let #[n] := a | return false -- mutually inductive types are not supported yet
let ok β deps.mapM fun f => f a
unless ok.and do return false
liftTermElabM <| mkOneInstance n cls tac mkInst
return true
/-- The deriving handler for `Functor`. -/
def functorDeriveHandler : DerivingHandlerNoArgs :=
higherOrderDeriveHandler ``Functor deriveFunctor []
initialize registerDerivingHandler ``Functor functorDeriveHandler
/-- Prove the functor laws and derive `LawfulFunctor`. -/
def deriveLawfulFunctor (m : MVarId) : TermElabM Unit := do
let rules (lβ : List (Name Γ Bool)) (lβ : List (Name)) (b : Bool) : MetaM Simp.Context := do
let mut s : SimpTheorems := {}
s β lβ.foldlM (fun s (n, b) => s.addConst n (inv := b)) s
s β lβ.foldlM (fun s n => s.addDeclToUnfold n) s
if b then
let hs β getPropHyps
s β hs.foldlM (fun s f => f.getDecl >>= fun d => s.add (.fvar f) #[] d.toExpr) s
return { simpTheorems := #[s] }
let .app (.app (.const ``LawfulFunctor _) F) _ β m.getType >>= instantiateMVars | failure
let some n := F.getAppFn.constName? | failure
let [mcn, mim, mcm] β m.applyConst ``LawfulFunctor.mk | failure
let (_, mcn) β mcn.introN 2
mcn.refl
let (#[_, x], mim) β mim.introN 2 | failure
let (some mim, _) β dsimpGoal mim (β rules [] [``Functor.map] false) | failure
let xs β mim.induction x (mkRecName n)
xs.forM fun β¨mim, _, _β© =>
mim.withContext do
if let (some (_, mim), _) β
simpGoal mim (β rules [(``Functor.map_id, false)] [.mkStr n "map"] true) then
mim.refl
let (#[_, _, _, _, _, x], mcm) β mcm.introN 6 | failure
let (some mcm, _) β dsimpGoal mcm (β rules [] [``Functor.map] false) | failure
let xs β mcm.induction x (mkRecName n)
xs.forM fun β¨mcm, _, _β© =>
mcm.withContext do
if let (some (_, mcm), _) β
simpGoal mcm (β rules [(``Functor.map_comp_map, true)] [.mkStr n "map"] true) then
mcm.refl
/-- The deriving handler for `LawfulFunctor`. -/
def lawfulFunctorDeriveHandler : DerivingHandlerNoArgs :=
higherOrderDeriveHandler ``LawfulFunctor deriveLawfulFunctor [functorDeriveHandler]
(fun n arg => mkAppOptM n #[arg, none])
initialize registerDerivingHandler ``LawfulFunctor lawfulFunctorDeriveHandler
/-- `nestedTraverse f Ξ± (List (Array (List Ξ±)))` synthesizes the expression
`traverse (traverse (traverse f))`. `nestedTraverse` assumes that `Ξ±` appears in
`(List (Array (List Ξ±)))` -/
partial def nestedTraverse (f v t : Expr) : TermElabM Expr := do
let t β instantiateMVars t
if β withNewMCtxDepth <| isDefEq t v then
return f
else if !v.occurs t.appFn! then
let cl β mkAppM ``Traversable #[t.appFn!]
let inst β synthInstance cl
let f' β nestedTraverse f v t.appArg!
mkAppOptM ``Traversable.traverse #[t.appFn!, inst, none, none, none, none, f']
else throwError "type {t} is not traversable with respect to variable {v}"
/--
For a sum type `inductive Foo (Ξ± : Type) | foo1 : List Ξ± β β β Foo Ξ± | ...`
``traverseField `Foo f `Ξ± `(x : List Ξ±)`` synthesizes
`traverse f x` as part of traversing `foo1`. -/
def traverseField (n : Name) (cl f v e : Expr) : TermElabM (Bool Γ Expr) := do
let t β whnf (β inferType e)
if t.getAppFn.constName = some n then
throwError "recursive types not supported"
else if v.occurs t then
let f' β nestedTraverse f v t
return (true, f'.app e)
else if β
(match t with
| .app t' _ => withNewMCtxDepth <| isDefEq t' cl
| _ => return false) then
Prod.mk true <$> mkAppM ``Comp.mk #[e]
else
return (false, e)
/--
For a sum type `inductive Foo (Ξ± : Type) | foo1 : List Ξ± β β β Foo Ξ± | ...`
``traverseConstructor `foo1 `Foo applInst f `Ξ± `Ξ² [`(x : List Ξ±), `(y : β)]``
synthesizes `foo1 <$> traverse f x <*> pure y.` -/
def traverseConstructor (c n : Name) (applInst f Ξ± Ξ² : Expr) (argsβ : List Expr)
(argsβ : List (Bool Γ Expr)) (m : MVarId) : TermElabM Unit := do
let ad β getAuxDefOfDeclName
let g β m.getType >>= instantiateMVars
let args' β argsβ.mapM (fun (y : Bool Γ Expr) =>
if y.1 then return (true, mkAppN (.fvar ad) #[g.appFn!, applInst, Ξ±, Ξ², f, y.2])
else traverseField n g.appFn! f Ξ± y.2)
let gargs := args'.filterMap (fun y => if y.1 then some y.2 else none)
let v β mkFunCtor c (argsβ.map (fun e => (false, e)) ++ args')
let pureInst β mkAppOptM ``Applicative.toPure #[none, applInst]
let constr' β mkAppOptM ``Pure.pure #[none, pureInst, none, v]
let r β gargs.foldlM
(fun e garg => mkFunUnit garg >>= fun e' => mkAppM ``Seq.seq #[e, e']) constr'
m.assign r
where
/-- `mkFunCtor ctor [(true, (argβ : m typeβ)), (false, (argβ : typeβ)), (true, (argβ : m typeβ)),
(false, (argβ : typeβ))]` makes `fun (xβ : typeβ) (xβ : typeβ) => ctor xβ argβ xβ argβ`. -/
mkFunCtor (c : Name) (args : List (Bool Γ Expr)) (fvars : Array Expr := #[])
(aargs : Array Expr := #[]) : TermElabM Expr := do
match args with
| (true, x) :: xs =>
let n β mkFreshUserName `x
let t β inferType x
withLocalDeclD n t.appArg! fun y => mkFunCtor c xs (fvars.push y) (aargs.push y)
| (false, x) :: xs => mkFunCtor c xs fvars (aargs.push x)
| [] => liftM <| mkAppOptM c (aargs.map some) >>= mkLambdaFVars fvars
/-- derive the `traverse` definition of a `Traversable` instance -/
def mkTraverse (type : Name) (m : MVarId) : TermElabM Unit := do
let vars β getFVarsNotImplementationDetails
let levels β getLevelNames
let (#[_, applInst, Ξ±, Ξ², f, x], m) β m.introN 6 [`m, `applInst, `Ξ±, `Ξ², `f, `x] | failure
m.withContext do
let xtype β x.getType
let target β m.getType >>= instantiateMVars
let motive β mkLambdaFVars #[.fvar x] target
let e β
mkCasesOnMatch type (levels.map Level.param) (vars.concat (.fvar Ξ±)) motive [] (.fvar x)
fun ctor fields => do
let m β mkFreshExprSyntheticOpaqueMVar target
let args := fields.map Expr.fvar
let argsβ β args.mapM fun a => do
let b := xtype.occurs (β inferType a)
return (b, a)
traverseConstructor
ctor type (.fvar applInst) (.fvar f) (.fvar Ξ±) (.fvar Ξ²)
(vars.concat (.fvar Ξ²)) argsβ m.mvarId!
instantiateMVars m
m.assign e
/-- derive the `traverse` definition and declare `Traversable` using this. -/
def deriveTraversable (m : MVarId) : TermElabM Unit := do
let levels β getLevelNames
let vars β getFVarsNotImplementationDetails
let .app (.const ``Traversable _) F β m.getType >>= instantiateMVars | failure
let some n := F.getAppFn.constName? | failure
let d β getConstInfo n
let [m] β run m <| evalTactic (β `(tactic| refine { traverse := @(?_) })) | failure
let t β m.getType >>= instantiateMVars
let n' := .mkStr n "traverse"
withDeclName n' <| withAuxDecl (.mkSimple "traverse") t n' fun ad => do
let m' := (β mkFreshExprSyntheticOpaqueMVar t).mvarId!
mkTraverse n m'
let e β instantiateMVars (mkMVar m')
let e := e.replaceFVar ad (mkAppN (.const n' (levels.map Level.param)) vars.toArray)
let e' β mkLambdaFVars vars.toArray e
let t' β mkForallFVars vars.toArray t
addPreDefinitions
#[{ ref := .missing
kind := .def
levelParams := levels
modifiers :=
{ isUnsafe := d.isUnsafe
visibility := .protected }
declName := n'
type := t'
value := e'
termination := .none }] {}
m.assign (mkAppN (mkConst n' (levels.map Level.param)) vars.toArray)
/-- The deriving handler for `Traversable`. -/
def traversableDeriveHandler : DerivingHandlerNoArgs :=
higherOrderDeriveHandler ``Traversable deriveTraversable [functorDeriveHandler]
initialize registerDerivingHandler ``Traversable traversableDeriveHandler
/-- Simplify the goal `m` using `functor_norm`. -/
def simpFunctorGoal (m : MVarId) (s : Simp.Context) (simprocs : Simp.SimprocsArray := {})
(discharge? : Option Simp.Discharge := none)
(simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[])
(stats : Simp.Stats := {}) :
MetaM (Option (Array FVarId Γ MVarId) Γ Simp.Stats) := do
let some e β getSimpExtension? `functor_norm | failure
let s' β e.getTheorems
simpGoal m { s with simpTheorems := s.simpTheorems.push s' } simprocs discharge? simplifyTarget
fvarIdsToSimp stats
/--
Run the following tactic:
```lean
intros _ .. x
dsimp only [Traversable.traverse, Functor.map]
induction x <;> (the simp tactic corresponding to s) <;> (tac)
```
-/
def traversableLawStarter (m : MVarId) (n : Name) (s : MetaM Simp.Context)
(tac : Array FVarId β InductionSubgoal β MVarId β MetaM Unit) : MetaM Unit := do
let s' β [``Traversable.traverse, ``Functor.map].foldlM
(fun s n => s.addDeclToUnfold n) ({} : SimpTheorems)
let (fi, m) β m.intros
m.withContext do
if let (some m, _) β dsimpGoal m { simpTheorems := #[s'] } then
let ma β m.induction fi.back (mkRecName n)
ma.forM fun is =>
is.mvarId.withContext do
if let (some (_, m), _) β simpFunctorGoal is.mvarId (β s) then
tac fi is m
/-- Prove the traversable laws and derive `LawfulTraversable`. -/
def deriveLawfulTraversable (m : MVarId) : TermElabM Unit := do
let rules (lβ : List (Name Γ Bool)) (lβ : List (Name)) (b : Bool) : MetaM Simp.Context := do
let mut s : SimpTheorems := {}
s β lβ.foldlM (fun s (n, b) => s.addConst n (inv := b)) s
s β lβ.foldlM (fun s n => s.addDeclToUnfold n) s
if b then
let hs β getPropHyps
s β hs.foldlM (fun s f => f.getDecl >>= fun d => s.add (.fvar f) #[] d.toExpr) s
pure <|
{ config := { failIfUnchanged := false, unfoldPartialApp := true },
simpTheorems := #[s] }
let .app (.app (.const ``LawfulTraversable _) F) _ β m.getType >>= instantiateMVars | failure
let some n := F.getAppFn.constName? | failure
let [mit, mct, mtmi, mn] β m.applyConst ``LawfulTraversable.mk | failure
let defEqns : MetaM Simp.Context := rules [] [.mkStr n "map", .mkStr n "traverse"] true
traversableLawStarter mit n defEqns fun _ _ m => m.refl
traversableLawStarter mct n defEqns fun _ _ m => do
if let (some (_, m), _) β simpFunctorGoal m
(β rules [] [.mkStr n "map", .mkStr n "traverse", ``Function.comp] true) then
m.refl
traversableLawStarter mtmi n defEqns fun _ _ m => do
if let (some (_, m), _) β
simpGoal m (β rules [(``Traversable.traverse_eq_map_id', false)] [] false) then
m.refl
traversableLawStarter mn n defEqns fun _ _ m => do
if let (some (_, m), _) β
simpGoal m (β rules [(``Traversable.naturality_pf, false)] [] false) then
m.refl
/-- The deriving handler for `LawfulTraversable`. -/
def lawfulTraversableDeriveHandler : DerivingHandlerNoArgs :=
higherOrderDeriveHandler ``LawfulTraversable deriveLawfulTraversable
[traversableDeriveHandler, lawfulFunctorDeriveHandler] (fun n arg => mkAppOptM n #[arg, none])
initialize registerDerivingHandler ``LawfulTraversable lawfulTraversableDeriveHandler
end Mathlib.Deriving.Traversable
|
Tactic\Eqns.lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Lean.Meta.Eqns
import Batteries.Lean.NameMapAttribute
import Lean.Elab.Exception
import Lean.Elab.InfoTree.Main
/-! # The `@[eqns]` attribute
This file provides the `eqns` attribute as a way of overriding the default equation lemmas. For
example
```lean4
def transpose {m n} (A : m β n β β) : n β m β β
| i, j => A j i
theorem transpose_apply {m n} (A : m β n β β) (i j) :
transpose A i j = A j i := rfl
attribute [eqns transpose_apply] transpose
theorem transpose_const {m n} (c : β) :
transpose (fun (i : m) (j : n) => c) = fun j i => c := by
funext i j -- the rw below does not work without this line
rw [transpose]
```
-/
open Lean Elab
syntax (name := eqns) "eqns" (ppSpace ident)* : attr
initialize eqnsAttribute : NameMapExtension (Array Name) β
registerNameMapAttribute {
name := `eqns
descr := "Overrides the equation lemmas for a declaration to the provided list"
add := fun
| declName, `(attr| eqns $[$names]*) => do
if let some _ := Meta.eqnsExt.getState (β getEnv) |>.map.find? declName then
throwError "There already exist stored eqns for '{declName}'; registering new equations \
will not have the desired effect."
names.mapM realizeGlobalConstNoOverloadWithInfo
| _, _ => Lean.Elab.throwUnsupportedSyntax }
initialize Lean.Meta.registerGetEqnsFn (fun name => do
pure (eqnsAttribute.find? (β getEnv) name))
|
Tactic\Eval.lean | /-
Copyright (c) 2024 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Qq.Macro
/-!
# The `eval%` term elaborator
This file provides the `eval% x` term elaborator, which evaluates the constant `x` at compile-time
in the interpreter, and interpolates it into the expression.
-/
open Qq Lean Elab Term
namespace Mathlib.Meta
/--
`eval% x` evaluates the term `x : X` in the interpreter, and then injects the resulting expression.
As an example:
```lean
example : 2^10 = eval% 2^10 := by
-- goal is `2^10 = 1024`
sorry
```
This only works if a `Lean.ToExpr X` instance is available.
Tip: you can use `show_term eval% x` to see the value of `eval% x`.
-/
syntax (name := eval_expr) "eval% " term : term
@[term_elab eval_expr, inherit_doc eval_expr]
unsafe def elabEvalExpr : Lean.Elab.Term.TermElab
| `(term| eval% $stx) => fun exp => do
let e β Lean.Elab.Term.elabTermAndSynthesize stx exp
let e β instantiateMVars e
let ee β Meta.mkAppM ``Lean.toExpr #[e]
Lean.Meta.evalExpr Expr q(Expr) ee (safety := .unsafe)
| _ => fun _ => Elab.throwUnsupportedSyntax
end Mathlib.Meta
|
Tactic\ExistsI.lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Gabriel Ebner, Moritz Doll
-/
/-!
# The `existsi` tactic
This file defines the `existsi` tactic: its purpose is to instantiate existential quantifiers.
Internally, it applies the `refine` tactic.
-/
namespace Mathlib.Tactic
/--
`existsi eβ, eβ, β―` applies the tactic `refine β¨eβ, eβ, β―, ?_β©`. It's purpose is to instantiate
existential quantifiers.
Examples:
```lean
example : β x : Nat, x = x := by
existsi 42
rfl
example : β x : Nat, β y : Nat, x = y := by
existsi 42, 42
rfl
```
-/
macro "existsi " es:term,+ : tactic =>
`(tactic| refine β¨$es,*, ?_β©)
|
Tactic\Explode.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Evgenia Karunus, Kyle Miller
-/
import Lean.Elab.Command
import Lean.PrettyPrinter
import Mathlib.Tactic.Explode.Datatypes
import Mathlib.Tactic.Explode.Pretty
/-!
# Explode command
This file contains the main code behind the `#explode` command.
If you have a theorem with a name `hi`, `#explode hi` will display a Fitch table.
-/
set_option linter.unusedVariables false
open Lean
namespace Mathlib.Explode
variable (select : Expr β MetaM Bool) (includeAllDeps : Bool) in
/-- Core `explode` algorithm.
- `select` is a condition for which expressions to process
- `includeAllDeps` is whether to include dependencies even if they were filtered out.
If `True`, then `none` is inserted for omitted dependencies
- `e` is the expression to process
- `depth` is the current abstraction depth
- `entries` is the table so far
- `start` is whether we are at the top-level of the expression, which
causes lambdas to use `Status.sintro` to prevent a layer of nesting.
-/
partial def explodeCore (e : Expr) (depth : Nat) (entries : Entries) (start : Bool := false) :
MetaM (Option Entry Γ Entries) := do
trace[explode] "depth = {depth}, start = {start}, e = {e}"
let e := e.cleanupAnnotations
if let some entry := entries.find? e then
trace[explode] "already seen"
return (entry, entries)
if !(β select e) then
trace[explode] "filtered out"
return (none, entries)
match e with
| .lam .. => do
trace[explode] ".lam"
Meta.lambdaTelescope e fun args body => do
let mut entries' := entries
let mut rdeps := []
for arg in args, i in [0:args.size] do
let (argEntry, entries'') := entries'.add arg
{ type := β addMessageContext <| β Meta.inferType arg
depth := depth
status :=
if start
then Status.sintro
else if i == 0 then Status.intro else Status.cintro
thm := β addMessageContext <| arg
deps := []
useAsDep := β select arg }
entries' := entries''
rdeps := some argEntry.line! :: rdeps
let (bodyEntry?, entries) β
explodeCore body (if start then depth else depth + 1) entries'
rdeps := consDep bodyEntry? rdeps
let (entry, entries) := entries.add e
{ type := β addMessageContext <| β Meta.inferType e
depth := depth
status := Status.lam
thm := "βI" -- TODO use "βI" if it's purely implications?
deps := rdeps.reverse
useAsDep := true }
return (entry, entries)
| .app .. => do
trace[explode] ".app"
-- We want to represent entire applications as a single line in the table
let fn := e.getAppFn
let args := e.getAppArgs
-- If the function is a `const`, then it's not local so we do not need an
-- entry in the table for it. We store the theorem name in the `thm` field
-- below, giving access to the theorem's type on hover in the UI.
-- Whether to include the entry could be controlled by a configuration option.
let (fnEntry?, entries) β
if fn.isConst then
pure (none, entries)
else
explodeCore fn depth entries
let deps := if fn.isConst then [] else consDep fnEntry? []
let mut entries' := entries
let mut rdeps := []
for arg in args do
let (appEntry?, entries'') β explodeCore arg depth entries'
entries' := entries''
rdeps := consDep appEntry? rdeps
let deps := deps ++ rdeps.reverse
let (entry, entries) := entries'.add e
{ type := β addMessageContext <| β Meta.inferType e
depth := depth
status := Status.reg
thm := β addMessageContext <| if fn.isConst then MessageData.ofConst fn else "βE"
deps := deps
useAsDep := true }
return (entry, entries)
| .letE varName varType val body _ => do
trace[explode] ".letE"
let varType := varType.cleanupAnnotations
Meta.withLocalDeclD varName varType fun var => do
let (valEntry?, entries) β explodeCore val depth entries
-- Add a synonym so that the substituted fvars refer to `valEntry?`
let entries := valEntry?.map (entries.addSynonym var) |>.getD entries
explodeCore (body.instantiate1 var) depth entries
| _ => do
-- Right now all of these are caught by this case case:
-- Expr.lit, Expr.forallE, Expr.const, Expr.sort, Expr.mvar, Expr.fvar, Expr.bvar
-- (Note: Expr.mdata is stripped by cleanupAnnotations)
-- Might be good to handle them individually.
trace[explode] ".{e.ctorName} (default handler)"
let (entry, entries) := entries.add e
{ type := β addMessageContext <| β Meta.inferType e
depth := depth
status := Status.reg
thm := β addMessageContext e
deps := []
useAsDep := β select e }
return (entry, entries)
where
/-- Prepend the `line` of the `Entry` to `deps` if it's not `none`, but if the entry isn't marked
with `useAsDep` then it's not added to the list at all. -/
consDep (entry? : Option Entry) (deps : List (Option Nat)) : List (Option Nat) :=
if let some entry := entry? then
if includeAllDeps || entry.useAsDep then entry.line! :: deps else deps
else
deps
/-- Main definition behind `#explode` command. -/
def explode (e : Expr) (filterProofs : Bool := true) : MetaM Entries := do
let filter (e : Expr) : MetaM Bool :=
if filterProofs then Meta.isProof e else return true
let (_, entries) β explodeCore (start := true) filter false e 0 default
return entries
open Elab in
/--
`#explode expr` displays a proof term in a line-by-line format somewhat akin to a Fitch-style
proof or the Metamath proof style.
For example, exploding the following theorem:
```lean
#explode iff_of_true
```
produces:
```lean
iff_of_true : β {a b : Prop}, a β b β (a β b)
0β β a β Prop
1β β b β Prop
2β β ha β a
3β β hb β b
4β β xβ β β a
5β4,3 β βI β a β b
6β β xβ β β b
7β6,2 β βI β b β a
8β5,7 β Iff.intro β a β b
9β0,1,2,3,8β βI β β {a b : Prop}, a β b β (a β b)
```
## Overview
The `#explode` command takes the body of the theorem and decomposes it into its parts,
displaying each expression constructor one at a time. The constructor is indicated
in some way in column 3, and its dependencies are recorded in column 2.
These are the main constructor types:
- Lambda expressions (`Expr.lam`). The expression `fun (h : p) => s` is displayed as
```lean
0β β h β β p
1β** β ** β β q
2β1,2 β βI β β (h : p), q
```
with `**` a wildcard, and there can be intervening steps between 0 and 1.
Nested lambda expressions can be merged, and `βI` can depend on a whole list of arguments.
- Applications (`Expr.app`). The expression `f a b c` is displayed as
```lean
0β** β f β A β B β C β D
1β** β a β A
2β** β b β B
3β** β c β C
1β0,1,2,3 β βE β D
```
There can be intervening steps between each of these.
As a special case, if `f` is a constant it can be omitted and the display instead looks like
```lean
0β** β a β A
1β** β b β B
2β** β c β C
3β1,2,3 β f β D
```
- Let expressions (`Expr.letE`) do not display in any special way, but they do
ensure that in `let x := v; b` that `v` is processed first and then `b`, rather
than first doing zeta reduction. This keeps lambda merging and application merging
from making proofs with `let` confusing to interpret.
- Everything else (constants, fvars, etc.) display `x : X` as
```lean
0β β x β X
```
## In more detail
The output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath
proof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are
"Step", "Hyp", "Ref", "Type" (or "Expression" in the case of Metamath):
* **Step**: An increasing sequence of numbers for each row in the proof, used in the Hyp fields.
* **Hyp**: The direct children of the current step. These are step numbers for the subexpressions
for this step's expression. For theorem applications, it's the theorem arguments, and for
foralls it is all the bound variables and the conclusion.
* **Ref**: The name of the theorem being applied. This is well-defined in Metamath, but in Lean
there are some special steps that may have long names because the structure of proof terms doesn't
exactly match this mold.
* If the theorem is `foo (x y : Z) : A x -> B y -> C x y`:
* the Ref field will contain `foo`,
* `x` and `y` will be suppressed, because term construction is not interesting, and
* the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term
like `@foo x y pA pB` where `pA` and `pB` are subproofs.
* In the Hyp column, suppressed terms are omitted, including terms that ought to be
suppressed but are not (in particular lambda arguments).
TODO: implement a configuration option to enable representing suppressed terms using
an `_` rather than a step number.
* If the head of the proof term is a local constant or lambda, then in this case the Ref will
say `βE` for forall-elimination. This happens when you have for example `h : A -> B` and
`ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `βE h ha` where `βE` is
(n-ary) modus ponens.
* If the proof term is a lambda, we will also use `βI` for forall-introduction, referencing the
body of the lambda. The indentation level will increase, and a bracket will surround the proof
of the body of the lambda, starting at a proof step labeled with the name of the lambda variable
and its type, and ending with the `βI` step. Metamath doesn't have steps like this, but the
style is based on Fitch proofs in first-order logic.
* **Type**: This contains the type of the proof term, the theorem being proven at the current step.
Also, it is common for a Lean theorem to begin with a sequence of lambdas introducing local
constants of the theorem. In order to minimize the indentation level, the `βI` steps at the end of
the proof will be introduced in a group and the indentation will stay fixed. (The indentation
brackets are only needed in order to delimit the scope of assumptions, and these assumptions
have global scope anyway so detailed tracking is not necessary.)
-/
elab "#explode " stx:term : command => withoutModifyingEnv <| Command.runTermElabM fun _ => do
let (heading, e) β try
-- Adapted from `#check` implementation
let theoremName : Name β realizeGlobalConstNoOverloadWithInfo stx
addCompletionInfo <| .id stx theoremName (danglingDot := false) {} none
let decl β getConstInfo theoremName
let c : Expr := .const theoremName (decl.levelParams.map mkLevelParam)
pure (m!"{MessageData.ofConst c} : {decl.type}", decl.value!)
catch _ =>
let e β Term.elabTerm stx none
Term.synthesizeSyntheticMVarsNoPostponing
let e β Term.levelMVarToParam (β instantiateMVars e)
pure (m!"{e} : {β Meta.inferType e}", e)
unless e.isSyntheticSorry do
let entries β explode e
let fitchTable : MessageData β entriesToMessageData entries
logInfo <|β addMessageContext m!"{heading}\n\n{fitchTable}\n"
|
Tactic\ExtendDoc.lean | /-
Copyright (c) 2023 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import Lean.Elab.ElabRules
import Lean.DocString
/-!
# `extend_doc` command
In a file where declaration `decl` is defined, writing
```lean
extend_doc decl
before "I will be added as a prefix to the docs of `decl`"
after "I will be added as a suffix to the docs of `decl`"
```
does what is probably clear: it extends the doc-string of `decl` by adding the string of
`before` at the beginning and the string of `after` at the end.
At least one of `before` and `after` must appear, but either one of them is optional.
-/
namespace Mathlib.Tactic.ExtendDocs
/-- `extend_docs <declName> before <prefix_string> after <suffix_string>` extends the
docs of `<declName>` by adding `<prefix_string>` before and `<suffix_string>` after. -/
syntax "extend_docs" ident (colGt &"before" str)? (colGt &"after" str)? : command
open Lean Elab Command in
elab_rules : command
| `(command| extend_docs $na:ident $[before $bef:str]? $[after $aft:str]?) => do
if bef.isNone && aft.isNone then throwError "expected at least one of 'before' or 'after'"
let declName β liftCoreM <| Elab.realizeGlobalConstNoOverloadWithInfo na
let bef := if bef.isNone then "" else (bef.get!).getString ++ "\n\n"
let aft := if aft.isNone then "" else "\n\n" ++ (aft.get!).getString
let oldDoc := (β findDocString? (β getEnv) declName).getD ""
addDocString declName <| bef ++ oldDoc ++ aft
end Mathlib.Tactic.ExtendDocs
|
Tactic\ExtractGoal.lean | /-
Copyright (c) 2017 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Kyle Miller, Damiano Testa
-/
import Lean.Elab.Tactic.ElabTerm
import Lean.Meta.Tactic.Cleanup
import Lean.PrettyPrinter
import Batteries.Lean.Meta.Inaccessible
/-!
# `extract_goal`: Format the current goal as a stand-alone example
Useful for testing tactics or creating
[minimal working examples](https://leanprover-community.github.io/mwe.html).
```lean
example (i j k : Nat) (hβ : i β€ j) (hβ : j β€ k) : i β€ k := by
extract_goal
/-
theorem extracted_1 (i j k : Nat) (hβ : i β€ j) (hβ : j β€ k) : i β€ k := sorry
-/
```
* TODO: Add tactic code actions?
* Output may produce lines with more than 100 characters
### Caveat
Tl;dr: sometimes, using `set_option [your pp option] in extract_goal` may work where `extract_goal`
does not.
The extracted goal may depend on imports and `pp` options, since it relies on delaboration.
For this reason, the extracted goal may not be equivalent to the given goal.
However, the tactic responds to pretty printing options.
For example, calling `set_option pp.all true in extract_goal` in the examples below actually works.
```lean
-- `theorem int_eq_nat` is the output of the `extract_goal` from the example below
-- the type ascription is removed and the `β` is replaced by `Int.ofNat`:
-- Lean infers the correct (false) statement
theorem int_eq_nat {z : Int} : β n, Int.ofNat n = z := sorry
example {z : Int} : β n : Nat, βn = z := by
extract_goal -- produces `int_eq_nat`
apply int_eq_nat -- works
```
However, importing `Batteries.Classes.Cast`, makes `extract_goal` produce a different theorem
```lean
import Batteries.Classes.Cast
-- `theorem extracted_1` is the output of the `extract_goal` from the example below
-- the type ascription is erased and the `β` is untouched:
-- Lean infers a different statement, since it fills in `β` with `id` and uses `n : Int`
theorem extracted_1 {z : Int} : β n, βn = z := β¨_, rflβ©
example {z : Int} : β n : Nat, βn = z := by
extract_goal
apply extracted_1
/-
tactic 'apply' failed, failed to unify
β n, n = ?z
with
β n, βn = z
z: Int
β’ β n, βn = z
-/
```
Similarly, the extracted goal may fail to type-check:
```lean
example (a : Ξ±) : β f : Ξ± β Ξ±, f a = a := by
extract_goal
exact β¨id, rflβ©
theorem extracted_1.{u_1} {Ξ± : Sort u_1} (a : Ξ±) : β f, f a = a := sorry
-- `f` is uninterpreted: `β’ β f, sorryAx Ξ± true = a`
```
and also
```lean
import Mathlib.Algebra.Polynomial.Basic
-- The `extract_goal` below produces this statement:
theorem extracted_1 : X = X := sorry
-- Yet, Lean is unable to figure out what is the coefficients Semiring for `X`
/-
typeclass instance problem is stuck, it is often due to metavariables
Semiring ?m.28495
-/
example : (X : Nat[X]) = X := by
extract_goal
```
-/
namespace Mathlib.Tactic.ExtractGoal
open Lean Elab Tactic Meta
/-- Have `extract_goal` extract the full local context. -/
syntax star := "*"
/-- Configuration for `extract_goal` for which variables from the context to include. -/
syntax config := star <|> (colGt ppSpace ident)*
/--
- `extract_goal` formats the current goal as a stand-alone theorem or definition after
cleaning up the local context of irrelevant variables.
A variable is *relevant* if (1) it occurs in the target type, (2) there is a relevant variable
that depends on it, or (3) the type of the variable is a proposition that depends on a
relevant variable.
If the target is `False`, then for convenience `extract_goal` includes all variables.
- `extract_goal *` formats the current goal without cleaning up the local context.
- `extract_goal a b c ...` formats the current goal after removing everything that the given
variables `a`, `b`, `c`, ... do not depend on.
- `extract_goal ... using name` uses the name `name` for the theorem or definition rather than
the autogenerated name.
The tactic tries to produce an output that can be copy-pasted and just work,
but its success depends on whether the expressions are amenable
to being unambiguously pretty printed.
The tactic responds to pretty printing options.
For example, `set_option pp.all true in extract_goal` gives the `pp.all` form.
-/
syntax (name := extractGoal) "extract_goal" config (" using " ident)? : tactic
elab_rules : tactic
| `(tactic| extract_goal $cfg:config $[using $name?]?) => do
let name β if let some name := name?
then pure name.getId
else mkAuxName ((β getCurrNamespace) ++ `extracted) 1
let msg β withoutModifyingEnv <| withoutModifyingState do
let g β getMainGoal
let g β do match cfg with
| `(config| *) => pure g
| `(config| ) =>
if (β g.getType >>= instantiateMVars).consumeMData.isConstOf ``False then
-- In a contradiction proof, it is not very helpful to clear all hypotheses!
pure g
else
g.cleanup
| `(config| $fvars:ident*) =>
-- Note: `getFVarIds` does `withMainContext`
g.cleanup (toPreserve := (β getFVarIds fvars)) (indirectProps := false)
| _ => throwUnsupportedSyntax
let (g, _) β g.renameInaccessibleFVars
let (_, g) β g.revert (clearAuxDeclsInsteadOfRevert := true) (β g.getDecl).lctx.getFVarIds
let ty β instantiateMVars (β g.getType)
if ty.hasExprMVar then
-- TODO: turn metavariables into new hypotheses?
throwError "Extracted goal has metavariables: {ty}"
let ty β Term.levelMVarToParam ty
let seenLevels := collectLevelParams {} ty
let levels := (β Term.getLevelNames).filter
fun u => seenLevels.visitedLevel.contains (.param u)
addAndCompile <| Declaration.axiomDecl
{ name := name
levelParams := levels
isUnsafe := false
type := ty }
let sig β addMessageContext <| MessageData.signature name
let cmd := if β Meta.isProp ty then "theorem" else "def"
pure m!"{cmd} {sig} := sorry"
logInfo msg
|
Tactic\ExtractLets.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Lean.Expr.Basic
import Mathlib.Tactic.Basic
/-!
# The `extract_lets at` tactic
This module defines a tactic `extract_lets ... at h` that can be used to (in essence) do `cases`
on a `let` expression.
-/
open Lean Elab Parser Meta Tactic
/-- Given a local hypothesis whose type is a `let` expression, then lift the `let` bindings to be
a new local definition. -/
def Lean.MVarId.extractLetsAt (mvarId : MVarId) (fvarId : FVarId) (names : Array Name) :
MetaM (Array FVarId Γ MVarId) := do
mvarId.checkNotAssigned `extractLetsAt
mvarId.withReverted #[fvarId] fun mvarId fvarIds => mvarId.withContext do
let mut mvarId := mvarId
let mut fvarIds' := #[]
for name in names do
let ty β Lean.instantiateMVars (β mvarId.getType)
mvarId β match ty with
| .letE n t v b ndep => process mvarId t (.letE n Β· v b ndep)
| .forallE n t v b => process mvarId t (.forallE n Β· v b)
| _ => throwTacticEx `extractLetsAt mvarId "unexpected auxiliary target"
let (fvarId', mvarId') β mvarId.intro name
fvarIds' := fvarIds'.push fvarId'
mvarId := mvarId'
return (fvarIds', fvarIds.map .some, mvarId)
where
/-- Check that `t` is a `let` and then do what's necessary to lift it over the binding
described by `mk`. -/
process (mvarId : MVarId) (t : Expr) (mk : Expr β Expr) : MetaM MVarId := do
let .letE n' t' v' b' _ := t.cleanupAnnotations
| throwTacticEx `extractLetsAt mvarId "insufficient number of `let` expressions"
-- Lift the let
withLetDecl n' t' v' fun fvar => do
let b' := b'.instantiate1 fvar
let ty' β mkLetFVars (usedLetOnly := false) #[fvar] <| mk b'
mvarId.change ty'
/-- A more limited version of `Lean.MVarId.introN` that ensures the goal is a
nested `let` expression. -/
def Lean.MVarId.extractLets (mvarId : MVarId) (names : Array Name) :
MetaM (Array FVarId Γ MVarId) :=
mvarId.withContext do
let ty := (β Lean.instantiateMVars (β mvarId.getType)).cleanupAnnotations
if ty.letDepth < names.size then
throwTacticEx `extractLets mvarId "insufficient number of `let` expressions"
mvarId.introN names.size names.toList
namespace Mathlib
/-- The `extract_lets at h` tactic takes a local hypothesis of the form `h : let x := v; b`
and introduces a new local definition `x := v` while changing `h` to be `h : b`. It can be thought
of as being a `cases` tactic for `let` expressions. It can also be thought of as being like
`intros at h` for `let` expressions.
For example, if `h : let x := 1; x = x`, then `extract_lets x at h` introduces `x : Nat := 1` and
changes `h` to `h : x = x`.
Just like `intros`, the `extract_lets` tactic either takes a list of names, in which case
that specifies the number of `let` bindings that must be extracted, or it takes no names, in which
case all the `let` bindings are extracted.
The tactic `extract_lets` (without `at`) or `extract_lets at h β’` acts as a weaker
form of `intros` on the goal that only introduces obvious `let`s. -/
syntax (name := extractLets) "extract_lets " (colGt (ident <|> hole))* (ppSpace location)? : tactic
@[tactic Mathlib.extractLets, inherit_doc extractLets]
def evalExtractLets : Tactic := fun stx => do
match stx with
| `(tactic| extract_lets) => doExtract none none
| `(tactic| extract_lets $hs*) => doExtract hs none
| `(tactic| extract_lets $loc:location) => doExtract none loc
| `(tactic| extract_lets $hs* $loc:location) => doExtract hs loc
| _ => throwUnsupportedSyntax
where
@[nolint docBlame]
setupNames (ids? : Option (TSyntaxArray [`ident, `Lean.Parser.Term.hole])) (ty : Expr) :
MetaM (Array Name) := do
if let some ids := ids? then
return ids.map getNameOfIdent'
else
return Array.mkArray (β instantiateMVars ty).cleanupAnnotations.letDepth `_
@[nolint docBlame]
doExtract (ids? : Option (TSyntaxArray [`ident, `Lean.Parser.Term.hole]))
(loc? : Option <| TSyntax `Lean.Parser.Tactic.location) :
TacticM Unit := do
let process (f : MVarId β Array Name β MetaM (Array FVarId Γ MVarId))
(ty : MVarId β MetaM Expr) : TacticM Unit := do
let fvarIds β liftMetaTacticAux fun mvarId => do
let ids β setupNames ids? (β ty mvarId)
let (fvarIds, mvarId) β f mvarId ids
return (fvarIds, [mvarId])
if let some ids := ids? then
withMainContext do
for stx in ids, fvarId in fvarIds do
Term.addLocalVarInfo stx (.fvar fvarId)
withLocation (expandOptLocation (mkOptionalNode loc?))
(atLocal := fun h β¦ do
process (fun mvarId ids => mvarId.extractLetsAt h ids) (fun _ => h.getType))
(atTarget := do
process (fun mvarId ids => mvarId.extractLets ids) (fun mvarId => mvarId.getType))
(failed := fun _ β¦ throwError "extract_lets tactic failed")
end Mathlib
|
Tactic\FailIfNoProgress.lean | /-
Copyright (c) 2023 Thomas Murrills. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Murrills
-/
import Lean.Elab.Tactic.Basic
import Lean.Meta.Tactic.Util
/-!
# Fail if no progress
This implements the `fail_if_no_progress` tactic, which fails if no actual progress is made by the
following tactic sequence.
"Actual progress" means that either the number of goals has changed, that the
number or presence of expressions in the context has changed, or that the type of some expression
in the context or the type of the goal is no longer definitionally equal to what it used to be at
reducible transparency.
This means that, for example, `1 - 1` changing to `0` does not count as actual progress, since
```lean
example : (1 - 1 = 0) := by with_reducible rfl
```
This tactic is useful in situations where we want to stop iterating some tactics if they're not
having any effect, e.g. `repeat (fail_if_no_progress simp <;> ring_nf)`.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic
/-- `fail_if_no_progress tacs` evaluates `tacs`, and fails if no progress is made on the main goal
or the local context at reducible transparency. -/
syntax (name := failIfNoProgress) "fail_if_no_progress " tacticSeq : tactic
/-- `lctxIsDefEq lβ lβ` compares two lists of `Option LocalDecl`s (as returned from e.g.
`(β (β getMainGoal).getDecl).lctx.decls.toList`). It returns `true` if they have the same
local declarations in the same order (up to defeq, without setting mvars), and `false` otherwise.
Assumption: this function is run with one of the local contexts as the current `MetaM` local
context, and one of the two lists consists of the `LocalDecl`s of that context. -/
def lctxIsDefEq : (lβ lβ : List (Option LocalDecl)) β MetaM Bool
| none :: lβ, lβ => lctxIsDefEq lβ lβ
| lβ, none :: lβ => lctxIsDefEq lβ lβ
| some dβ :: lβ, some dβ :: lβ => do
unless dβ.isLet == dβ.isLet do
return false
unless dβ.fvarId == dβ.fvarId do
-- Without compatible fvarids, `isDefEq` checks for later entries will not make sense
return false
unless (β withNewMCtxDepth <| isDefEq dβ.type dβ.type) do
return false
if dβ.isLet then
unless (β withNewMCtxDepth <| isDefEq dβ.value dβ.value) do
return false
lctxIsDefEq lβ lβ
| [], [] => return true
| _, _ => return false
/-- Run `tacs : TacticM Unit` on `goal`, and fail if no progress is made. -/
def runAndFailIfNoProgress (goal : MVarId) (tacs : TacticM Unit) : TacticM (List MVarId) := do
let l β run goal tacs
try
let [newGoal] := l | failure
goal.withContext do
-- Check that the local contexts are compatible
let ctxDecls := (β goal.getDecl).lctx.decls.toList
let newCtxDecls := (β newGoal.getDecl).lctx.decls.toList
guard <|β withNewMCtxDepth <| withReducible <| lctxIsDefEq ctxDecls newCtxDecls
-- They are compatible, so now we can check that the goals are equivalent
guard <|β withNewMCtxDepth <| withReducible <| isDefEq (β newGoal.getType) (β goal.getType)
catch _ =>
return l
throwError "no progress made on\n{goal}"
elab_rules : tactic
| `(tactic| fail_if_no_progress $tacs) => do
let goal β getMainGoal
let l β runAndFailIfNoProgress goal (evalTactic tacs)
replaceMainGoal l
|
Tactic\FBinop.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Tactic.ToExpr
/-! # Elaborator for functorial binary operators
`fbinop% f x y` elaborates `f x y` for `x : S Ξ±` and `y : S' Ξ²`, taking into account
any coercions that the "functors" `S` and `S'` possess.
While `binop%` tries to solve for a single minimal type, `fbinop%` tries to solve
the parameterized problem of solving for a single minimal "functor."
The code is drawn from the Lean 4 core `binop%` elaborator. Two simplifications made were
1. It is assumed that every `f` has a "homogeneous" instance
(think `Set.prod : Set Ξ± β Set Ξ² β Set (Ξ± Γ Ξ²)`).
2. It is assumed that there are no "non-homogeneous" default instances.
It also makes the assumption that the binop wants to be as homogeneous as possible.
For example, when the type of an argument is unknown it will try to unify the argument's type
with `S _`, which can help certain elaboration problems proceed (like for `{a,b,c}` notation).
The main goal is to support generic set product notation and have it elaborate in a convenient way.
-/
namespace FBinopElab
open Lean Elab Term Meta
initialize registerTraceClass `Elab.fbinop
/-- `fbinop% f x y` elaborates `f x y` for `x : S Ξ±` and `y : S' Ξ²`, taking into account
any coercions that the "functors" `S` and `S'` possess. -/
syntax:max (name := prodSyntax) "fbinop% " ident ppSpace term:max ppSpace term:max : term
/-- Tree recording the structure of the `fbinop%` expression. -/
private inductive Tree where
/-- Leaf of the tree. Stores the generated `InfoTree` from elaborating `val`. -/
| term (ref : Syntax) (infoTrees : PersistentArray InfoTree) (val : Expr)
/-- An `fbinop%` node.
`ref` is the original syntax that expanded into `binop%`.
`f` is the constant for the binary operator -/
| binop (ref : Syntax) (f : Expr) (lhs rhs : Tree)
/-- Store macro expansion information to make sure that "go to definition" behaves
similarly to notation defined without using `fbinop%`. -/
| macroExpansion (macroName : Name) (stx stx' : Syntax) (nested : Tree)
private partial def toTree (s : Syntax) : TermElabM Tree := do
let result β go s
synthesizeSyntheticMVars (postpone := .yes)
return result
where
go (s : Syntax) : TermElabM Tree := do
match s with
| `(fbinop% $f $lhs $rhs) => processBinOp s f lhs rhs
| `(($e)) =>
if hasCDot e then
processLeaf s
else
go e
| _ =>
withRef s do
match β liftMacroM <| expandMacroImpl? (β getEnv) s with
| some (macroName, s?) =>
let s' β liftMacroM <| liftExcept s?
withPushMacroExpansionStack s s' do
return .macroExpansion macroName s s' (β go s')
| none => processLeaf s
processBinOp (ref : Syntax) (f lhs rhs : Syntax) := do
let some f β resolveId? f | throwUnknownConstant f.getId
return .binop ref f (β go lhs) (β go rhs)
processLeaf (s : Syntax) := do
let e β elabTerm s none
let info β getResetInfoTrees
return .term s info e
/-- Records a "functor", which is some function `Type u β Type v`. We only
allow `c a1 ... an` for `c` a constant. This is so we can abstract out the universe variables. -/
structure SRec where
name : Name
args : Array Expr
deriving Inhabited, ToExpr
/-- Given a type expression, try to remove the last argument(s) and create an `SRec` for the
underlying "functor". Only applies to function applications with a constant head, and,
after dropping all instance arguments, it requires that the remaining last argument be a type.
Returns the `SRec` and the argument. -/
private partial def extractS (e : Expr) : TermElabM (Option (SRec Γ Expr)) :=
match e with
| .letE .. => extractS (e.letBody!.instantiate1 e.letValue!)
| .mdata _ b => extractS b
| .app .. => do
let f := e.getAppFn
let .const n _ := f | return none
let mut args := e.getAppArgs
let mut info := (β getFunInfoNArgs f args.size).paramInfo
for _ in [0 : args.size - 1] do
if info.back.isInstImplicit then
args := args.pop
info := info.pop
else
break
let x := args.back
unless β Meta.isType x do return none
return some ({name := n, args := args.pop}, x)
| _ => return none
/-- Computes `S x := c a1 ... an x` if it is type correct.
Inserts instance arguments after `x`. -/
private def applyS (S : SRec) (x : Expr) : TermElabM (Option Expr) :=
try
let f β mkConstWithFreshMVarLevels S.name
let v β elabAppArgs f #[] ((S.args.push x).map .expr)
(expectedType? := none) (explicit := true) (ellipsis := false)
-- Now elaborate any remaining instance arguments
elabAppArgs v #[] #[] (expectedType? := none) (explicit := false) (ellipsis := false)
catch _ =>
return none
/-- For a given argument `x`, checks if there is a coercion from `fromS x` to `toS x`
if these expressions are type correct. -/
private def hasCoeS (fromS toS : SRec) (x : Expr) : TermElabM Bool := do
let some fromType β applyS fromS x | return false
let some toType β applyS toS x | return false
trace[Elab.fbinop] m!"fromType = {fromType}, toType = {toType}"
withLocalDeclD `v fromType fun v => do
match β coerceSimple? v toType with
| .some _ => return true
| .none => return false
| .undef => return false -- TODO: should we do something smarter here?
/-- Result returned by `analyze`. -/
private structure AnalyzeResult where
maxS? : Option SRec := none
/-- `true` if there are two types `Ξ±` and `Ξ²` where we don't have coercions in any direction. -/
hasUncomparable : Bool := false
/-- Compute a minimal `SRec` for an expression tree. -/
private def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do
let maxS? β
match expectedType? with
| none => pure none
| some expectedType =>
let expectedType β instantiateMVars expectedType
if let some (S, _) β extractS expectedType then
pure S
else
pure none
(go t *> get).run' { maxS? }
where
go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do
unless (β get).hasUncomparable do
match t with
| .macroExpansion _ _ _ nested => go nested
| .binop _ _ lhs rhs => go lhs; go rhs
| .term _ _ val =>
let type β instantiateMVars (β inferType val)
let some (S, x) β extractS type
| return -- Rather than marking as incomparable, let's hope there's a coercion!
match (β get).maxS? with
| none => modify fun s => { s with maxS? := S }
| some maxS =>
let some maxSx β applyS maxS x | return -- Same here.
unless β withNewMCtxDepth <| isDefEqGuarded maxSx type do
if β hasCoeS S maxS x then
return ()
else if β hasCoeS maxS S x then
modify fun s => { s with maxS? := S }
else
trace[Elab.fbinop] "uncomparable types: {maxSx}, {type}"
modify fun s => { s with hasUncomparable := true }
private def mkBinOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr := do
elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none)
(explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)
/-- Turn a tree back into an expression. -/
private def toExprCore (t : Tree) : TermElabM Expr := do
match t with
| .term _ trees e =>
modifyInfoState (fun s => { s with trees := s.trees ++ trees }); return e
| .binop ref f lhs rhs =>
withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo .anonymous ref) do
let lhs β toExprCore lhs
let mut rhs β toExprCore rhs
mkBinOp f lhs rhs
| .macroExpansion macroName stx stx' nested =>
withRef stx <| withInfoContext' stx (mkInfo := mkTermInfo macroName stx) do
withMacroExpansion stx stx' do
toExprCore nested
/-- Try to coerce elements in the tree to `maxS` when needed. -/
private def applyCoe (t : Tree) (maxS : SRec) : TermElabM Tree := do
go t none
where
go (t : Tree) (f? : Option Expr) : TermElabM Tree := do
match t with
| .binop ref f lhs rhs =>
let lhs' β go lhs f
let rhs' β go rhs f
return .binop ref f lhs' rhs'
| .term ref trees e =>
let type β instantiateMVars (β inferType e)
trace[Elab.fbinop] "visiting {e} : {type}"
let some (_, x) β extractS type
| -- We want our operators to be "homogenous" so do a defeq check as an elaboration hint
let x' β mkFreshExprMVar none
let some maxType β applyS maxS x' | trace[Elab.fbinop] "mvar apply failed"; return t
trace[Elab.fbinop] "defeq hint {maxType} =?= {type}"
_ β isDefEqGuarded maxType type
return t
let some maxType β applyS maxS x
| trace[Elab.fbinop] "applying {Lean.toExpr maxS} {x} failed"
return t
trace[Elab.fbinop] "{type} =?= {maxType}"
if β isDefEqGuarded maxType type then
return t
else
trace[Elab.fbinop] "added coercion: {e} : {type} => {maxType}"
withRef ref <| return .term ref trees (β mkCoe maxType e)
| .macroExpansion macroName stx stx' nested =>
withRef stx <| withPushMacroExpansionStack stx stx' do
return .macroExpansion macroName stx stx' (β go nested f?)
private def toExpr (tree : Tree) (expectedType? : Option Expr) : TermElabM Expr := do
let r β analyze tree expectedType?
trace[Elab.fbinop] "hasUncomparable: {r.hasUncomparable}, maxType: {Lean.toExpr r.maxS?}"
if r.hasUncomparable || r.maxS?.isNone then
let result β toExprCore tree
ensureHasType expectedType? result
else
let result β toExprCore (β applyCoe tree r.maxS?.get!)
trace[Elab.fbinop] "result: {result}"
ensureHasType expectedType? result
@[term_elab prodSyntax]
def elabBinOp : TermElab := fun stx expectedType? => do
toExpr (β toTree stx) expectedType?
end FBinopElab
|
Tactic\FieldSimp.lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel, David Renshaw
-/
import Lean.Elab.Tactic.Basic
import Lean.Meta.Tactic.Simp.Main
import Mathlib.Algebra.Group.Units
import Mathlib.Tactic.Positivity.Core
import Mathlib.Tactic.NormNum.Core
import Mathlib.Util.DischargerAsTactic
import Qq
/-!
# `field_simp` tactic
Tactic to clear denominators in algebraic expressions, based on `simp` with a specific simpset.
-/
namespace Mathlib.Tactic.FieldSimp
open Lean Elab.Tactic Parser.Tactic Lean.Meta
open Qq
initialize registerTraceClass `Tactic.field_simp
/-- Constructs a trace message for the `discharge` function. -/
private def dischargerTraceMessage {Ξ΅ : Type*} (prop: Expr) :
Except Ξ΅ (Option Expr) β SimpM MessageData
| .error _ | .ok none => return m!"{crossEmoji} discharge {prop}"
| .ok (some _) => return m!"{checkEmoji} discharge {prop}"
open private Simp.dischargeUsingAssumption? from Lean.Meta.Tactic.Simp.Rewrite
/-- Discharge strategy for the `field_simp` tactic. -/
partial def discharge (prop : Expr) : SimpM (Option Expr) :=
withTraceNode `Tactic.field_simp (dischargerTraceMessage prop) do
-- Discharge strategy 1: Use assumptions
if let some r β Simp.dischargeUsingAssumption? prop then
return some r
-- Discharge strategy 2: Normalize inequalities using NormNum
let prop : Q(Prop) β (do pure prop)
let pf? β match prop with
| ~q(($e : $Ξ±) β $b) =>
try
let res β Mathlib.Meta.NormNum.derive (Ξ± := (q(Prop) : Q(Type))) prop
match res with
| .isTrue pf => pure (some pf)
| _ => pure none
catch _ =>
pure none
| _ => pure none
if let some pf := pf? then return some pf
-- Discharge strategy 3: Use positivity
let pf? β
try some <$> Mathlib.Meta.Positivity.solve prop
catch _ => pure none
if let some pf := pf? then return some pf
-- Discharge strategy 4: Use the simplifier
let ctx β readThe Simp.Context
let stats : Simp.Stats := { (β get) with }
-- Porting note: mathlib3's analogous field_simp discharger `field_simp.ne_zero`
-- does not explicitly call `simp` recursively like this. It's unclear to me
-- whether this is because
-- 1) Lean 3 simp dischargers automatically call `simp` recursively. (Do they?),
-- 2) mathlib3 norm_num1 is able to handle any needed discharging, or
-- 3) some other reason?
let β¨simpResult, stats'β© β
simp prop { ctx with dischargeDepth := ctx.dischargeDepth + 1 } #[(β Simp.getSimprocs)]
discharge stats
set { (β get) with usedTheorems := stats'.usedTheorems, diag := stats'.diag }
if simpResult.expr.isConstOf ``True then
try
return some (β mkOfEqTrue (β simpResult.getProof))
catch _ =>
return none
else
return none
@[inherit_doc discharge]
elab "field_simp_discharge" : tactic => wrapSimpDischarger Mathlib.Tactic.FieldSimp.discharge
/--
The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d`
where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully
crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by
iterating the following steps:
- write an inverse as a division
- in any product, move the division to the right
- if there are several divisions in a product, group them together at the end and write them as a
single division
- reduce a sum to a common denominator
If the goal is an equality, this simpset will also clear the denominators, so that the proof
can normally be concluded by an application of `ring`.
`field_simp [hx, hy]` is a short form for
`simp (disch := field_simp_discharge) [-one_div, -one_divp, -mul_eq_zero, hx, hy, field_simps]`
Note that this naive algorithm will not try to detect common factors in denominators to reduce the
complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle
complicated expressions in the next step.
As always with the simplifier, reduction steps will only be applied if the preconditions of the
lemmas can be checked. This means that proofs that denominators are nonzero should be included. The
fact that a product is nonzero when all factors are, and that a power of a nonzero number is
nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums)
should be given explicitly. If your expression is not completely reduced by the simplifier
invocation, check the denominators of the resulting expression and provide proofs that they are
nonzero to enable further progress.
To check that denominators are nonzero, `field_simp` will look for facts in the context, and
will try to apply `norm_num` to close numerical goals.
The invocation of `field_simp` removes the lemma `one_div` from the simpset, as this lemma
works against the algorithm explained above. It also removes
`mul_eq_zero : x * y = 0 β x = 0 β¨ y = 0`, as `norm_num` can not work on disjunctions to
close goals of the form `24 β 0`, and replaces it with `mul_ne_zero : x β 0 β y β 0 β x * y β 0`
creating two goals instead of a disjunction.
For example,
```lean
example (a b c d x y : β) (hx : x β 0) (hy : y β 0) :
a + b / x + c / x^2 + d / x^3 = a + xβ»ΒΉ * (y * b / y + (d / x + c) / x) := by
field_simp
ring
```
Moreover, the `field_simp` tactic can also take care of inverses of units in
a general (commutative) monoid/ring and partial division `/β`, see `Algebra.Group.Units`
for the definition. Analogue to the case above, the lemma `one_divp` is removed from the simpset
as this works against the algorithm. If you have objects with an `IsUnit x` instance like
`(x : R) (hx : IsUnit x)`, you should lift them with
`lift x to RΛ£ using id hx; rw [IsUnit.unit_of_val_units] clear hx`
before using `field_simp`.
See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions
that have numerals in denominators.
The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to
entirely remove (numeric) division from the expression by multiplying by a factor.
-/
syntax (name := fieldSimp) "field_simp" (config)? (discharger)? (&" only")?
(simpArgs)? (location)? : tactic
elab_rules : tactic
| `(tactic| field_simp $[$cfg:config]? $[(discharger := $dis)]? $[only%$only?]?
$[$sa:simpArgs]? $[$loc:location]?) => withMainContext do
let cfg β elabSimpConfig (mkOptionalNode cfg) .simp
-- The `field_simp` discharger relies on recursively calling the discharger.
-- Prior to https://github.com/leanprover/lean4/pull/3523,
-- the maxDischargeDepth wasn't actually being checked: now we have to set it higher.
let cfg := { cfg with maxDischargeDepth := max cfg.maxDischargeDepth 7 }
let loc := expandOptLocation (mkOptionalNode loc)
let dis β match dis with
| none => pure discharge
| some d => do
let β¨_, dβ© β tacticToDischarge d
pure d
let thms0 β if only?.isSome then
simpOnlyBuiltins.foldlM (Β·.addConst Β·) ({} : SimpTheorems)
else do
let thms0 β getSimpTheorems
let thms0 β thms0.erase (.decl ``one_div)
let thms0 β thms0.erase (.decl `mul_eq_zero)
thms0.erase (.decl ``one_divp)
let some ext β getSimpExtension? `field_simps | throwError "field_simps not found"
let thms β ext.getTheorems
let ctx : Simp.Context := {
simpTheorems := #[thms, thms0]
congrTheorems := β getSimpCongrTheorems
config := cfg
}
let mut r β elabSimpArgs (sa.getD β¨.missingβ©) ctx (simprocs := {}) (eraseLocal := false) .simp
if r.starArg then
r β do
let ctx := r.ctx
let mut simpTheorems := ctx.simpTheorems
let hs β getPropHyps
for h in hs do
unless simpTheorems.isErased (.fvar h) do
simpTheorems β simpTheorems.addTheorem (.fvar h) (β h.getDecl).toExpr
let ctx := { ctx with simpTheorems }
pure { ctx, simprocs := {} }
_ β simpLocation r.ctx {} dis loc
end FieldSimp
end Tactic
end Mathlib
|
Tactic\FinCases.lean | /-
Copyright (c) 2022 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Hanting Zhang
-/
import Mathlib.Tactic.Core
import Mathlib.Lean.Expr.Basic
import Mathlib.Data.Fintype.Basic
/-!
# The `fin_cases` tactic.
Given a hypothesis of the form `h : x β (A : List Ξ±)`, `x β (A : Finset Ξ±)`,
or `x β (A : Multiset Ξ±)`,
or a hypothesis of the form `h : A`, where `[Fintype A]` is available,
`fin_cases h` will repeatedly call `cases` to split the goal into
separate cases for each possible value.
-/
open Lean.Meta
namespace Lean.Elab.Tactic
/-- If `e` is of the form `x β (A : List Ξ±)`, `x β (A : Finset Ξ±)`, or `x β (A : Multiset Ξ±)`,
return `some Ξ±`, otherwise `none`. -/
def getMemType {m : Type β Type} [Monad m] [MonadError m] (e : Expr) : m (Option Expr) := do
match e.getAppFnArgs with
| (``Membership.mem, #[_, type, _, _, _]) =>
match type.getAppFnArgs with
| (``List, #[Ξ±]) => return Ξ±
| (``Multiset, #[Ξ±]) => return Ξ±
| (``Finset, #[Ξ±]) => return Ξ±
| _ => throwError "Hypothesis must be of type `x β (A : List Ξ±)`, `x β (A : Finset Ξ±)`, \
or `x β (A : Multiset Ξ±)`"
| _ => return none
/--
Recursively runs the `cases` tactic on a hypothesis `h`.
As long as two goals are produced, `cases` is called recursively on the second goal,
and we return a list of the first goals which appeared.
This is useful for hypotheses of the form `h : a β [lβ, lβ, ...]`,
which will be transformed into a sequence of goals with hypotheses `h : a = lβ`, `h : a = lβ`,
and so on.
-/
partial def unfoldCases (g : MVarId) (h : FVarId) : MetaM (List MVarId) := do
let gs β g.cases h
try
let #[gβ, gβ] := gs | throwError "unexpected number of cases"
let gs β unfoldCases gβ.mvarId gβ.fields[2]!.fvarId!
return gβ.mvarId :: gs
catch _ => return []
/-- Implementation of the `fin_cases` tactic. -/
partial def finCasesAt (g : MVarId) (hyp : FVarId) : MetaM (List MVarId) := g.withContext do
let type β hyp.getType >>= instantiateMVars
match β getMemType type with
| some _ => unfoldCases g hyp
| none =>
-- Deal with `x : A`, where `[Fintype A]` is available:
let inst β synthInstance (β mkAppM ``Fintype #[type])
let elems β mkAppOptM ``Fintype.elems #[type, inst]
let t β mkAppM ``Membership.mem #[.fvar hyp, elems]
let v β mkAppOptM ``Fintype.complete #[type, inst, Expr.fvar hyp]
let (fvar, g) β (β g.assert `this t v).intro1P
finCasesAt g fvar
/--
`fin_cases h` performs case analysis on a hypothesis of the form
`h : A`, where `[Fintype A]` is available, or
`h : a β A`, where `A : Finset X`, `A : Multiset X` or `A : List X`.
As an example, in
```
example (f : β β Prop) (p : Fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := by
fin_cases p; simp
all_goals assumption
```
after `fin_cases p; simp`, there are three goals, `f 0`, `f 1`, and `f 2`.
-/
syntax (name := finCases) "fin_cases " ("*" <|> term,+) (" with " term,+)? : tactic
/-!
`fin_cases` used to also have two modifiers, `fin_cases ... with ...` and `fin_cases ... using ...`.
With neither actually used in mathlib, they haven't been re-implemented here.
In case someone finds a need for them, and wants to re-implement, the relevant sections of
the doc-string are preserved here:
---
`fin_cases h with l` takes a list of descriptions for the cases of `h`.
These should be definitionally equal to and in the same order as the
default enumeration of the cases.
For example,
```
example (x y : β) (h : x β [1, 2]) : x = y := by
fin_cases h with 1, 1+1
```
produces two cases: `1 = y` and `1 + 1 = y`.
When using `fin_cases a` on data `a` defined with `let`,
the tactic will not be able to clear the variable `a`,
and will instead produce hypotheses `this : a = ...`.
These hypotheses can be given a name using `fin_cases a using ha`.
For example,
```
example (f : β β Fin 3) : True := by
let a := f 3
fin_cases a using ha
```
produces three goals with hypotheses
`ha : a = 0`, `ha : a = 1`, and `ha : a = 2`.
-/
/- TODO: In mathlib3 we ran `norm_num` when there is no `with` clause. Is this still useful? -/
/- TODO: can we name the cases generated according to their values,
rather than `tail.tail.tail.head`? -/
@[tactic finCases] elab_rules : tactic
| `(tactic| fin_cases $[$hyps:ident],*) => withMainContext <| focus do
for h in hyps do
allGoals <| liftMetaTactic (finCasesAt Β· (β getFVarId h))
end Tactic
end Elab
end Lean
|
Tactic\Find.lean | /-
Copyright (c) 2021 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Batteries.Util.Cache
import Lean.HeadIndex
import Lean.Elab.Command
/-!
# The `#find` command and tactic.
The `#find` command finds definitions & lemmas using pattern matching on the type. For instance:
```lean
#find _ + _ = _ + _
#find ?n + _ = _ + ?n
#find (_ : Nat) + _ = _ + _
#find Nat β Nat
```
Inside tactic proofs, there is a `#find` tactic with the same syntax,
or the `find` tactic which looks for lemmas which are `apply`able against the current goal.
-/
open Lean
open Lean.Meta
open Lean.Elab
open Lean.Elab
open Batteries.Tactic
namespace Mathlib.Tactic.Find
private partial def matchHyps : List Expr β List Expr β List Expr β MetaM Bool
| p::ps, oldHyps, h::newHyps => do
let pt β inferType p
let t β inferType h
if (β isDefEq pt t) then
matchHyps ps [] (oldHyps ++ newHyps)
else
matchHyps (p::ps) (h::oldHyps) newHyps
| [], _, _ => pure true
| _::_, _, [] => pure false
-- from Lean.Server.Completion
private def isBlackListed (declName : Name) : MetaM Bool := do
let env β getEnv
pure <| declName.isInternal
|| isAuxRecursor env declName
|| isNoConfusion env declName
<||> isRec declName
<||> isMatcher declName
initialize findDeclsPerHead : DeclCache (Lean.HashMap HeadIndex (Array Name)) β
DeclCache.mk "#find: init cache" failure {} fun _ c headMap β¦ do
if (β isBlackListed c.name) then
return headMap
-- TODO: this should perhaps use `forallTelescopeReducing` instead,
-- to avoid leaking metavariables.
let (_, _, ty) β forallMetaTelescopeReducing c.type
let head := ty.toHeadIndex
pure <| headMap.insert head (headMap.findD head #[] |>.push c.name)
def findType (t : Expr) : TermElabM Unit := withReducible do
let t β instantiateMVars t
let head := (β forallMetaTelescopeReducing t).2.2.toHeadIndex
let pat β abstractMVars t
let env β getEnv
let mut numFound := 0
for n in (β findDeclsPerHead.get).findD head #[] do
let c := env.find? n |>.get!
let cTy := c.instantiateTypeLevelParams (β mkFreshLevelMVars c.numLevelParams)
let found β forallTelescopeReducing cTy fun cParams cTy' β¦ do
let pat := pat.expr.instantiateLevelParamsArray pat.paramNames
(β mkFreshLevelMVars pat.numMVars).toArray
let (_, _, pat) β lambdaMetaTelescope pat
let (patParams, _, pat) β forallMetaTelescopeReducing pat
isDefEq cTy' pat <&&> matchHyps patParams.toList [] cParams.toList
if found then
numFound := numFound + 1
if numFound > 20 then
logInfo m!"maximum number of search results reached"
break
logInfo m!"{n}: {cTy}"
open Lean.Elab.Command in
/-
The `#find` command finds definitions & lemmas using pattern matching on the type. For instance:
```lean
#find _ + _ = _ + _
#find ?n + _ = _ + ?n
#find (_ : Nat) + _ = _ + _
#find Nat β Nat
```
Inside tactic proofs, the `#find` tactic can be used instead.
There is also the `find` tactic which looks for
lemmas which are `apply`able against the current goal.
-/
elab "#find " t:term : command =>
liftTermElabM do
let t β Term.elabTerm t none
Term.synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true)
findType t
/- (Note that you'll get an error trying to run these here:
``cannot evaluate `[init]` declaration 'findDeclsPerHead' in the same module``
but they will work fine in a new file!) -/
-- #find _ + _ = _ + _
-- #find _ + _ = _ + _
-- #find ?n + _ = _ + ?n
-- #find (_ : Nat) + _ = _ + _
-- #find Nat β Nat
-- #find ?n β€ ?m β ?n + _ β€ ?m + _
open Lean.Elab.Tactic
/-
Display theorems (and definitions) whose result type matches the current goal,
i.e. which should be `apply`able.
```lean
example : True := by find
```
`find` will not affect the goal by itself and should be removed from the finished proof.
For a command that takes the type to search for as an argument,
see `#find`, which is also available as a tactic.
-/
elab "find" : tactic => do
findType (β getMainTarget)
/-
Tactic version of the `#find` command.
See also the `find` tactic to search for theorems matching the current goal.
-/
elab "#find " t:term : tactic => do
let t β Term.elabTerm t none
Term.synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true)
findType t
|
Tactic\FunProp.lean | import Mathlib.Tactic.FunProp.Attr
import Mathlib.Tactic.FunProp.Core
import Mathlib.Tactic.FunProp.Decl
import Mathlib.Tactic.FunProp.Elab
import Mathlib.Tactic.FunProp.FunctionData
import Mathlib.Tactic.FunProp.Mor
import Mathlib.Tactic.FunProp.RefinedDiscrTree
import Mathlib.Tactic.FunProp.StateList
import Mathlib.Tactic.FunProp.Theorems
import Mathlib.Tactic.FunProp.ToBatteries
import Mathlib.Tactic.FunProp.Types
|
Tactic\GCongr.lean | /-
Copyright (c) 2023 Mario Carneiro, Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Heather Macbeth
-/
import Mathlib.Tactic.Positivity.Core
import Mathlib.Tactic.GCongr.Core
/-! # Setup for the `gcongr` tactic
The core implementation of the `gcongr` ("generalized congruence") tactic is in the file
`Tactic.GCongr.Core`. In this file we set it up for use across the library by listing
`positivity` as a first-pass discharger for side goals (`gcongr_discharger`). -/
macro_rules | `(tactic| gcongr_discharger) => `(tactic| positivity)
|
Tactic\Generalize.lean | /-
Copyright (c) 2024 Lean FRO, LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Lean.Elab.Binders
import Lean.Elab.Tactic.ElabTerm
import Lean.Meta.Tactic.Generalize
/-!
# Backwards compatibility shim for `generalize`.
In https://github.com/leanprover/lean4/pull/3575 the transparency setting for `generalize` was
changed to `instances`. This file provides a shim for the old setting, so that users who
haven't updated their code yet can still use `generalize` with the old setting.
This file can be removed once all uses of the compatibility shim have been removed from Mathlib.
(Possibly we will instead add a `transparency` argument to `generalize`.
This would also allow removing this file.
-/
open Lean Elab Tactic Meta in
/-- Backwards compatibility shim for `generalize`. -/
elab "generalize'" h:ident " : " t:term:51 " = " x:ident : tactic => do
withMainContext do
let mut xIdents := #[]
let mut hIdents := #[]
let mut args := #[]
hIdents := hIdents.push h
let expr β elabTerm t none
xIdents := xIdents.push x
args := args.push { hName? := h.getId, expr, xName? := x.getId : GeneralizeArg }
let hyps := #[]
let mvarId β getMainGoal
mvarId.withContext do
let (_, newVars, mvarId) β mvarId.generalizeHyp args hyps (transparency := default)
mvarId.withContext do
for v in newVars, id in xIdents ++ hIdents do
Term.addLocalVarInfo id (.fvar v)
replaceMainGoal [mvarId]
|
Tactic\GeneralizeProofs.lean | /-
Copyright (c) 2022 Alex J. Best. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex J. Best, Kyle Miller
-/
import Lean.Elab.Tactic.Config
import Lean.Elab.Tactic.Location
import Mathlib.Lean.Expr.Basic
/-!
# The `generalize_proofs` tactic
Generalize any proofs occurring in the goal or in chosen hypotheses,
replacing them by local hypotheses.
When these hypotheses are named, this makes it easy to refer to these proofs later in a proof,
commonly useful when dealing with functions like `Classical.choose` that produce data from proofs.
It is also useful to eliminate proof terms to handle issues with dependent types.
For example:
```lean
example : List.nthLe [1, 2] 1 (by simp) = 2 := by
-- β’ [1, 2].nthLe 1 β― = 2
generalize_proofs h
-- h : 1 < [1, 2].length
-- β’ [1, 2].nthLe 1 h = 2
```
The tactic is similar in spirit to `Lean.Meta.AbstractNestedProofs` in core.
One difference is that it the tactic tries to propagate expected types so that
we get `1 < [1, 2].length` in the above example rather than `1 < Nat.succ 1`.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Parser.Tactic Elab.Tactic
initialize registerTraceClass `Tactic.generalize_proofs
namespace GeneralizeProofs
/--
Configuration for the `generalize_proofs` tactic.
-/
structure Config where
/-- The maximum recursion depth when generalizing proofs.
When `maxDepth > 0`, then proofs are generalized from the types of the generalized proofs too. -/
maxDepth : Nat := 8
/-- When `abstract` is `true`, then the tactic will create universally quantified proofs
to account for bound variables.
When it is `false` then such proofs are left alone. -/
abstract : Bool := true
/-- (Debugging) When `true`, enables consistency checks. -/
debug : Bool := false
/-- Elaborates a `Parser.Tactic.config` for `generalize_proofs`. -/
declare_config_elab elabConfig Config
/-- State for the `MGen` monad. -/
structure GState where
/-- Mapping from propositions to an fvar in the local context with that type. -/
propToFVar : ExprMap Expr
/-- Monad used to generalize proofs.
Carries `Mathlib.Tactic.GeneralizeProofs.Config` and `Mathlib.Tactic.GeneralizeProofs.State`. -/
abbrev MGen := ReaderT Config <| StateRefT GState MetaM
/-- Inserts a prop/fvar pair into the `propToFVar` map. -/
def MGen.insertFVar (prop fvar : Expr) : MGen Unit :=
modify fun s β¦ { s with propToFVar := s.propToFVar.insert prop fvar }
/-- Context for the `MAbs` monad. -/
structure AContext where
/-- The local fvars corresponding to bound variables.
Abstraction needs to be sure that these variables do not appear in abstracted terms. -/
fvars : Array Expr := #[]
/-- A copy of `propToFVar` from `GState`. -/
propToFVar : ExprMap Expr
/-- The recursion depth, for how many times `visit` is called from within `visitProof. -/
depth : Nat := 0
/-- The initial local context, for resetting when recursing. -/
initLCtx : LocalContext
/-- The tactic configuration. -/
config : Config
/-- State for the `MAbs` monad. -/
structure AState where
/-- The prop/proof triples to add to the local context.
The proofs must not refer to fvars in `fvars`. -/
generalizations : Array (Expr Γ Expr) := #[]
/-- Map version of `generalizations`. Use `MAbs.findProof?` and `MAbs.insertProof`. -/
propToProof : ExprMap Expr := {}
/--
Monad used to abstract proofs, to prepare for generalization.
Has a cache (of expr/type? pairs),
and it also has a reader context `Mathlib.Tactic.GeneralizeProofs.AContext`
and a state `Mathlib.Tactic.GeneralizeProofs.AState`.
-/
abbrev MAbs := ReaderT AContext <| MonadCacheT (Expr Γ Option Expr) Expr <| StateRefT AState MetaM
/-- Runs `MAbs` in `MGen`. Returns the value and the `generalizations`. -/
def MGen.runMAbs {Ξ± : Type} (mx : MAbs Ξ±) : MGen (Ξ± Γ Array (Expr Γ Expr)) := do
let s β get
let (x, s') β mx
|>.run { initLCtx := β getLCtx, propToFVar := s.propToFVar, config := (β read) }
|>.run |>.run {}
return (x, s'.generalizations)
/--
Finds a proof of `prop` by looking at `propToFVar` and `propToProof`.
-/
def MAbs.findProof? (prop : Expr) : MAbs (Option Expr) := do
if let some pf := (β read).propToFVar.find? prop then
return pf
else
return (β get).propToProof.find? prop
/--
Generalize `prop`, where `proof` is its proof.
-/
def MAbs.insertProof (prop pf : Expr) : MAbs Unit := do
if (β read).config.debug then
unless β isDefEq prop (β inferType pf) do
throwError "insertProof: proof{indentD pf}does not have type{indentD prop}"
unless β Lean.MetavarContext.isWellFormed (β read).initLCtx pf do
throwError "insertProof: proof{indentD pf}\nis not well-formed in the initial context\n\
fvars: {(β read).fvars}"
unless β Lean.MetavarContext.isWellFormed (β read).initLCtx prop do
throwError "insertProof: proof{indentD prop}\nis not well-formed in the initial context\n\
fvars: {(β read).fvars}"
modify fun s β¦
{ s with
generalizations := s.generalizations.push (prop, pf)
propToProof := s.propToProof.insert prop pf }
/-- Runs `x` with an additional local variable. -/
def MAbs.withLocal {Ξ± : Type} (fvar : Expr) (x : MAbs Ξ±) : MAbs Ξ± :=
withReader (fun r => {r with fvars := r.fvars.push fvar}) x
/-- Runs `x` with an increased recursion depth and the initial local context, clearing `fvars`. -/
def MAbs.withRecurse {Ξ± : Type} (x : MAbs Ξ±) : MAbs Ξ± := do
withLCtx (β read).initLCtx (β getLocalInstances) do
withReader (fun r => {r with fvars := #[], depth := r.depth + 1}) x
/--
Computes expected types for each argument to `f`,
given that the type of `mkAppN f args` is supposed to be `ty?`
(where if `ty?` is none, there's no type to propagate inwards).
-/
def appArgExpectedTypes (f : Expr) (args : Array Expr) (ty? : Option Expr) :
MetaM (Array (Option Expr)) :=
withTransparency .all <| withNewMCtxDepth do
-- Try using the expected type, but (*) below might find a bad solution
(guard ty?.isSome *> go f args ty?) <|> go f args none
where
/-- Core implementation for `appArgExpectedTypes`. -/
go (f : Expr) (args : Array Expr) (ty? : Option Expr) : MetaM (Array (Option Expr)) := do
-- Metavariables for each argument to `f`:
let mut margs := #[]
-- The current type of `mAppN f margs`:
let mut fty β inferType f
-- Whether we have already unified the type `ty?` with `fty` (once `margs` is filled)
let mut unifiedFTy := false
for i in [0 : args.size] do
unless i < margs.size do
let (margs', _, fty') β forallMetaBoundedTelescope fty (args.size - i)
if margs'.isEmpty then throwError "could not make progress at argument {i}"
fty := fty'
margs := margs ++ margs'
let arg := args[i]!
let marg := margs[i]!
if !unifiedFTy && margs.size == args.size then
if let some ty := ty? then
unifiedFTy := (β observing? <| isDefEq fty ty).getD false -- (*)
unless β isDefEq (β inferType marg) (β inferType arg) do
throwError s!"failed isDefEq types {i}, {β ppExpr marg}, {β ppExpr arg}"
unless β isDefEq marg arg do
throwError s!"failed isDefEq values {i}, {β ppExpr marg}, {β ppExpr arg}"
unless β marg.mvarId!.isAssigned do
marg.mvarId!.assign arg
margs.mapM fun marg => do
-- Note: all mvars introduced by `appArgExpectedTypes` are assigned by this point
-- so there is no mvar leak.
return (β instantiateMVars (β inferType marg)).cleanupAnnotations
/--
Does `mkLambdaFVars fvars e` but
1. zeta reduces let bindings
2. only includes used fvars
3. returns the list of fvars that were actually abstracted
-/
def mkLambdaFVarsUsedOnly (fvars : Array Expr) (e : Expr) : MetaM (Array Expr Γ Expr) := do
let mut e := e
let mut fvars' : List Expr := []
for i' in [0:fvars.size] do
let i := fvars.size - i' - 1
let fvar := fvars[i]!
e β mkLambdaFVars #[fvar] e
match e with
| .letE _ _ v b _ =>
e := b.instantiate1 v
| .lam _ _ b _ =>
if b.hasLooseBVars then
fvars' := fvar :: fvars'
else
e := b
| _ => unreachable!
return (fvars'.toArray, e)
/--
Abstract proofs occurring in the expression.
A proof is *abstracted* if it is of the form `f a b ...` where `a b ...` are bound variables
(that is, they are variables that are not present in the initial local context)
and where `f` contains no bound variables.
In this form, `f` can be immediately lifted to be a local variable and generalized.
The abstracted proofs are recorded in the state.
This function is careful to track the type of `e` based on where it's used,
since the inferred type might be different.
For example, `(by simp : 1 < [1, 2].length)` has `1 < Nat.succ 1` as the inferred type,
but from knowing it's an argument to `List.nthLe` we can deduce `1 < [1, 2].length`.
-/
partial def abstractProofs (e : Expr) (ty? : Option Expr) : MAbs Expr := do
if (β read).depth β€ (β read).config.maxDepth then
MAbs.withRecurse <| visit (β instantiateMVars e) ty?
else
return e
where
/--
Core implementation of `abstractProofs`.
-/
visit (e : Expr) (ty? : Option Expr) : MAbs Expr := do
trace[Tactic.generalize_proofs] "visit (fvars := {(β read).fvars}) e is {e}"
if (β read).config.debug then
if let some ty := ty? then
unless β isDefEq (β inferType e) ty do
throwError "visit: type of{indentD e}\nis not{indentD ty}"
if e.isAtomic then
return e
else
checkCache (e, ty?) fun _ β¦ do
if β isProof e then
visitProof e ty?
else
match e with
| .forallE n t b i =>
withLocalDecl n i (β visit t none) fun x β¦ MAbs.withLocal x do
mkForallFVars #[x] (β visit (b.instantiate1 x) none)
| .lam n t b i => do
withLocalDecl n i (β visit t none) fun x β¦ MAbs.withLocal x do
let ty'? β
if let some ty := ty? then
let .forallE _ _ tyB _ β whnfD ty
| throwError "Expecting forall in abstractProofs .lam"
pure <| some <| tyB.instantiate1 x
else
pure none
mkLambdaFVars #[x] (β visit (b.instantiate1 x) ty'?)
| .letE n t v b _ =>
let t' β visit t none
withLetDecl n t' (β visit v t') fun x β¦ MAbs.withLocal x do
mkLetFVars #[x] (β visit (b.instantiate1 x) ty?)
| .app .. =>
e.withApp fun f args β¦ do
let f' β visit f none
let argTys β appArgExpectedTypes f' args ty?
let mut args' := #[]
for arg in args, argTy in argTys do
args' := args'.push <| β visit arg argTy
return mkAppN f' args'
| .mdata _ b => return e.updateMData! (β visit b ty?)
-- Giving up propagating expected types for `.proj`, which we shouldn't see anyway:
| .proj _ _ b => return e.updateProj! (β visit b none)
| _ => unreachable!
/--
Core implementation of abstracting a proof.
-/
visitProof (e : Expr) (ty? : Option Expr) : MAbs Expr := do
let eOrig := e
let fvars := (β read).fvars
-- Strip metadata and beta reduce, in case there are some false dependencies
let e := e.withApp' fun f args => f.beta args
-- If head is atomic and arguments are bound variables, then it's already abstracted.
if e.withApp' fun f args => f.isAtomic && args.all fvars.contains then
return e
-- Abstract `fvars` out of `e` to make the abstracted proof `pf`
-- The use of `mkLambdaFVarsUsedOnly` is *key* to make sure that the fvars in `fvars`
-- don't leak into the expression, since that would poison the cache in `MonadCacheT`.
let e β
if let some ty := ty? then
if (β read).config.debug then
unless β isDefEq ty (β inferType e) do
throwError m!"visitProof: incorrectly propagated type{indentD ty}\nfor{indentD e}"
mkExpectedTypeHint e ty
else pure e
trace[Tactic.generalize_proofs] "before mkLambdaFVarsUsedOnly, e = {e}\nfvars={fvars}"
if (β read).config.debug then
unless β Lean.MetavarContext.isWellFormed (β getLCtx) e do
throwError m!"visitProof: proof{indentD e}\nis not well-formed in the current context\n\
fvars: {fvars}"
let (fvars', pf) β mkLambdaFVarsUsedOnly fvars e
if !(β read).config.abstract && !fvars'.isEmpty then
trace[Tactic.generalize_proofs] "'abstract' is false and proof uses fvars, not abstracting"
return eOrig
trace[Tactic.generalize_proofs] "after mkLambdaFVarsUsedOnly, pf = {pf}\nfvars'={fvars'}"
if (β read).config.debug then
unless β Lean.MetavarContext.isWellFormed (β read).initLCtx pf do
throwError m!"visitProof: proof{indentD pf}\nis not well-formed in the initial context\n\
fvars: {fvars}\n{(β mkFreshExprMVar none).mvarId!}"
let pfTy β instantiateMVars (β inferType pf)
-- Visit the proof type to normalize it and abstract more proofs
let pfTy β abstractProofs pfTy none
-- Check if there is already a recorded proof for this proposition.
trace[Tactic.generalize_proofs] "finding {pfTy}"
if let some pf' β MAbs.findProof? pfTy then
trace[Tactic.generalize_proofs] "found proof"
return mkAppN pf' fvars'
-- Record the proof in the state and return the proof.
MAbs.insertProof pfTy pf
trace[Tactic.generalize_proofs] "added proof"
return mkAppN pf fvars'
/--
Create a mapping of all propositions in the local context to their fvars.
-/
def initialPropToFVar : MetaM (ExprMap Expr) := do
-- Visit decls in reverse order so that in case there are duplicates,
-- earlier proofs are preferred
(β getLCtx).foldrM (init := {}) fun decl m => do
if !decl.isImplementationDetail then
let ty := (β instantiateMVars decl.type).cleanupAnnotations
if β Meta.isProp ty then
return m.insert ty decl.toExpr
return m
/--
Generalizes the proofs in the type `e` and runs `k` in a local context with these propositions.
This continuation `k` is passed
1. an array of fvars for the propositions
2. an array of proof terms (extracted from `e`) that prove these propositions
3. the generalized `e`, which refers to these fvars
The `propToFVar` map is updated with the new proposition fvars.
-/
partial def withGeneralizedProofs {Ξ± : Type} [Inhabited Ξ±] (e : Expr) (ty? : Option Expr)
(k : Array Expr β Array Expr β Expr β MGen Ξ±) :
MGen Ξ± := do
let propToFVar := (β get).propToFVar
trace[Tactic.generalize_proofs] "pre-abstracted{indentD e}\npropToFVar: {propToFVar.toArray}"
let (e, generalizations) β MGen.runMAbs <| abstractProofs e ty?
trace[Tactic.generalize_proofs] "\
post-abstracted{indentD e}\nnew generalizations: {generalizations}"
let rec
/-- Core loop for `withGeneralizedProofs`, adds generalizations one at a time. -/
go [Inhabited Ξ±] (i : Nat) (fvars pfs : Array Expr)
(proofToFVar propToFVar : ExprMap Expr) : MGen Ξ± := do
if h : i < generalizations.size then
let (ty, pf) := generalizations[i]
let ty := (β instantiateMVars (ty.replace proofToFVar.find?)).cleanupAnnotations
withLocalDeclD (β mkFreshUserName `pf) ty fun fvar => do
go (i + 1) (fvars := fvars.push fvar) (pfs := pfs.push pf)
(proofToFVar := proofToFVar.insert pf fvar)
(propToFVar := propToFVar.insert ty fvar)
else
withNewLocalInstances fvars 0 do
let e' := e.replace proofToFVar.find?
trace[Tactic.generalize_proofs] "after: e' = {e}"
modify fun s => { s with propToFVar }
k fvars pfs e'
go 0 #[] #[] (proofToFVar := {}) (propToFVar := propToFVar)
/--
Main loop for `Lean.MVarId.generalizeProofs`.
The `fvars` array is the array of fvars to generalize proofs for,
and `rfvars` is the array of fvars that have been reverted.
The `g` metavariable has all of these fvars reverted.
-/
partial def generalizeProofsCore
(g : MVarId) (fvars rfvars : Array FVarId) (target : Bool) :
MGen (Array Expr Γ MVarId) :=
go g 0 #[]
where
/-- Loop for `generalizeProofsCore`. -/
go (g : MVarId) (i : Nat) (hs : Array Expr) : MGen (Array Expr Γ MVarId) := g.withContext do
let tag β g.getTag
if h : i < rfvars.size then
trace[Tactic.generalize_proofs] "generalizeProofsCore {i}{g}\n{(β get).propToFVar.toArray}"
let fvar := rfvars[i]
if fvars.contains fvar then
-- This is one of the hypotheses that was intentionally reverted.
let tgt β instantiateMVars <| β g.getType
let ty := tgt.bindingDomain!.cleanupAnnotations
if β pure tgt.isLet <&&> Meta.isProp ty then
-- Clear the proof value (using proof irrelevance) and `go` again
let tgt' := Expr.forallE tgt.bindingName! ty tgt.bindingBody! .default
let g' β mkFreshExprSyntheticOpaqueMVar tgt' tag
g.assign <| .app g' tgt.letValue!
return β go g'.mvarId! i hs
if let some pf := (β get).propToFVar.find? ty then
-- Eliminate this local hypothesis using the pre-existing proof, using proof irrelevance
let tgt' := tgt.bindingBody!.instantiate1 pf
let g' β mkFreshExprSyntheticOpaqueMVar tgt' tag
g.assign <| .lam tgt.bindingName! tgt.bindingDomain! g' tgt.bindingInfo!
return β go g'.mvarId! (i + 1) hs
-- Now the main case, handling forall or let
match tgt with
| .forallE n t b bi =>
let prop β Meta.isProp t
withGeneralizedProofs t none fun hs' pfs' t' => do
let t' := t'.cleanupAnnotations
let tgt' := Expr.forallE n t' b bi
let g' β mkFreshExprSyntheticOpaqueMVar tgt' tag
g.assign <| mkAppN (β mkLambdaFVars hs' g') pfs'
let (fvar', g') β g'.mvarId!.intro1P
g'.withContext do Elab.pushInfoLeaf <|
.ofFVarAliasInfo { id := fvar', baseId := fvar, userName := β fvar'.getUserName }
if prop then
-- Make this prop available as a proof
MGen.insertFVar t' (.fvar fvar')
go g' (i + 1) (hs ++ hs')
| .letE n t v b _ =>
withGeneralizedProofs t none fun hs' pfs' t' => do
withGeneralizedProofs v t' fun hs'' pfs'' v' => do
let tgt' := Expr.letE n t' v' b false
let g' β mkFreshExprSyntheticOpaqueMVar tgt' tag
g.assign <| mkAppN (β mkLambdaFVars (hs' ++ hs'') g') (pfs' ++ pfs'')
let (fvar', g') β g'.mvarId!.intro1P
g'.withContext do Elab.pushInfoLeaf <|
.ofFVarAliasInfo { id := fvar', baseId := fvar, userName := β fvar'.getUserName }
go g' (i + 1) (hs ++ hs' ++ hs'')
| _ => unreachable!
else
-- This is one of the hypotheses that was incidentally reverted.
let (fvar', g') β g.intro1P
g'.withContext do Elab.pushInfoLeaf <|
.ofFVarAliasInfo { id := fvar', baseId := fvar, userName := β fvar'.getUserName }
go g' (i + 1) hs
else if target then
trace[Tactic.generalize_proofs] "\
generalizeProofsCore target{g}\n{(β get).propToFVar.toArray}"
withGeneralizedProofs (β g.getType) none fun hs' pfs' ty' => do
let g' β mkFreshExprSyntheticOpaqueMVar ty' tag
g.assign <| mkAppN (β mkLambdaFVars hs' g') pfs'
return (hs ++ hs', g'.mvarId!)
else
return (hs, g)
end GeneralizeProofs
/--
Generalize proofs in the hypotheses `fvars` and, if `target` is true, the target.
Returns the fvars for the generalized proofs and the new goal.
If a hypothesis is a proposition and a `let` binding, this will clear the value of the let binding.
If a hypothesis is a proposition that already appears in the local context, it will be eliminated.
Only *nontrivial* proofs are generalized. These are proofs that aren't of the form `f a b ...`
where `f` is atomic and `a b ...` are bound variables.
These sorts of proofs cannot be meaningfully generalized, and also these are the sorts of proofs
that are left in a term after generalization.
-/
partial def _root_.Lean.MVarId.generalizeProofs
(g : MVarId) (fvars : Array FVarId) (target : Bool) (config : GeneralizeProofs.Config := {}) :
MetaM (Array Expr Γ MVarId) := do
let (rfvars, g) β g.revert fvars (clearAuxDeclsInsteadOfRevert := true)
g.withContext do
let s := { propToFVar := β GeneralizeProofs.initialPropToFVar }
GeneralizeProofs.generalizeProofsCore g fvars rfvars target |>.run config |>.run' s
/--
`generalize_proofs ids* [at locs]?` generalizes proofs in the current goal,
turning them into new local hypotheses.
- `generalize_proofs` generalizes proofs in the target.
- `generalize_proofs at hβ hβ` generalized proofs in hypotheses `hβ` and `hβ`.
- `generalize_proofs at *` generalizes proofs in the entire local context.
- `generalize_proofs pfβ pfβ pfβ` uses names `pfβ`, `pfβ`, and `pfβ` for the generalized proofs.
These can be `_` to not name proofs.
If a proof is already present in the local context, it will use that rather than create a new
local hypothesis.
When doing `generalize_proofs at h`, if `h` is a let binding, its value is cleared,
and furthermore if `h` duplicates a preceding local hypothesis then it is eliminated.
The tactic is able to abstract proofs from under binders, creating universally quantified
proofs in the local context.
To disable this, use `generalize_proofs (config := { abstract := false })`.
The tactic is also set to recursively abstract proofs from the types of the generalized proofs.
This can be controlled with the `maxDepth` configuration option,
with `generalize_proofs (config := { maxDepth := 0 })` turning this feature off.
For example:
```lean
example : List.nthLe [1, 2] 1 (by simp) = 2 := by
-- β’ [1, 2].nthLe 1 β― = 2
generalize_proofs h
-- h : 1 < [1, 2].length
-- β’ [1, 2].nthLe 1 h = 2
```
-/
elab (name := generalizeProofsElab) "generalize_proofs" config?:(Parser.Tactic.config)?
hs:(ppSpace colGt binderIdent)* loc?:(location)? : tactic => withMainContext do
let config β GeneralizeProofs.elabConfig (mkOptionalNode config?)
let (fvars, target) β
match expandOptLocation (Lean.mkOptionalNode loc?) with
| .wildcard => pure ((β getLCtx).getFVarIds, true)
| .targets t target => pure (β getFVarIds t, target)
liftMetaTactic1 fun g => do
let (pfs, g) β g.generalizeProofs fvars target config
-- Rename the proofs using `hs` and record info
g.withContext do
let mut lctx β getLCtx
for h in hs, fvar in pfs do
if let `(binderIdent| $s:ident) := h then
lctx := lctx.setUserName fvar.fvarId! s.getId
Expr.addLocalVarInfoForBinderIdent fvar h
withLCtx lctx (β getLocalInstances) do
let g' β mkFreshExprSyntheticOpaqueMVar (β g.getType) (β g.getTag)
g.assign g'
return g'.mvarId!
|
Tactic\Group.lean | /-
Copyright (c) 2020. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Massot
-/
import Mathlib.Tactic.Ring
import Mathlib.Tactic.FailIfNoProgress
import Mathlib.Algebra.Group.Commutator
/-!
# `group` tactic
Normalizes expressions in the language of groups. The basic idea is to use the simplifier
to put everything into a product of group powers (`zpow` which takes a group element and an
integer), then simplify the exponents using the `ring` tactic. The process needs to be repeated
since `ring` can normalize an exponent to zero, leading to a factor that can be removed
before collecting exponents again. The simplifier step also uses some extra lemmas to avoid
some `ring` invocations.
## Tags
group_theory
-/
namespace Mathlib.Tactic.Group
open Lean
open Lean.Meta
open Lean.Parser.Tactic
open Lean.Elab.Tactic
-- The next three lemmas are not general purpose lemmas, they are intended for use only by
-- the `group` tactic.
@[to_additive]
theorem zpow_trick {G : Type*} [Group G] (a b : G) (n m : β€) :
a * b ^ n * b ^ m = a * b ^ (n + m) := by rw [mul_assoc, β zpow_add]
@[to_additive]
theorem zpow_trick_one {G : Type*} [Group G] (a b : G) (m : β€) :
a * b * b ^ m = a * b ^ (m + 1) := by rw [mul_assoc, mul_self_zpow]
@[to_additive]
theorem zpow_trick_one' {G : Type*} [Group G] (a b : G) (n : β€) :
a * b ^ n * b = a * b ^ (n + 1) := by rw [mul_assoc, mul_zpow_self]
/-- Auxiliary tactic for the `group` tactic. Calls the simplifier only. -/
syntax (name := aux_groupβ) "aux_groupβ" (location)? : tactic
macro_rules
| `(tactic| aux_groupβ $[at $location]?) =>
`(tactic| simp (config := {decide := false, failIfUnchanged := false}) only
[commutatorElement_def, mul_one, one_mul,
β zpow_neg_one, β zpow_natCast, β zpow_mul,
Int.ofNat_add, Int.ofNat_mul,
Int.mul_neg_eq_neg_mul_symm, Int.neg_mul_eq_neg_mul_symm, neg_neg,
one_zpow, zpow_zero, zpow_one, mul_zpow_neg_one,
β mul_assoc,
β zpow_add, β zpow_add_one, β zpow_one_add, zpow_trick, zpow_trick_one, zpow_trick_one',
tsub_self, sub_self, add_neg_self, neg_add_self]
$[at $location]?)
/-- Auxiliary tactic for the `group` tactic. Calls `ring_nf` to normalize exponents. -/
syntax (name := aux_groupβ) "aux_groupβ" (location)? : tactic
macro_rules
| `(tactic| aux_groupβ $[at $location]?) =>
`(tactic| ring_nf $[at $location]?)
/-- Tactic for normalizing expressions in multiplicative groups, without assuming
commutativity, using only the group axioms without any information about which group
is manipulated.
(For additive commutative groups, use the `abel` tactic instead.)
Example:
```lean
example {G : Type} [Group G] (a b c d : G) (h : c = (a*b^2)*((b*b)β»ΒΉ*aβ»ΒΉ)*d) : a*c*dβ»ΒΉ = a := by
group at h -- normalizes `h` which becomes `h : c = d`
rw [h] -- the goal is now `a*d*dβ»ΒΉ = a`
group -- which then normalized and closed
```
-/
syntax (name := group) "group" (location)? : tactic
macro_rules
| `(tactic| group $[$loc]?) =>
`(tactic| repeat (fail_if_no_progress (aux_groupβ $[$loc]? <;> aux_groupβ $[$loc]?)))
end Group
end Tactic
end Mathlib
|
Tactic\GuardGoalNums.lean | /-
Copyright (c) 2022 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import Lean.Elab.Tactic.Basic
/-!
A tactic stub file for the `guard_goal_nums` tactic.
-/
open Lean Meta Elab Tactic
/-- `guard_goal_nums n` succeeds if there are exactly `n` goals and fails otherwise. -/
elab (name := guardGoalNums) "guard_goal_nums " n:num : tactic => do
let numGoals := (β getGoals).length
guard (numGoals = n.getNat) <|>
throwError "expected {n.getNat} goals but found {numGoals}"
|
Tactic\GuardHypNums.lean | /-
Copyright (c) 2022 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import Lean.Elab.Tactic.Basic
/-!
A tactic stub file for the `guard_hyp_nums` tactic.
-/
open Lean Meta Elab Tactic
/--
`guard_hyp_nums n` succeeds if there are exactly `n` hypotheses and fails otherwise.
Note that, depending on what options are set, some hypotheses in the local context might
not be printed in the goal view. This tactic computes the total number of hypotheses,
not the number of visible hypotheses.
-/
elab (name := guardHypNums) "guard_hyp_nums " n:num : tactic => do
let numHyps := (β getLCtx).size
guard (numHyps = n.getNat) <|>
throwError "expected {n.getNat} hypotheses but found {numHyps}"
|
Tactic\Have.lean | /-
Copyright (c) 2022 Arthur Paulino. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Edward Ayers, Mario Carneiro
-/
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Meta.Tactic.Assert
/-!
# Extending `have`, `let` and `suffices`
This file extends the `have`, `let` and `suffices` tactics to allow the addition of hypotheses to
the context without requiring their proofs to be provided immediately.
As a style choice, this should not be used in mathlib; but is provided for downstream users who
preferred the old style.
-/
namespace Mathlib.Tactic
open Lean Elab.Tactic Meta Parser Term Syntax.MonadTraverser
/-- A parser for optional binder identifiers -/
def optBinderIdent : Parser := leading_parser
-- Note: the withResetCache is because leading_parser seems to add a cache boundary,
-- which causes the `hygieneInfo` parser not to be able to undo the trailing whitespace
(ppSpace >> Term.binderIdent) <|> withResetCache hygieneInfo
/-- Retrieves the name of the optional identifier, if provided. Returns `this` otherwise -/
def optBinderIdent.name (id : TSyntax ``optBinderIdent) : Name :=
if id.raw[0].isIdent then id.raw[0].getId else HygieneInfo.mkIdent β¨id.raw[0]β© `this |>.getId
/--
Uses `checkColGt` to prevent
```lean
have h
exact Nat
```
From being interpreted as
```lean
have h
exact Nat
```
-/
def haveIdLhs' : Parser :=
optBinderIdent >> many (ppSpace >>
checkColGt "expected to be indented" >> letIdBinder) >> optType
syntax "have" haveIdLhs' : tactic
syntax "let " haveIdLhs' : tactic
syntax "suffices" haveIdLhs' : tactic
open Elab Term in
/--
Adds hypotheses to the context, turning them into goals to be proved later if their proof terms
aren't provided (`t: Option Term := none`).
If the bound term is intended to be kept in the context, pass `keepTerm : Bool := true`. This is
useful when extending the `let` tactic, which is expected to show the proof term in the infoview.
-/
def haveLetCore (goal : MVarId) (name : TSyntax ``optBinderIdent)
(bis : Array (TSyntax ``letIdBinder))
(t : Option Term) (keepTerm : Bool) : TermElabM (MVarId Γ MVarId) :=
let declFn := if keepTerm then MVarId.define else MVarId.assert
goal.withContext do
let n := optBinderIdent.name name
let elabBinders k := if bis.isEmpty then k #[] else elabBinders bis k
let (goal1, t, p) β elabBinders fun es β¦ do
let t β match t with
| none => mkFreshTypeMVar
| some stx => withRef stx do
let e β Term.elabType stx
Term.synthesizeSyntheticMVars (postpone := .no)
instantiateMVars e
let p β mkFreshExprMVar t MetavarKind.syntheticOpaque n
pure (p.mvarId!, β mkForallFVars es t, β mkLambdaFVars es p)
let (fvar, goal2) β (β declFn goal n t p).intro1P
goal2.withContext do
Term.addTermInfo' (isBinder := true) name.raw[0] (mkFVar fvar)
pure (goal1, goal2)
/-- An extension of the `have` tactic that turns the hypothesis into a goal to be proved later -/
elab_rules : tactic
| `(tactic| have $n:optBinderIdent $bs* $[: $t:term]?) => do
let (goal1, goal2) β haveLetCore (β getMainGoal) n bs t false
replaceMainGoal [goal1, goal2]
/--
An extension of the `suffices` tactic that turns the hypothesis into a goal to be proved later
-/
elab_rules : tactic
| `(tactic| suffices $n:optBinderIdent $bs* $[: $t:term]?) => do
let (goal1, goal2) β haveLetCore (β getMainGoal) n bs t false
replaceMainGoal [goal2, goal1]
/-- An extension of the `let` tactic that turns the hypothesis into a goal to be proved later -/
elab_rules : tactic
| `(tactic| let $n:optBinderIdent $bs* $[: $t:term]?) => withMainContext do
let (goal1, goal2) β haveLetCore (β getMainGoal) n bs t true
replaceMainGoal [goal1, goal2]
|
Tactic\HaveI.lean | /-
Copyright (c) 2023 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
/-!
# Variants of `haveI`/`letI` for use in do-notation.
This files implements the `haveI'` and `letI'` macros which have the same semantics as
`haveI` and `letI`, but are `doElem`s and can be used inside do-notation.
They need an apostrophe after their name for disambiguation with the term variants.
This is necessary because the do-notation has a hardcoded list of keywords which can appear both
as term-mode and do-elem syntax (like for example `let` or `have`).
-/
namespace Mathlib.Tactic.HaveI
local syntax "haveIDummy" haveDecl : term
macro_rules
| `(assert! haveIDummy $hd:haveDecl; $body) => `(haveI $hd:haveDecl; $body)
/--
`haveI'` behaves like `have`, but inlines the value instead of producing a `let_fun` term.
(This is the do-notation version of the term-mode `haveI`.)
-/
macro "haveI' " hd:haveDecl : doElem =>
`(doElem| assert! haveIDummy $hd:haveDecl)
local syntax "letIDummy" haveDecl : term
macro_rules
| `(assert! letIDummy $hd:haveDecl; $body) => `(letI $hd:haveDecl; $body)
/--
`letI` behaves like `let`, but inlines the value instead of producing a `let_fun` term.
(This is the do-notation version of the term-mode `haveI`.)
-/
macro "letI' " hd:haveDecl : doElem =>
`(doElem| assert! letIDummy $hd:haveDecl)
|
Tactic\HelpCmd.lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Elab.Syntax
import Lean.DocString
/-!
# The `#help` command
The `#help` command can be used to list all definitions in a variety of extensible aspects of lean.
* `#help option` lists options (used in `set_option myOption`)
* `#help attr` lists attributes (used in `@[myAttr] def foo := ...`)
* `#help cats` lists syntax categories (like `term`, `tactic`, `stx` etc)
* `#help cat C` lists elements of syntax category C
* `#help term`, `#help tactic`, `#help conv`, `#help command`
are shorthand for `#help cat term` etc.
* `#help cat+ C` also shows `elab` and `macro` definitions associated to the syntaxes
All forms take an optional identifier to narrow the search; for example `#help option pp` shows
only `pp.*` options.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic Command
/--
The command `#help option` shows all options that have been defined in the current environment.
Each option has a format like:
```
option pp.all : Bool := false
(pretty printer) display coercions, implicit parameters, proof terms, fully qualified names,
universe, and disable beta reduction and notations during pretty printing
```
This says that `pp.all` is an option which can be set to a `Bool` value, and the default value is
`false`. If an option has been modified from the default using e.g. `set_option pp.all true`,
it will appear as a `(currently: true)` note next to the option.
The form `#help option id` will show only options that begin with `id`.
-/
syntax withPosition("#help " colGt &"option" (colGt ppSpace Parser.rawIdent)?) : command
private def elabHelpOption (id : Option Ident) : CommandElabM Unit := do
let id := id.map (Β·.raw.getId.toString false)
let mut decls : Lean.RBMap _ _ compare := {}
for (name, decl) in show Lean.RBMap .. from β getOptionDecls do
let name := name.toString false
if let some id := id then
if !id.isPrefixOf name then
continue
decls := decls.insert name decl
let mut msg := Format.nil
let opts β getOptions
if decls.isEmpty then
match id with
| some id => throwError "no options start with {id}"
| none => throwError "no options found (!)"
for (name, decl) in decls do
let mut msg1 := match decl.defValue with
| .ofString val => s!"String := {repr val}"
| .ofBool val => s!"Bool := {repr val}"
| .ofName val => s!"Name := {repr val}"
| .ofNat val => s!"Nat := {repr val}"
| .ofInt val => s!"Int := {repr val}"
| .ofSyntax val => s!"Syntax := {repr val}"
if let some val := opts.find (.mkSimple name) then
msg1 := s!"{msg1} (currently: {val})"
msg := msg ++ .nest 2 (f!"option {name} : {msg1}" ++ .line ++ decl.descr) ++ .line ++ .line
logInfo msg
elab_rules : command | `(#help option $(id)?) => elabHelpOption id
/--
The command `#help attribute` (or the short form `#help attr`) shows all attributes that have been
defined in the current environment.
Each attribute has a format like:
```
[inline]: mark definition to always be inlined
```
This says that `inline` is an attribute that can be placed on definitions like
`@[inline] def foo := 1`. (Individual attributes may have restrictions on where they can be
applied; see the attribute's documentation for details.) Both the attribute's `descr` field as well
as the docstring will be displayed here.
The form `#help attr id` will show only attributes that begin with `id`.
-/
syntax withPosition("#help " colGt (&"attr" <|> &"attribute")
(colGt ppSpace Parser.rawIdent)?) : command
private def elabHelpAttr (id : Option Ident) : CommandElabM Unit := do
let id := id.map (Β·.raw.getId.toString false)
let mut decls : Lean.RBMap _ _ compare := {}
/-
#adaptation_note
On nightly-2024-06-21, added the `.toList` here:
without it the requisite `ForIn` instance can't be found.
-/
for (name, decl) in (β attributeMapRef.get).toList do
let name := name.toString false
if let some id := id then
if !id.isPrefixOf name then
continue
decls := decls.insert name decl
let mut msg := Format.nil
let env β getEnv
if decls.isEmpty then
match id with
| some id => throwError "no attributes start with {id}"
| none => throwError "no attributes found (!)"
for (name, decl) in decls do
let mut msg1 := s!"[{name}]: {decl.descr}"
if let some doc β findDocString? env decl.ref then
msg1 := s!"{msg1}\n{doc.trim}"
msg := msg ++ .nest 2 msg1 ++ .line ++ .line
logInfo msg
elab_rules : command
| `(#help attr $(id)?) => elabHelpAttr id
| `(#help attribute $(id)?) => elabHelpAttr id
/-- Gets the initial string token in a parser description. For example, for a declaration like
`syntax "bla" "baz" term : tactic`, it returns `some "bla"`. Returns `none` for syntax declarations
that don't start with a string constant. -/
partial def getHeadTk (e : Expr) : Option String :=
match e.getAppFnArgs with
| (``ParserDescr.node, #[_, _, p])
| (``ParserDescr.trailingNode, #[_, _, _, p])
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "withPosition")), p])
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "atomic")), p])
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "ppRealGroup")), p])
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "ppRealFill")), p])
| (``Parser.ppRealFill, #[p])
| (``Parser.withAntiquot, #[_, p])
| (``Parser.leadingNode, #[_, _, p])
| (``Parser.trailingNode, #[_, _, _, p])
| (``Parser.group, #[p])
| (``Parser.withCache, #[_, p])
| (``Parser.withResetCache, #[p])
| (``Parser.withPosition, #[p])
| (``Parser.withOpen, #[p])
| (``Parser.withPositionAfterLinebreak, #[p])
| (``Parser.suppressInsideQuot, #[p])
| (``Parser.ppRealGroup, #[p])
| (``Parser.ppIndent, #[p])
| (``Parser.ppDedent, #[p])
=> getHeadTk p
| (``ParserDescr.binary, #[.app _ (.lit (.strVal "andthen")), p, q])
| (``HAndThen.hAndThen, #[_, _, _, _, p, .lam _ _ q _])
=> getHeadTk p <|> getHeadTk q
| (``ParserDescr.nonReservedSymbol, #[.lit (.strVal tk), _])
| (``ParserDescr.symbol, #[.lit (.strVal tk)])
| (``Parser.nonReservedSymbol, #[.lit (.strVal tk), _])
| (``Parser.symbol, #[.lit (.strVal tk)])
| (``Parser.unicodeSymbol, #[.lit (.strVal tk), _])
=> pure tk
| _ => none
/--
The command `#help cats` shows all syntax categories that have been defined in the
current environment.
Each syntax has a format like:
```
category command [Lean.Parser.initFnβ]
```
The name of the syntax category in this case is `command`, and `Lean.Parser.initFnβ` is the
name of the declaration that introduced it. (It is often an anonymous declaration like this,
but you can click to go to the definition.) It also shows the doc string if available.
The form `#help cats id` will show only syntax categories that begin with `id`.
-/
syntax withPosition("#help " colGt &"cats" (colGt ppSpace Parser.rawIdent)?) : command
private def elabHelpCats (id : Option Ident) : CommandElabM Unit := do
let id := id.map (Β·.raw.getId.toString false)
let mut decls : Lean.RBMap _ _ compare := {}
for (name, cat) in (Parser.parserExtension.getState (β getEnv)).categories do
let name := name.toString false
if let some id := id then
if !id.isPrefixOf name then
continue
decls := decls.insert name cat
let mut msg := MessageData.nil
let env β getEnv
if decls.isEmpty then
match id with
| some id => throwError "no syntax categories start with {id}"
| none => throwError "no syntax categories found (!)"
for (name, cat) in decls do
let mut msg1 := m!"category {name} [{mkConst cat.declName}]"
if let some doc β findDocString? env cat.declName then
msg1 := msg1 ++ Format.line ++ doc.trim
msg := msg ++ .nest 2 msg1 ++ (.line ++ .line : Format)
logInfo msg
elab_rules : command | `(#help cats $(id)?) => elabHelpCats id
/--
The command `#help cat C` shows all syntaxes that have been defined in syntax category `C` in the
current environment.
Each syntax has a format like:
```
syntax "first"... [Parser.tactic.first]
`first | tac | ...` runs each `tac` until one succeeds, or else fails.
```
The quoted string is the leading token of the syntax, if applicable. It is followed by the full
name of the syntax (which you can also click to go to the definition), and the documentation.
* The form `#help cat C id` will show only attributes that begin with `id`.
* The form `#help cat+ C` will also show information about any `macro`s and `elab`s
associated to the listed syntaxes.
-/
syntax withPosition("#help " colGt &"cat" "+"? colGt ident
(colGt ppSpace (Parser.rawIdent <|> str))?) : command
private def elabHelpCat (more : Option Syntax) (catStx : Ident) (id : Option String) :
CommandElabM Unit := do
let mut decls : Lean.RBMap _ _ compare := {}
let mut rest : Lean.RBMap _ _ compare := {}
let catName := catStx.getId.eraseMacroScopes
let some cat := (Parser.parserExtension.getState (β getEnv)).categories.find? catName
| throwErrorAt catStx "{catStx} is not a syntax category"
liftTermElabM <| Term.addCategoryInfo catStx catName
let env β getEnv
for (k, _) in cat.kinds do
let mut used := false
if let some tk := do getHeadTk (β (β env.find? k).value?) then
let tk := tk.trim
if let some id := id then
if !id.isPrefixOf tk then
continue
used := true
decls := decls.insert tk ((decls.findD tk #[]).push k)
if !used && id.isNone then
rest := rest.insert (k.toString false) k
let mut msg := MessageData.nil
if decls.isEmpty && rest.isEmpty then
match id with
| some id => throwError "no {catName} declarations start with {id}"
| none => throwError "no {catName} declarations found"
let env β getEnv
let addMsg (k : SyntaxNodeKind) (msg msg1 : MessageData) : CommandElabM MessageData := do
let mut msg1 := msg1
if let some doc β findDocString? env k then
msg1 := msg1 ++ Format.line ++ doc.trim
msg1 := .nest 2 msg1
if more.isSome then
let addElabs {Ξ±} (type : String) (attr : KeyedDeclsAttribute Ξ±)
(msg : MessageData) : CommandElabM MessageData := do
let mut msg := msg
for e in attr.getEntries env k do
let x := e.declName
msg := msg ++ Format.line ++ m!"+ {type} {mkConst x}"
if let some doc β findDocString? env x then
msg := msg ++ .nest 2 (Format.line ++ doc.trim)
pure msg
msg1 β addElabs "macro" macroAttribute msg1
match catName with
| `term => msg1 β addElabs "term elab" Term.termElabAttribute msg1
| `command => msg1 β addElabs "command elab" commandElabAttribute msg1
| `tactic | `conv => msg1 β addElabs "tactic elab" tacticElabAttribute msg1
| _ => pure ()
return msg ++ msg1 ++ (.line ++ .line : Format)
for (name, ks) in decls do
for k in ks do
msg β addMsg k msg m!"syntax {repr name}... [{mkConst k}]"
for (_, k) in rest do
msg β addMsg k msg m!"syntax ... [{mkConst k}]"
logInfo msg
elab_rules : command
| `(#help cat $[+%$more]? $cat) => elabHelpCat more cat none
| `(#help cat $[+%$more]? $cat $id:ident) => elabHelpCat more cat (id.getId.toString false)
| `(#help cat $[+%$more]? $cat $id:str) => elabHelpCat more cat id.getString
/--
The command `#help term` shows all term syntaxes that have been defined in the current environment.
See `#help cat` for more information.
-/
syntax withPosition("#help " colGt &"term" "+"?
(colGt ppSpace (Parser.rawIdent <|> str))?) : command
macro_rules
| `(#help term%$tk $[+%$more]? $(id)?) =>
`(#help cat$[+%$more]? $(mkIdentFrom tk `term) $(id)?)
/--
The command `#help tactic` shows all tactics that have been defined in the current environment.
See `#help cat` for more information.
-/
syntax withPosition("#help " colGt &"tactic" "+"?
(colGt ppSpace (Parser.rawIdent <|> str))?) : command
macro_rules
| `(#help tactic%$tk $[+%$more]? $(id)?) =>
`(#help cat$[+%$more]? $(mkIdentFrom tk `tactic) $(id)?)
/--
The command `#help conv` shows all tactics that have been defined in the current environment.
See `#help cat` for more information.
-/
syntax withPosition("#help " colGt &"conv" "+"?
(colGt ppSpace (Parser.rawIdent <|> str))?) : command
macro_rules
| `(#help conv%$tk $[+%$more]? $(id)?) =>
`(#help cat$[+%$more]? $(mkIdentFrom tk `conv) $(id)?)
/--
The command `#help command` shows all commands that have been defined in the current environment.
See `#help cat` for more information.
-/
syntax withPosition("#help " colGt &"command" "+"?
(colGt ppSpace (Parser.rawIdent <|> str))?) : command
macro_rules
| `(#help command%$tk $[+%$more]? $(id)?) =>
`(#help cat$[+%$more]? $(mkIdentFrom tk `command) $(id)?)
|
Tactic\HigherOrder.lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import Lean.Elab.Term
import Lean.Meta.Tactic.Apply
import Lean.Meta.Tactic.Assumption
import Lean.Meta.MatchUtil
import Lean.Meta.Tactic.Intro
import Lean.Elab.DeclarationRange
import Mathlib.Tactic.Attr.Register
/-!
# HigherOrder attribute
This file defines the `@[higher_order]` attribute that applies to lemmas of the shape
`β x, f (g x) = h x`. It derives an auxiliary lemma of the form `f β g = h` for reasoning about
higher-order functions.
-/
open Lean Name Meta Elab Expr Term
namespace Lean.Parser.Attr
syntax (name := higherOrder) "higher_order" (ppSpace ident)? : attr
end Lean.Parser.Attr
namespace Tactic
/-- `mkComp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f β g β h`. If `e = v` it returns `id`. -/
def mkComp (v : Expr) : Expr β MetaM Expr
| .app f e =>
if e.equal v then
return f
else do
if v.occurs f then
throwError "mkComp failed occurs check"
let e' β mkComp v e
mkAppM ``Function.comp #[f, e']
| e => do
guard (e.equal v)
let t β inferType e
mkAppOptM ``id #[t]
/--
From a lemma of the shape `β x, f (g x) = h x`
derive an auxiliary lemma of the form `f β g = h`
for reasoning about higher-order functions.
-/
partial def mkHigherOrderType (e : Expr) : MetaM Expr := do
if not e.isForall then
throwError "not a forall"
withLocalDecl e.bindingName! e.binderInfo e.bindingDomain! fun fvar => do
let body := instantiate1 e.bindingBody! fvar
if body.isForall then
let exp β mkHigherOrderType body
mkForallFVars #[fvar] exp (binderInfoForMVars := e.binderInfo)
else
let some (_, lhs, rhs) β matchEq? body | throwError "not an equality {β ppExpr body}"
mkEq (β mkComp fvar lhs) (β mkComp fvar rhs)
/-- A user attribute that applies to lemmas of the shape `β x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f β g = h` for reasoning about higher-order functions.
-/
def higherOrderGetParam (thm : Name) (stx : Syntax) : AttrM Name := do
match stx with
| `(attr| higher_order $[$name]?) =>
let ref := (name : Option Syntax).getD stx[0]
let hothmName :=
if let some sname := name then
updatePrefix sname.getId thm.getPrefix
else
thm.appendAfter "\'"
MetaM.run' <| TermElabM.run' <| do
let lvl := (β getConstInfo thm).levelParams
let typ β instantiateMVars (β inferType <| .const thm (lvl.map mkLevelParam))
let hot β mkHigherOrderType typ
let prf β do
let mvar β mkFreshExprMVar hot
let (_, mvarId) β mvar.mvarId!.intros
let [mvarId] β mvarId.apply (β mkConst ``funext) | throwError "failed"
let (_, mvarId) β mvarId.intro1
let lmvr β mvarId.apply (β mkConst thm)
lmvr.forM fun mv β¦ mv.assumption
instantiateMVars mvar
addDecl <| .thmDecl
{ name := hothmName
levelParams := lvl
type := hot
value := prf }
addDeclarationRanges hothmName
{ range := β getDeclarationRange (β getRef)
selectionRange := β getDeclarationRange ref }
_ β addTermInfo (isBinder := true) ref <| β mkConstWithLevelParams hothmName
let hsm := simpExtension.getState (β getEnv) |>.lemmaNames.contains (.decl thm)
if hsm then
addSimpTheorem simpExtension hothmName true false .global 1000
let some fcn β getSimpExtension? `functor_norm | failure
let hfm := fcn.getState (β getEnv) |>.lemmaNames.contains <| .decl thm
if hfm then
addSimpTheorem fcn hothmName true false .global 1000
return hothmName
| _ => throwUnsupportedSyntax
/-- The `higher_order` attribute. From a lemma of the shape `β x, f (g x) = h x` derive an
auxiliary lemma of the form `f β g = h` for reasoning about higher-order functions.
Syntax: `[higher_order]` or `[higher_order name]` where the given name is used for the
generated theorem. -/
initialize higherOrderAttr : ParametricAttribute Name β
registerParametricAttribute {
name := `higherOrder,
descr :=
"From a lemma of the shape `β x, f (g x) = h x` derive an auxiliary lemma of the
form `f β g = h` for reasoning about higher-order functions.
Syntax: `[higher_order]` or `[higher_order name]`, where the given name is used for the
generated theorem.",
getParam := higherOrderGetParam }
end Tactic
|
Tactic\Hint.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Lean.Meta.Tactic.TryThis
import Batteries.Linter.UnreachableTactic
import Batteries.Control.Nondet.Basic
import Mathlib.Tactic.FailIfNoProgress
/-!
# The `hint` tactic.
The `hint` tactic tries the kitchen sink:
it runs every tactic registered via the `register_hint tac` command
on the current goal, and reports which ones succeed.
## Future work
It would be nice to run the tactics in parallel.
-/
open Lean Elab Tactic
open Lean.Meta.Tactic.TryThis
namespace Mathlib.Tactic.Hint
/-- An environment extension for registering hint tactics. -/
initialize hintExtension : SimplePersistentEnvExtension (TSyntax `tactic) (List (TSyntax `tactic)) β
registerSimplePersistentEnvExtension {
addEntryFn := (Β·.cons)
addImportedFn := mkStateFromImportedEntries (Β·.cons) {}
}
/-- Register a new hint tactic. -/
def addHint (stx : TSyntax `tactic) : CoreM Unit := do
modifyEnv fun env => hintExtension.addEntry env stx
/-- Return the list of registered hint tactics. -/
def getHints : CoreM (List (TSyntax `tactic)) := return hintExtension.getState (β getEnv)
open Lean.Elab.Command in
/--
Register a tactic for use with the `hint` tactic, e.g. `register_hint simp_all`.
-/
elab (name := registerHintStx) "register_hint" tac:tactic : command => liftTermElabM do
-- remove comments
let tac : TSyntax `tactic := β¨tac.raw.copyHeadTailInfoFrom .missingβ©
addHint tac
initialize
Batteries.Linter.UnreachableTactic.ignoreTacticKindsRef.modify fun s => s.insert ``registerHintStx
/--
Construct a suggestion for a tactic.
* Check the passed `MessageLog` for an info message beginning with "Try this: ".
* If found, use that as the suggestion.
* Otherwise use the provided syntax.
* Also, look for remaining goals and pretty print them after the suggestion.
-/
def suggestion (tac : TSyntax `tactic) (msgs : MessageLog := {}) : TacticM Suggestion := do
-- TODO `addExactSuggestion` has an option to construct `postInfo?`
-- Factor that out so we can use it here instead of copying and pasting?
let goals β getGoals
let postInfo? β if goals.isEmpty then pure none else
let mut str := "\nRemaining subgoals:"
for g in goals do
let e β PrettyPrinter.ppExpr (β instantiateMVars (β g.getType))
str := str ++ Format.pretty ("\nβ’ " ++ e)
pure (some str)
let style? := if goals.isEmpty then some .success else none
let msg? β msgs.toList.findM? fun m => do pure <|
m.severity == MessageSeverity.information && (β m.data.toString).startsWith "Try this: "
let suggestion β match msg? with
| some m => pure <| SuggestionText.string (((β m.data.toString).drop 10).takeWhile (Β· != '\n'))
| none => pure <| SuggestionText.tsyntax tac
return { suggestion, postInfo?, style? }
/-- Run a tactic, returning any new messages rather than adding them to the message log. -/
def withMessageLog (t : TacticM Unit) : TacticM MessageLog := do
let initMsgs β modifyGetThe Core.State fun st => (st.messages, { st with messages := {} })
t
modifyGetThe Core.State fun st => (st.messages, { st with messages := initMsgs })
/--
Run a tactic, but revert any changes to info trees.
We use this to inhibit the creation of widgets by subsidiary tactics.
-/
def withoutInfoTrees (t : TacticM Unit) : TacticM Unit := do
let trees := (β getInfoState).trees
t
modifyInfoState fun s => { s with trees }
/--
Run all tactics registered using `register_hint`.
Print a "Try these:" suggestion for each of the successful tactics.
If one tactic succeeds and closes the goal, we don't look at subsequent tactics.
-/
-- TODO We could run the tactics in parallel.
-- TODO With widget support, could we run the tactics in parallel
-- and do live updates of the widget as results come in?
def hint (stx : Syntax) : TacticM Unit := do
let tacs := Nondet.ofList (β getHints)
let results := tacs.filterMapM fun t : TSyntax `tactic => do
if let some msgs β observing? (withMessageLog (withoutInfoTrees (evalTactic t))) then
return some (β getGoals, β suggestion t msgs)
else
return none
let results β (results.toMLList.takeUpToFirst fun r => r.1.1.isEmpty).asArray
let results := results.qsort (Β·.1.1.length < Β·.1.1.length)
addSuggestions stx (results.map (Β·.1.2))
match results.find? (Β·.1.1.isEmpty) with
| some r =>
-- We don't restore the entire state, as that would delete the suggestion messages.
setMCtx r.2.term.meta.meta.mctx
| none => admitGoal (β getMainGoal)
/--
The `hint` tactic tries every tactic registered using `register_hint tac`,
and reports any that succeed.
-/
syntax (name := hintStx) "hint" : tactic
@[inherit_doc hintStx]
elab_rules : tactic
| `(tactic| hint%$tk) => hint tk
end Mathlib.Tactic.Hint
|
Tactic\InferParam.lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Mario Carneiro
-/
import Lean.Elab.Tactic.Basic
import Lean.Meta.Tactic.Replace
/-!
# Infer an optional parameter
In this file we define a tactic `infer_param` that closes a goal with default value by using
this default value.
-/
namespace Mathlib.Tactic
open Lean Elab Tactic Meta
/-- Close a goal of the form `optParam Ξ± a` or `autoParam Ξ± stx` by using `a`. -/
elab (name := inferOptParam) "infer_param" : tactic => do
let tgt β getMainTarget
if let some val := tgt.getOptParamDefault? then
liftMetaTactic fun goal => do goal.assign val; pure []
else if let some (.const tacticDecl ..) := tgt.getAutoParamTactic? then
match evalSyntaxConstant (β getEnv) (β getOptions) tacticDecl with
| .error err => throwError err
| Except.ok tacticSyntax =>
liftMetaTactic1 fun goal => do
goal.replaceTargetDefEq (β goal.getType).consumeTypeAnnotations
evalTactic tacticSyntax
else throwError
"`infer_param` only solves goals of the form `optParam _ _` or `autoParam _ _`, not {tgt}"
|
Tactic\Inhabit.lean | /-
Copyright (c) 2022 Joshua Clune. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joshua Clune
-/
import Lean
import Mathlib.Tactic.TypeStar
/-!
Defines the `inhabit Ξ±` tactic, which tries to construct an `Inhabited Ξ±` instance,
constructively or otherwise.
-/
open Lean.Meta
namespace Lean.Elab.Tactic
/-- Derives `Inhabited Ξ±` from `Nonempty Ξ±` with `Classical.choice`-/
noncomputable def nonempty_to_inhabited (Ξ± : Sort*) (_ : Nonempty Ξ±) : Inhabited Ξ± :=
Inhabited.mk (Classical.ofNonempty)
/-- Derives `Inhabited Ξ±` from `Nonempty Ξ±` without `Classical.choice`
assuming `Ξ±` is of type `Prop`-/
def nonempty_prop_to_inhabited (Ξ± : Prop) (Ξ±_nonempty : Nonempty Ξ±) : Inhabited Ξ± :=
Inhabited.mk <| Nonempty.elim Ξ±_nonempty id
/--
`inhabit Ξ±` tries to derive a `Nonempty Ξ±` instance and
then uses it to make an `Inhabited Ξ±` instance.
If the target is a `Prop`, this is done constructively. Otherwise, it uses `Classical.choice`.
-/
syntax (name := inhabit) "inhabit " atomic(ident " : ")? term : tactic
/-- `evalInhabit` takes in the MVarId of the main goal, runs the core portion of the inhabit tactic,
and returns the resulting MVarId -/
def evalInhabit (goal : MVarId) (h_name : Option Ident) (term : Syntax) : TacticM MVarId := do
goal.withContext do
let e β Tactic.elabTerm term none
let e_lvl β Meta.getLevel e
let inhabited_e := mkApp (mkConst ``Inhabited [e_lvl]) e
let nonempty_e := mkApp (mkConst ``Nonempty [e_lvl]) e
let nonempty_e_pf β synthInstance nonempty_e
let h_name : Name :=
match h_name with
| some h_name => h_name.getId
| none => `inhabited_h
let pf β
if β isProp e then Meta.mkAppM ``nonempty_prop_to_inhabited #[e, nonempty_e_pf]
else Meta.mkAppM ``nonempty_to_inhabited #[e, nonempty_e_pf]
let (_, r) β (β goal.assert h_name inhabited_e pf).intro1P
return r
elab_rules : tactic
| `(tactic| inhabit $[$h_name:ident :]? $term) => do
let goal β evalInhabit (β getMainGoal) h_name term
replaceMainGoal [goal]
|
Tactic\IntervalCases.lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Mario Carneiro
-/
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.FinCases
/-!
# Case bash on variables in finite intervals
This file provides the tactic `interval_cases`. `interval_cases n` will:
1. inspect hypotheses looking for lower and upper bounds of the form `a β€ n` or `a < n` and `n < b`
or `n β€ b`, including the bound `0 β€ n` for `n : β` automatically.
2. call `fin_cases` on the synthesised hypothesis `n β Set.Ico a b`,
assuming an appropriate `Fintype` instance can be found for the type of `n`.
Currently, `n` must be of type `β` or `β€` (TODO: generalize).
You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`,
where the hypotheses should be of the form `hl : a β€ n` and `hu : n < b`. In that case,
`interval_cases` calls `fin_cases` on the resulting hypothesis `h : n β Set.Ico a b`.
-/
namespace Mathlib.Tactic
open Lean Meta Elab Tactic Term Qq Int
namespace IntervalCases
/-- The result of `interval_cases` is a list of goals,
one for each integer value between the bounds. -/
structure IntervalCasesSubgoal where
/-- The target expression, a numeral in the input type -/
rhs : Expr
/-- The numeric value of the target expression -/
value : Int
/-- The new subgoal, of the form `β’ x = rhs β tgt` -/
goal : MVarId
/--
A `Bound` represents the result of analyzing a lower or upper bound expression.
If `e` is the scrutinee expression, then a lower bound expression like `3 < e`
is normalized to `Β¬e β€ 3` and represented as `.lt 3`, and an upper bound expression
like `e β€ 5` is represented as `.le 5`.
-/
inductive Bound
/-- A strictly less-than lower bound `n β± e` or upper bound `e β± n`. (`interval_cases` uses
less-equal exclusively, so less-than bounds are actually written as not-less-equal
with flipped arguments.) -/
| lt (n : β€)
/-- A less-than-or-equal lower bound `n β€ e` or upper bound `e β€ n`. -/
| le (n : β€)
/--
Assuming `Bound` represents a lower bound, this returns the (inclusive)
least integer value which is allowed. So `3 β€ e` means the lower bound is 3 and
`3 < e` means the lower bound is `4`.
-/
def Bound.asLower : Bound β β€
| .lt n => n + 1
| .le n => n
/--
Assuming `Bound` represents an upper bound, this returns the (inclusive)
greatest integer value which is allowed. So `e β€ 3` means the lower bound is 3 and
`e < 3` means the upper bound is `2`. Note that in the case of `e < 0` on `Nat`
the upper bound is `-1`, which is not representable as a `Nat`;
this is why we have to treat the `.lt` and `.le` cases separately instead of normalizing
everything to `.le` bounds.
-/
def Bound.asUpper : Bound β β€
| .lt n => n - 1
| .le n => n
/--
Given a type `ty` (the type of a hypothesis in the context or a provided expression),
attempt to parse it as an inequality, and return `(a, b, strict, positive)`, where
`positive` means it is a negated inequality and `strict` means it is a strict inequality
(`a < b` or `a β± b`). `a` is always the lesser argument and `b` the greater one.
-/
def parseBound (ty : Expr) : MetaM (Expr Γ Expr Γ Bool Γ Bool) := do
let ty β whnfR ty
if ty.isAppOfArity ``Not 1 then
let ty β whnfR ty.appArg!
if ty.isAppOfArity ``LT.lt 4 then
pure (ty.appArg!, ty.appFn!.appArg!, false, false)
else if ty.isAppOfArity ``LE.le 4 then
pure (ty.appArg!, ty.appFn!.appArg!, true, false)
else failure
else if ty.isAppOfArity ``LT.lt 4 then
pure (ty.appFn!.appArg!, ty.appArg!, true, true)
else if ty.isAppOfArity ``LE.le 4 then
pure (ty.appFn!.appArg!, ty.appArg!, false, true)
else failure
/-- A "typeclass" (not actually a class) of methods for the type-specific handling of
`interval_cases`. To add support for a new type, you have to implement this interface and add
a dispatch case for it in `intervalCases`. -/
structure Methods where
/-- Given `e`, construct `(bound, n, p)` where `p` is a proof of `n β€ e` or `n < e`
(characterized by `bound`), or `failure` if the type is not lower-bounded. -/
initLB (e : Expr) : MetaM (Bound Γ Expr Γ Expr) := failure
/-- Given `e`, construct `(bound, n, p)` where `p` is a proof of `e β€ n` or `e < n`
(characterized by `bound`), or `failure` if the type is not upper-bounded. -/
initUB (e : Expr) : MetaM (Bound Γ Expr Γ Expr) := failure
/-- Given `a, b`, prove `a β€ b` or fail. -/
proveLE : Expr β Expr β MetaM Expr
/-- Given `a, b`, prove `a β± b` or fail. -/
proveLT : Expr β Expr β MetaM Expr
/-- Given `a, b, a', p` where `p` proves `a β± b` and `a' := a+1`, prove `a' β€ b`. -/
roundUp : Expr β Expr β Expr β Expr β MetaM Expr
/-- Given `a, b, b', p` where `p` proves `a β± b` and `b' := b-1`, prove `a β€ b'`. -/
roundDown : Expr β Expr β Expr β Expr β MetaM Expr
/-- Given `e`, return `(z, n, p)` where `p : e = n` and `n` is a numeral
appropriate for the type denoting the integer `z`. -/
eval : Expr β MetaM (Int Γ Expr Γ Expr)
/-- Construct the canonical numeral for integer `z`, or fail if `z` is out of range. -/
mkNumeral : Int β MetaM Expr
variable {Ξ± : Type*} {a b a' b' : Ξ±}
theorem of_not_lt_left [LinearOrder Ξ±] (h : Β¬(a:Ξ±) < b) (eq : a = a') : b β€ a' := eq βΈ not_lt.1 h
theorem of_not_lt_right [LinearOrder Ξ±] (h : Β¬(a:Ξ±) < b) (eq : b = b') : b' β€ a := eq βΈ not_lt.1 h
theorem of_not_le_left [LE Ξ±] (h : Β¬(a:Ξ±) β€ b) (eq : a = a') : Β¬a' β€ b := eq βΈ h
theorem of_not_le_right [LE Ξ±] (h : Β¬(a:Ξ±) β€ b) (eq : b = b') : Β¬a β€ b' := eq βΈ h
theorem of_lt_left [LinearOrder Ξ±] (h : (a:Ξ±) < b) (eq : a = a') : Β¬b β€ a' := eq βΈ not_le.2 h
theorem of_lt_right [LinearOrder Ξ±] (h : (a:Ξ±) < b) (eq : b = b') : Β¬b' β€ a := eq βΈ not_le.2 h
theorem of_le_left [LE Ξ±] (h : (a:Ξ±) β€ b) (eq : a = a') : a' β€ b := eq βΈ h
theorem of_le_right [LE Ξ±] (h : (a:Ξ±) β€ b) (eq : b = b') : a β€ b' := eq βΈ h
/--
Given a proof `pf`, attempts to parse it as an upper (`lb = false`) or lower (`lb = true`)
bound on `n`. If successful, it returns `(bound, n, pf')` where `n` is a numeral and
`pf'` proves `n β€ e` or `n β± e` (as described by `bound`).
-/
def Methods.getBound (m : Methods) (e : Expr) (pf : Expr) (lb : Bool) :
MetaM (Bound Γ Expr Γ Expr) := do
let (e', c) β match β parseBound (β inferType pf), lb with
| (b, a, false, false), false =>
let (z, a', eq) β m.eval a; pure (b, .le z, a', β mkAppM ``of_not_lt_left #[pf, eq])
| (b, a, false, false), true =>
let (z, b', eq) β m.eval b; pure (a, .le z, b', β mkAppM ``of_not_lt_right #[pf, eq])
| (a, b, false, true), false =>
let (z, b', eq) β m.eval b; pure (a, .le z, b', β mkAppM ``of_le_right #[pf, eq])
| (a, b, false, true), true =>
let (z, a', eq) β m.eval a; pure (b, .le z, a', β mkAppM ``of_le_left #[pf, eq])
| (b, a, true, false), false =>
let (z, a', eq) β m.eval a; pure (b, .lt z, a', β mkAppM ``of_not_le_left #[pf, eq])
| (b, a, true, false), true =>
let (z, b', eq) β m.eval b; pure (a, .lt z, b', β mkAppM ``of_not_le_right #[pf, eq])
| (a, b, true, true), false =>
let (z, b', eq) β m.eval b; pure (a, .lt z, b', β mkAppM ``of_lt_right #[pf, eq])
| (a, b, true, true), true =>
let (z, a', eq) β m.eval a; pure (b, .lt z, a', β mkAppM ``of_lt_left #[pf, eq])
let .true β withNewMCtxDepth <| withReducible <| isDefEq e e' | failure
pure c
theorem le_of_not_le_of_le {hi n lo : Ξ±} [LinearOrder Ξ±] (h1 : Β¬hi β€ n) (h2 : hi β€ lo) :
(n:Ξ±) β€ lo :=
le_trans (le_of_not_le h1) h2
/--
Given `(z1, e1, p1)` a lower bound on `e` and `(z2, e2, p2)` an upper bound on `e`,
such that the distance between the bounds is negative, returns a proof of `False`.
-/
def Methods.inconsistentBounds (m : Methods)
(z1 z2 : Bound) (e1 e2 p1 p2 e : Expr) : MetaM Expr := do
match z1, z2 with
| .le lo, .lt hi =>
if lo == hi then return p2.app p1
return p2.app (β mkAppM ``le_trans #[β m.proveLE e2 e1, p1])
| .lt lo, .le hi =>
if lo == hi then return p1.app p2
return p1.app (β mkAppM ``le_trans #[p2, β m.proveLE e2 e1])
| .le _, .le _ => return (β m.proveLT e2 e1).app (β mkAppM ``le_trans #[p1, p2])
| .lt lo, .lt hi =>
if hi β€ lo then return p1.app (β mkAppM ``le_of_not_le_of_le #[p2, β m.proveLE e2 e1])
let e3 β m.mkNumeral (hi - 1)
let p3 β m.roundDown e e2 e3 p2
return p1.app (β mkAppM ``le_trans #[p3, β m.proveLE e3 e1])
/--
Given `(z1, e1, p1)` a lower bound on `e` and `(z2, e2, p2)` an upper bound on `e`, such that the
distance between the bounds matches the number of `cases` in the subarray (which must be positive),
proves the goal `g` using the metavariables in the array by recursive bisection.
This is the core of the tactic, producing a case tree of if statements which bottoms out
at the `cases`.
-/
partial def Methods.bisect (m : Methods) (g : MVarId) (cases : Subarray IntervalCasesSubgoal)
(z1 z2 : Bound) (e1 e2 p1 p2 e : Expr) : MetaM Unit := g.withContext do
if 1 < cases.size then
let tgt β g.getType
let mid := cases.size / 2
let z3 := z1.asLower + mid
let e3 β m.mkNumeral z3
let le β mkAppM ``LE.le #[e3, e]
let gβ β mkFreshExprMVar (β mkArrow (mkNot le) tgt) .syntheticOpaque
let gβ β mkFreshExprMVar (β mkArrow le tgt) .syntheticOpaque
g.assign <| β mkAppM ``dite #[le, gβ, gβ]
let (xβ, gβ) β gβ.mvarId!.intro1
m.bisect gβ cases[:mid] z1 (.lt z3) e1 e3 p1 (.fvar xβ) e
let (xβ, gβ) β gβ.mvarId!.intro1
m.bisect gβ cases[mid:] (.le z3) z2 e3 e2 (.fvar xβ) p2 e
else if _x : 0 < cases.size then
let { goal, rhs, .. } := cases[0]
let pfβ β match z1 with | .le _ => pure p1 | .lt _ => m.roundUp e1 e rhs p1
let pfβ β match z2 with | .le _ => pure p2 | .lt _ => m.roundDown e e2 rhs p2
g.assign (.app (.mvar goal) (β mkAppM ``le_antisymm #[pfβ, pfβ]))
else panic! "no goals"
/-- A `Methods` implementation for `β`.
This tells `interval_cases` how to work on natural numbers. -/
def natMethods : Methods where
initLB (e : Q(β)) :=
pure (.le 0, q(0), q(Nat.zero_le $e))
eval e := do
let β¨z, e, pβ© := (β NormNum.derive (Ξ± := (q(β) : Q(Type))) e).toRawIntEq.get!
pure (z, e, p)
proveLE (lhs rhs : Q(β)) := mkDecideProof q($lhs β€ $rhs)
proveLT (lhs rhs : Q(β)) := mkDecideProof q(Β¬$rhs β€ $lhs)
roundUp (lhs rhs _ : Q(β)) (p : Q(Β¬$rhs β€ $lhs)) := pure q(Nat.gt_of_not_le $p)
roundDown (lhs _ rhs' : Q(β)) (p : Q(Β¬Nat.succ $rhs' β€ $lhs)) := pure q(Nat.ge_of_not_lt $p)
mkNumeral
| (i : β) => pure q($i)
| _ => failure
theorem _root_.Int.add_one_le_of_not_le {a b : β€} (h : Β¬b β€ a) : a + 1 β€ b :=
Int.add_one_le_iff.2 (Int.not_le.1 h)
theorem _root_.Int.le_sub_one_of_not_le {a b : β€} (h : Β¬b β€ a) : a β€ b - 1 :=
Int.le_sub_one_iff.2 (Int.not_le.1 h)
/-- A `Methods` implementation for `β€`.
This tells `interval_cases` how to work on integers. -/
def intMethods : Methods where
eval e := do
let β¨z, e, pβ© := (β NormNum.derive (Ξ± := (q(β€) : Q(Type))) e).toRawIntEq.get!
pure (z, e, p)
proveLE (lhs rhs : Q(β€)) := mkDecideProof q($lhs β€ $rhs)
proveLT (lhs rhs : Q(β€)) := mkDecideProof q(Β¬$rhs β€ $lhs)
roundUp (lhs rhs _ : Q(β€)) (p : Q(Β¬$rhs β€ $lhs)) := pure q(Int.add_one_le_of_not_le $p)
roundDown (lhs rhs _ : Q(β€)) (p : Q(Β¬$rhs β€ $lhs)) := pure q(Int.le_sub_one_of_not_le $p)
mkNumeral
| (i : Nat) => let n : Q(β) := mkRawNatLit i; pure q(OfNat.ofNat $n : β€)
| .negSucc i => let n : Q(β) := mkRawNatLit (i+1); pure q(-OfNat.ofNat $n : β€)
/--
`intervalCases` proves goal `g` by splitting into cases for each integer between the given bounds.
Parameters:
* `g`: the goal, which can have any type `β’ tgt` (it works in both proofs and programs)
* `e`: the scrutinee, the expression we are proving is bounded between integers
* `e'`: a version of `e` used for error messages. (This is used by the `interval_cases` frontend
tactic because it uses a fresh variable for `e`, so it is more helpful to show the
pre-generalized expression in error messages.)
* `lbs`: A list of candidate lower bound expressions.
The tactic will automatically pick the best lower bound it can find from the list.
* `ubs`: A list of candidate upper bound expressions.
The tactic will automatically pick the best upper bound it can find from the list.
* `mustUseBounds`: If true, the tactic will fail if it is unable to parse any of the
given `ubs` or `lbs` into bounds. If false (the default), these will be silently skipped
and an error message is only produced if we could not find any bounds (including those supplied
by the type itself, e.g. if we are working over `Nat` or `Fin n`).
Returns an array of `IntervalCasesSubgoal`, one per subgoal. A subgoal has the following fields:
* `rhs`: the numeral expression for this case
* `value`: the integral value of `rhs`
* `goal`: the subgoal of type `β’ e = rhs β tgt`
Note that this tactic does not perform any substitution or introduction steps -
all subgoals are in the same context as `goal` itself.
-/
def intervalCases (g : MVarId) (e e' : Expr) (lbs ubs : Array Expr) (mustUseBounds := false) :
MetaM (Array IntervalCasesSubgoal) := g.withContext do
let Ξ± β whnfR (β inferType e)
let m β
if Ξ±.isConstOf ``Nat then pure natMethods else
if Ξ±.isConstOf ``Int then pure intMethods else
-- if Ξ±.isConstOf ``PNat then pure pnatMethods else
throwError "interval_cases failed: unsupported type {Ξ±}"
let mut lb β try? (m.initLB e)
for pf in lbs do
if let some lb1 β try? (m.getBound e pf true) then
if lb.all (Β·.1.asLower < lb1.1.asLower) then
lb := some lb1
else if mustUseBounds then
throwError "interval_cases failed: provided bound '{β inferType pf}' cannot be evaluated"
let mut ub β try? (m.initUB e)
for pf in ubs do
if let some ub1 β try? (m.getBound e pf false) then
if ub.all (Β·.1.asUpper > ub1.1.asUpper) then
ub := some ub1
else if mustUseBounds then
throwError "interval_cases failed: provided bound '{β inferType pf}' cannot be evaluated"
match lb, ub with
| some (z1, e1, p1), some (z2, e2, p2) =>
if z1.asLower > z2.asUpper then
(β g.exfalso).assign (β m.inconsistentBounds z1 z2 e1 e2 p1 p2 e)
pure #[]
else
let mut goals := #[]
let lo := z1.asLower
let tgt β g.getType
let tag β g.getTag
for i in [:(z2.asUpper-lo+1).toNat] do
let z := lo+i
let rhs β m.mkNumeral z
let ty β mkArrow (β mkEq e rhs) tgt
let goal β mkFreshExprMVar ty .syntheticOpaque (appendTag tag (.mkSimple (toString z)))
goals := goals.push { rhs, value := z, goal := goal.mvarId! }
m.bisect g goals.toSubarray z1 z2 e1 e2 p1 p2 e
pure goals
| none, some _ => throwError "interval_cases failed: could not find lower bound on {e'}"
| some _, none => throwError "interval_cases failed: could not find upper bound on {e'}"
| none, none => throwError "interval_cases failed: could not find bounds on {e'}"
end IntervalCases
open IntervalCases
/--
`interval_cases n` searches for upper and lower bounds on a variable `n`,
and if bounds are found,
splits into separate cases for each possible value of `n`.
As an example, in
```
example (n : β) (wβ : n β₯ 3) (wβ : n < 5) : n = 3 β¨ n = 4 := by
interval_cases n
all_goals simp
```
after `interval_cases n`, the goals are `3 = 3 β¨ 3 = 4` and `4 = 3 β¨ 4 = 4`.
You can also explicitly specify a lower and upper bound to use,
as `interval_cases using hl, hu`.
The hypotheses should be in the form `hl : a β€ n` and `hu : n < b`,
in which case `interval_cases` calls `fin_cases` on the resulting fact `n β Set.Ico a b`.
You can specify a name `h` for the new hypothesis,
as `interval_cases h : n` or `interval_cases h : n using hl, hu`.
-/
syntax (name := intervalCases) "interval_cases" (ppSpace colGt atomic(binderIdent " : ")? term)?
(" using " term ", " term)? : tactic
elab_rules : tactic
| `(tactic| interval_cases $[$[$h :]? $e]? $[using $lb, $ub]?) => do
let g β getMainGoal
let cont x h? subst g e lbs ubs mustUseBounds : TacticM Unit := do
let goals β IntervalCases.intervalCases g (.fvar x) e lbs ubs mustUseBounds
let gs β goals.mapM fun { goal, .. } => do
let (fv, g) β goal.intro1
let (subst, g) β substCore g fv (fvarSubst := subst)
if let some hStx := h.getD none then
if let some fv := h? then
g.withContext <| (subst.get fv).addLocalVarInfoForBinderIdent hStx
pure g
replaceMainGoal gs.toList
g.withContext do
let hName? := (h.getD none).map fun
| `(binderIdent| $n:ident) => n.getId
| _ => `_
match e, lb, ub with
| e, some lb, some ub =>
let e β if let some e := e then Tactic.elabTerm e none else mkFreshExprMVar none
let lb' β Tactic.elabTerm lb none
let ub' β Tactic.elabTerm ub none
let lbTy β inferType lb'
let ubTy β inferType ub'
try
let (_, hi, _) β parseBound lbTy
let .true β isDefEq e hi | failure
catch _ => throwErrorAt lb "expected a term of the form _ < {e} or _ β€ {e}, got {lbTy}"
try
let (lo, _) β parseBound ubTy
let .true β isDefEq e lo | failure
catch _ => throwErrorAt ub "expected a term of the form {e} < _ or {e} β€ _, got {ubTy}"
let (subst, xs, g) β g.generalizeHyp #[{ expr := e, hName? }] (β getFVarIdsAt g)
g.withContext do
cont xs[0]! xs[1]? subst g e #[subst.apply lb'] #[subst.apply ub'] (mustUseBounds := true)
| some e, none, none =>
let e β Tactic.elabTerm e none
let (subst, xs, g) β g.generalizeHyp #[{ expr := e, hName? }] (β getFVarIdsAt g)
let x := xs[0]!
g.withContext do
let e := subst.apply e
let mut lbs := #[]
let mut ubs := #[]
for ldecl in β getLCtx do
try
let (lo, hi, _) β parseBound ldecl.type
if β withNewMCtxDepth <| withReducible <| isDefEq (.fvar x) lo then
ubs := ubs.push (.fvar ldecl.fvarId)
else if β withNewMCtxDepth <| withReducible <| isDefEq (.fvar x) hi then
lbs := lbs.push (.fvar ldecl.fvarId)
else failure
catch _ => pure ()
cont x xs[1]? subst g e lbs ubs (mustUseBounds := false)
| _, _, _ => throwUnsupportedSyntax
end Tactic
end Mathlib
|
Tactic\IrreducibleDef.lean | /-
Copyright (c) 2021 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean
import Mathlib.Tactic.Eqns
import Mathlib.Data.Subtype
/-!
# Irreducible definitions
This file defines an `irreducible_def` command,
which works almost like the `def` command
except that the introduced definition
does not reduce to the value.
Instead, the command
adds a `_def` lemma
which can be used for rewriting.
```
irreducible_def frobnicate (a b : Nat) :=
a + b
example : frobnicate a 0 = a := by
simp [frobnicate_def]
```
-/
namespace Lean.Elab.Command
open Term Meta
/-- `delta% t` elaborates to a head-delta reduced version of `t`. -/
elab "delta% " t:term : term <= expectedType => do
let t β elabTerm t expectedType
synthesizeSyntheticMVars
let t β instantiateMVars t
let some t β delta? t | throwError "cannot delta reduce {t}"
pure t
/-- `eta_helper f = (Β· + 3)` elabs to `β x, f x = x + 3` -/
local elab "eta_helper " t:term : term => do
let t β elabTerm t none
let some (_, lhs, rhs) := t.eq? | throwError "not an equation: {t}"
synthesizeSyntheticMVars
let rhs β instantiateMVars rhs
lambdaTelescope rhs fun xs rhs β¦ do
let lhs := (mkAppN lhs xs).headBeta
mkForallFVars xs <|β mkEq lhs rhs
/-- `val_proj x` elabs to the *primitive projection* `@x.val`. -/
local elab "val_proj " e:term : term => do
let e β elabTerm (β `(($e : Subtype _))) none
return mkProj ``Subtype 0 e
/--
Executes the commands,
and stops after the first error.
In short, S-A-F-E.
-/
local syntax "stop_at_first_error" (ppLine command)* : command
open Command in elab_rules : command
| `(stop_at_first_error $[$cmds]*) => do
for cmd in cmds do
elabCommand cmd.raw
if (β get).messages.hasErrors then break
syntax irredDefLemma := atomic(" (" &"lemma" " := ") ident ")"
/--
Introduces an irreducible definition.
`irreducible_def foo := 42` generates
a constant `foo : Nat` as well as
a theorem `foo_def : foo = 42`.
-/
elab mods:declModifiers "irreducible_def" n_id:declId n_def:(irredDefLemma)?
declSig:ppIndent(optDeclSig) val:declVal :
command => do
let declSig : TSyntax ``Parser.Command.optDeclSig := β¨declSig.rawβ© -- HACK
let (n, us) β match n_id with
| `(Parser.Command.declId| $n:ident $[.{$us,*}]?) => pure (n, us)
| _ => throwUnsupportedSyntax
let us' := us.getD { elemsAndSeps := #[] }
let n_def β match n_def.getD β¨mkNullNodeβ© with
| `(irredDefLemma| (lemma := $id)) => pure id
| _ => pure <| mkIdentFrom n <| (Β·.review) <|
let scopes := extractMacroScopes n.getId
{ scopes with name := scopes.name.appendAfter "_def" }
let `(Parser.Command.declModifiersF|
$[$doc:docComment]? $[@[$attrs,*]]?
$[$vis]? $[$nc:noncomputable]? $[$uns:unsafe]?) := mods
| throwError "unsupported modifiers {format mods}"
let attrs := attrs.getD {}
let prot := vis.filter (Β· matches `(Parser.Command.visibility| protected))
let priv := vis.filter (Β· matches `(Parser.Command.visibility| private))
elabCommand <|<- `(stop_at_first_error
$[$nc:noncomputable]? $[$uns]? def definition$[.{$us,*}]? $declSig:optDeclSig $val
$[$nc:noncomputable]? $[$uns]? opaque wrapped$[.{$us,*}]? : Subtype (Eq @definition.{$us',*}) :=
β¨_, rflβ©
$[$doc:docComment]? $[private%$priv]? $[$nc:noncomputable]? $[$uns]?
def $n:ident$[.{$us,*}]? :=
val_proj @wrapped.{$us',*}
$[private%$priv]? $[$uns:unsafe]? theorem $n_def:ident $[.{$us,*}]? :
eta_helper Eq @$n.{$us',*} @(delta% @definition) := by
intros
delta $n:ident
rw [show wrapped = β¨@definition.{$us',*}, rflβ© from Subtype.ext wrapped.2.symm]
rfl
attribute [irreducible] $n definition
attribute [eqns $n_def] $n
attribute [$attrs:attrInstance,*] $n)
if prot.isSome then
modifyEnv (addProtected Β· ((β getCurrNamespace) ++ n.getId))
|
Tactic\ITauto.lean | /-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Batteries.Logic
import Batteries.Tactic.Exact
import Mathlib.Tactic.Hint
import Mathlib.Tactic.DeriveToExpr
import Mathlib.Util.AtomM
import Mathlib.Init.Logic
import Qq
/-!
# Intuitionistic tautology (`itauto`) decision procedure
The `itauto` tactic will prove any intuitionistic tautology. It implements the well known
`G4ip` algorithm:
[Dyckhoff, *Contraction-free sequent calculi for intuitionistic logic*][dyckhoff_1992].
All built in propositional connectives are supported: `True`, `False`, `And`, `Or`, `β`,
`Not`, `Iff`, `Xor'`, as well as `Eq` and `Ne` on propositions. Anything else, including definitions
and predicate logical connectives (`β` and `β`), are not supported, and will have to be
simplified or instantiated before calling this tactic.
The resulting proofs will never use any axioms except possibly `propext`, and `propext` is only
used if the input formula contains an equality of propositions `p = q`. Using `itauto!`, one can
enable the selective use of LEM for case splitting on specified propositions.
## Implementation notes
The core logic of the prover is in three functions:
* `prove : Context β IProp β StateM Nat (Bool Γ Proof)`: The main entry point.
Gets a context and a goal, and returns a `proof` object or fails, using `StateM Nat` for the name
generator.
* `search : Context β IProp β StateM Nat (Bool Γ Proof)`: Same meaning as `proof`, called during the
search phase (see below).
* `Context.add : IProp β Proof β Context β Except (IProp β Proof) Context`: Adds a proposition with
its proof into the context, but it also does some simplifications on the spot while doing so.
It will either return the new context, or if it happens to notice a proof of false, it will
return a function to compute a proof of any proposition in the original context.
The intuitionistic logic rules are separated into three groups:
* level 1: No splitting, validity preserving: apply whenever you can.
Left rules in `Context.add`, right rules in `prove`.
* `Context.add`:
* simplify `Ξ, β€ β’ B` to `Ξ β’ B`
* `Ξ, β₯ β’ B` is true
* simplify `Ξ, A β§ B β’ C` to `Ξ, A, B β’ C`
* simplify `Ξ, β₯ β A β’ B` to `Ξ β’ B`
* simplify `Ξ, β€ β A β’ B` to `Ξ, A β’ B`
* simplify `Ξ, A β§ B β C β’ D` to `Ξ, A β B β C β’ D`
* simplify `Ξ, A β¨ B β C β’ D` to `Ξ, A β C, B β C β’ D`
* `prove`:
* `Ξ β’ β€` is true
* simplify `Ξ β’ A β B` to `Ξ, A β’ B`
* `search`:
* `Ξ, P β’ P` is true
* simplify `Ξ, P, P β A β’ B` to `Ξ, P, A β’ B`
* level 2: Splitting rules, validity preserving: apply after level 1 rules. Done in `prove`
* simplify `Ξ β’ A β§ B` to `Ξ β’ A` and `Ξ β’ B`
* simplify `Ξ, A β¨ B β’ C` to `Ξ, A β’ C` and `Ξ, B β’ C`
* level 3: Splitting rules, not validity preserving: apply only if nothing else applies.
Done in `search`
* `Ξ β’ A β¨ B` follows from `Ξ β’ A`
* `Ξ β’ A β¨ B` follows from `Ξ β’ B`
* `Ξ, (Aβ β Aβ) β C β’ B` follows from `Ξ, Aβ β C, Aβ β’ Aβ` and `Ξ, C β’ B`
This covers the core algorithm, which only handles `True`, `False`, `And`, `Or`, and `β`.
For `Iff` and `Eq`, we treat them essentially the same as `(p β q) β§ (q β p)`, although we use
a different `IProp` representation because we have to remember to apply different theorems during
replay. For definitions like `Not` and `Xor'`, we just eagerly unfold them. (This could potentially
cause a blowup issue for `Xor'`, but it isn't used very often anyway. We could add it to the `IProp`
grammar if it matters.)
## Tags
propositional logic, intuitionistic logic, decision procedure
-/
namespace Mathlib.Tactic.ITauto
/-- Different propositional constructors that are variants of "and" for the purposes of the
theorem prover. -/
inductive AndKind | and | iff | eq
deriving Lean.ToExpr, DecidableEq
instance : Inhabited AndKind := β¨AndKind.andβ©
/-- A reified inductive type for propositional logic. -/
inductive IProp : Type
| var : Nat β IProp -- propositional atoms P_i
| true : IProp -- β€
| false : IProp -- β₯
| and' : AndKind β IProp β IProp β IProp -- p β§ q, p β q, p = q
| or : IProp β IProp β IProp -- p β¨ q
| imp : IProp β IProp β IProp -- p β q
deriving Lean.ToExpr, DecidableEq
/-- Constructor for `p β§ q`. -/
@[match_pattern] def IProp.and : IProp β IProp β IProp := .and' .and
/-- Constructor for `p β q`. -/
@[match_pattern] def IProp.iff : IProp β IProp β IProp := .and' .iff
/-- Constructor for `p = q`. -/
@[match_pattern] def IProp.eq : IProp β IProp β IProp := .and' .eq
/-- Constructor for `Β¬ p`. -/
@[match_pattern] def IProp.not (a : IProp) : IProp := a.imp .false
/-- Constructor for `xor p q`. -/
@[match_pattern] def IProp.xor (a b : IProp) : IProp := (a.and b.not).or (b.and a.not)
instance : Inhabited IProp := β¨IProp.trueβ©
/-- Given the contents of an `And` variant, return the two conjuncts. -/
def AndKind.sides : AndKind β IProp β IProp β IProp Γ IProp
| .and, A, B => (A, B)
| _, A, B => (A.imp B, B.imp A)
/-- Debugging printer for propositions. -/
def IProp.format : IProp β Std.Format
| .var i => f!"v{i}"
| .true => f!"β€"
| .false => f!"β₯"
| .and p q => f!"({p.format} β§ {q.format})"
| .iff p q => f!"({p.format} β {q.format})"
| .eq p q => f!"({p.format} = {q.format})"
| .or p q => f!"({p.format} β¨ {q.format})"
| .imp p q => f!"({p.format} β {q.format})"
instance : Std.ToFormat IProp := β¨IProp.formatβ©
/-- A comparator for `AndKind`. (There should really be a derive handler for this.) -/
def AndKind.cmp (p q : AndKind) : Ordering := by
cases p <;> cases q
exacts [.eq, .lt, .lt, .gt, .eq, .lt, .gt, .gt, .eq]
/-- A comparator for propositions. (There should really be a derive handler for this.) -/
def IProp.cmp (p q : IProp) : Ordering := by
cases p <;> cases q
case var.var p q => exact compare p q
case true.true => exact .eq
case false.false => exact .eq
case and'.and' ap pβ pβ aq qβ qβ => exact (ap.cmp aq).then <| (pβ.cmp qβ).then (pβ.cmp qβ)
case or.or pβ pβ qβ qβ => exact (pβ.cmp qβ).then (pβ.cmp qβ)
case imp.imp pβ pβ qβ qβ => exact (pβ.cmp qβ).then (pβ.cmp qβ)
exacts [.lt, .lt, .lt, .lt, .lt,
.gt, .lt, .lt, .lt, .lt,
.gt, .gt, .lt, .lt, .lt,
.gt, .gt, .gt, .lt, .lt,
.gt, .gt, .gt, .gt, .lt,
.gt, .gt, .gt, .gt, .gt]
instance : LT IProp := β¨fun p q => p.cmp q = .ltβ©
instance : DecidableRel (@LT.lt IProp _) := fun _ _ => inferInstanceAs (Decidable (_ = _))
open Lean (Name)
/-- A reified inductive proof type for intuitionistic propositional logic. -/
inductive Proof
/-- `β’ A`, causes failure during reconstruction -/
| sorry : Proof
/-- `(n: A) β’ A` -/
| hyp (n : Name) : Proof
/-- `β’ β€` -/
| triv : Proof
/-- `(p: β₯) β’ A` -/
| exfalso' (p : Proof) : Proof
/-- `(p: (x: A) β’ B) β’ A β B` -/
| intro (x : Name) (p : Proof) : Proof
/--
* `ak = .and`: `(p: A β§ B) β’ A`
* `ak = .iff`: `(p: A β B) β’ A β B`
* `ak = .eq`: `(p: A = B) β’ A β B`
-/
| andLeft (ak : AndKind) (p : Proof) : Proof
/--
* `ak = .and`: `(p: A β§ B) β’ B`
* `ak = .iff`: `(p: A β B) β’ B β A`
* `ak = .eq`: `(p: A = B) β’ B β A`
-/
| andRight (ak : AndKind) (p : Proof) : Proof
/--
* `ak = .and`: `(pβ: A) (pβ: B) β’ A β§ B`
* `ak = .iff`: `(pβ: A β B) (pβ: B β A) β’ A β B`
* `ak = .eq`: `(pβ: A β B) (pβ: B β A) β’ A = B`
-/
| andIntro (ak : AndKind) (pβ pβ : Proof) : Proof
/--
* `ak = .and`: `(p: A β§ B β C) β’ A β B β C`
* `ak = .iff`: `(p: (A β B) β C) β’ (A β B) β (B β A) β C`
* `ak = .eq`: `(p: (A = B) β C) β’ (A β B) β (B β A) β C`
-/
| curry (ak : AndKind) (p : Proof) : Proof
/-- This is a partial application of curry.
* `ak = .and`: `(p: A β§ B β C) (q : A) β’ B β C`
* `ak = .iff`: `(p: (A β B) β C) (q: A β B) β’ (B β A) β C`
* `ak = .eq`: `(p: (A β B) β C) (q: A β B) β’ (B β A) β C`
-/
| curryβ (ak : AndKind) (p q : Proof) : Proof
/-- `(p: A β B) (q: A) β’ B` -/
| app' : Proof β Proof β Proof
/-- `(p: A β¨ B β C) β’ A β C` -/
| orImpL (p : Proof) : Proof
/-- `(p: A β¨ B β C) β’ B β C` -/
| orImpR (p : Proof) : Proof
/-- `(p: A) β’ A β¨ B` -/
| orInL (p : Proof) : Proof
/-- `(p: B) β’ A β¨ B` -/
| orInR (p : Proof) : Proof
/-- `(pβ: A β¨ B) (pβ: (x: A) β’ C) (pβ: (x: B) β’ C) β’ C` -/
| orElim' (pβ : Proof) (x : Name) (pβ pβ : Proof) : Proof
/-- `(pβ: Decidable A) (pβ: (x: A) β’ C) (pβ: (x: Β¬ A) β’ C) β’ C` -/
| decidableElim (classical : Bool) (pβ x : Name) (pβ pβ : Proof) : Proof
/--
* `classical = false`: `(p: Decidable A) β’ A β¨ Β¬A`
* `classical = true`: `(p: Prop) β’ p β¨ Β¬p`
-/
| em (classical : Bool) (p : Name) : Proof
/-- The variable `x` here names the variable that will be used in the elaborated proof.
* `(p: ((x:A) β B) β C) β’ B β C`
-/
| impImpSimp (x : Name) (p : Proof) : Proof
deriving Lean.ToExpr
instance : Inhabited Proof := β¨Proof.trivβ©
/-- Debugging printer for proof objects. -/
def Proof.format : Proof β Std.Format
| .sorry => "sorry"
| .hyp i => Std.format i
| .triv => "triv"
| .exfalso' p => f!"(exfalso {p.format})"
| .intro x p => f!"(fun {x} β¦ {p.format})"
| .andLeft _ p => f!"{p.format} .1"
| .andRight _ p => f!"{p.format} .2"
| .andIntro _ p q => f!"β¨{p.format}, {q.format}β©"
| .curry _ p => f!"(curry {p.format})"
| .curryβ _ p q => f!"(curry {p.format} {q.format})"
| .app' p q => f!"({p.format} {q.format})"
| .orImpL p => f!"(orImpL {p.format})"
| .orImpR p => f!"(orImpR {p.format})"
| .orInL p => f!"(Or.inl {p.format})"
| .orInR p => f!"(Or.inr {p.format})"
| .orElim' p x q r => f!"({p.format}.elim (fun {x} β¦ {q.format}) (fun {x} β¦ {r.format})"
| .em false p => f!"(Decidable.em {p})"
| .em true p => f!"(Classical.em {p})"
| .decidableElim _ p x q r => f!"({p}.elim (fun {x} β¦ {q.format}) (fun {x} β¦ {r.format})"
| .impImpSimp _ p => f!"(impImpSimp {p.format})"
instance : Std.ToFormat Proof := β¨Proof.formatβ©
/-- A variant on `Proof.exfalso'` that performs opportunistic simplification. -/
def Proof.exfalso : IProp β Proof β Proof
| .false, p => p
| _, p => .exfalso' p
/-- A variant on `Proof.orElim'` that performs opportunistic simplification. -/
def Proof.orElim : Proof β Name β Proof β Proof β Proof
| .em cl p, x, q, r => .decidableElim cl p x q r
| p, x, q, r => .orElim' p x q r
/-- A variant on `Proof.app'` that performs opportunistic simplification.
(This doesn't do full normalization because we don't want the proof size to blow up.) -/
def Proof.app : Proof β Proof β Proof
| .curry ak p, q => .curryβ ak p q
| .curryβ ak p q, r => p.app (q.andIntro ak r)
| .orImpL p, q => p.app q.orInL
| .orImpR p, q => p.app q.orInR
| .impImpSimp x p, q => p.app (.intro x q)
| p, q => p.app' q
-- Note(Mario): the typechecker is disabled because it requires proofs to carry around additional
-- props. These can be retrieved from the git history (rev 6c96d2ff7) if you want to re-enable this.
/-
/-- A typechecker for the `Proof` type. This is not used by the tactic but can be used for
debugging. -/
def Proof.check : Lean.NameMap IProp β Proof β Option IProp
| _, .sorry A => some A
| Ξ, .hyp i => Ξ.find? i
| _, triv => some .true
| Ξ, .exfalso' A p => guard (p.check Ξ = some .false) *> pure A
| Ξ, .intro x A p => do let B β p.check (Ξ.insert x A); pure (.imp A B)
| Ξ, .andLeft ak p => do
let .and' ak' A B β p.check Ξ | none
guard (ak = ak') *> pure (ak.sides A B).1
| Ξ, .andRight ak p => do
let .and' ak' A B β p.check Ξ | none
guard (ak = ak') *> pure (ak.sides A B).2
| Ξ, .andIntro .and p q => do
let A β p.check Ξ; let B β q.check Ξ
pure (A.and B)
| Ξ, .andIntro ak p q => do
let .imp A B β p.check Ξ | none
let C β q.check Ξ; guard (C = .imp B A) *> pure (A.and' ak B)
| Ξ, .curry ak p => do
let .imp (.and' ak' A B) C β p.check Ξ | none
let (A', B') := ak.sides A B
guard (ak = ak') *> pure (A'.imp $ B'.imp C)
| Ξ, .curryβ ak p q => do
let .imp (.and' ak' A B) C β p.check Ξ | none
let Aβ β q.check Ξ
let (A', B') := ak.sides A B
guard (ak = ak' β§ Aβ = A') *> pure (B'.imp C)
| Ξ, .app' p q => do
let .imp A B β p.check Ξ | none
let A' β q.check Ξ
guard (A = A') *> pure B
| Ξ, .orImpL B p => do
let .imp (.or A B') C β p.check Ξ | none
guard (B = B') *> pure (A.imp C)
| Ξ, .orImpR A p => do
let .imp (.or A' B) C β p.check Ξ | none
guard (A = A') *> pure (B.imp C)
| Ξ, .orInL B p => do let A β p.check Ξ; pure (A.or B)
| Ξ, .orInR A p => do let B β p.check Ξ; pure (A.or B)
| Ξ, .orElim' p x q r => do
let .or A B β p.check Ξ | none
let C β q.check (Ξ.insert x A)
let C' β r.check (Ξ.insert x B)
guard (C = C') *> pure C
| _, .em _ _ A => pure (A.or A.not)
| Ξ, .decidableElim _ A _ x pβ pβ => do
let C β pβ.check (Ξ.insert x A)
let C' β pβ.check (Ξ.insert x A.not)
guard (C = C') *> pure C
| Ξ, .impImpSimp _ A p => do
let .imp (.imp A' B) C β p.check Ξ | none
guard (A = A') *> pure (B.imp C)
-/
/-- Get a new name in the pattern `h0, h1, h2, ...` -/
@[inline] def freshName : StateM Nat Name := fun n => (Name.mkSimple s!"h{n}", n + 1)
/-- The context during proof search is a map from propositions to proof values. -/
def Context := Lean.RBMap IProp Proof IProp.cmp
/-- Debug printer for the context. -/
def Context.format (Ξ : Context) : Std.Format :=
Ξ.fold (init := "") fun f P p => P.format ++ " := " ++ p.format ++ ",\n" ++ f
instance : Std.ToFormat Context := β¨Context.formatβ©
/-- Insert a proposition and its proof into the context, as in `have : A := p`. This will eagerly
apply all level 1 rules on the spot, which are rules that don't split the goal and are validity
preserving: specifically, we drop `β€` and `A β β€` hypotheses, close the goal if we find a `β₯`
hypothesis, split all conjunctions, and also simplify `β₯ β A` (drop), `β€ β A` (simplify to `A`),
`A β§ B β C` (curry to `A β B β C`) and `A β¨ B β C` (rewrite to `(A β C) β§ (B β C)` and split). -/
partial def Context.add : IProp β Proof β Context β Except (IProp β Proof) Context
| .true, _, Ξ => pure Ξ
| .false, p, _ => throw fun A => .exfalso A p
| .and' ak A B, p, Ξ => do
let (A, B) := ak.sides A B
let Ξ β Ξ.add A (p.andLeft ak)
Ξ.add B (p.andRight ak)
| .imp .false _, _, Ξ => pure Ξ
| .imp .true A, p, Ξ => Ξ.add A (p.app .triv)
| .imp (.and' ak A B) C, p, Ξ =>
let (A, B) := ak.sides A B
Ξ.add (A.imp (B.imp C)) (p.curry ak)
| .imp (.or A B) C, p, Ξ => do
let Ξ β Ξ.add (A.imp C) p.orImpL
Ξ.add (B.imp C) p.orImpR
| .imp _ .true, _, Ξ => pure Ξ
| A, p, Ξ => pure (Ξ.insert A p)
/-- Add `A` to the context `Ξ` with proof `p`. This version of `Context.add` takes a continuation
and a target proposition `B`, so that in the case that `β₯` is found we can skip the continuation
and just prove `B` outright. -/
@[inline] def Context.withAdd (Ξ : Context) (A : IProp) (p : Proof) (B : IProp)
(f : Context β IProp β StateM Nat (Bool Γ Proof)) : StateM Nat (Bool Γ Proof) :=
match Ξ.add A p with
| .ok Ξ_A => f Ξ_A B
| .error p => pure (true, p B)
/-- Map a function over the proof (regardless of whether the proof is successful or not). -/
def mapProof (f : Proof β Proof) : Bool Γ Proof β Bool Γ Proof
| (b, p) => (b, f p)
/-- Convert a value-with-success to an optional value. -/
def isOk : (Bool Γ Proof) Γ Nat β Option (Proof Γ Nat)
| ((false, _), _) => none
| ((true, p), n) => some (p, n)
/-- Skip the continuation and return a failed proof if the boolean is false. -/
def whenOk : Bool β IProp β StateM Nat (Bool Γ Proof) β StateM Nat (Bool Γ Proof)
| false, _, _ => pure (false, .sorry)
| true, _, f => f
mutual
/-- The search phase, which deals with the level 3 rules, which are rules that are not validity
preserving and so require proof search. One obvious one is the or-introduction rule: we prove
`A β¨ B` by proving `A` or `B`, and we might have to try one and backtrack.
There are two rules dealing with implication in this category: `p, p β C β’ B` where `p` is an
atom (which is safe if we can find it but often requires the right search to expose the `p`
assumption), and `(Aβ β Aβ) β C β’ B`. We decompose the double implication into two subgoals: one to
prove `Aβ β Aβ`, which can be written `Aβ β C, Aβ β’ Aβ` (where we used `Aβ` to simplify
`(Aβ β Aβ) β C`), and one to use the consequent, `C β’ B`. The search here is that there are
potentially many implications to split like this, and we have to try all of them if we want to be
complete. -/
partial def search (Ξ : Context) (B : IProp) : StateM Nat (Bool Γ Proof) := do
if let some p := Ξ.find? B then return (true, p)
fun n =>
let searchβ := Ξ.fold (init := none) fun r A p => do
if let some r := r then return r
let .imp A' C := A | none
if let some q := Ξ.find? A' then
isOk <| Context.withAdd (Ξ.erase A) C (p.app q) B prove n
else
let .imp Aβ Aβ := A' | none
let Ξ : Context := Ξ.erase A
let (a, n) := freshName n
let (pβ, n) β isOk <| Ξ.withAdd Aβ (.hyp a) Aβ (fun Ξ_Aβ Aβ =>
Ξ_Aβ.withAdd (IProp.imp Aβ C) (.impImpSimp a p) Aβ prove) n
isOk <| Ξ.withAdd C (p.app (.intro a pβ)) B prove n
if let some (r, n) := searchβ then
((true, r), n)
else if let .or Bβ Bβ := B then
match (mapProof .orInL <$> prove Ξ Bβ) n with
| ((false, _), _) => (mapProof .orInR <$> prove Ξ Bβ) n
| r => r
else ((false, .sorry), n)
/-- The main prover. This receives a context of proven or assumed lemmas and a target proposition,
and returns a proof or `none` (with state for the fresh variable generator).
The intuitionistic logic rules are separated into three groups:
* level 1: No splitting, validity preserving: apply whenever you can.
Left rules in `Context.add`, right rules in `prove`
* level 2: Splitting rules, validity preserving: apply after level 1 rules. Done in `prove`
* level 3: Splitting rules, not validity preserving: apply only if nothing else applies.
Done in `search`
The level 1 rules on the right of the turnstile are `Ξ β’ β€` and `Ξ β’ A β B`, these are easy to
handle. The rule `Ξ β’ A β§ B` is a level 2 rule, also handled here. If none of these apply, we try
the level 2 rule `A β¨ B β’ C` by searching the context and splitting all ors we find. Finally, if
we don't make any more progress, we go to the search phase.
-/
partial def prove (Ξ : Context) (B : IProp) : StateM Nat (Bool Γ Proof) :=
match B with
| .true => pure (true, .triv)
| .imp A B => do
let a β freshName
mapProof (.intro a) <$> Ξ.withAdd A (.hyp a) B prove
| .and' ak A B => do
let (A, B) := ak.sides A B
let (ok, p) β prove Ξ A
mapProof (p.andIntro ak) <$> whenOk ok B (prove Ξ B)
| B =>
Ξ.fold
(init := fun found Ξ => bif found then prove Ξ B else search Ξ B)
(f := fun IH A p found Ξ => do
if let .or Aβ Aβ := A then
let Ξ : Context := Ξ.erase A
let a β freshName
let (ok, pβ) β Ξ.withAdd Aβ (.hyp a) B fun Ξ _ => IH true Ξ
mapProof (.orElim p a pβ) <$>
whenOk ok B (Ξ.withAdd Aβ (.hyp a) B fun Ξ _ => IH true Ξ)
else IH found Ξ)
(found := false) (Ξ := Ξ)
end
open Lean Qq Meta
/-- Reify an `Expr` into a `IProp`, allocating anything non-propositional as an atom in the
`AtomM` state. -/
partial def reify (e : Q(Prop)) : AtomM IProp :=
match e with
| ~q(True) => return .true
| ~q(False) => return .false
| ~q(Β¬ $a) => return .not (β reify a)
| ~q($a β§ $b) => return .and (β reify a) (β reify b)
| ~q($a β¨ $b) => return .or (β reify a) (β reify b)
| ~q($a β $b) => return .iff (β reify a) (β reify b)
| ~q(Xor' $a $b) => return .xor (β reify a) (β reify b)
| ~q(@Eq Prop $a $b) => return .eq (β reify a) (β reify b)
| ~q(@Ne Prop $a $b) => return .not (.eq (β reify a) (β reify b))
| e =>
if e.isArrow then return .imp (β reify e.bindingDomain!) (β reify e.bindingBody!)
else return .var (β AtomM.addAtom e)
/-- Once we have a proof object, we have to apply it to the goal. -/
partial def applyProof (g : MVarId) (Ξ : NameMap Expr) (p : Proof) : MetaM Unit :=
match p with
| .sorry => throwError "itauto failed\n{g}"
| .hyp n => do g.assignIfDefeq (β liftOption (Ξ.find? n))
| .triv => g.assignIfDefeq q(trivial)
| .exfalso' p => do
let A β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q(False)
g.assignIfDefeq q(@False.elim $A $t)
applyProof t.mvarId! Ξ p
| .intro x p => do
let (e, g) β g.intro x; g.withContext do
applyProof g (Ξ.insert x (.fvar e)) p
| .andLeft .and p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A β§ $B)
g.assignIfDefeq q(And.left $t)
applyProof t.mvarId! Ξ p
| .andLeft .iff p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A β $B)
g.assignIfDefeq q(Iff.mp $t)
applyProof t.mvarId! Ξ p
| .andLeft .eq p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A = $B)
g.assignIfDefeq q(cast $t)
applyProof t.mvarId! Ξ p
| .andRight .and p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A β§ $B)
g.assignIfDefeq q(And.right $t)
applyProof t.mvarId! Ξ p
| .andRight .iff p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A β $B)
g.assignIfDefeq q(Iff.mpr $t)
applyProof t.mvarId! Ξ p
| .andRight .eq p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ q($A = $B)
g.assignIfDefeq q(cast (Eq.symm $t))
applyProof t.mvarId! Ξ p
| .andIntro .and p q => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ (u := .zero) A
let tβ β mkFreshExprMVarQ (u := .zero) B
g.assignIfDefeq q(And.intro $tβ $tβ)
applyProof tβ.mvarId! Ξ p
applyProof tβ.mvarId! Ξ q
| .andIntro .iff p q => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β $B)
let tβ β mkFreshExprMVarQ q($B β $A)
g.assignIfDefeq q(Iff.intro $tβ $tβ)
applyProof tβ.mvarId! Ξ p
applyProof tβ.mvarId! Ξ q
| .andIntro .eq p q => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β $B)
let tβ β mkFreshExprMVarQ q($B β $A)
g.assignIfDefeq q(propext (Iff.intro $tβ $tβ))
applyProof tβ.mvarId! Ξ p
applyProof tβ.mvarId! Ξ q
| .app' p q => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β $B)
let tβ β mkFreshExprMVarQ (u := .zero) A
g.assignIfDefeq q($tβ $tβ)
applyProof tβ.mvarId! Ξ p
applyProof tβ.mvarId! Ξ q
| .orInL p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ (u := .zero) A
g.assignIfDefeq q(@Or.inl $A $B $t)
applyProof t.mvarId! Ξ p
| .orInR p => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let t β mkFreshExprMVarQ (u := .zero) B
g.assignIfDefeq q(@Or.inr $A $B $t)
applyProof t.mvarId! Ξ p
| .orElim' p x pβ pβ => do
let A β mkFreshExprMVarQ q(Prop)
let B β mkFreshExprMVarQ q(Prop)
let C β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β¨ $B)
let tβ β mkFreshExprMVarQ q($A β $C)
let tβ β mkFreshExprMVarQ q($B β $C)
g.assignIfDefeq q(Or.elim $tβ $tβ $tβ)
applyProof tβ.mvarId! Ξ p
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
| .em false n => do
let A β mkFreshExprMVarQ q(Prop)
let e : Q(Decidable $A) β liftOption (Ξ.find? n)
let .true β Meta.isDefEq (β Meta.inferType e) q(Decidable $A) | failure
g.assignIfDefeq q(@Decidable.em $A $e)
| .em true n => do
let A : Q(Prop) β liftOption (Ξ.find? n)
g.assignIfDefeq q(@Classical.em $A)
| .decidableElim false n x pβ pβ => do
let A β mkFreshExprMVarQ q(Prop)
let e : Q(Decidable $A) β liftOption (Ξ.find? n)
let .true β Meta.isDefEq (β Meta.inferType e) q(Decidable $A) | failure
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β $B)
let tβ β mkFreshExprMVarQ q(Β¬$A β $B)
g.assignIfDefeq q(@dite $B $A $e $tβ $tβ)
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
| .decidableElim true n x pβ pβ => do
let A : Q(Prop) β liftOption (Ξ.find? n)
let B β mkFreshExprMVarQ q(Prop)
let tβ β mkFreshExprMVarQ q($A β $B)
let tβ β mkFreshExprMVarQ q(Β¬$A β $B)
g.assignIfDefeq q(@Classical.byCases $A $B $tβ $tβ)
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
let (e, tβ) β tβ.mvarId!.intro x; tβ.withContext do
applyProof tβ (Ξ.insert x (.fvar e)) pβ
| .curry .. | .curryβ .. | .orImpL .. | .orImpR .. | .impImpSimp .. => do
let (e, g) β g.intro1; g.withContext do
applyProof g (Ξ.insert e.name (.fvar e)) (p.app (.hyp e.name))
/-- A decision procedure for intuitionistic propositional logic.
* `useDec` will add `a β¨ Β¬ a` to the context for every decidable atomic proposition `a`.
* `useClassical` will allow `a β¨ Β¬ a` to be added even if the proposition is not decidable,
using classical logic.
* `extraDec` will add `a β¨ Β¬ a` to the context for specified (not necessarily atomic)
propositions `a`.
-/
def itautoCore (g : MVarId)
(useDec useClassical : Bool) (extraDec : Array Expr) : MetaM Unit := do
AtomM.run (β getTransparency) do
let mut hs := mkRBMap ..
let t β g.getType
let (g, t) β if β isProp t then pure (g, β reify t) else pure (β g.exfalso, .false)
let mut Ξ : Except (IProp β Proof) ITauto.Context := .ok (mkRBMap ..)
let mut decs := mkRBMap ..
for ldecl in β getLCtx do
if !ldecl.isImplementationDetail then
let e := ldecl.type
if β isProp e then
let A β reify e
let n := ldecl.fvarId.name
hs := hs.insert n (Expr.fvar ldecl.fvarId)
Ξ := do (β Ξ).add A (.hyp n)
else
if let .const ``Decidable _ := e.getAppFn then
let p : Q(Prop) := e.appArg!
if useDec then
let A β reify p
decs := decs.insert A (false, Expr.fvar ldecl.fvarId)
let addDec (force : Bool) (decs : RBMap IProp (Bool Γ Expr) IProp.cmp) (e : Q(Prop)) := do
let A β reify e
let dec_e := q(Decidable $e)
let res β trySynthInstance q(Decidable $e)
if !(res matches .some _) && !useClassical then
if force then _ β synthInstance dec_e
pure decs
else
pure (decs.insert A (match res with | .some e => (false, e) | _ => (true, e)))
decs β extraDec.foldlM (addDec true) decs
if useDec then
let mut decided := mkRBTree Nat compare
if let .ok Ξ' := Ξ then
decided := Ξ'.fold (init := decided) fun m p _ =>
match p with
| .var i => m.insert i
| .not (.var i) => m.insert i
| _ => m
let ats := (β get).atoms
for e in ats, i in [0:ats.size] do
if !decided.contains i then
decs β addDec false decs e
for (A, cl, pf) in decs do
let n β mkFreshId
hs := hs.insert n pf
Ξ := return (β Ξ).insert (A.or A.not) (.em cl n)
let p : Proof :=
match Ξ with
| .ok Ξ => (prove Ξ t 0).1.2
| .error p => p t
applyProof g hs p
open Elab Tactic
/-- A decision procedure for intuitionistic propositional logic. Unlike `finish` and `tauto!` this
tactic never uses the law of excluded middle (without the `!` option), and the proof search is
tailored for this use case. (`itauto!` will work as a classical SAT solver, but the algorithm is
not very good in this situation.)
```lean
example (p : Prop) : Β¬ (p β Β¬ p) := by itauto
```
`itauto [a, b]` will additionally attempt case analysis on `a` and `b` assuming that it can derive
`Decidable a` and `Decidable b`. `itauto *` will case on all decidable propositions that it can
find among the atomic propositions, and `itauto! *` will case on all propositional atoms.
*Warning:* This can blow up the proof search, so it should be used sparingly.
-/
syntax (name := itauto) "itauto" "!"? (" *" <|> (" [" term,* "]"))? : tactic
elab_rules : tactic
| `(tactic| itauto $[!%$cl]?) => liftMetaTactic (itautoCore Β· false cl.isSome #[] *> pure [])
| `(tactic| itauto $[!%$cl]? *) => liftMetaTactic (itautoCore Β· true cl.isSome #[] *> pure [])
| `(tactic| itauto $[!%$cl]? [$hs,*]) => withMainContext do
let hs β hs.getElems.mapM (Term.elabTermAndSynthesize Β· none)
liftMetaTactic (itautoCore Β· true cl.isSome hs *> pure [])
@[inherit_doc itauto] syntax (name := itauto!) "itauto!" (" *" <|> (" [" term,* "]"))? : tactic
macro_rules
| `(tactic| itauto!) => `(tactic| itauto !)
| `(tactic| itauto! *) => `(tactic| itauto ! *)
| `(tactic| itauto! [$hs,*]) => `(tactic| itauto ! [$hs,*])
-- add_hint_tactic itauto
-- add_tactic_doc
-- { Name := "itauto"
-- category := DocCategory.tactic
-- declNames := [`tactic.interactive.itauto]
-- tags := ["logic", "propositional logic", "intuitionistic logic", "decision procedure"] }
|
Tactic\Lemma.lean | /-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kyle Miller
-/
import Lean.Parser.Command
/-!
# Support for `lemma` as a synonym for `theorem`.
-/
open Lean
/-- `lemma` means the same as `theorem`. It is used to denote "less important" theorems -/
syntax (name := lemma) declModifiers
group("lemma " declId ppIndent(declSig) declVal) : command
/-- Implementation of the `lemma` command, by macro expansion to `theorem`. -/
@[macro Β«lemmaΒ»] def expandLemma : Macro := fun stx =>
-- Not using a macro match, to be more resilient against changes to `lemma`.
-- This implementation ensures that any future changes to `theorem` are reflected in `lemma`
let stx := stx.modifyArg 1 fun stx =>
let stx := stx.modifyArg 0 (mkAtomFrom Β· "theorem" (canonical := true))
stx.setKind ``Parser.Command.theorem
pure <| stx.setKind ``Parser.Command.declaration
|
Tactic\Lift.lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import Mathlib.Tactic.Basic
import Batteries.Lean.Expr
import Batteries.Lean.Meta.UnusedNames
/-!
# lift tactic
This file defines the `lift` tactic, allowing the user to lift elements from one type to another
under a specified condition.
## Tags
lift, tactic
-/
/-- A class specifying that you can lift elements from `Ξ±` to `Ξ²` assuming `cond` is true.
Used by the tactic `lift`. -/
class CanLift (Ξ± Ξ² : Sort*) (coe : outParam <| Ξ² β Ξ±) (cond : outParam <| Ξ± β Prop) : Prop where
/-- An element of `Ξ±` that satisfies `cond` belongs to the range of `coe`. -/
prf : β x : Ξ±, cond x β β y : Ξ², coe y = x
instance : CanLift Int Nat (fun n : Nat β¦ n) (0 β€ Β·) :=
β¨fun n hn β¦ β¨n.natAbs, Int.natAbs_of_nonneg hnβ©β©
/-- Enable automatic handling of pi types in `CanLift`. -/
instance Pi.canLift (ΞΉ : Sort*) (Ξ± Ξ² : ΞΉ β Sort*) (coe : β i, Ξ² i β Ξ± i) (P : β i, Ξ± i β Prop)
[β i, CanLift (Ξ± i) (Ξ² i) (coe i) (P i)] :
CanLift (β i, Ξ± i) (β i, Ξ² i) (fun f i β¦ coe i (f i)) fun f β¦ β i, P i (f i) where
prf f hf := β¨fun i => Classical.choose (CanLift.prf (f i) (hf i)),
funext fun i => Classical.choose_spec (CanLift.prf (f i) (hf i))β©
theorem Subtype.exists_pi_extension {ΞΉ : Sort*} {Ξ± : ΞΉ β Sort*} [ne : β i, Nonempty (Ξ± i)]
{p : ΞΉ β Prop} (f : β i : Subtype p, Ξ± i) :
β g : β i : ΞΉ, Ξ± i, (fun i : Subtype p => g i) = f := by
haveI : DecidablePred p := fun i β¦ Classical.propDecidable (p i)
exact β¨fun i => if hi : p i then f β¨i, hiβ© else Classical.choice (ne i),
funext fun i β¦ dif_pos i.2β©
instance PiSubtype.canLift (ΞΉ : Sort*) (Ξ± : ΞΉ β Sort*) [β i, Nonempty (Ξ± i)] (p : ΞΉ β Prop) :
CanLift (β i : Subtype p, Ξ± i) (β i, Ξ± i) (fun f i => f i) fun _ => True where
prf f _ := Subtype.exists_pi_extension f
-- TODO: test if we need this instance in Lean 4
instance PiSubtype.canLift' (ΞΉ : Sort*) (Ξ± : Sort*) [Nonempty Ξ±] (p : ΞΉ β Prop) :
CanLift (Subtype p β Ξ±) (ΞΉ β Ξ±) (fun f i => f i) fun _ => True :=
PiSubtype.canLift ΞΉ (fun _ => Ξ±) p
instance Subtype.canLift {Ξ± : Sort*} (p : Ξ± β Prop) :
CanLift Ξ± { x // p x } Subtype.val p where prf a ha :=
β¨β¨a, haβ©, rflβ©
namespace Mathlib.Tactic
open Lean Parser Tactic Elab Tactic Meta
/-- Lift an expression to another type.
* Usage: `'lift' expr 'to' expr ('using' expr)? ('with' id (id id?)?)?`.
* If `n : β€` and `hn : n β₯ 0` then the tactic `lift n to β using hn` creates a new
constant of type `β`, also named `n` and replaces all occurrences of the old variable `(n : β€)`
with `βn` (where `n` in the new variable). It will remove `n` and `hn` from the context.
+ So for example the tactic `lift n to β using hn` transforms the goal
`n : β€, hn : n β₯ 0, h : P n β’ n = 3` to `n : β, h : P βn β’ βn = 3`
(here `P` is some term of type `β€ β Prop`).
* The argument `using hn` is optional, the tactic `lift n to β` does the same, but also creates a
new subgoal that `n β₯ 0` (where `n` is the old variable).
This subgoal will be placed at the top of the goal list.
+ So for example the tactic `lift n to β` transforms the goal
`n : β€, h : P n β’ n = 3` to two goals
`n : β€, h : P n β’ n β₯ 0` and `n : β, h : P βn β’ βn = 3`.
* You can also use `lift n to β using e` where `e` is any expression of type `n β₯ 0`.
* Use `lift n to β with k` to specify the name of the new variable.
* Use `lift n to β with k hk` to also specify the name of the equality `βk = n`. In this case, `n`
will remain in the context. You can use `rfl` for the name of `hk` to substitute `n` away
(i.e. the default behavior).
* You can also use `lift e to β with k hk` where `e` is any expression of type `β€`.
In this case, the `hk` will always stay in the context, but it will be used to rewrite `e` in
all hypotheses and the target.
+ So for example the tactic `lift n + 3 to β using hn with k hk` transforms the goal
`n : β€, hn : n + 3 β₯ 0, h : P (n + 3) β’ n + 3 = 2 * n` to the goal
`n : β€, k : β, hk : βk = n + 3, h : P βk β’ βk = 2 * n`.
* The tactic `lift n to β using h` will remove `h` from the context. If you want to keep it,
specify it again as the third argument to `with`, like this: `lift n to β using h with n rfl h`.
* More generally, this can lift an expression from `Ξ±` to `Ξ²` assuming that there is an instance
of `CanLift Ξ± Ξ²`. In this case the proof obligation is specified by `CanLift.prf`.
* Given an instance `CanLift Ξ² Ξ³`, it can also lift `Ξ± β Ξ²` to `Ξ± β Ξ³`; more generally, given
`Ξ² : Ξ a : Ξ±, Type*`, `Ξ³ : Ξ a : Ξ±, Type*`, and `[Ξ a : Ξ±, CanLift (Ξ² a) (Ξ³ a)]`, it
automatically generates an instance `CanLift (Ξ a, Ξ² a) (Ξ a, Ξ³ a)`.
`lift` is in some sense dual to the `zify` tactic. `lift (z : β€) to β` will change the type of an
integer `z` (in the supertype) to `β` (the subtype), given a proof that `z β₯ 0`;
propositions concerning `z` will still be over `β€`. `zify` changes propositions about `β` (the
subtype) to propositions about `β€` (the supertype), without changing the type of any variable.
-/
syntax (name := lift) "lift " term " to " term (" using " term)?
(" with " ident (ppSpace colGt ident)? (ppSpace colGt ident)?)? : tactic
/-- Generate instance for the `lift` tactic. -/
def Lift.getInst (old_tp new_tp : Expr) : MetaM (Expr Γ Expr Γ Expr) := do
let coe β mkFreshExprMVar (some <| .forallE `a new_tp old_tp .default)
let p β mkFreshExprMVar (some <| .forallE `a old_tp (.sort .zero) .default)
let inst_type β mkAppM ``CanLift #[old_tp, new_tp, coe, p]
let inst β synthInstance inst_type -- TODO: catch error
return (β instantiateMVars p, β instantiateMVars coe, β instantiateMVars inst)
/-- Main function for the `lift` tactic. -/
def Lift.main (e t : TSyntax `term) (hUsing : Option (TSyntax `term))
(newVarName newEqName : Option (TSyntax `ident)) (keepUsing : Bool) : TacticM Unit :=
withMainContext do
-- Are we using a new variable for the lifted var?
let isNewVar := !newVarName.isNone
-- Name of the new hypothesis containing the equality of the lifted variable with the old one
-- rfl if none is given
let newEqName := (newEqName.map Syntax.getId).getD `rfl
-- Was a new hypothesis given?
let isNewEq := newEqName != `rfl
let e β elabTerm e none
let goal β getMainGoal
if !(β inferType (β instantiateMVars (β goal.getType))).isProp then throwError
"lift tactic failed. Tactic is only applicable when the target is a proposition."
if newVarName == none β§ !e.isFVar then throwError
"lift tactic failed. When lifting an expression, a new variable name must be given"
let (p, coe, inst) β Lift.getInst (β inferType e) (β Term.elabType t)
let prf β match hUsing with
| some h => elabTermEnsuringType h (p.betaRev #[e])
| none => mkFreshExprMVar (some (p.betaRev #[e]))
let newVarName β match newVarName with
| some v => pure v.getId
| none => e.fvarId!.getUserName
let prfEx β mkAppOptM ``CanLift.prf #[none, none, coe, p, inst, e, prf]
let prfEx β instantiateMVars prfEx
let prfSyn β prfEx.toSyntax
-- if we have a new variable, but no hypothesis name was provided, we temporarily use a dummy
-- hypothesis name
let newEqName β if isNewVar && !isNewEq then withMainContext <| getUnusedUserName `tmpVar
else pure newEqName
let newEqIdent := mkIdent newEqName
-- Run rcases on the proof of the lift condition
replaceMainGoal (β Lean.Elab.Tactic.RCases.rcases #[(none, prfSyn)]
(.tuple Syntax.missing <| [newVarName, newEqName].map (.one Syntax.missing)) goal)
-- if we use a new variable, then substitute it everywhere
if isNewVar then
for decl in β getLCtx do
if decl.userName != newEqName then
let declIdent := mkIdent decl.userName
-- The line below fails if $declIdent is there only once.
evalTactic (β `(tactic| simp (config := {failIfUnchanged := false})
only [β $newEqIdent] at $declIdent $declIdent))
evalTactic (β `(tactic| simp (config := {failIfUnchanged := false}) only [β $newEqIdent]))
-- Clear the temporary hypothesis used for the new variable name if applicable
if isNewVar && !isNewEq then
evalTactic (β `(tactic| clear $newEqIdent))
-- Clear the "using" hypothesis if it's a variable in the context
if prf.isFVar && !keepUsing then
let some hUsingStx := hUsing | throwError "lift tactic failed: unreachable code was reached"
evalTactic (β `(tactic| clear $hUsingStx))
evalTactic (β `(tactic| try clear $hUsingStx))
if hUsing.isNone then withMainContext <| setGoals (prf.mvarId! :: (β getGoals))
elab_rules : tactic
| `(tactic| lift $e to $t $[using $h]?) => withMainContext <| Lift.main e t h none none False
elab_rules : tactic | `(tactic| lift $e to $t $[using $h]?
with $newVarName) => withMainContext <| Lift.main e t h newVarName none False
elab_rules : tactic | `(tactic| lift $e to $t $[using $h]?
with $newVarName $newEqName) => withMainContext <| Lift.main e t h newVarName newEqName False
elab_rules : tactic | `(tactic| lift $e to $t $[using $h]?
with $newVarName $newEqName $newPrfName) => withMainContext do
if h.isNone then Lift.main e t h newVarName newEqName False
else
let some h := h | unreachable!
if h.raw == newPrfName then Lift.main e t h newVarName newEqName True
else Lift.main e t h newVarName newEqName False
end Mathlib.Tactic
|
Tactic\LiftLets.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Tactic.Basic
/-!
# The `lift_lets` tactic
This module defines a tactic `lift_lets` that can be used to pull `let` bindings as far out
of an expression as possible.
-/
open Lean Elab Parser Meta Tactic
/-- Configuration for `Lean.Expr.liftLets` and the `lift_lets` tactic. -/
structure Lean.Expr.LiftLetsConfig where
/-- Whether to lift lets out of proofs. The default is not to. -/
proofs : Bool := false
/-- Whether to merge let bindings if they have the same type and value.
This test is by syntactic equality, not definitional equality.
The default is to merge. -/
merge : Bool := true
/--
Auxiliary definition for `Lean.Expr.liftLets`. Takes a list of the accumulated fvars.
This list is used during the computation to merge let bindings.
-/
private partial def Lean.Expr.liftLetsAux (config : LiftLetsConfig) (e : Expr) (fvars : Array Expr)
(f : Array Expr β Expr β MetaM Expr) : MetaM Expr := do
if (e.find? Expr.isLet).isNone then
-- If `e` contains no `let` expressions, then we can avoid recursing into it.
return β f fvars e
if !config.proofs then
if β Meta.isProof e then
return β f fvars e
match e with
| .letE n t v b _ =>
t.liftLetsAux config fvars fun fvars t' =>
v.liftLetsAux config fvars fun fvars v' => do
if config.merge then
-- Eliminate the let binding if there is already one of the same type and value.
let fvar? β fvars.findM? (fun fvar => do
let decl β fvar.fvarId!.getDecl
return decl.type == t' && decl.value? == some v')
if let some fvar' := fvar? then
return β (b.instantiate1 fvar').liftLetsAux config fvars f
withLetDecl n t' v' fun fvar =>
(b.instantiate1 fvar).liftLetsAux config (fvars.push fvar) f
| .app x y =>
x.liftLetsAux config fvars fun fvars x' => y.liftLetsAux config fvars fun fvars y' =>
f fvars (.app x' y')
| .proj n idx s =>
s.liftLetsAux config fvars fun fvars s' => f fvars (.proj n idx s')
| .lam n t b i =>
t.liftLetsAux config fvars fun fvars t => do
-- Enter the binding, do liftLets, and lift out liftable lets
let e' β withLocalDecl n i t fun fvar => do
(b.instantiate1 fvar).liftLetsAux config fvars fun fvars2 b => do
-- See which bindings can't be migrated out
let deps β collectForwardDeps #[fvar] false
let fvars2 := fvars2[fvars.size:].toArray
let (fvars2, fvars2') := fvars2.partition deps.contains
mkLetFVars fvars2' (β mkLambdaFVars #[fvar] (β mkLetFVars fvars2 b))
-- Re-enter the new lets; we do it this way to keep the local context clean
insideLets e' fvars fun fvars e'' => f fvars e''
| .forallE n t b i =>
t.liftLetsAux config fvars fun fvars t => do
-- Enter the binding, do liftLets, and lift out liftable lets
let e' β withLocalDecl n i t fun fvar => do
(b.instantiate1 fvar).liftLetsAux config fvars fun fvars2 b => do
-- See which bindings can't be migrated out
let deps β collectForwardDeps #[fvar] false
let fvars2 := fvars2[fvars.size:].toArray
let (fvars2, fvars2') := fvars2.partition deps.contains
mkLetFVars fvars2' (β mkForallFVars #[fvar] (β mkLetFVars fvars2 b))
-- Re-enter the new lets; we do it this way to keep the local context clean
insideLets e' fvars fun fvars e'' => f fvars e''
| .mdata _ e => e.liftLetsAux config fvars f
| _ => f fvars e
where
-- Like the whole `Lean.Expr.liftLets`, but only handles lets
insideLets {Ξ±} (e : Expr) (fvars : Array Expr) (f : Array Expr β Expr β MetaM Ξ±) : MetaM Ξ± := do
match e with
| .letE n t v b _ =>
withLetDecl n t v fun fvar => insideLets (b.instantiate1 fvar) (fvars.push fvar) f
| _ => f fvars e
/-- Take all the `let`s in an expression and move them outwards as far as possible.
All top-level `let`s are added to the local context, and then `f` is called with the list
of local bindings (each an fvar) and the new expression.
Let bindings are merged if they have the same type and value.
Use `e.liftLets mkLetFVars` to get a defeq expression with all `let`s lifted as far as possible. -/
def Lean.Expr.liftLets (e : Expr) (f : Array Expr β Expr β MetaM Expr)
(config : LiftLetsConfig := {}) : MetaM Expr :=
e.liftLetsAux config #[] f
namespace Mathlib.Tactic
declare_config_elab elabConfig Lean.Expr.LiftLetsConfig
/--
Lift all the `let` bindings in the type of an expression as far out as possible.
When applied to the main goal, this gives one the ability to `intro` embedded `let` expressions.
For example,
```lean
example : (let x := 1; x) = 1 := by
lift_lets
-- β’ let x := 1; x = 1
intro x
sorry
```
During the lifting process, let bindings are merged if they have the same type and value.
-/
syntax (name := lift_lets) "lift_lets" (Parser.Tactic.config)? (ppSpace location)? : tactic
elab_rules : tactic
| `(tactic| lift_lets $[$cfg:config]? $[$loc:location]?) => do
let config β elabConfig (mkOptionalNode cfg)
withLocation (expandOptLocation (Lean.mkOptionalNode loc))
(atLocal := fun h β¦ liftMetaTactic1 fun mvarId β¦ do
let hTy β instantiateMVars (β h.getType)
mvarId.changeLocalDecl h (β hTy.liftLets mkLetFVars config))
(atTarget := liftMetaTactic1 fun mvarId β¦ do
let ty β instantiateMVars (β mvarId.getType)
mvarId.change (β ty.liftLets mkLetFVars config))
(failed := fun _ β¦ throwError "lift_lets tactic failed")
end Mathlib.Tactic
|
Tactic\Linarith.lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import Mathlib.Tactic.Linarith.Frontend
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Hint
/-!
We register `linarith` with the `hint` tactic.
-/
register_hint linarith
|
Tactic\LinearCombination.lean | /-
Copyright (c) 2022 Abby J. Goldberg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Abby J. Goldberg, Mario Carneiro
-/
import Mathlib.Tactic.Ring
/-!
# linear_combination Tactic
In this file, the `linear_combination` tactic is created. This tactic, which
works over `Ring`s, attempts to simplify the target by creating a linear combination
of a list of equalities and subtracting it from the target. This file also includes a
definition for `linear_combination_config`. A `linear_combination_config`
object can be passed into the tactic, allowing the user to specify a
normalization tactic.
## Implementation Notes
This tactic works by creating a weighted sum of the given equations with the
given coefficients. Then, it subtracts the right side of the weighted sum
from the left side so that the right side equals 0, and it does the same with
the target. Afterwards, it sets the goal to be the equality between the
lefthand side of the new goal and the lefthand side of the new weighted sum.
Lastly, calls a normalization tactic on this target.
## References
* <https://leanprover.zulipchat.com/#narrow/stream/239415-metaprogramming-.2F.20tactics/topic/Linear.20algebra.20tactic/near/213928196>
-/
namespace Mathlib.Tactic.LinearCombination
open Lean hiding Rat
open Elab Meta Term
variable {Ξ± : Type*} {a a' aβ aβ b b' bβ bβ c : Ξ±}
theorem pf_add_c [Add Ξ±] (p : a = b) (c : Ξ±) : a + c = b + c := p βΈ rfl
theorem c_add_pf [Add Ξ±] (p : b = c) (a : Ξ±) : a + b = a + c := p βΈ rfl
theorem add_pf [Add Ξ±] (pβ : (aβ:Ξ±) = bβ) (pβ : aβ = bβ) : aβ + aβ = bβ + bβ := pβ βΈ pβ βΈ rfl
theorem pf_sub_c [Sub Ξ±] (p : a = b) (c : Ξ±) : a - c = b - c := p βΈ rfl
theorem c_sub_pf [Sub Ξ±] (p : b = c) (a : Ξ±) : a - b = a - c := p βΈ rfl
theorem sub_pf [Sub Ξ±] (pβ : (aβ:Ξ±) = bβ) (pβ : aβ = bβ) : aβ - aβ = bβ - bβ := pβ βΈ pβ βΈ rfl
theorem neg_pf [Neg Ξ±] (p : (a:Ξ±) = b) : -a = -b := p βΈ rfl
theorem pf_mul_c [Mul Ξ±] (p : a = b) (c : Ξ±) : a * c = b * c := p βΈ rfl
theorem c_mul_pf [Mul Ξ±] (p : b = c) (a : Ξ±) : a * b = a * c := p βΈ rfl
theorem mul_pf [Mul Ξ±] (pβ : (aβ:Ξ±) = bβ) (pβ : aβ = bβ) : aβ * aβ = bβ * bβ := pβ βΈ pβ βΈ rfl
theorem inv_pf [Inv Ξ±] (p : (a:Ξ±) = b) : aβ»ΒΉ = bβ»ΒΉ := p βΈ rfl
theorem pf_div_c [Div Ξ±] (p : a = b) (c : Ξ±) : a / c = b / c := p βΈ rfl
theorem c_div_pf [Div Ξ±] (p : b = c) (a : Ξ±) : a / b = a / c := p βΈ rfl
theorem div_pf [Div Ξ±] (pβ : (aβ:Ξ±) = bβ) (pβ : aβ = bβ) : aβ / aβ = bβ / bβ := pβ βΈ pβ βΈ rfl
/--
Performs macro expansion of a linear combination expression,
using `+`/`-`/`*`/`/` on equations and values.
* `some p` means that `p` is a syntax corresponding to a proof of an equation.
For example, if `h : a = b` then `expandLinearCombo (2 * h)` returns `some (c_add_pf 2 h)`
which is a proof of `2 * a = 2 * b`.
* `none` means that the input expression is not an equation but a value;
the input syntax itself is used in this case.
-/
partial def expandLinearCombo (stx : Syntax.Term) : TermElabM (Option Syntax.Term) := do
let mut result β match stx with
| `(($e)) => expandLinearCombo e
| `($eβ + $eβ) => do
match β expandLinearCombo eβ, β expandLinearCombo eβ with
| none, none => pure none
| some pβ, none => ``(pf_add_c $pβ $eβ)
| none, some pβ => ``(c_add_pf $pβ $eβ)
| some pβ, some pβ => ``(add_pf $pβ $pβ)
| `($eβ - $eβ) => do
match β expandLinearCombo eβ, β expandLinearCombo eβ with
| none, none => pure none
| some pβ, none => ``(pf_sub_c $pβ $eβ)
| none, some pβ => ``(c_sub_pf $pβ $eβ)
| some pβ, some pβ => ``(sub_pf $pβ $pβ)
| `(-$e) => do
match β expandLinearCombo e with
| none => pure none
| some p => ``(neg_pf $p)
| `(β $e) => do
match β expandLinearCombo e with
| none => pure none
| some p => ``(Eq.symm $p)
| `($eβ * $eβ) => do
match β expandLinearCombo eβ, β expandLinearCombo eβ with
| none, none => pure none
| some pβ, none => ``(pf_mul_c $pβ $eβ)
| none, some pβ => ``(c_mul_pf $pβ $eβ)
| some pβ, some pβ => ``(mul_pf $pβ $pβ)
| `($eβ»ΒΉ) => do
match β expandLinearCombo e with
| none => pure none
| some p => ``(inv_pf $p)
| `($eβ / $eβ) => do
match β expandLinearCombo eβ, β expandLinearCombo eβ with
| none, none => pure none
| some pβ, none => ``(pf_div_c $pβ $eβ)
| none, some pβ => ``(c_div_pf $pβ $eβ)
| some pβ, some pβ => ``(div_pf $pβ $pβ)
| e => do
let e β elabTerm e none
let eType β inferType e
let .true := (β withReducible do whnf eType).isEq | pure none
some <$> e.toSyntax
return result.map fun r => β¨r.raw.setInfo (SourceInfo.fromRef stx true)β©
theorem eq_transβ (p : (a:Ξ±) = b) (pβ : a = a') (pβ : b = b') : a' = b' := pβ βΈ pβ βΈ p
theorem eq_of_add [AddGroup Ξ±] (p : (a:Ξ±) = b) (H : (a' - b') - (a - b) = 0) : a' = b' := by
rw [β sub_eq_zero] at p β’; rwa [sub_eq_zero, p] at H
theorem eq_of_add_pow [Ring Ξ±] [NoZeroDivisors Ξ±] (n : β) (p : (a:Ξ±) = b)
(H : (a' - b')^n - (a - b) = 0) : a' = b' := by
rw [β sub_eq_zero] at p β’; apply pow_eq_zero (n := n); rwa [sub_eq_zero, p] at H
/-- Implementation of `linear_combination` and `linear_combination2`. -/
def elabLinearCombination
(norm? : Option Syntax.Tactic) (exp? : Option Syntax.NumLit) (input : Option Syntax.Term)
(twoGoals := false) : Tactic.TacticM Unit := Tactic.withMainContext do
let p β match input with
| none => `(Eq.refl 0)
| some e => withSynthesize do
match β expandLinearCombo e with
| none => `(Eq.refl $e)
| some p => pure p
let norm := norm?.getD (Unhygienic.run `(tactic| ring1))
Tactic.evalTactic <| β withFreshMacroScope <|
if twoGoals then
`(tactic| (
refine eq_transβ $p ?a ?b
case' a => $norm:tactic
case' b => $norm:tactic))
else
match exp? with
| some n =>
if n.getNat = 1 then `(tactic| (refine eq_of_add $p ?a; case' a => $norm:tactic))
else `(tactic| (refine eq_of_add_pow $n $p ?a; case' a => $norm:tactic))
| _ => `(tactic| (refine eq_of_add $p ?a; case' a => $norm:tactic))
/--
The `(norm := $tac)` syntax says to use `tac` as a normalization postprocessor for
`linear_combination`. The default normalizer is `ring1`, but you can override it with `ring_nf`
to get subgoals from `linear_combination` or with `skip` to disable normalization.
-/
syntax normStx := atomic(" (" &"norm" " := ") withoutPosition(tactic) ")"
/--
The `(exp := n)` syntax for `linear_combination` says to take the goal to the `n`th power before
subtracting the given combination of hypotheses.
-/
syntax expStx := atomic(" (" &"exp" " := ") withoutPosition(num) ")"
/--
`linear_combination` attempts to simplify the target by creating a linear combination
of a list of equalities and subtracting it from the target.
The tactic will create a linear
combination by adding the equalities together from left to right, so the order
of the input hypotheses does matter. If the `normalize` field of the
configuration is set to false, then the tactic will simply set the user up to
prove their target using the linear combination instead of normalizing the subtraction.
Note: The left and right sides of all the equalities should have the same
type, and the coefficients should also have this type. There must be
instances of `Mul` and `AddGroup` for this type.
* The input `e` in `linear_combination e` is a linear combination of proofs of equalities,
given as a sum/difference of coefficients multiplied by expressions.
The coefficients may be arbitrary expressions.
The expressions can be arbitrary proof terms proving equalities.
Most commonly they are hypothesis names `h1, h2, ...`.
* `linear_combination (norm := tac) e` runs the "normalization tactic" `tac`
on the subgoal(s) after constructing the linear combination.
* The default normalization tactic is `ring1`, which closes the goal or fails.
* To get a subgoal in the case that it is not immediately provable, use
`ring_nf` as the normalization tactic.
* To avoid normalization entirely, use `skip` as the normalization tactic.
* `linear_combination (exp := n) e` will take the goal to the `n`th power before subtracting the
combination `e`. In other words, if the goal is `t1 = t2`, `linear_combination (exp := n) e`
will change the goal to `(t1 - t2)^n = 0` before proceeding as above.
This feature is not supported for `linear_combination2`.
* `linear_combination2 e` is the same as `linear_combination e` but it produces two
subgoals instead of one: rather than proving that `(a - b) - (a' - b') = 0` where
`a' = b'` is the linear combination from `e` and `a = b` is the goal,
it instead attempts to prove `a = a'` and `b = b'`.
Because it does not use subtraction, this form is applicable also to semirings.
* Note that a goal which is provable by `linear_combination e` may not be provable
by `linear_combination2 e`; in general you may need to add a coefficient to `e`
to make both sides match, as in `linear_combination2 e + c`.
* You can also reverse equalities using `β h`, so for example if `hβ : a = b`
then `2 * (β h)` is a proof of `2 * b = 2 * a`.
Example Usage:
```
example (x y : β€) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
linear_combination 1*h1 - 2*h2
example (x y : β€) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
linear_combination h1 - 2*h2
example (x y : β€) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
linear_combination (norm := ring_nf) -2*h2
/- Goal: x * y + x * 2 - 1 = 0 -/
example (x y z : β) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2)
(hc : x + 2*y + z = 2) :
-3*x - 3*y - 4*z = 2 := by
linear_combination ha - hb - 2*hc
example (x y : β) (h1 : x + y = 3) (h2 : 3*x = 7) :
x*x*y + y*x*y + 6*x = 3*x*y + 14 := by
linear_combination x*y*h1 + 2*h2
example (x y : β€) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := by
linear_combination (norm := skip) 2*h1
simp
axiom qc : β
axiom hqc : qc = 2*qc
example (a b : β) (h : β p q : β, p = q) : 3*a + qc = 3*b + 2*qc := by
linear_combination 3 * h a b + hqc
```
-/
syntax (name := linearCombination) "linear_combination"
(normStx)? (expStx)? (ppSpace colGt term)? : tactic
elab_rules : tactic
| `(tactic| linear_combination $[(norm := $tac)]? $[(exp := $n)]? $(e)?) =>
elabLinearCombination tac n e
@[inherit_doc linearCombination]
syntax "linear_combination2" (normStx)? (ppSpace colGt term)? : tactic
elab_rules : tactic
| `(tactic| linear_combination2 $[(norm := $tac)]? $(e)?) => elabLinearCombination tac none e true
end LinearCombination
end Tactic
end Mathlib
|
Tactic\Linter.lean | /-
This is the `Linter`s file: it only imports files defining linters and is
intended to be imported fairly early in `Mathlib`.
This file is ignored by `shake`:
* it is in `ignoreAll`, meaning that all its imports are considered necessary;
* it is in `ignoreImport`, meaning that where it is imported, it is considered necessary.
-/
import Mathlib.Tactic.Linter.GlobalAttributeIn
import Mathlib.Tactic.Linter.HashCommandLinter
import Mathlib.Tactic.Linter.HaveLetLinter
import Mathlib.Tactic.Linter.Lint
import Mathlib.Tactic.Linter.RefineLinter
import Mathlib.Tactic.Linter.Style
import Mathlib.Tactic.Linter.UnusedTactic
|
Tactic\Measurability.lean | /-
Copyright (c) 2023 Miyahara KΕ. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Miyahara KΕ
-/
import Mathlib.Tactic.Measurability.Init
import Mathlib.Algebra.Group.Defs
/-!
# Measurability
We define the `measurability` tactic using `aesop`. -/
open Lean.Parser.Tactic (config)
attribute [aesop (rule_sets := [Measurable]) unfold norm] Function.comp
-- FIXME: `npowRec` is an internal implementation detail,
-- and `aesop` certainly should not know about it.
-- If anyone is working on the `measurability` tactic, please try to fix this!
attribute [aesop (rule_sets := [Measurable]) norm] npowRec
/--
The `measurability` attribute used to tag measurability statements for the `measurability` tactic.-/
macro "measurability" : attr =>
`(attr|aesop safe apply (rule_sets := [$(Lean.mkIdent `Measurable):ident]))
/--
The tactic `measurability` solves goals of the form `Measurable f`, `AEMeasurable f`,
`StronglyMeasurable f`, `AEStronglyMeasurable f ΞΌ`, or `MeasurableSet s` by applying lemmas tagged
with the `measurability` user attribute. -/
macro "measurability" (config)? : tactic =>
`(tactic| aesop (config := { terminal := true })
(rule_sets := [$(Lean.mkIdent `Measurable):ident]))
/--
The tactic `measurability?` solves goals of the form `Measurable f`, `AEMeasurable f`,
`StronglyMeasurable f`, `AEStronglyMeasurable f ΞΌ`, or `MeasurableSet s` by applying lemmas tagged
with the `measurability` user attribute, and suggests a faster proof script that can be substituted
for the tactic call in case of success. -/
macro "measurability?" (config)? : tactic =>
`(tactic| aesop? (config := { terminal := true })
(rule_sets := [$(Lean.mkIdent `Measurable):ident]))
-- Todo: implement `measurability!` and `measurability!?` and add configuration,
-- original syntax was (same for the missing `measurability` variants):
syntax (name := measurability!) "measurability!" (config)? : tactic
syntax (name := measurability!?) "measurability!?" (config)? : tactic
|
Tactic\MinImports.lean | /-
Copyright (c) 2024 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import ImportGraph.Imports
/-! # `#min_imports in` a command to find minimal imports
`#min_imports in stx` scans the syntax `stx` to find a collection of minimal imports that should be
sufficient for `stx` to make sense.
If `stx` is a command, then it also elaborates `stx` and, in case it is a declaration, then
it also finds the imports implied by the declaration.
Unlike the related `#find_home`, this command takes into account notation and tactic information.
## Limitations
Parsing of `attribute`s is hard and the command makes minimal effort to support them.
Here is an example where the command fails to notice a dependency:
```lean
import Mathlib.Data.Sym.Sym2.Init -- the actual minimal import
import Aesop.Frontend.Attribute -- the import that `#min_imports in` suggests
import Mathlib.Tactic.MinImports
-- import Aesop.Frontend.Attribute
#min_imports in
@[aesop (rule_sets := [Sym2]) [safe [constructors, cases], norm]]
inductive Rel (Ξ± : Type) : Ξ± Γ Ξ± β Ξ± Γ Ξ± β Prop
| refl (x y : Ξ±) : Rel _ (x, y) (x, y)
| swap (x y : Ξ±) : Rel _ (x, y) (y, x)
-- `import Mathlib.Data.Sym.Sym2.Init` is not detected by `#min_imports in`.
```
## Todo
*Examples*
When parsing an `example`, `#min_imports in` retrieves all the information that it can from the
`Syntax` of the `example`, but, since the `example` is not added to the environment, it fails
to retrieve any `Expr` information about the proof term.
It would be desirable to make `#min_imports in example ...` inspect the resulting proof and
report imports, but this feature is missing for the moment.
*Using `InfoTrees`*
It may be more efficient (not necessarily in terms of speed, but of simplicity of code),
to inspect the `InfoTrees` for each command and retrieve information from there.
I have not looked into this yet.
-/
open Lean Elab Command
namespace Mathlib.Command.MinImports
/-- `getSyntaxNodeKinds stx` takes a `Syntax` input `stx` and returns the `NameSet` of all the
`SyntaxNodeKinds` and all the identifiers contained in `stx`. -/
partial
def getSyntaxNodeKinds : Syntax β NameSet
| .node _ kind args =>
((args.map getSyntaxNodeKinds).foldl (NameSet.append Β· Β·) {}).insert kind
| .ident _ _ nm _ => NameSet.empty.insert nm
| _ => {}
/-- extracts the names of the declarations in `env` on which `decl` depends. -/
-- source:
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Counting.20prerequisites.20of.20a.20theorem/near/425370265
def getVisited (env : Environment) (decl : Name) : NameSet :=
let (_, { visited, .. }) := CollectAxioms.collect decl |>.run env |>.run {}
visited
/-- `getId stx` takes as input a `Syntax` `stx`.
If `stx` contains a `declId`, then it returns the `ident`-syntax for the `declId`.
If `stx` is a nameless instance, then it also tries to fetch the `ident` for the instance.
Otherwise it returns `.missing`. -/
def getId (stx : Syntax) : CommandElabM Syntax := do
-- If the command contains a `declId`, we use the implied `ident`.
match stx.find? (Β·.isOfKind ``Lean.Parser.Command.declId) with
| some declId => return declId[0]
| none =>
-- Otherwise, the command could be a nameless `instance`.
match stx.find? (Β·.isOfKind ``Lean.Parser.Command.instance) with
| none => return .missing
| some stx => do
-- if it is a nameless `instance`, we retrieve the autogenerated name
let dv β mkDefViewOfInstance {} stx
return dv.declId[0]
/-- `getIds stx` extracts all identifiers, collecting them in a `NameSet`. -/
partial
def getIds : Syntax β NameSet
| .node _ _ args => (args.map getIds).foldl (Β·.append Β·) {}
| .ident _ _ nm _ => NameSet.empty.insert nm
| _ => {}
/-- `getAttrNames stx` extracts `attribute`s from `stx`.
It does not collect `simp`, `ext`, `to_additive`.
It should collect almost all other attributes, e.g., `fun_prop`. -/
def getAttrNames (stx : Syntax) : NameSet :=
match stx.find? (Β·.isOfKind ``Lean.Parser.Term.attributes) with
| none => {}
| some stx => getIds stx
/-- `getAttrs env stx` returns all attribute declaration names contained in `stx` and registered
in the `Environment `env`. -/
def getAttrs (env : Environment) (stx : Syntax) : NameSet :=
Id.run do
let mut new : NameSet := {}
for attr in (getAttrNames stx) do
match getAttributeImpl env attr with
| .ok attr => new := new.insert attr.ref
| .error .. => pure ()
return new
/-- `previousInstName nm` takes as input a name `nm`, assuming that it is the name of an
auto-generated "nameless" `instance`.
If `nm` ends in `..._n`, where `n` is a number, it returns the same name, but with `_n` replaced
by `_(n-1)`, unless `n β€ 1`, in which case it simply removes the `_n` suffix.
-/
def previousInstName : Name β Name
| nm@(.str init tail) =>
let last := tail.takeRightWhile (Β· != '_')
let newTail := match last.toNat? with
| some (n + 2) => s!"_{n + 1}"
| _ => ""
let newTailPrefix := tail.dropRightWhile (Β· != '_')
if newTailPrefix.isEmpty then nm else
let newTail :=
(if newTailPrefix.back == '_' then newTailPrefix.dropRight 1 else newTailPrefix) ++ newTail
.str init newTail
| nm => nm
/--`getAllImports cmd id` takes a `Syntax` input `cmd` and returns the `NameSet` of all the
module names that are implied by
* the `SyntaxNodeKinds`,
* the attributes of `cmd` (if there are any),
* the identifiers contained in `cmd`,
* if `cmd` adds a declaration `d` to the environment, then also all the module names implied by `d`.
The argument `id` is expected to be an identifier.
It is used either for the internally generated name of a "nameless" `instance` or when parsing
an identifier representing the name of a declaration.
-/
def getAllImports (cmd id : Syntax) (dbg? : Bool := false) :
CommandElabM NameSet := do
let env β getEnv
let id1 β getId cmd
let ns β getCurrNamespace
let id2 := mkIdentFrom id1 (previousInstName id1.getId)
let nm β liftCoreM do (
-- try the visible name or the current "nameless" `instance` name
realizeGlobalConstNoOverload id1 <|>
-- otherwise, guess what the previous "nameless" `instance` name was
realizeGlobalConstNoOverload id2 <|>
-- failing everything, use the current namespace followed by the visible name
return ns ++ id1.getId)
-- We collect the implied declaration names, the `SyntaxNodeKinds` and the attributes.
let ts := getVisited env nm
|>.append (getVisited env id.getId)
|>.append (getSyntaxNodeKinds cmd)
|>.append (getAttrs env cmd)
if dbg? then dbg_trace "{ts.toArray.qsort Name.lt}"
let mut hm : HashMap Nat Name := {}
for imp in env.header.moduleNames do
hm := hm.insert ((env.getModuleIdx? imp).getD default) imp
let mut fins : NameSet := {}
for t1 in ts do
let tns := t1::(β resolveGlobalName t1).map Prod.fst
for t in tns do
let new := match env.getModuleIdxFor? t with
| some t => (hm.find? t).get!
| none => .anonymous -- instead of `getMainModule`, we omit the current module
if !fins.contains new then fins := fins.insert new
return fins.erase .anonymous
/-- `getIrredundantImports env importNames` takes an `Environment` and a `NameSet` as inputs.
Assuming that `importNames` are module names,
it returns the `NameSet` consisting of a minimal collection of module names whose transitive
closure is enough to parse (and elaborate) `cmd`. -/
def getIrredundantImports (env : Environment) (importNames : NameSet) : NameSet :=
importNames.diff (env.findRedundantImports importNames.toArray)
/-- `minImpsCore stx id` is the internal function to elaborate the `#min_imports in` command.
It collects the irredundant imports to parse and elaborate `stx` and logs
```lean
import A
import B
...
import Z
```
The `id` input is expected to be the name of the declaration that is currently processed.
It is used to provide the internally generated name for "nameless" `instance`s.
-/
def minImpsCore (stx id : Syntax) : CommandElabM Unit := do
let tot := getIrredundantImports (β getEnv) (β getAllImports stx id)
let fileNames := tot.toArray.qsort Name.lt
logInfoAt (β getRef) m!"{"\n".intercalate (fileNames.map (s!"import {Β·}")).toList}"
/-- `#min_imports in cmd` scans the syntax `cmd` and the declaration obtained by elaborating `cmd`
to find a collection of minimal imports that should be sufficient for `cmd` to work. -/
syntax (name := minImpsStx) "#min_imports in" command : command
@[inherit_doc minImpsStx]
syntax "#min_imports in" term : command
elab_rules : command
| `(#min_imports in $cmd:command) => do
-- In case `cmd` is a "nameless" `instance`, we produce its name.
-- It is important that this is collected *before* adding the declaration to the environment,
-- since `getId` probes the name-generator using the current environment: if the declaration
-- were already present, `getId` would return a new name that does not clash with it!
let id β getId cmd
Elab.Command.elabCommand cmd <|> pure ()
minImpsCore cmd id
| `(#min_imports in $cmd:term) => minImpsCore cmd cmd
end Mathlib.Command.MinImports
|
Tactic\MkIffOfInductiveProp.lean | /-
Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, David Renshaw
-/
import Lean
import Mathlib.Lean.Meta
import Mathlib.Lean.Name
import Mathlib.Tactic.TypeStar
/-!
# mk_iff_of_inductive_prop
This file defines a command `mk_iff_of_inductive_prop` that generates `iff` rules for
inductive `Prop`s. For example, when applied to `List.Chain`, it creates a declaration with
the following type:
```lean
β {Ξ± : Type*} (R : Ξ± β Ξ± β Prop) (a : Ξ±) (l : List Ξ±),
Chain R a l β l = [] β¨ β (b : Ξ±) (l' : List Ξ±), R a b β§ Chain R b l β§ l = b :: l'
```
This tactic can be called using either the `mk_iff_of_inductive_prop` user command or
the `mk_iff` attribute.
-/
namespace Mathlib.Tactic.MkIff
open Lean Meta Elab
/-- `select m n` runs `right` `m` times; if `m < n`, then it also runs `left` once.
Fails if `n < m`. -/
private def select (m n : Nat) (goal : MVarId) : MetaM MVarId :=
match m,n with
| 0, 0 => pure goal
| 0, (_ + 1) => do
let [new_goal] β goal.nthConstructor `left 0 (some 2)
| throwError "expected only one new goal"
pure new_goal
| (m + 1), (n + 1) => do
let [new_goal] β goal.nthConstructor `right 1 (some 2)
| throwError "expected only one new goal"
select m n new_goal
| _, _ => failure
/-- `compactRelation bs as_ps`: Produce a relation of the form:
```lean
R := fun as β¦ β bs, β_i a_i = p_i[bs]
```
This relation is user-visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and
hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`.
-/
partial def compactRelation :
List Expr β List (Expr Γ Expr) β List (Option Expr) Γ List (Expr Γ Expr) Γ (Expr β Expr)
| [], as_ps => ([], as_ps, id)
| b::bs, as_ps =>
match as_ps.span (fun β¨_, pβ© β¦ p != b) with
| (_, []) => -- found nothing in ps equal to b
let (bs, as_ps', subst) := compactRelation bs as_ps
(b::bs, as_ps', subst)
| (psβ, (a, _) :: psβ) => -- found one that matches b. Remove it.
let i := fun e β¦ e.replaceFVar b a
let (bs, as_ps', subst) :=
compactRelation (bs.map i) ((psβ ++ psβ).map (fun β¨a, pβ© β¦ (a, i p)))
(none :: bs, as_ps', i β subst)
private def updateLambdaBinderInfoD! (e : Expr) : Expr :=
match e with
| .lam n domain body _ => .lam n domain body .default
| _ => panic! "lambda expected"
/-- Generates an expression of the form `β (args), inner`. `args` is assumed to be a list of fvars.
When possible, `p β§ q` is used instead of `β (_ : p), q`. -/
def mkExistsList (args : List Expr) (inner : Expr) : MetaM Expr :=
args.foldrM
(fun arg i:Expr => do
let t β inferType arg
let l := (β inferType t).sortLevel!
if arg.occurs i || l != Level.zero
then pure (mkApp2 (.const `Exists [l]) t
(updateLambdaBinderInfoD! <| β mkLambdaFVars #[arg] i))
else pure <| mkApp2 (mkConst `And) t i)
inner
/-- `mkOpList op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.
Returns `empty` if the list is empty. -/
def mkOpList (op : Expr) (empty : Expr) : List Expr β Expr
| [] => empty
| [e] => e
| (e :: es) => mkApp2 op e <| mkOpList op empty es
/-- `mkAndList [x1, x2, ...]` is defined as `x1 β§ (x2 β§ ...)`, or `True` if the list is empty. -/
def mkAndList : List Expr β Expr := mkOpList (mkConst `And) (mkConst `True)
/-- `mkOrList [x1, x2, ...]` is defined as `x1 β¨ (x2 β¨ ...)`, or `False` if the list is empty. -/
def mkOrList : List Expr β Expr := mkOpList (mkConst `Or) (mkConst `False)
/-- Drops the final element of a list. -/
def List.init {Ξ± : Type*} : List Ξ± β List Ξ±
| [] => []
| [_] => []
| a::l => a::init l
/-- Auxiliary data associated with a single constructor of an inductive declaration.
-/
structure Shape : Type where
/-- For each forall-bound variable in the type of the constructor, minus
the "params" that apply to the entire inductive type, this list contains `true`
if that variable has been kept after `compactRelation`.
For example, `List.Chain.nil` has type
```lean
β {Ξ± : Type u_1} {R : Ξ± β Ξ± β Prop} {a : Ξ±}, List.Chain R a []`
```
and the first two variables `Ξ±` and `R` are "params", while the `a : Ξ±` gets
eliminated in a `compactRelation`, so `variablesKept = [false]`.
`List.Chain.cons` has type
```lean
β {Ξ± : Type u_1} {R : Ξ± β Ξ± β Prop} {a b : Ξ±} {l : List Ξ±},
R a b β List.Chain R b l β List.Chain R a (b :: l)
```
and the `a : Ξ±` gets eliminated, so `variablesKept = [false,true,true,true,true]`.
-/
variablesKept : List Bool
/-- The number of equalities, or `none` in the case when we've reduced something
of the form `p β§ True` to just `p`.
-/
neqs : Option Nat
/-- Converts an inductive constructor `c` into a `Shape` that will be used later in
while proving the iff theorem, and a proposition representing the constructor.
-/
def constrToProp (univs : List Level) (params : List Expr) (idxs : List Expr) (c : Name) :
MetaM (Shape Γ Expr) := do
let type := (β getConstInfo c).instantiateTypeLevelParams univs
let type' β Meta.forallBoundedTelescope type (params.length) fun fvars ty β¦ do
pure <| ty.replaceFVars fvars params.toArray
Meta.forallTelescope type' fun fvars ty β¦ do
let idxs_inst := ty.getAppArgs.toList.drop params.length
let (bs, eqs, subst) := compactRelation fvars.toList (idxs.zip idxs_inst)
let eqs β eqs.mapM (fun β¨idx, instβ© β¦ do
let ty β idx.fvarId!.getType
let instTy β inferType inst
let u := (β inferType ty).sortLevel!
if β isDefEq ty instTy
then pure (mkApp3 (.const `Eq [u]) ty idx inst)
else pure (mkApp4 (.const `HEq [u]) ty idx instTy inst))
let (n, r) β match bs.filterMap id, eqs with
| [], [] => do
pure (some 0, (mkConst `True))
| bs', [] => do
let t : Expr β bs'.getLast!.fvarId!.getType
let l := (β inferType t).sortLevel!
if l == Level.zero then do
let r β mkExistsList (List.init bs') t
pure (none, subst r)
else do
let r β mkExistsList bs' (mkConst `True)
pure (some 0, subst r)
| bs', _ => do
let r β mkExistsList bs' (mkAndList eqs)
pure (some eqs.length, subst r)
pure (β¨bs.map Option.isSome, nβ©, r)
/-- Splits the goal `n` times via `refine β¨?_,?_β©`, and then applies `constructor` to
close the resulting subgoals.
-/
def splitThenConstructor (mvar : MVarId) (n : Nat) : MetaM Unit :=
match n with
| 0 => do
let (subgoals',_) β Term.TermElabM.run <| Tactic.run mvar do
Tactic.evalTactic (β `(tactic| constructor))
let [] := subgoals' | throwError "expected no subgoals"
pure ()
| n + 1 => do
let (subgoals,_) β Term.TermElabM.run <| Tactic.run mvar do
Tactic.evalTactic (β `(tactic| refine β¨?_,?_β©))
let [sg1, sg2] := subgoals | throwError "expected two subgoals"
let (subgoals',_) β Term.TermElabM.run <| Tactic.run sg1 do
Tactic.evalTactic (β `(tactic| constructor))
let [] := subgoals' | throwError "expected no subgoals"
splitThenConstructor sg2 n
/-- Proves the left to right direction of a generated iff theorem.
`shape` is the output of a call to `constrToProp`.
-/
def toCases (mvar : MVarId) (shape : List Shape) : MetaM Unit :=
do
let β¨h, mvar'β© β mvar.intro1
let subgoals β mvar'.cases h
let _ β (shape.zip subgoals.toList).enum.mapM fun β¨p, β¨β¨shape, tβ©, subgoalβ©β© β¦ do
let vars := subgoal.fields
let si := (shape.zip vars.toList).filterMap (fun β¨c,vβ© β¦ if c then some v else none)
let mvar'' β select p (subgoals.size - 1) subgoal.mvarId
match t with
| none => do
let v := vars.get! (shape.length - 1)
let mv β mvar''.existsi (List.init si)
mv.assign v
| some n => do
let mv β mvar''.existsi si
splitThenConstructor mv (n - 1)
pure ()
/-- Calls `cases` on `h` (assumed to be a binary sum) `n` times, and returns
the resulting subgoals and their corresponding new hypotheses.
-/
def nCasesSum (n : Nat) (mvar : MVarId) (h : FVarId) : MetaM (List (FVarId Γ MVarId)) :=
match n with
| 0 => pure [(h, mvar)]
| n' + 1 => do
let #[sg1, sg2] β mvar.cases h | throwError "expected two case subgoals"
let #[Expr.fvar fvar1] β pure sg1.fields | throwError "expected fvar"
let #[Expr.fvar fvar2] β pure sg2.fields | throwError "expected fvar"
let rest β nCasesSum n' sg2.mvarId fvar2
pure ((fvar1, sg1.mvarId)::rest)
/-- Calls `cases` on `h` (assumed to be a binary product) `n` times, and returns
the resulting subgoal and the new hypotheses.
-/
def nCasesProd (n : Nat) (mvar : MVarId) (h : FVarId) : MetaM (MVarId Γ List FVarId) :=
match n with
| 0 => pure (mvar, [h])
| n' + 1 => do
let #[sg] β mvar.cases h | throwError "expected one case subgoals"
let #[Expr.fvar fvar1, Expr.fvar fvar2] β pure sg.fields | throwError "expected fvar"
let (mvar', rest) β nCasesProd n' sg.mvarId fvar2
pure (mvar', fvar1::rest)
/--
Iterate over two lists, if the first element of the first list is `false`, insert `none` into the
result and continue with the tail of first list. Otherwise, wrap the first element of the second
list with `some` and continue with the tails of both lists. Return when either list is empty.
Example:
```
listBoolMerge [false, true, false, true] [0, 1, 2, 3, 4] = [none, (some 0), none, (some 1)]
```
-/
def listBoolMerge {Ξ± : Type*} : List Bool β List Ξ± β List (Option Ξ±)
| [], _ => []
| false :: xs, ys => none :: listBoolMerge xs ys
| true :: xs, y :: ys => some y :: listBoolMerge xs ys
| true :: _, [] => []
/-- Proves the right to left direction of a generated iff theorem.
-/
def toInductive (mvar : MVarId) (cs : List Name)
(gs : List Expr) (s : List Shape) (h : FVarId) :
MetaM Unit := do
match s.length with
| 0 => do let _ β mvar.cases h
pure ()
| (n + 1) => do
let subgoals β nCasesSum n mvar h
let _ β (cs.zip (subgoals.zip s)).mapM fun β¨constr_name, β¨h, mvβ©, bs, eβ© β¦ do
let n := (bs.filter id).length
let (mvar', _fvars) β match e with
| none => nCasesProd (n-1) mv h
| some 0 => do let β¨mvar', fvarsβ© β nCasesProd n mv h
let mvar'' β mvar'.tryClear fvars.getLast!
pure β¨mvar'', fvarsβ©
| some (e + 1) => do
let (mv', fvars) β nCasesProd n mv h
let lastfv := fvars.getLast!
let (mv2, fvars') β nCasesProd e mv' lastfv
/- `fvars'.foldlM subst mv2` fails when we have dependent equalities (`HEq`).
`subst` will change the dependent hypotheses, so that the `uniq` local names
are wrong afterwards. Instead we revert them and pull them out one-by-one. -/
let (_, mv3) β mv2.revert fvars'.toArray
let mv4 β fvars'.foldlM (fun mv _ β¦ do let β¨fv, mv'β© β mv.intro1; subst mv' fv) mv3
pure (mv4, fvars)
mvar'.withContext do
let fvarIds := (β getLCtx).getFVarIds.toList
let gs := fvarIds.take gs.length
let hs := (fvarIds.reverse.take n).reverse
let m := gs.map some ++ listBoolMerge bs hs
let args β m.mapM fun a β¦
match a with
| some v => pure (mkFVar v)
| none => mkFreshExprMVar none
let c β mkConstWithFreshMVarLevels constr_name
let e := mkAppN c args.toArray
let t β inferType e
let mt β mvar'.getType
let _ β isDefEq t mt -- infer values for those mvars we just made
mvar'.assign e
/-- Implementation for both `mk_iff` and `mk_iff_of_inductive_prop`.
-/
def mkIffOfInductivePropImpl (ind : Name) (rel : Name) (relStx : Syntax) : MetaM Unit := do
let .inductInfo inductVal β getConstInfo ind |
throwError "mk_iff only applies to inductive declarations"
let constrs := inductVal.ctors
let params := inductVal.numParams
let type := inductVal.type
let univNames := inductVal.levelParams
let univs := univNames.map mkLevelParam
/- we use these names for our universe parameters, maybe we should construct a copy of them
using `uniq_name` -/
let (thmTy, shape) β Meta.forallTelescope type fun fvars ty β¦ do
if !ty.isProp then throwError "mk_iff only applies to prop-valued declarations"
let lhs := mkAppN (mkConst ind univs) fvars
let fvars' := fvars.toList
let shape_rhss β constrs.mapM (constrToProp univs (fvars'.take params) (fvars'.drop params))
let (shape, rhss) := shape_rhss.unzip
pure (β mkForallFVars fvars (mkApp2 (mkConst `Iff) lhs (mkOrList rhss)), shape)
let mvar β mkFreshExprMVar (some thmTy)
let mvarId := mvar.mvarId!
let (fvars, mvarId') β mvarId.intros
let [mp, mpr] β mvarId'.apply (mkConst `Iff.intro) | throwError "failed to split goal"
toCases mp shape
let β¨mprFvar, mpr'β© β mpr.intro1
toInductive mpr' constrs ((fvars.toList.take params).map .fvar) shape mprFvar
addDecl <| .thmDecl {
name := rel
levelParams := univNames
type := thmTy
value := β instantiateMVars mvar
}
addDeclarationRanges rel {
range := β getDeclarationRange (β getRef)
selectionRange := β getDeclarationRange relStx
}
addConstInfo relStx rel
/--
Applying the `mk_iff` attribute to an inductively-defined proposition `mk_iff` makes an `iff` rule
`r` with the shape `βps is, i as β β_j, βcs, is = cs`, where `ps` are the type parameters, `is` are
the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each of the
constructors, and the equalities `is = cs` are the instantiations for each constructor for each of
the indices to the inductive type `i`.
In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would
be just `c = i` for some index `i`.
For example, if we try the following:
```lean
@[mk_iff]
structure Foo (m n : Nat) : Prop where
equal : m = n
sum_eq_two : m + n = 2
```
Then `#check foo_iff` returns:
```lean
foo_iff : β (m n : Nat), Foo m n β m = n β§ m + n = 2
```
You can add an optional string after `mk_iff` to change the name of the generated lemma.
For example, if we try the following:
```lean
@[mk_iff bar]
structure Foo (m n : Nat) : Prop where
equal : m = n
sum_eq_two : m + n = 2
```
Then `#check bar` returns:
```lean
bar : β (m n : β), Foo m n β m = n β§ m + n = 2
```
See also the user command `mk_iff_of_inductive_prop`.
-/
syntax (name := mkIff) "mk_iff" (ppSpace ident)? : attr
/--
`mk_iff_of_inductive_prop i r` makes an `iff` rule for the inductively-defined proposition `i`.
The new rule `r` has the shape `βps is, i as β β_j, βcs, is = cs`, where `ps` are the type
parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the
parameters for each of the constructors, and the equalities `is = cs` are the instantiations for
each constructor for each of the indices to the inductive type `i`.
In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would
be just `c = i` for some index `i`.
For example, `mk_iff_of_inductive_prop` on `List.Chain` produces:
```lean
β { Ξ± : Type*} (R : Ξ± β Ξ± β Prop) (a : Ξ±) (l : List Ξ±),
Chain R a l β l = [] β¨ β(b : Ξ±) (l' : List Ξ±), R a b β§ Chain R b l β§ l = b :: l'
```
See also the `mk_iff` user attribute.
-/
syntax (name := mkIffOfInductiveProp) "mk_iff_of_inductive_prop " ident ppSpace ident : command
elab_rules : command
| `(command| mk_iff_of_inductive_prop $i:ident $r:ident) =>
Command.liftCoreM <| MetaM.run' do
mkIffOfInductivePropImpl i.getId r.getId r
initialize Lean.registerBuiltinAttribute {
name := `mkIff
descr := "Generate an `iff` lemma for an inductive `Prop`."
add := fun decl stx _ => Lean.Meta.MetaM.run' do
let (tgt, idStx) β match stx with
| `(attr| mk_iff $tgt:ident) =>
pure ((β mkDeclName (β getCurrNamespace) {} tgt.getId).1, tgt.raw)
| `(attr| mk_iff) => pure (decl.decapitalize.appendAfter "_iff", stx)
| _ => throwError "unrecognized syntax"
mkIffOfInductivePropImpl decl tgt idStx
}
|
Tactic\ModCases.lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Heather Macbeth
-/
import Mathlib.Data.Int.ModEq
/-! # `mod_cases` tactic
The `mod_cases` tactic does case disjunction on `e % n`, where `e : β€` or `e : β`,
to yield `n` new subgoals corresponding to the possible values of `e` modulo `n`.
-/
namespace Mathlib.Tactic.ModCases
open Lean Meta Elab Tactic Term Qq
namespace IntMod
open Int
/--
`OnModCases n a lb p` represents a partial proof by cases that
there exists `0 β€ z < n` such that `a β‘ z (mod n)`.
It asserts that if `β z, lb β€ z < n β§ a β‘ z (mod n)` holds, then `p`
(where `p` is the current goal).
-/
def OnModCases (n : β) (a : β€) (lb : β) (p : Sort*) :=
β z, lb β€ z β§ z < n β§ a β‘ βz [ZMOD βn] β p
/--
The first theorem we apply says that `β z, 0 β€ z < n β§ a β‘ z (mod n)`.
The actual mathematical content of the proof is here.
-/
@[inline] def onModCases_start (p : Sort*) (a : β€) (n : β) (hn : Nat.ble 1 n = true)
(H : OnModCases n a (nat_lit 0) p) : p :=
H (a % βn).toNat <| by
have := ofNat_pos.2 <| Nat.le_of_ble_eq_true hn
have nonneg := emod_nonneg a <| Int.ne_of_gt this
refine β¨Nat.zero_le _, ?_, ?_β©
Β· rw [Int.toNat_lt nonneg]; exact Int.emod_lt_of_pos _ this
Β· rw [Int.ModEq, Int.toNat_of_nonneg nonneg, emod_emod]
/--
The end point is that once we have reduced to `β z, n β€ z < n β§ a β‘ z (mod n)`
there are no more cases to consider.
-/
@[inline] def onModCases_stop (p : Sort*) (n : β) (a : β€) : OnModCases n a n p :=
fun _ h => (Nat.not_lt.2 h.1 h.2.1).elim
/--
The successor case decomposes `β z, b β€ z < n β§ a β‘ z (mod n)` into
`a β‘ b (mod n) β¨ β z, b+1 β€ z < n β§ a β‘ z (mod n)`,
and the `a β‘ b (mod n) β p` case becomes a subgoal.
-/
@[inline] def onModCases_succ {p : Sort*} {n : β} {a : β€} (b : β)
(h : a β‘ OfNat.ofNat b [ZMOD OfNat.ofNat n] β p) (H : OnModCases n a (Nat.add b 1) p) :
OnModCases n a b p :=
fun z β¨hβ, hββ© => if e : b = z then h (e βΈ hβ.2) else H _ β¨Nat.lt_of_le_of_ne hβ e, hββ©
/--
Proves an expression of the form `OnModCases n a b p` where `n` and `b` are raw nat literals
and `b β€ n`. Returns the list of subgoals `?gi : a β‘ i [ZMOD n] β p`.
-/
partial def proveOnModCases {u : Level} (n : Q(β)) (a : Q(β€)) (b : Q(β)) (p : Q(Sort u)) :
MetaM (Q(OnModCases $n $a $b $p) Γ List MVarId) := do
if n.natLit! β€ b.natLit! then
haveI' : $b =Q $n := β¨β©
pure (q(onModCases_stop $p $n $a), [])
else
let ty := q($a β‘ OfNat.ofNat $b [ZMOD OfNat.ofNat $n] β $p)
let g β mkFreshExprMVarQ ty
have b1 : Q(β) := mkRawNatLit (b.natLit! + 1)
haveI' : $b1 =Q ($b).succ := β¨β©
let (pr, acc) β proveOnModCases n a b1 p
pure (q(onModCases_succ $b $g $pr), g.mvarId! :: acc)
/--
Int case of `mod_cases h : e % n`.
-/
def modCases (h : TSyntax `Lean.binderIdent) (e : Q(β€)) (n : β) : TacticM Unit := do
let β¨u, p, gβ© β inferTypeQ (.mvar (β getMainGoal))
have lit : Q(β) := mkRawNatLit n
let pβ : Nat.ble 1 $lit =Q true := β¨β©
let (pβ, gs) β proveOnModCases lit e (mkRawNatLit 0) p
let gs β gs.mapM fun g => do
let (fvar, g) β match h with
| `(binderIdent| $n:ident) => g.intro n.getId
| _ => g.intro `H
g.withContext <| (Expr.fvar fvar).addLocalVarInfoForBinderIdent h
pure g
g.mvarId!.assign q(onModCases_start $p $e $lit $pβ $pβ)
replaceMainGoal gs
end IntMod
namespace NatMod
/--
`OnModCases n a lb p` represents a partial proof by cases that
there exists `0 β€ m < n` such that `a β‘ m (mod n)`.
It asserts that if `β m, lb β€ m < n β§ a β‘ m (mod n)` holds, then `p`
(where `p` is the current goal).
-/
def OnModCases (n : β) (a : β) (lb : β) (p : Sort _) :=
β m, lb β€ m β§ m < n β§ a β‘ m [MOD n] β p
/--
The first theorem we apply says that `β m, 0 β€ m < n β§ a β‘ m (mod n)`.
The actual mathematical content of the proof is here.
-/
@[inline] def onModCases_start (p : Sort _) (a : β) (n : β) (hn : Nat.ble 1 n = true)
(H : OnModCases n a (nat_lit 0) p) : p :=
H (a % n) <| by
refine β¨Nat.zero_le _, ?_, ?_β©
Β· exact Nat.mod_lt _ (Nat.le_of_ble_eq_true hn)
Β· rw [Nat.ModEq, Nat.mod_mod]
/--
The end point is that once we have reduced to `β m, n β€ m < n β§ a β‘ m (mod n)`
there are no more cases to consider.
-/
@[inline] def onModCases_stop (p : Sort _) (n : β) (a : β) : OnModCases n a n p :=
fun _ h => (Nat.not_lt.2 h.1 h.2.1).elim
/--
The successor case decomposes `β m, b β€ m < n β§ a β‘ m (mod n)` into
`a β‘ b (mod n) β¨ β m, b+1 β€ m < n β§ a β‘ m (mod n)`,
and the `a β‘ b (mod n) β p` case becomes a subgoal.
-/
@[inline] def onModCases_succ {p : Sort _} {n : β} {a : β} (b : β)
(h : a β‘ b [MOD n] β p) (H : OnModCases n a (Nat.add b 1) p) :
OnModCases n a b p :=
fun z β¨hβ, hββ© => if e : b = z then h (e βΈ hβ.2) else H _ β¨Nat.lt_of_le_of_ne hβ e, hββ©
/--
Proves an expression of the form `OnModCases n a b p` where `n` and `b` are raw nat literals
and `b β€ n`. Returns the list of subgoals `?gi : a β‘ i [MOD n] β p`.
-/
partial def proveOnModCases {u : Level} (n : Q(β)) (a : Q(β)) (b : Q(β)) (p : Q(Sort u)) :
MetaM (Q(OnModCases $n $a $b $p) Γ List MVarId) := do
if n.natLit! β€ b.natLit! then
pure ((q(onModCases_stop $p $n $a) : Expr), [])
else
let ty := q($a β‘ $b [MOD $n] β $p)
let g β mkFreshExprMVarQ ty
let ((pr : Q(OnModCases $n $a (Nat.add $b 1) $p)), acc) β
proveOnModCases n a (mkRawNatLit (b.natLit! + 1)) p
pure ((q(onModCases_succ $b $g $pr) : Expr), g.mvarId! :: acc)
/--
Nat case of `mod_cases h : e % n`.
-/
def modCases (h : TSyntax `Lean.binderIdent) (e : Q(β)) (n : β) : TacticM Unit := do
let β¨u, p, gβ© β inferTypeQ (.mvar (β getMainGoal))
have lit : Q(β) := mkRawNatLit n
let pβ : Q(Nat.ble 1 $lit = true) := (q(Eq.refl true) : Expr)
let (pβ, gs) β proveOnModCases lit e (mkRawNatLit 0) p
let gs β gs.mapM fun g => do
let (fvar, g) β match h with
| `(binderIdent| $n:ident) => g.intro n.getId
| _ => g.intro `H
g.withContext <| (Expr.fvar fvar).addLocalVarInfoForBinderIdent h
pure g
g.mvarId!.assign q(onModCases_start $p $e $lit $pβ $pβ)
replaceMainGoal gs
end NatMod
/--
* The tactic `mod_cases h : e % 3` will perform a case disjunction on `e`.
If `e : β€`, then it will yield subgoals containing the assumptions
`h : e β‘ 0 [ZMOD 3]`, `h : e β‘ 1 [ZMOD 3]`, `h : e β‘ 2 [ZMOD 3]`
respectively. If `e : β` instead, then it works similarly, except with
`[MOD 3]` instead of `[ZMOD 3]`.
* In general, `mod_cases h : e % n` works
when `n` is a positive numeral and `e` is an expression of type `β` or `β€`.
* If `h` is omitted as in `mod_cases e % n`, it will be default-named `H`.
-/
syntax "mod_cases " (atomic(binderIdent ":"))? term:71 " % " num : tactic
elab_rules : tactic
| `(tactic| mod_cases $[$h :]? $e % $n) => do
let n := n.getNat
if n == 0 then Elab.throwUnsupportedSyntax
let h := h.getD (β `(binderIdent| _))
withMainContext do
let e β Tactic.elabTerm e none
let Ξ± : Q(Type) β inferType e
match Ξ± with
| ~q(β€) => IntMod.modCases h e n
| ~q(β) => NatMod.modCases h e n
| _ => throwError "mod_cases only works with Int and Nat"
end ModCases
end Tactic
end Mathlib
|
Tactic\Monotonicity.lean | import Mathlib.Tactic.Monotonicity.Basic
import Mathlib.Tactic.Monotonicity.Lemmas
|
Tactic\MoveAdd.lean | /-
Copyright (c) 2023 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Damiano Testa
-/
import Mathlib.Algebra.Group.Basic
import Mathlib.Init.Order.LinearOrder
/-!
# `move_add` a tactic for moving summands in expressions
The tactic `move_add` rearranges summands in expressions.
The tactic takes as input a list of terms, each one optionally preceded by `β`.
A term preceded by `β` gets moved to the left, while a term without `β` gets moved to the right.
* Empty input: `move_add []`
In this case, the effect of `move_add []` is equivalent to `simp only [β add_assoc]`:
essentially the tactic removes all visible parentheses.
* Singleton input: `move_add [a]` and `move_add [β a]`
If `β’ b + a + c` is (a summand in) the goal, then
* `move_add [β a]` changes the goal to `a + b + c` (effectively, `a` moved to the left).
* `move_add [a]` changes the goal to `b + c + a` (effectively, `a` moved to the right);
The tactic reorders *all* sub-expressions of the target at the same same.
For instance, if `β’ 0 < if b + a < b + a + c then a + b else b + a` is the goal, then
* `move_add [a]` changes the goal to `0 < if b + a < b + c + a then b + a else b + a`
(`a` moved to the right in three sums);
* `move_add [β a]` changes the goal to `0 < if a + b < a + b + c then a + b else a + b`
(`a` again moved to the left in three sums).
* Longer inputs: `move_add [..., a, ..., β b, ...]`
If the list contains more than one term, the tactic effectively tries to move each term preceded
by `β` to the left, each term not preceded by `β` to the right
*maintaining the relative order in the call*.
Thus, applying `move_add [a, b, c, β d, β e]` returns summands of the form
`d + e + [...] + a + b + c`, i.e. `d` and `e` have the same relative position in the input list
and in the final rearrangement (and similarly for `a, b, c`).
In particular, `move_add [a, b]` likely has the same effect as
`move_add [a]; move_add [b]`: first, we move `a` to the right, then we move `b` also to the
right, *after* `a`.
However, if the terms matched by `a` and `b` do not overlap, then `move_add [β a, β b]`
has the same effect as `move_add [b]; move_add [a]`:
first, we move `b` to the left, then we move `a` also to the left, *before* `a`.
The behaviour in the situation where `a` and `b` overlap is unspecified: `move_add`
will descend into subexpressions, but the order in which they are visited depends
on which rearrangements have already happened.
Also note, though, that `move_add [a, b]` may differ `move_add [a]; move_add [b]`,
for instance when `a` and `b` are `DefEq`.
* Unification of inputs and repetitions: `move_add [_, β _, a * _]`
The matching of the user inputs with the atoms of the summands in the target expression
is performed via checking `DefEq` and selecting the first, still available match.
Thus, if a sum in the target is `2 * 3 + 4 * (5 + 6) + 4 * 7 + 10 * 10`, then
`move_add [4 * _]` moves the summand `4 * (5 + 6)` to the right.
The unification of later terms only uses the atoms in the target that have not yet been unified.
Thus, if again the target contains `2 * 3 + 4 * (5 + 6) + 4 * 7 + 10 * 10`, then
`move_add [_, β _, 4 * _]`
matches
* the first input (`_`) with `2 * 3`;
* the second input (`_`) with `4 * (5 + 6)`;
* the third input (`4 * _`) with `4 * 7`.
The resulting permutation therefore places `2 * 3` and `4 * 7` to the left (in this order) and
`4 * (5 + 6)` to the right: `2 * 3 + 4 * 7 + 10 * 10 + 4 * (5 + 6)`.
For the technical description, look at `Mathlib.MoveAdd.weight` and `Mathlib.MoveAdd.reorderUsing`.
`move_add` is the specialization of a more general `move_oper` tactic that takes a binary,
associative, commutative operation and a list of "operand atoms" and rearranges the operation.
## Extension notes
To work with a general associative, commutative binary operation, `move_oper`
needs to have inbuilt the lemmas asserting the analogues of
`add_comm, add_assoc, add_left_comm` for the new operation.
Currently, `move_oper` supports `HAdd.hAdd`, `HMul.hMul`, `And`, `Or`, `Max.max`, `Min.min`.
These lemmas should be added to `Mathlib.MoveAdd.move_oper_simpCtx`.
See `test/MoveAdd.lean` for sample usage of `move_oper`.
## Implementation notes
The main driver behind the tactic is `Mathlib.MoveAdd.reorderAndSimp`.
The tactic takes the target, replaces the maximal subexpressions whose head symbol is the given
operation and replaces them by their reordered versions.
Once that is done, it tries to replace the initial goal with the permuted one by using `simp`.
Currently, no attempt is made at guiding `simp` by doing a `congr`-like destruction of the goal.
This will be the content of a later PR.
-/
open Lean Expr
/-- `getExprInputs e` inspects the outermost constructor of `e` and returns the array of all the
arguments to that constructor that are themselves `Expr`essions. -/
def Lean.Expr.getExprInputs : Expr β Array Expr
| app fn arg => #[fn, arg]
| lam _ bt bb _ => #[bt, bb]
| forallE _ bt bb _ => #[bt, bb]
| letE _ t v b _ => #[t, v, b]
| mdata _ e => #[e]
| proj _ _ e => #[e]
| _ => #[]
/-- `size e` returns the number of subexpressions of `e`. -/
partial
def Lean.Expr.size (e : Expr) : β := (e.getExprInputs.map size).foldl (Β· + Β·) 1
namespace Mathlib.MoveAdd
section ExprProcessing
section reorder
variable {Ξ± : Type*} [BEq Ξ±]
/-!
## Reordering the variables
This section produces the permutations of the variables for `move_add`.
The user controls the final order by passing a list of terms to the tactic.
Each term can be preceded by `β` or not.
In the final ordering,
* terms preceded by `β` appear first,
* terms not preceded by `β` appear last,
* all remaining terms remain in their current relative order.
-/
/-- `uniquify L` takes a list `L : List Ξ±` as input and it returns a list `L' : List (Ξ± Γ β)`.
The two lists `L` and `L'.map Prod.fst` coincide.
The second component of each entry `(a, n)` in `L'` is the number of times that `a` appears in `L`
before the current location.
The resulting list of pairs has no duplicates.
-/
def uniquify : List Ξ± β List (Ξ± Γ β)
| [] => []
| m::ms =>
let lms := uniquify ms
(m, 0) :: (lms.map fun (x, n) => if x == m then (x, n + 1) else (x, n))
variable [Inhabited Ξ±]
/-- Return a sorting key so that all `(a, true)`s are in the list's order
and sorted before all `(a, false)`s, which are also in the list's order.
Although `weight` does not require this, we use `weight` in the case where the list obtained
from `L` by only keeping the first component (i.e. `L.map Prod.fst`) has no duplicates.
The properties that we mention here assume that this is the case.
Thus, `weight L` is a function `Ξ± β β€` with the following properties:
* if `(a, true) β L`, then `weight L a` is strictly negative;
* if `(a, false) β L`, then `weight L a` is strictly positive;
* if neither `(a, true)` nor `(a, false)` is in `L`, then `weight L a = 0`.
Moreover, the function `weight L` is strictly monotone increasing on both
`{a : Ξ± | (a, true) β L}` and `{a : Ξ± | (a, false) β L}`,
in the sense that if `a' = (a, true)` and `b' = (b, true)` are in `L`,
then `a'` appears before `b'` in `L` if and only if `weight L a < weight L b` and
similarly for the pairs with second coordinate equal to `false`.
-/
def weight (L : List (Ξ± Γ Bool)) (a : Ξ±) : β€ :=
let l := L.length
match L.find? (Prod.fst Β· == a) with
| some (_, b) => if b then - l + (L.indexOf (a, b) : β€) else (L.indexOf (a, b) + 1 : β€)
| none => 0
/-- `reorderUsing toReorder instructions` produces a reordering of `toReorder : List Ξ±`,
following the requirements imposed by `instructions : List (Ξ± Γ Bool)`.
These are the requirements:
* elements of `toReorder` that appear with `true` in `instructions` appear at the
*beginning* of the reordered list, in the order in which they appear in `instructions`;
* similarly, elements of `toReorder` that appear with `false` in `instructions` appear at the
*end* of the reordered list, in the order in which they appear in `instructions`;
* finally, elements of `toReorder` that do not appear in `instructions` appear "in the middle"
with the order that they had in `toReorder`.
For example,
* `reorderUsing [0, 1, 2] [(0, false)] = [1, 2, 0]`,
* `reorderUsing [0, 1, 2] [(1, true)] = [1, 0, 2]`,
* `reorderUsing [0, 1, 2] [(1, true), (0, false)] = [1, 2, 0]`.
-/
def reorderUsing (toReorder : List Ξ±) (instructions : List (Ξ± Γ Bool)) : List Ξ± :=
let uInstructions :=
let (as, as?) := instructions.unzip
(uniquify as).zip as?
let uToReorder := (uniquify toReorder).toArray
let reorder := uToReorder.qsort fun x y =>
match uInstructions.find? (Prod.fst Β· == x), uInstructions.find? (Prod.fst Β· == y) with
| none, none => (uToReorder.getIdx? x).get! β€ (uToReorder.getIdx? y).get!
| _, _ => weight uInstructions x β€ weight uInstructions y
(reorder.map Prod.fst).toList
end reorder
/-- `prepareOp sum` takes an `Expr`ession as input. It assumes that `sum` is a well-formed
term representing a repeated application of a binary operation and that the summands are the
last two arguments passed to the operation.
It returns the expression consisting of the operation with all its arguments already applied,
except for the last two.
This is similar to `Lean.Meta.mkAdd, Lean.Meta.mkMul`, except that the resulting operation is
primed to work with operands of the same type as the ones already appearing in `sum`.
This is useful to rearrange the operands.
-/
def prepareOp (sum : Expr) : Expr :=
let opargs := sum.getAppArgs
(opargs.toList.take (opargs.size - 2)).foldl (fun x y => Expr.app x y) sum.getAppFn
/-- `sumList prepOp left_assoc? exs` assumes that `prepOp` is an `Expr`ession representing a
binary operation already fully applied up until its last two arguments and assumes that the
last two arguments are the operands of the operation.
Such an expression is the result of `prepareOp`.
If `exs` is the list `[eβ, eβ, ..., eβ]` of `Expr`essions, then `sumList prepOp left_assoc? exs`
returns
* `prepOp (prepOp( ... prepOp (prepOp eβ eβ) eβ) ... eβ)`, if `left_assoc?` is `false`, and
* `prepOp eβ (prepOp eβ (... prepOp (prepOp eβββ eβ))`, if `left_assoc?` is `true`.
-/
partial
def sumList (prepOp : Expr) (left_assoc? : Bool) : List Expr β Expr
| [] => default
| [a] => a
| a::as =>
if left_assoc? then
Expr.app (prepOp.app a) (sumList prepOp true as)
else
as.foldl (fun x y => Expr.app (prepOp.app x) y) a
end ExprProcessing
open Meta
variable (op : Name)
variable (R : Expr) in
/-- If `sum` is an expression consisting of repeated applications of `op`, then `getAddends`
returns the Array of those recursively determined arguments whose type is DefEq to `R`. -/
partial def getAddends (sum : Expr) : MetaM (Array Expr) := do
if sum.isAppOf op then
let inR β sum.getAppArgs.filterM fun r => do isDefEq R (β inferType r <|> pure R)
let new β inR.mapM (getAddends Β·)
return new.foldl Array.append #[]
else return #[sum]
/-- Recursively compute the Array of `getAddends` Arrays by recursing into the expression `sum`
looking for instance of the operation `op`.
Possibly returns duplicates!
-/
partial def getOps (sum : Expr) : MetaM (Array ((Array Expr) Γ Expr)) := do
let summands β getAddends op (β inferType sum <|> return sum) sum
let (first, rest) := if summands.size == 1 then (#[], sum.getExprInputs) else
(#[(summands, sum)], summands)
let rest β rest.mapM getOps
return rest.foldl Array.append first
/-- `rankSums op tgt instructions` takes as input
* the name `op` of a binary operation,
* an `Expr`ession `tgt`,
* a list `instructions` of pair `(expression, boolean)`.
It extracts the maximal subexpressions of `tgt` whose head symbol is `op`
(i.e. the maximal subexpressions that consist only of applications of the binary operation `op`),
it rearranges the operands of such subexpressions following the order implied by `instructions`
(as in `reorderUsing`),
it returns the list of pairs of expressions `(old_sum, new_sum)`, for which `old_sum β new_sum`
sorted by decreasing value of `Lean.Expr.size`.
In particular, a subexpression of an `old_sum` can only appear *after* its over-expression.
-/
def rankSums (tgt : Expr) (instructions : List (Expr Γ Bool)) : MetaM (List (Expr Γ Expr)) := do
let sums β getOps op (β instantiateMVars tgt)
let candidates := sums.map fun (addends, sum) => do
let reord := reorderUsing addends.toList instructions
let left_assoc? := sum.getAppFn.isConstOf `And || sum.getAppFn.isConstOf `Or
let resummed := sumList (prepareOp sum) left_assoc? reord
if (resummed != sum) then some (sum, resummed) else none
return (candidates.toList.reduceOption.toArray.qsort
(fun x y : Expr Γ Expr β¦ (y.1.size β€ x.1.size))).toList
/-- `permuteExpr op tgt instructions` takes the same input as `rankSums` and returns the
expression obtained from `tgt` by replacing all `old_sum`s by the corresponding `new_sum`.
If there were no required changes, then `permuteExpr` reports this in its second factor. -/
def permuteExpr (tgt : Expr) (instructions : List (Expr Γ Bool)) : MetaM Expr := do
let permInstructions β rankSums op tgt instructions
if permInstructions == [] then throwError "The goal is already in the required form"
let mut permTgt := tgt
-- We cannot do `Expr.replace` all at once here, we need to follow
-- the order of the instructions.
for (old, new) in permInstructions do
permTgt := permTgt.replace (if Β· == old then new else none)
return permTgt
/-- `pairUp L R` takes to lists `L R : List Expr` as inputs.
It scans the elements of `L`, looking for a corresponding `DefEq` `Expr`ession in `R`.
If it finds one such element `d`, then it sets the element `d : R` aside, removing it from `R`, and
it continues with the matching on the remainder of `L` and on `R.erase d`.
At the end, it returns the sublist of `R` of the elements that were matched to some element of `R`,
in the order in which they appeared in `L`,
as well as the sublist of `L` of elements that were not matched, also in the order in which they
appeared in `L`.
Example:
```lean
#eval do
let L := [mkNatLit 0, (β mkFreshExprMVar (some (mkConst ``Nat))), mkNatLit 0] -- i.e. [0, _, 0]
let R := [mkNatLit 0, mkNatLit 0, mkNatLit 1] -- i.e. [0, 1]
dbg_trace f!"{(β pairUp L R)}"
/- output:
`([0, 0], [0])`
the output LHS list `[0, 0]` consists of the first `0` and the `MVarId`.
the output RHS list `[0]` corresponds to the last `0` in `L`.
-/
```
-/
def pairUp : List (Expr Γ Bool Γ Syntax) β List Expr β
MetaM ((List (Expr Γ Bool)) Γ List (Expr Γ Bool Γ Syntax))
| (m::ms), l => do
match β l.findM? (isDefEq Β· m.1) with
| none => let (found, unfound) β pairUp ms l; return (found, m::unfound)
| some d => let (found, unfound) β pairUp ms (l.erase d)
return ((d, m.2.1)::found, unfound)
| _, _ => return ([], [])
/-- `move_oper_simpCtx` is the `Simp.Context` for the reordering internal to `move_oper`.
To support a new binary operation, extend the list in this definition, so that it contains
enough lemmas to allow `simp` to close a generic permutation goal for the new binary operation.
-/
def move_oper_simpCtx : MetaM Simp.Context := do
let simpNames := Elab.Tactic.simpOnlyBuiltins ++ [
``add_comm, ``add_assoc, ``add_left_comm, -- for `HAdd.hAdd`
``mul_comm, ``mul_assoc, ``mul_left_comm, -- for `HMul.hMul`
``and_comm, ``and_assoc, ``and_left_comm, -- for `and`
``or_comm, ``or_assoc, ``or_left_comm, -- for `or`
``max_comm, ``max_assoc, ``max_left_comm, -- for `max`
``min_comm, ``min_assoc, ``min_left_comm -- for `min`
]
let simpThms β simpNames.foldlM (Β·.addConst Β·) ({} : SimpTheorems)
return { simpTheorems := #[simpThms] }
/-- `reorderAndSimp mv op instr` takes as input an `MVarId` `mv`, the name `op` of a binary
operation and a list of "instructions" `instr` that it passes to `permuteExpr`.
* It creates a version `permuted_mv` of `mv` with subexpressions representing `op`-sums reordered
following `instructions`.
* It produces 2 temporary goals by applying `Eq.mpr` and unifying the resulting meta-variable with
`permuted_mv`: `[β’ mv = permuted_mv, β’ permuted_mv]`.
* It tries to solve the goal `mv = permuted_mv` by a simple-minded `simp` call, using the
`op`-analogues of `add_comm, add_assoc, add_left_comm`.
-/
def reorderAndSimp (mv : MVarId) (instr : List (Expr Γ Bool)) :
MetaM (List MVarId) := mv.withContext do
let permExpr β permuteExpr op (β mv.getType'') instr
-- generate the implication `permutedMv β mv = permutedMv β mv`
let eqmpr β mkAppM ``Eq.mpr #[β mkFreshExprMVar (β mkEq (β mv.getType) permExpr)]
let twoGoals β mv.apply eqmpr
guard (twoGoals.length == 2) <|>
throwError m!"There should only be 2 goals, instead of {twoGoals.length}"
-- `permGoal` is the single goal `mv_permuted`, possibly more operations will be permuted later on
let permGoal β twoGoals.filterM fun v => return !(β v.isAssigned)
match β (simpGoal (permGoal[1]!) (β move_oper_simpCtx)) with
| (some x, _) => throwError m!"'move_oper' could not solve {indentD x.2}"
| (none, _) => return permGoal
/-- `unifyMovements` takes as input
* an array of `Expr Γ Bool Γ Syntax`, as in the output of `parseArrows`,
* the `Name` `op` of a binary operation,
* an `Expr`ession `tgt`.
It unifies each `Expr`ession appearing as a first factor of the array with the atoms
for the operation `op` in the expression `tgt`, returning
* the lists of pairs of a matched subexpression with the corresponding `Bool`ean;
* a pair of a list of error messages and the corresponding list of Syntax terms where the error
should be thrown;
* an array of debugging messages.
-/
def unifyMovements (data : Array (Expr Γ Bool Γ Syntax)) (tgt : Expr) :
MetaM (List (Expr Γ Bool) Γ (List MessageData Γ List Syntax) Γ Array MessageData) := do
let ops β getOps op tgt
let atoms := (ops.map Prod.fst).flatten.toList.filter (!isBVar Β·)
-- `instr` are the unified user-provided terms, `neverMatched` are non-unified ones
let (instr, neverMatched) β pairUp data.toList atoms
let dbgMsg := #[m!"Matching of input variables:\n\
* pre-match: {data.map (Prod.snd β Prod.snd)}\n\
* post-match: {instr}",
m!"\nMaximum number of iterations: {ops.size}"]
-- if there are `neverMatched` terms, return the parsed terms and the syntax
let errMsg := neverMatched.map fun (t, a, stx) => (if a then m!"β {t}" else m!"{t}", stx)
return (instr, errMsg.unzip, dbgMsg)
section parsing
open Elab Parser Tactic
/-- `parseArrows` parses an input of the form `[a, β b, _ * (1 : β€)]`, consisting of a list of
terms, each optionally preceded by the arrow `β`.
It returns an array of triples consisting of
* the `Expr`ession corresponding to the parsed term,
* the `Bool`ean `true` if the arrow is present in front of the term,
* the underlying `Syntax` of the given term.
E.g. convert `[a, β b, _ * (1 : β€)]` to
``[(a, false, `(a)), (b, true, `(b)), (_ * 1, false, `(_ * 1))]``.
-/
def parseArrows : TSyntax `Lean.Parser.Tactic.rwRuleSeq β TermElabM (Array (Expr Γ Bool Γ Syntax))
| `(rwRuleSeq| [$rs,*]) => do
rs.getElems.mapM fun rstx => do
let r : Syntax := rstx
return (β Term.elabTerm r[1]! none, ! r[0]!.isNone, rstx)
| _ => failure
initialize registerTraceClass `Tactic.move_oper
/-- The tactic `move_add` rearranges summands of expressions.
Calling `move_add [a, β b, ...]` matches `a, b,...` with summands in the main goal.
It then moves `a` to the far right and `b` to the far left of each addition in which they appear.
The side to which the summands are moved is determined by the presence or absence of the arrow `β`.
The inputs `a, b,...` can be any terms, also with underscores.
The tactic uses the first "new" summand that unifies with each one of the given inputs.
There is a multiplicative variant, called `move_mul`.
There is also a general tactic for a "binary associative commutative operation": `move_oper`.
In this case the syntax requires providing first a term whose head symbol is the operation.
E.g. `move_oper HAdd.hAdd [...]` is the same as `move_add`, while `move_oper Max.max [...]`
rearranges `max`s.
-/
elab (name := moveOperTac) "move_oper" id:ident rws:rwRuleSeq : tactic => withMainContext do
-- parse the operation
let op := id.getId
-- parse the list of terms
let (instr, (unmatched, stxs), dbgMsg) β unifyMovements op (β parseArrows rws)
(β instantiateMVars (β getMainTarget))
unless unmatched.length = 0 do
let _ β stxs.mapM (logErrorAt Β· "") -- underline all non-matching terms
trace[Tactic.move_oper] dbgMsg.foldl (fun x y => (x.compose y).compose "\n\n---\n") ""
throwErrorAt stxs[0]! m!"Errors:\nThe terms in '{unmatched}' were not matched to any atom"
-- move around the operands
replaceMainGoal (β reorderAndSimp op (β getMainGoal) instr)
@[inherit_doc moveOperTac]
elab "move_add" rws:rwRuleSeq : tactic => do
let hadd := mkIdent ``HAdd.hAdd
evalTactic (β `(tactic| move_oper $hadd $rws))
@[inherit_doc moveOperTac]
elab "move_mul" rws:rwRuleSeq : tactic => do
let hmul := mkIdent ``HMul.hMul
evalTactic (β `(tactic| move_oper $hmul $rws))
end parsing
|
Tactic\NoncommRing.lean | /-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux, Scott Morrison, Oliver Nash
-/
import Mathlib.Algebra.Group.Action.Defs
import Mathlib.Tactic.Abel
/-! # The `noncomm_ring` tactic
Solve goals in not necessarily commutative rings.
This tactic is rudimentary, but useful for solving simple goals in noncommutative rings. One
glaring flaw is that numeric powers are unfolded entirely with `pow_succ` and can easily exceed the
maximum recursion depth.
`noncomm_ring` is just a `simp only [some lemmas]` followed by `abel`. It automatically uses `abel1`
to close the goal, and if that doesn't succeed, defaults to `abel_nf`.
-/
namespace Mathlib.Tactic.NoncommRing
section nat_lit_mul
variable {R : Type*} [NonAssocSemiring R] (r : R) (n : β)
lemma nat_lit_mul_eq_nsmul [n.AtLeastTwo] : no_index (OfNat.ofNat n) * r = n β’ r := by
simp only [nsmul_eq_mul, Nat.cast_eq_ofNat]
lemma mul_nat_lit_eq_nsmul [n.AtLeastTwo] : r * no_index (OfNat.ofNat n) = n β’ r := by
simp only [nsmul_eq_mul', Nat.cast_eq_ofNat]
end nat_lit_mul
open Lean.Parser.Tactic
/-- A tactic for simplifying identities in not-necessarily-commutative rings.
An example:
```lean
example {R : Type*} [Ring R] (a b c : R) : a * (b + c + c - b) = 2 * a * c := by
noncomm_ring
```
You can use `noncomm_ring [h]` to also simplify using `h`.
-/
syntax (name := noncomm_ring) "noncomm_ring" (config)? (discharger)?
(" [" ((simpStar <|> simpErase <|> simpLemma),*,?) "]")? : tactic
macro_rules
| `(tactic| noncomm_ring $[$cfg]? $[$disch]? $[[$rules,*]]?) => do
let rules' := rules.getD β¨#[]β©
let tac β `(tactic|
(first | simp $cfg ? $disch ? only [
-- Expand everything out.
add_mul, mul_add, sub_eq_add_neg,
-- Right associate all products.
mul_assoc,
-- Expand powers to numerals.
pow_one, pow_zero, pow_succ,
-- Replace multiplication by numerals with `zsmul`.
one_mul, mul_one, zero_mul, mul_zero,
nat_lit_mul_eq_nsmul, mul_nat_lit_eq_nsmul,
-- Pull `zsmul n` out the front so `abel` can see them.
mul_smul_comm, smul_mul_assoc,
-- Pull out negations.
neg_mul, mul_neg,
-- user-specified simp lemmas
$rules',*] |
fail "`noncomm_ring` simp lemmas don't apply; try `abel` instead") <;>
first | abel1 | abel_nf)
-- if a manual rewrite rule is provided, we repeat the tactic
-- (since abel might simplify and allow the rewrite to apply again)
if rules.isSome then `(tactic| repeat1 ($tac;)) else `(tactic| $tac)
end Mathlib.Tactic.NoncommRing
|
Tactic\Nontriviality.lean | /-
Copyright (c) 2020 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel, Mario Carneiro
-/
import Mathlib.Tactic.Nontriviality.Core
/-! # The `nontriviality` tactic. -/
|
Tactic\NormNum.lean | import Mathlib.Tactic.NormNum.Basic
import Mathlib.Tactic.NormNum.OfScientific
import Mathlib.Tactic.NormNum.Eq
import Mathlib.Tactic.NormNum.Ineq
import Mathlib.Tactic.NormNum.Pow
import Mathlib.Tactic.NormNum.Inv
import Mathlib.Tactic.NormNum.DivMod
import Mathlib.Data.Rat.Cast.Order
|
Tactic\NthRewrite.lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import Lean.Elab.Tactic.Rewrite
/-!
# `nth_rewrite` tactic
The tactic `nth_rewrite` and `nth_rw` are variants of `rewrite` and `rw` that only performs the
`n`th possible rewrite.
-/
namespace Mathlib.Tactic
open Lean Elab Tactic Meta Parser.Tactic
/-- `nth_rewrite` is a variant of `rewrite` that only changes the `n`α΅Κ° _occurrence_ of the
expression to be rewritten. `nth_rewrite n [eqβ, eqβ,..., eqβ]` will rewrite the `n`α΅Κ° _occurrence_
of each of the `m` equalities `eqα΅’`in that order. Occurrences are counted beginning with `1` in
order of precedence.
For example,
```lean
example (h : a = 1) : a + a + a + a + a = 5 := by
nth_rewrite 2 [h]
/-
a: β
h: a = 1
β’ a + 1 + a + a + a = 5
-/
```
Notice that the second occurrence of `a` from the left has been rewritten by `nth_rewrite`.
To understand the importance of order of precedence, consider the example below
```lean
example (a b c : Nat) : (a + b) + c = (b + a) + c := by
nth_rewrite 2 [Nat.add_comm] -- β’ (b + a) + c = (b + a) + c
```
Here, although the occurrence parameter is `2`, `(a + b)` is rewritten to `(b + a)`. This happens
because in order of precedence, the first occurrence of `_ + _` is the one that adds `a + b` to `c`.
The occurrence in `a + b` counts as the second occurrence.
If a term `t` is introduced by rewriting with `eqα΅’`, then this instance of `t` will be counted as an
_occurrence_ of `t` for all subsequent rewrites of `t` with `eqβ±Ό` for `j > i`. This behaviour is
illustrated by the example below
```lean
example (h : a = a + b) : a + a + a + a + a = 0 := by
nth_rewrite 3 [h, h]
/-
a b: β
h: a = a + b
β’ a + a + (a + b + b) + a + a = 0
-/
```
Here, the first `nth_rewrite` with `h` introduces an additional occurrence of `a` in the goal.
That is, the goal state after the first rewrite looks like below
```lean
/-
a b: β
h: a = a + b
β’ a + a + (a + b) + a + a = 0
-/
```
This new instance of `a` also turns out to be the third _occurrence_ of `a`. Therefore,
the next `nth_rewrite` with `h` rewrites this `a`.
-/
syntax (name := nthRewriteSeq) "nth_rewrite" (config)? ppSpace num rwRuleSeq (location)? : tactic
@[inherit_doc nthRewriteSeq, tactic nthRewriteSeq] def evalNthRewriteSeq : Tactic := fun stx => do
match stx with
| `(tactic| nth_rewrite $[$_cfg]? $n $_rules $[$_loc]?) =>
-- [TODO] `stx` should not be used directly, but the corresponding functions do not yet exist
-- in Lean 4 core
let cfg β elabRewriteConfig stx[1]
let loc := expandOptLocation stx[4]
let occ := Occurrences.pos [n.getNat]
let cfg := { cfg with occs := occ }
withRWRulesSeq stx[0] stx[3] fun symm term => do
withLocation loc
(rewriteLocalDecl term symm Β· cfg)
(rewriteTarget term symm cfg)
(throwTacticEx `nth_rewrite Β· "did not find instance of the pattern in the current goal")
| _ => throwUnsupportedSyntax
/--
`nth_rw` is a variant of `rw` that only changes the `n`α΅Κ° _occurrence_ of the expression to be
rewritten. Like `rw`, and unlike `nth_rewrite`, it will try to close the goal by trying `rfl`
afterwards. `nth_rw n [eqβ, eqβ,..., eqβ]` will rewrite the `n`α΅Κ° _occurrence_ of each of the
`m` equalities `eqα΅’`in that order. Occurrences are counted beginning with `1` in
order of precedence. For example,
```lean
example (h : a = 1) : a + a + a + a + a = 5 := by
nth_rw 2 [h]
/-
a: β
h: a = 1
β’ a + 1 + a + a + a = 5
-/
```
Notice that the second occurrence of `a` from the left has been rewritten by `nth_rewrite`.
To understand the importance of order of precedence, consider the example below
```lean
example (a b c : Nat) : (a + b) + c = (b + a) + c := by
nth_rewrite 2 [Nat.add_comm] -- β’ (b + a) + c = (b + a) + c
```
Here, although the occurrence parameter is `2`, `(a + b)` is rewritten to `(b + a)`. This happens
because in order of precedence, the first occurrence of `_ + _` is the one that adds `a + b` to `c`.
The occurrence in `a + b` counts as the second occurrence.
If a term `t` is introduced by rewriting with `eqα΅’`, then this instance of `t` will be counted as an
_occurrence_ of `t` for all subsequent rewrites of `t` with `eqβ±Ό` for `j > i`. This behaviour is
illustrated by the example below
```lean
example (h : a = a + b) : a + a + a + a + a = 0 := by
nth_rw 3 [h, h]
/-
a b: β
h: a = a + b
β’ a + a + (a + b + b) + a + a = 0
-/
```
Here, the first `nth_rw` with `h` introduces an additional occurrence of `a` in the goal. That is,
the goal state after the first rewrite looks like below
```lean
/-
a b: β
h: a = a + b
β’ a + a + (a + b) + a + a = 0
-/
```
This new instance of `a` also turns out to be the third _occurrence_ of `a`. Therefore,
the next `nth_rw` with `h` rewrites this `a`.
Further, `nth_rw` will close the remaining goal with `rfl` if possible.
-/
macro (name := nthRwSeq) "nth_rw" c:(config)? ppSpace n:num s:rwRuleSeq l:(location)? : tactic =>
-- Note: This is a direct copy of `nth_rw` from core.
match s with
| `(rwRuleSeq| [$rs,*]%$rbrak) =>
-- We show the `rfl` state on `]`
`(tactic| (nth_rewrite $(c)? $n [$rs,*] $(l)?; with_annotate_state $rbrak
(try (with_reducible rfl))))
| _ => Macro.throwUnsupported
|
Tactic\Observe.lean | /-
Copyright (c) 2023 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Lean.Meta.Tactic.TryThis
import Lean.Elab.Tactic.ElabTerm
import Lean.Meta.Tactic.LibrarySearch
/-!
# The `observe` tactic.
`observe hp : p` asserts the proposition `p`, and tries to prove it using `exact?`.
-/
namespace Mathlib.Tactic.LibrarySearch
open Lean Meta Elab Tactic Meta.Tactic.TryThis LibrarySearch
/-- `observe hp : p` asserts the proposition `p`, and tries to prove it using `exact?`.
If no proof is found, the tactic fails.
In other words, this tactic is equivalent to `have hp : p := by exact?`.
If `hp` is omitted, then the placeholder `this` is used.
The variant `observe? hp : p` will emit a trace message of the form `have hp : p := proof_term`.
This may be particularly useful to speed up proofs. -/
syntax (name := observe) "observe" "?"? (ppSpace ident)? " : " term
(" using " (colGt term),+)? : tactic
elab_rules : tactic |
`(tactic| observe%$tk $[?%$trace]? $[$n?:ident]? : $t:term $[using $[$required:term],*]?) => do
let name : Name := match n? with
| none => `this
| some n => n.getId
withMainContext do
let (type, _) β elabTermWithHoles t none (β getMainTag) true
let .mvar goal β mkFreshExprMVar type | failure
if let some _ β librarySearch goal then
reportOutOfHeartbeats `library_search tk
throwError "observe did not find a solution"
else
let v := (β instantiateMVars (mkMVar goal)).headBeta
if trace.isSome then
addHaveSuggestion tk (some name) type v
let (_, newGoal) β (β getMainGoal).note name v
replaceMainGoal [newGoal]
@[inherit_doc observe] macro "observe?" h:(ppSpace ident)? " : " t:term : tactic =>
`(tactic| observe ? $[$h]? : $t)
@[inherit_doc observe]
macro "observe?" h:(ppSpace ident)? " : " t:term " using " terms:(colGt term),+ : tactic =>
`(tactic| observe ? $[$h]? : $t using $[$terms],*)
end Mathlib.Tactic.LibrarySearch
|
Tactic\Peel.lean | /-
Copyright (c) 2023 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import Mathlib.Order.Filter.Basic
import Mathlib.Tactic.Basic
/-!
# The `peel` tactic
`peel h with h' idents*` tries to apply `forall_imp` (or `Exists.imp`, or `Filter.Eventually.mp`,
`Filter.Frequently.mp` and `Filter.eventually_of_forall`) with the argument `h` and uses `idents*`
to introduce variables with the supplied names, giving the "peeled" argument the name `h'`.
One can provide a numeric argument as in `peel 4 h` which will peel 4 quantifiers off
the expressions automatically name any variables not specifically named in the `with` clause.
In addition, the user may supply a term `e` via `... using e` in order to close the goal
immediately. In particular, `peel h using e` is equivalent to `peel h; exact e`. The `using` syntax
may be paired with any of the other features of `peel`.
-/
namespace Mathlib.Tactic.Peel
open Lean Expr Meta Elab Tactic
/--
Peels matching quantifiers off of a given term and the goal and introduces the relevant variables.
- `peel e` peels all quantifiers (at reducible transparency),
using `this` for the name of the peeled hypothesis.
- `peel e with h` is `peel e` but names the peeled hypothesis `h`.
If `h` is `_` then uses `this` for the name of the peeled hypothesis.
- `peel n e` peels `n` quantifiers (at default transparency).
- `peel n e with x y z ... h` peels `n` quantifiers, names the peeled hypothesis `h`,
and uses `x`, `y`, `z`, and so on to name the introduced variables; these names may be `_`.
If `h` is `_` then uses `this` for the name of the peeled hypothesis.
The length of the list of variables does not need to equal `n`.
- `peel e with xβ ... xβ h` is `peel n e with xβ ... xβ h`.
There are also variants that apply to an iff in the goal:
- `peel n` peels `n` quantifiers in an iff.
- `peel with xβ ... xβ` peels `n` quantifiers in an iff and names them.
Given `p q : β β Prop`, `h : β x, p x`, and a goal `β’ : β x, q x`, the tactic `peel h with x h'`
will introduce `x : β`, `h' : p x` into the context and the new goal will be `β’ q x`. This works
with `β`, as well as `βαΆ ` and `βαΆ `, and it can even be applied to a sequence of quantifiers. Note
that this is a logically weaker setup, so using this tactic is not always feasible.
For a more complex example, given a hypothesis and a goal:
```
h : β Ξ΅ > (0 : β), β N : β, β n β₯ N, 1 / (n + 1 : β) < Ξ΅
β’ β Ξ΅ > (0 : β), β N : β, β n β₯ N, 1 / (n + 1 : β) β€ Ξ΅
```
(which differ only in `<`/`β€`), applying `peel h with Ξ΅ hΞ΅ N n hn h_peel` will yield a tactic state:
```
h : β Ξ΅ > (0 : β), β N : β, β n β₯ N, 1 / (n + 1 : β) < Ξ΅
Ξ΅ : β
hΞ΅ : 0 < Ξ΅
N n : β
hn : N β€ n
h_peel : 1 / (n + 1 : β) < Ξ΅
β’ 1 / (n + 1 : β) β€ Ξ΅
```
and the goal can be closed with `exact h_peel.le`.
Note that in this example, `h` and the goal are logically equivalent statements, but `peel`
*cannot* be immediately applied to show that the goal implies `h`.
In addition, `peel` supports goals of the form `(β x, p x) β β x, q x`, or likewise for any
other quantifier. In this case, there is no hypothesis or term to supply, but otherwise the syntax
is the same. So for such goals, the syntax is `peel 1` or `peel with x`, and after which the
resulting goal is `p x β q x`. The `congr!` tactic can also be applied to goals of this form using
`congr! 1 with x`. While `congr!` applies congruence lemmas in general, `peel` can be relied upon
to only apply to outermost quantifiers.
Finally, the user may supply a term `e` via `... using e` in order to close the goal
immediately. In particular, `peel h using e` is equivalent to `peel h; exact e`. The `using` syntax
may be paired with any of the other features of `peel`.
This tactic works by repeatedly applying lemmas such as `forall_imp`, `Exists.imp`,
`Filter.Eventually.mp`, `Filter.Frequently.mp`, and `Filter.eventually_of_forall`.
-/
syntax (name := peel)
"peel" (num)? (ppSpace colGt term)?
(" with" (ppSpace colGt (ident <|> hole))+)? (usingArg)? : tactic
private lemma and_imp_left_of_imp_imp {p q r : Prop} (h : r β p β q) : r β§ p β r β§ q := by tauto
private theorem eventually_imp {Ξ± : Type*} {p q : Ξ± β Prop} {f : Filter Ξ±}
(hq : β (x : Ξ±), p x β q x) (hp : βαΆ (x : Ξ±) in f, p x) : βαΆ (x : Ξ±) in f, q x :=
Filter.Eventually.mp hp (Filter.eventually_of_forall hq)
private theorem frequently_imp {Ξ± : Type*} {p q : Ξ± β Prop} {f : Filter Ξ±}
(hq : β (x : Ξ±), p x β q x) (hp : βαΆ (x : Ξ±) in f, p x) : βαΆ (x : Ξ±) in f, q x :=
Filter.Frequently.mp hp (Filter.eventually_of_forall hq)
private theorem eventually_congr {Ξ± : Type*} {p q : Ξ± β Prop} {f : Filter Ξ±}
(hq : β (x : Ξ±), p x β q x) : (βαΆ (x : Ξ±) in f, p x) β βαΆ (x : Ξ±) in f, q x := by
congr! 2; exact hq _
private theorem frequently_congr {Ξ± : Type*} {p q : Ξ± β Prop} {f : Filter Ξ±}
(hq : β (x : Ξ±), p x β q x) : (βαΆ (x : Ξ±) in f, p x) β βαΆ (x : Ξ±) in f, q x := by
congr! 2; exact hq _
/-- The list of constants that are regarded as being quantifiers. -/
def quantifiers : List Name :=
[``Exists, ``And, ``Filter.Eventually, ``Filter.Frequently]
/-- If `unfold` is false then do `whnfR`, otherwise unfold everything that's not a quantifier,
according to the `quantifiers` list. -/
def whnfQuantifier (p : Expr) (unfold : Bool) : MetaM Expr := do
if unfold then
whnfHeadPred p fun e =>
if let .const n .. := e.getAppFn then
return !(n β quantifiers)
else
return false
else
whnfR p
/-- Throws an error saying `ty` and `target` could not be matched up. -/
def throwPeelError {Ξ± : Type} (ty target : Expr) : MetaM Ξ± :=
throwError "Tactic 'peel' could not match quantifiers in{indentD ty}\nand{indentD target}"
/-- If `f` is a lambda then use its binding name to generate a new hygienic name,
and otherwise choose a new hygienic name. -/
def mkFreshBinderName (f : Expr) : MetaM Name :=
mkFreshUserName (if let .lam n .. := f then n else `a)
/-- Applies a "peel theorem" with two main arguments, where the first is the new goal
and the second can be filled in using `e`. Then it intros two variables with the
provided names.
If, for example, `goal : β y : Ξ±, q y` and `thm := Exists.imp`, the metavariable returned has
type `q x` where `x : Ξ±` has been introduced into the context. -/
def applyPeelThm (thm : Name) (goal : MVarId)
(e : Expr) (ty target : Expr) (n : Name) (n' : Name) :
MetaM (FVarId Γ List MVarId) := do
let new_goal :: ge :: _ β goal.applyConst thm <|> throwPeelError ty target
| throwError "peel: internal error"
ge.assignIfDefeq e <|> throwPeelError ty target
let (fvars, new_goal) β new_goal.introN 2 [n, n']
return (fvars[1]!, [new_goal])
/-- This is the core to the `peel` tactic.
It tries to match `e` and `goal` as quantified statements (using `β` and the quantifiers in
the `quantifiers` list), then applies "peel theorems" using `applyPeelThm`.
We treat `β§` as a quantifier for sake of dealing with quantified statements
like `β Ξ΄ > (0 : β), q Ξ΄`, which is notation for `β Ξ΄, Ξ΄ > (0 : β) β§ q Ξ΄`. -/
def peelCore (goal : MVarId) (e : Expr) (n? : Option Name) (n' : Name) (unfold : Bool) :
MetaM (FVarId Γ List MVarId) := goal.withContext do
let ty β whnfQuantifier (β inferType e) unfold
let target β whnfQuantifier (β goal.getType) unfold
if ty.isForall && target.isForall then
applyPeelThm ``forall_imp goal e ty target (β n?.getDM (mkFreshUserName target.bindingName!)) n'
else if ty.getAppFn.isConst
&& ty.getAppNumArgs == target.getAppNumArgs
&& ty.getAppFn == target.getAppFn then
match target.getAppFnArgs with
| (``Exists, #[_, p]) =>
applyPeelThm ``Exists.imp goal e ty target (β n?.getDM (mkFreshBinderName p)) n'
| (``And, #[_, _]) =>
applyPeelThm ``and_imp_left_of_imp_imp goal e ty target (β n?.getDM (mkFreshUserName `p)) n'
| (``Filter.Eventually, #[_, p, _]) =>
applyPeelThm ``eventually_imp goal e ty target (β n?.getDM (mkFreshBinderName p)) n'
| (``Filter.Frequently, #[_, p, _]) =>
applyPeelThm ``frequently_imp goal e ty target (β n?.getDM (mkFreshBinderName p)) n'
| _ => throwPeelError ty target
else
throwPeelError ty target
/-- Given a list `l` of names, this peels `num` quantifiers off of the expression `e` and
the main goal and introduces variables with the provided names until the list of names is exhausted.
Note: the name `n?` (with default `this`) is used for the name of the expression `e` with
quantifiers peeled. -/
def peelArgs (e : Expr) (num : Nat) (l : List Name) (n? : Option Name) (unfold : Bool := true) :
TacticM Unit := do
match num with
| 0 => return
| num + 1 =>
let fvarId β liftMetaTacticAux (peelCore Β· e l.head? (n?.getD `this) unfold)
peelArgs (.fvar fvarId) num l.tail n?
unless num == 0 do
if let some mvarId β observing? do (β getMainGoal).clear fvarId then
replaceMainGoal [mvarId]
/-- Similar to `peelArgs` but peels arbitrarily many quantifiers. Returns whether or not
any quantifiers were peeled. -/
partial def peelUnbounded (e : Expr) (n? : Option Name) (unfold : Bool := false) :
TacticM Bool := do
let fvarId? β observing? <| liftMetaTacticAux (peelCore Β· e none (n?.getD `this) unfold)
if let some fvarId := fvarId? then
let peeled β peelUnbounded (.fvar fvarId) n?
if peeled then
if let some mvarId β observing? do (β getMainGoal).clear fvarId then
replaceMainGoal [mvarId]
return true
else
return false
/-- Peel off a single quantifier from an `β`. -/
def peelIffAux : TacticM Unit := do
evalTactic (β `(tactic| focus
first | apply forall_congr'
| apply exists_congr
| apply eventually_congr
| apply frequently_congr
| apply and_congr_right
| fail "failed to apply a quantifier congruence lemma."))
/-- Peel off quantifiers from an `β` and assign the names given in `l` to the introduced
variables. -/
def peelArgsIff (l : List Name) : TacticM Unit := withMainContext do
match l with
| [] => pure ()
| h :: hs =>
peelIffAux
let goal β getMainGoal
let (_, new_goal) β goal.intro h
replaceMainGoal [new_goal]
peelArgsIff hs
elab_rules : tactic
| `(tactic| peel $[$num?:num]? $e:term $[with $l?* $n?]?) => withMainContext do
/- we use `elabTermForApply` instead of `elabTerm` so that terms passed to `peel` can contain
quantifiers with implicit bound variables without causing errors or requiring `@`. -/
let e β elabTermForApply e false
let n? := n?.bind fun n => if n.raw.isIdent then pure n.raw.getId else none
let l := (l?.getD #[]).map getNameOfIdent' |>.toList
-- If num is not present and if there are any provided variable names,
-- use the number of variable names.
let num? := num?.map (Β·.getNat) <|> if l.isEmpty then none else l.length
if let some num := num? then
peelArgs e num l n?
else
unless β peelUnbounded e n? do
throwPeelError (β inferType e) (β getMainTarget)
| `(tactic| peel $n:num) => peelArgsIff <| .replicate n.getNat `_
| `(tactic| peel with $args*) => peelArgsIff (args.map getNameOfIdent').toList
macro_rules
| `(tactic| peel $[$n:num]? $[$e:term]? $[with $h*]? using $u:term) =>
`(tactic| peel $[$n:num]? $[$e:term]? $[with $h*]?; exact $u)
end Peel
end Tactic
end Mathlib
|
Tactic\Polyrith.lean | /-
Copyright (c) 2022 Dhruv Bhatia. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dhruv Bhatia, Eric Wieser, Mario Carneiro
-/
import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Tactic.LinearCombination
/-!
# polyrith Tactic
In this file, the `polyrith` tactic is created. This tactic, which
works over `Field`s, attempts to prove a multivariate polynomial target over said
field by using multivariable polynomial hypotheses/proof terms over the same field.
Used as is, the tactic makes use of those hypotheses in the local context that are
over the same field as the target. However, the user can also specify which hypotheses
from the local context to use, along with proof terms that might not already be in the
local context. Note: since this tactic uses SageMath via an API call done in Python,
it can only be used with a working internet connection, and with a local installation of Python.
## Implementation Notes
The tactic `linear_combination` is often used to prove such goals by allowing the user to
specify a coefficient for each hypothesis. If the target polynomial can be written as a
linear combination of the hypotheses with the chosen coefficients, then the `linear_combination`
tactic succeeds. In other words, `linear_combination` is a certificate checker, and it is left
to the user to find a collection of good coefficients. The `polyrith` tactic automates this
process using the theory of Groebner bases.
Polyrith does this by first parsing the relevant hypotheses into a form that Python can understand.
It then calls a Python file that uses the SageMath API to compute the coefficients. These
coefficients are then sent back to Lean, which parses them into pexprs. The information is then
given to the `linear_combination` tactic, which completes the process by checking the certificate.
In fact, `polyrith` uses Sage to test for membership in the *radical* of the ideal.
This means it searches for a linear combination of hypotheses that add up to a *power* of the goal.
When this power is not 1, it uses the `(exp := n)` feature of `linear_combination` to report the
certificate.
`polyrith` calls an external python script `scripts/polyrith_sage.py`. Because this is not a Lean
file, changes to this script may not be noticed during Lean compilation if you have already
generated olean files. If you are modifying this python script, you likely know what you're doing;
remember to force recompilation of any files that call `polyrith`.
## TODO
* Give Sage more information about the specific ring being used for the coefficients. For now,
we always use β (or `QQ` in Sage).
* Handle `β’` terms.
* Support local Sage installations.
## References
* See the book [*Ideals, Varieties, and Algorithms*][coxlittleOshea1997] by David Cox, John Little,
and Donal O'Shea for the background theory on Groebner bases
* This code was heavily inspired by the code for the tactic `linarith`, which was written by
Robert Lewis, who advised me on this project as part of a Computer Science independent study
at Brown University.
-/
namespace Mathlib.Tactic.Polyrith
open Lean hiding Rat
open Meta Ring Qq PrettyPrinter AtomM
initialize registerTraceClass `Meta.Tactic.polyrith
/-! # Poly Datatype -/
/--
A datatype representing the semantics of multivariable polynomials.
Each `Poly` can be converted into a string.
-/
inductive Poly
| const : β β Poly
| var : β β Poly
| hyp : Term β Poly
| add : Poly β Poly β Poly
| sub : Poly β Poly β Poly
| mul : Poly β Poly β Poly
| div : Poly β Poly β Poly
| pow : Poly β Poly β Poly
| neg : Poly β Poly
deriving BEq, Repr
/--
This converts a poly object into a string representing it. The string
maintains the semantic structure of the poly object.
The output of this function must be valid Python syntax, and it assumes the variables `varN` from
`scripts/polyrith.py.`
-/
def Poly.format : Poly β Lean.Format
| .const z => toString z
| .var n => s!"var{n}"
| .hyp e => s!"hyp{e}" -- this one can't be used by python
| .add p q => s!"({p.format} + {q.format})"
| .sub p q => s!"({p.format} - {q.format})"
| .mul p q => s!"({p.format} * {q.format})"
| .div p q => s!"({p.format} / {q.format})" -- this one can't be used by python
| .pow p q => s!"({p.format} ^ {q.format})"
| .neg p => s!"-{p.format}"
instance : Lean.ToFormat Poly := β¨Poly.formatβ©
instance : ToString Poly := β¨(toString Β·.format)β©
instance : Repr Poly := β¨fun p _ => p.formatβ©
instance : Inhabited Poly := β¨Poly.const 0β©
instance : Quote β€ where quote
| .ofNat n => quote n
| .negSucc n => Unhygienic.run `(-$(quote n))
instance : Quote β where
quote q :=
if q.den = 1 then quote q.num
else Unhygienic.run `($(quote q.num) / $(quote q.den))
variable (vars : Array Syntax.Term) in
/-- Converts a `Poly` expression into a `Syntax` suitable as an input to `linear_combination`. -/
def Poly.toSyntax : Poly β Unhygienic Syntax.Term
| .const z => pure (quote z)
| .var n => pure vars[n]!
| .hyp stx => pure stx
| .add p q => do `($(β p.toSyntax) + $(β q.toSyntax))
| .sub p q => do `($(β p.toSyntax) - $(β q.toSyntax))
| .mul p q => do `($(β p.toSyntax) * $(β q.toSyntax))
| .div p q => do `($(β p.toSyntax) / $(β q.toSyntax))
| .pow p q => do `($(β p.toSyntax) ^ $(β q.toSyntax))
| .neg p => do `(-$(β p.toSyntax))
/-- Reifies a ring expression of type `Ξ±` as a `Poly`. -/
partial def parse {u : Level} {Ξ± : Q(Type u)} (sΞ± : Q(CommSemiring $Ξ±))
(c : Ring.Cache sΞ±) (e : Q($Ξ±)) : AtomM Poly := do
let els := do
try pure <| Poly.const (β (β NormNum.derive e).toRat)
catch _ => pure <| Poly.var (β addAtom e)
let .const n _ := (β withReducible <| whnf e).getAppFn | els
match n, c.rΞ± with
| ``HAdd.hAdd, _ | ``Add.add, _ => match e with
| ~q($a + $b) => pure <| (β parse sΞ± c a).add (β parse sΞ± c b)
| _ => els
| ``HMul.hMul, _ | ``Mul.mul, _ => match e with
| ~q($a * $b) => pure <| (β parse sΞ± c a).mul (β parse sΞ± c b)
| _ => els
| ``HSMul.hSMul, _ => match e with
| ~q(($a : β) β’ ($b : Β«$Ξ±Β»)) => pure <| (β parse sβ .nat a).mul (β parse sΞ± c b)
| _ => els
| ``HPow.hPow, _ | ``Pow.pow, _ => match e with
| ~q($a ^ $b) =>
try pure <| (β parse sΞ± c a).pow (.const (β (β NormNum.derive (u := .zero) b).toRat))
catch _ => els
| _ => els
| ``Neg.neg, some _ => match e with
| ~q(-$a) => pure <| (β parse sΞ± c a).neg
| ``HSub.hSub, some _ | ``Sub.sub, some _ => match e with
| ~q($a - $b) => pure <| (β parse sΞ± c a).sub (β parse sΞ± c b)
| _ => els
| _, _ => els
/-- The possible hypothesis sources for a polyrith proof. -/
inductive Source where
/-- `input n` refers to the `n`'th input `ai` in `polyrith [a1, ..., an]`. -/
| input : Nat β Source
/-- `fvar h` refers to hypothesis `h` from the local context. -/
| fvar : FVarId β Source
/-- The first half of `polyrith` produces a list of arguments to be sent to Sage. -/
def parseContext (only : Bool) (hyps : Array Expr) (tgt : Expr) :
AtomM (Expr Γ Array (Source Γ Poly) Γ Poly) := do
let fail {Ξ±} : AtomM Ξ± := throwError "polyrith failed: target is not an equality in semirings"
let some (Ξ±, eβ, eβ) := (β whnfR <|β instantiateMVars tgt).eq? | fail
let .sort u β instantiateMVars (β whnf (β inferType Ξ±)) | unreachable!
let some v := u.dec | throwError "not a type{indentExpr Ξ±}"
have Ξ± : Q(Type v) := Ξ±
have eβ : Q($Ξ±) := eβ; have eβ : Q($Ξ±) := eβ
let sΞ± β synthInstanceQ (q(CommSemiring $Ξ±) : Q(Type v))
let c β mkCache sΞ±
let tgt := (β parse sΞ± c eβ).sub (β parse sΞ± c eβ)
let rec
/-- Parses a hypothesis and adds it to the `out` list. -/
processHyp src ty out := do
if let some (Ξ², eβ, eβ) := (β instantiateMVars ty).eq? then
if β withTransparency (β read).red <| isDefEq Ξ± Ξ² then
return out.push (src, (β parse sΞ± c eβ).sub (β parse sΞ± c eβ))
pure out
let mut out := #[]
if !only then
for ldecl in β getLCtx do
out β processHyp (.fvar ldecl.fvarId) ldecl.type out
for hyp in hyps, i in [:hyps.size] do
out β processHyp (.input i) (β inferType hyp) out
pure (Ξ±, out, tgt)
/-- Constructs the list of arguments to pass to the external sage script `polyrith_sage.py`. -/
def createSageArgs (trace : Bool) (Ξ± : Expr) (atoms : Nat)
(hyps : Array (Source Γ Poly)) (tgt : Poly) : Array String :=
let hyps := hyps.map (toString Β·.2) |>.toList.toString
#[toString trace, toString Ξ±, toString atoms, hyps, toString tgt]
/-- A JSON parser for `β` specific to the return value of `polyrith_sage.py`. -/
local instance : FromJson β where fromJson?
| .arr #[a, b] => return (β fromJson? a : β€) / (β fromJson? b : β)
| _ => .error "expected array with two elements"
/-- Removes an initial `-` sign from a polynomial with negative leading coefficient. -/
def Poly.unNeg? : Poly β Option Poly
| .mul a b => return .mul (β a.unNeg?) b
| .const i => if i < 0 then some (.const (-i)) else none
| .neg p => p
| _ => none
/-- Adds two polynomials, performing some simple simplifications for presentation like
`a + -b = a - b`. -/
def Poly.add' : Poly β Poly β Poly
| .const 0, p => match p.unNeg? with
| some np => .neg np
| none => p
| p, .const 0 => p
| a, b => match b.unNeg? with
| some nb => a.sub nb
| none => a.add b
/-- Multiplies two polynomials, performing some simple simplifications for presentation like
`1 * a = a`. -/
def Poly.mul' : Poly β Poly β Poly
| .const 0, _ => .const 0
| .const 1, p
| p, .const 1 => p
| a, b => a.mul b
/-- Extracts the divisor `c : β` from a polynomial of the form `1/c * b`. -/
def Poly.unDiv? : Poly β Option (Poly Γ β)
| .mul a b => do let (a, r) β a.unDiv?; return (.mul' a b, r)
| .const r => if r.num = 1 β§ r.den β 1 then some (.const r.num, r.den) else none
| .neg p => do let (p, r) β p.unDiv?; return (.neg p, r)
| _ => none
/-- Constructs a power expression `v_i ^ j`, performing some simplifications in trivial cases. -/
def Poly.pow' : β β β β Poly
| _, 0 => .const 1
| i, 1 => .var i
| i, k => .pow (.var i) (.const k)
/-- Constructs a sum from a monadic function supplying the monomials. -/
def Poly.sumM {m : Type β Type*} {Ξ± : Type*} [Monad m] (a : Array Ξ±) (f : Ξ± β m Poly) : m Poly :=
a.foldlM (init := .const 0) fun p a => return p.add' (β f a)
instance : FromJson Poly where
fromJson? j := do
Poly.sumM (β j.getArr?) fun j => do
let mut mon := .const (β fromJson? (β j.getArrVal? 1))
for j in β (β j.getArrVal? 0).getArr? do
mon := mon.mul' (.pow' (β fromJson? (β j.getArrVal? 0)) (β fromJson? (β j.getArrVal? 1)))
pure mon
/-- A schema for the data reported by the Sage calculation -/
structure SageCoeffAndPower where
/-- The function call produces an array of polynomials
parallel to the input list of hypotheses. -/
coeffs : Array Poly
/-- Sage produces an exponent (default 1) in the case where the hypothesess
sum to a power of the goal. -/
power : β
deriving FromJson, Repr
/-- The result of a sage call in the success case. -/
structure SageSuccess where
/-- The script returns a string containing python script to be sent to the remote server,
when the tracing option is set. -/
trace : Option String := none
/-- The main result of the function call is an array of polynomials
parallel to the input list of hypotheses and an exponent for the goal. -/
data : Option SageCoeffAndPower := none
deriving FromJson, Repr
/-- The result of a sage call in the failure case. -/
structure SageError where
/-- The error kind -/
name : String
/-- The error message -/
value : String
deriving FromJson
/-- The result of a sage call. -/
def SageResult := Except SageError SageSuccess
instance : FromJson SageResult where fromJson? j := do
if let .ok true := fromJson? <| j.getObjValD "success" then
return .ok (β fromJson? j)
else
return .error (β fromJson? j)
/--
This tactic calls python from the command line with the args in `arg_list`.
The output printed to the console is parsed as a `Json`.
It assumes that `python3` is available on the path.
-/
def sageOutput (args : Array String) : IO SageResult := do
let path := (β getMathlibDir) / "scripts" / "polyrith_sage.py"
unless β path.pathExists do
throw <| IO.userError "could not find python script scripts/polyrith_sage.py"
let out β IO.Process.output { cmd := "python3", args := #[path.toString] ++ args }
if out.exitCode != 0 then
throw <| IO.userError <|
s!"scripts/polyrith_sage.py exited with code {out.exitCode}:\n\n{out.stderr}"
match Json.parse out.stdout >>= fromJson? with
| .ok v => return v
| .error e => throw <| .userError e
/--
This is the main body of the `polyrith` tactic. It takes in the following inputs:
* `only : Bool` - This represents whether the user used the key word "only"
* `hyps : Array Expr` - the hypotheses/proof terms selected by the user
* `traceOnly : Bool` - If enabled, the returned syntax will be `.missing`
First, the tactic converts the target into a `Poly`, and finds out what type it
is an equality of. (It also fills up a list of `Expr`s with its atoms). Then, it
collects all the relevant hypotheses/proof terms from the context, and from those
selected by the user, taking into account whether `only` is true. (The list of atoms is
updated accordingly as well).
This information is used to create a list of args that get used in a call to
the appropriate python file that executes a grobner basis computation. The
output of this computation is a `String` representing the certificate. This
string is parsed into a list of `Poly` objects that are then converted into
`Expr`s (using the updated list of atoms).
the names of the hypotheses, along with the corresponding coefficients are
given to `linear_combination`. If that tactic succeeds, the user is prompted
to replace the call to `polyrith` with the appropriate call to
`linear_combination`.
Returns `.error g` if this was a "dry run" attempt that does not actually invoke sage.
-/
def polyrith (g : MVarId) (only : Bool) (hyps : Array Expr)
(traceOnly := false) : MetaM (Except MVarId (TSyntax `tactic)) := do
IO.sleep 10 -- otherwise can lead to weird errors when actively editing code with polyrith calls
g.withContext <| AtomM.run .reducible do
let (Ξ±, hyps', tgt) β parseContext only hyps (β g.getType)
let rec
/-- Try to prove the goal by `ring` and fail with the given message otherwise. -/
byRing msg := do
let stx β `(tactic| ring)
try
let ([], _) β Elab.runTactic g stx | failure
return .ok stx
catch _ => throwError "{msg} and the goal is not provable by ring"
if hyps'.isEmpty then
return β byRing "polyrith did not find any relevant hypotheses"
let vars := (β get).atoms.size
match β sageOutput (createSageArgs traceOnly Ξ± vars hyps' tgt) with
| .ok { trace, data } =>
if let some trace := trace then logInfo trace
if let some {coeffs := polys, power := pow} := data then
let vars β liftM <| (β get).atoms.mapM delab
let p β Poly.sumM (polys.zip hyps') fun (p, src, _) => do
let h := .hyp (β delab (match src with | .input i => hyps[i]! | .fvar h => .fvar h))
pure <| match p.unDiv? with
| some (p, den) => (p.mul' h).div (.const den)
| none => p.mul' h
let stx := (withRef (β getRef) <| p.toSyntax vars).run
let tac β
if let .const 0 := p then `(tactic| linear_combination)
else if pow = 1 then `(tactic| linear_combination $stx:term)
else `(tactic| linear_combination (exp := $(quote pow)) $stx:term)
try
guard (β Elab.runTactic g tac).1.isEmpty
catch _ => throwError
"polyrith found the following certificate, but it failed to close the goal:\n{stx}"
pure <| .ok tac
else if traceOnly then
return .error g
else throwError "internal error: no output available"
| .error { name, value } =>
throwError "polyrith failed to retrieve a solution from Sage! {name}: {value}"
/--
Attempts to prove polynomial equality goals through polynomial arithmetic
on the hypotheses (and additional proof terms if the user specifies them).
It proves the goal by generating an appropriate call to the tactic
`linear_combination`. If this call succeeds, the call to `linear_combination`
is suggested to the user.
* `polyrith` will use all relevant hypotheses in the local context.
* `polyrith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context.
* `polyrith only [h1, h2, h3, t1, t2, t3]` will use only local hypotheses
`h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context.
Notes:
* This tactic only works with a working internet connection, since it calls Sage
using the SageCell web API at <https://sagecell.sagemath.org/>.
Many thanks to the Sage team and organization for allowing this use.
* This tactic assumes that the user has `python3` installed and available on the path.
(Test by opening a terminal and executing `python3 --version`.)
It also assumes that the `requests` library is installed: `python3 -m pip install requests`.
Examples:
```lean
example (x y : β) (h1 : x*y + 2*x = 1) (h2 : x = y) :
x*y = -2*y + 1 := by
polyrith
-- Try this: linear_combination h1 - 2 * h2
example (x y z w : β) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by
polyrith
-- Try this: linear_combination (2 * y + x) * hzw
constant scary : β a b : β, a + b = 0
example (a b c d : β) (h : a + b = 0) (h2: b + c = 0) : a + b + c + d = 0 := by
polyrith only [scary c d, h]
-- Try this: linear_combination scary c d + h
```
-/
syntax "polyrith" (&" only")? (" [" term,* "]")? : tactic
open Elab Tactic
elab_rules : tactic
| `(tactic| polyrith%$tk $[only%$onlyTk]? $[[$hyps,*]]?) => do
let hyps β hyps.map (Β·.getElems) |>.getD #[] |>.mapM (elabTerm Β· none)
let traceMe β Lean.isTracingEnabledFor `Meta.Tactic.polyrith
match β polyrith (β getMainGoal) onlyTk.isSome hyps traceMe with
| .ok stx =>
replaceMainGoal []
if !traceMe then Lean.Meta.Tactic.TryThis.addSuggestion tk stx
| .error g => replaceMainGoal [g]
end Polyrith
end Tactic
end Mathlib
|
Tactic\Positivity.lean | import Mathlib.Tactic.Positivity.Basic
import Mathlib.Tactic.NormNum.Basic
import Mathlib.Init.Data.Int.Order
|
Tactic\PPWithUniv.lean | /-
Copyright (c) 2023 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean
/-!
# Attribute to pretty-print universe level parameters by default
This module contains the `pp_with_univ` attribute, which enables pretty-printing
of universe parameters for the associated declaration. This is helpful for definitions like
`Ordinal`, where the universe levels are both relevant and not deducible from the arguments.
-/
namespace Mathlib.PPWithUniv
open Lean Parser PrettyPrinter Delaborator SubExpr Elab Command
/--
Delaborator that prints the current application with universe parameters on the head symbol,
unless `pp.universes` is explicitly set to `false`.
-/
def delabWithUniv : Delab :=
whenPPOption (Β·.get pp.universes.name true) <|
let enablePPUnivOnHead subExpr :=
let expr := subExpr.expr
let expr := mkAppN (expr.getAppFn.setOption pp.universes.name true) expr.getAppArgs
{ subExpr with expr }
withTheReader SubExpr enablePPUnivOnHead delabApp
/--
`attribute [pp_with_univ] Ordinal` instructs the pretty-printer to
print `Ordinal.{u}` with universe parameters by default
(unless `pp.universes` is explicitly set to `false`).
-/
syntax (name := ppWithUnivAttr) "pp_with_univ" : attr
initialize registerBuiltinAttribute {
name := `ppWithUnivAttr
descr := ""
applicationTime := .afterCompilation
add := fun src ref kind => match ref with
| `(attr| pp_with_univ) => do
liftCommandElabM <| withRef ref do
let attr β Elab.elabAttr <| β `(Term.attrInstance| delab $(mkIdent <| `app ++ src))
liftTermElabM <| Term.applyAttributes ``delabWithUniv #[{attr with kind}]
| _ => throwUnsupportedSyntax }
|
Tactic\ProdAssoc.lean | /-
Copyright (c) 2023 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import Mathlib.Lean.Expr.Basic
import Mathlib.Logic.Equiv.Defs
/-!
# Associativity of products
This file constructs a term elaborator for "obvious" equivalences between iterated products.
For example,
```lean
(prod_assoc% : (Ξ± Γ Ξ²) Γ (Ξ³ Γ Ξ΄) β Ξ± Γ (Ξ² Γ Ξ³) Γ Ξ΄)
```
gives the "obvious" equivalence between `(Ξ± Γ Ξ²) Γ (Ξ³ Γ Ξ΄)` and `Ξ± Γ (Ξ² Γ Ξ³) Γ Ξ΄`.
-/
namespace Lean.Expr
open Lean Meta
/-- A helper type to keep track of universe levels and types in iterated produts. -/
inductive ProdTree where
| type (tp : Expr) (l : Level)
| prod (fst snd : ProdTree) (lfst lsnd : Level)
deriving Repr
/-- The iterated product corresponding to a `ProdTree`. -/
def ProdTree.getType : ProdTree β Expr
| type tp _ => tp
| prod fst snd u v => mkAppN (.const ``Prod [u,v]) #[fst.getType, snd.getType]
/-- The number of types appearing in an iterated product encoded as a `ProdTree`. -/
def ProdTree.size : ProdTree β Nat
| type _ _ => 1
| prod fst snd _ _ => fst.size + snd.size
/-- The components of an interated product, presented as a `ProdTree`. -/
def ProdTree.components : ProdTree β List Expr
| type tp _ => [tp]
| prod fst snd _ _ => fst.components ++ snd.components
/-- Make a `ProdTree` out of an `Expr`. -/
partial def mkProdTree (e : Expr) : MetaM ProdTree :=
match e.consumeMData with
| .app (.app (.const ``Prod [u,v]) X) Y => do
return .prod (β X.mkProdTree) (β Y.mkProdTree) u v
| X => do
let some u := (β whnfD <| β inferType X).type? | throwError "Not a type{indentExpr X}"
return .type X u
/-- Given `P : ProdTree` representing an iterated product and `e : Expr` which
should correspond to a term of the iterated product, this will return
a list, whose items correspond to the leaves of `P` (i.e. the types appearing in the product),
where each item is the appropriate composition of `Prod.fst` and `Prod.snd` applied to `e`
resulting in an element of the type corresponding to the leaf.
For example, if `P` corresponds to `(X Γ Y) Γ Z` and `t : (X Γ Y) Γ Z`, then this
should return `[t.fst.fst, t.fst.snd, t.snd]`.
-/
def ProdTree.unpack (t : Expr) : ProdTree β MetaM (List Expr)
| type _ _ => return [t]
| prod fst snd u v => do
let fst' β fst.unpack <| mkAppN (.const ``Prod.fst [u,v]) #[fst.getType, snd.getType, t]
let snd' β snd.unpack <| mkAppN (.const ``Prod.snd [u,v]) #[fst.getType, snd.getType, t]
return fst' ++ snd'
/-- This function should act as the "reverse" of `ProdTree.unpack`, constructing
a term of the iterated product out of a list of terms of the types appearing in the product. -/
def ProdTree.pack (ts : List Expr) : ProdTree β MetaM Expr
| type _ _ => do
match ts with
| [] => throwError "Can't pack the empty list."
| [a] => return a
| _ => throwError "Failed due to size mismatch."
| prod fst snd u v => do
let fstSize := fst.size
let sndSize := snd.size
unless ts.length == fstSize + sndSize do throwError "Failed due to size mismatch."
let tsfst := ts.toArray[:fstSize] |>.toArray.toList
let tssnd := ts.toArray[fstSize:] |>.toArray.toList
let mk : Expr := mkAppN (.const ``Prod.mk [u,v]) #[fst.getType, snd.getType]
return .app (.app mk (β fst.pack tsfst)) (β snd.pack tssnd)
/-- Converts a term `e` in an iterated product `P1` into a term of an iterated product `P2`.
Here `e` is an `Expr` representing the term, and the iterated products are represented
by terms of `ProdTree`. -/
def ProdTree.convertTo (P1 P2 : ProdTree) (e : Expr) : MetaM Expr :=
return β P2.pack <| β P1.unpack e
/-- Given two expressions corresponding to iterated products of the same types, associated in
possibly different ways, this constructs the "obvious" function from one to the other. -/
def mkProdFun (a b : Expr) : MetaM Expr := do
let pa β a.mkProdTree
let pb β b.mkProdTree
unless pa.components.length == pb.components.length do
throwError "The number of components in{indentD a}\nand{indentD b}\nmust match."
for (x,y) in pa.components.zip pb.components do
unless β isDefEq x y do
throwError "Component{indentD x}\nis not definitionally equal to component{indentD y}."
withLocalDeclD `t a fun fvar => do
mkLambdaFVars #[fvar] (β pa.convertTo pb fvar)
/-- Construct the equivalence between iterated products of the same type, associated
in possibly different ways. -/
def mkProdEquiv (a b : Expr) : MetaM Expr := do
let some u := (β whnfD <| β inferType a).type? | throwError "Not a type{indentExpr a}"
let some v := (β whnfD <| β inferType b).type? | throwError "Not a type{indentExpr b}"
return mkAppN (.const ``Equiv.mk [.succ u,.succ v])
#[a, b, β mkProdFun a b, β mkProdFun b a,
.app (.const ``rfl [.succ u]) a,
.app (.const ``rfl [.succ v]) b]
/-- IMPLEMENTATION: Syntax used in the implementation of `prod_assoc%`.
This elaborator postpones if there are metavariables in the expected type,
and to propagate the fact that this elaborator produces an `Equiv`,
the `prod_assoc%` macro sets things up with a type ascription.
This enables using `prod_assoc%` with, for example `Equiv.trans` dot notation. -/
syntax (name := prodAssocStx) "prod_assoc_internal%" : term
open Elab Term in
/-- Elaborator for `prod_assoc%`. -/
@[term_elab prodAssocStx]
def elabProdAssoc : TermElab := fun stx expectedType? => do
match stx with
| `(prod_assoc_internal%) => do
let some expectedType β tryPostponeIfHasMVars? expectedType?
| throwError "expected type must be known"
let .app (.app (.const ``Equiv _) a) b := expectedType
| throwError "Expected type{indentD expectedType}\nis not of the form `Ξ± β Ξ²`."
mkProdEquiv a b
| _ => throwUnsupportedSyntax
/--
`prod_assoc%` elaborates to the "obvious" equivalence between iterated products of types,
regardless of how the products are parenthesized.
The `prod_assoc%` term uses the expected type when elaborating.
For example, `(prod_assoc% : (Ξ± Γ Ξ²) Γ (Ξ³ Γ Ξ΄) β Ξ± Γ (Ξ² Γ Ξ³) Γ Ξ΄)`.
The elaborator can handle holes in the expected type,
so long as they eventually get filled by unification.
```lean
example : (Ξ± Γ Ξ²) Γ (Ξ³ Γ Ξ΄) β Ξ± Γ (Ξ² Γ Ξ³) Γ Ξ΄ :=
(prod_assoc% : _ β Ξ± Γ Ξ² Γ Ξ³ Γ Ξ΄).trans prod_assoc%
```
-/
macro "prod_assoc%" : term => `((prod_assoc_internal% : _ β _))
end Lean.Expr
|
Tactic\ProjectionNotation.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Lean
/-!
# Pretty printing projection notation
**Deprecated** as of 2024-05-02 with Lean v4.8.0 since dot notation is now default with
the introduction of `pp.fieldNotation.generalized`, which handles dot notation pervasively
and correctly.
This module contains the `@[pp_dot]` attribute, which is used to configure functions to pretty print
using projection notation (i.e., like `x.f y` rather than `C.f x y`).
Core's projection delaborator collapses chains of ancestor projections.
For example, to turn `x.toFoo.toBar` into `x.toBar`.
The `pp_dot` attribute works together with this delaborator to completely collapse such chains.
-/
namespace Mathlib.ProjectionNotation
open Lean Parser Elab Term
open PrettyPrinter.Delaborator SubExpr
open Lean.Elab.Command
/-- Given a function `f` that is either a true projection or a generalized projection
(i.e., a function that works using extended field notation, a.k.a. "dot notation"), generates
an `app_unexpander` for it to get it to pretty print using dot notation.
See also the docstring of the `pp_dot` attribute. -/
def mkExtendedFieldNotationUnexpander (f : Name) : CommandElabM Unit := do
let .str A projName := f | throwError "Projection name must end in a string component."
if let some _ := getStructureInfo? (β getEnv) A then
-- If this is for a structure, then generate an extra `.toA` remover.
-- It's easier to handle the two cases completely separately than to try to merge them.
let .str _ A' := A | throwError "{A} must end in a string component"
let toA : Name := .str .anonymous ("to" ++ A')
elabCommand <| β `(command|
@[app_unexpander $(mkIdent f)]
aux_def $(mkIdent <| Name.str f "unexpander") : Lean.PrettyPrinter.Unexpander := fun
-- Having a zero-argument pattern prevents unnecessary parenthesization in output
| `($$_ $$(x).$(mkIdent toA))
| `($$_ $$x) => set_option hygiene false in `($$(x).$(mkIdent (.mkSimple projName)))
| _ => throw ())
else
elabCommand <| β `(command|
@[app_unexpander $(mkIdent f)]
aux_def $(mkIdent <| Name.str f "unexpander") : Lean.PrettyPrinter.Unexpander := fun
-- Having this zero-argument pattern prevents unnecessary parenthesization in output
| `($$_ $$x) => set_option hygiene false in `($$(x).$(mkIdent (.mkSimple projName)))
| _ => throw ())
/--
Adding the `@[pp_dot]` attribute defines an `app_unexpander` for the given function to
support pretty printing the function using extended field notation ("dot notation").
This particular attribute is *only* for functions whose first explicit argument is the
receiver of the generalized field notation. That is to say, it is only meant for
transforming `C.f c x y z ...` to `c.f x y z ...` for `c : C`.
It can be used to help get projection notation to work for function-valued structure fields,
since the built-in projection delaborator cannot handle excess arguments.
Example for generalized field notation:
```
structure A where
n : Nat
@[pp_dot]
def A.foo (a : A) (m : Nat) : Nat := a.n + m
```
Now, `A.foo x m` pretty prints as `x.foo m`. If `A` is a structure, it also adds a rule that
`A.foo x.toA m` pretty prints as `x.foo m`. This rule is meant to combine with core's
the projection collapse delaborator, where together `A.foo x.toB.toA m`
will pretty print as `x.foo m`.
Since the mentioned rule is a purely syntactic transformation,
it might lead to output that does not round trip, though this can only occur if
there exists an `A`-valued `toA` function that is not a parent projection that
happens to be pretty printable using dot notation.
Here is an example to illustrate the round tripping issue:
```lean
import Mathlib.Tactic.ProjectionNotation
structure A where n : Int
@[pp_dot]
def A.inc (a : A) (k : Int) : Int := a.n + k
structure B where n : Nat
def B.toA (b : B) : A := β¨b.nβ©
variable (b : B)
#check A.inc b.toA 1
-- (B.toA b).inc 1 : Int
attribute [pp_dot] B.toA
#check A.inc b.toA 1
-- b.inc 1 : Int
#check b.inc 1
-- invalid field 'inc', the environment does not contain 'B.inc'
```
To avoid this, don't use `pp_dot` for coercion functions
such as `B.toA`.
-/
syntax (name := ppDotAttr) "pp_dot" : attr
initialize registerBuiltinAttribute {
name := `ppDotAttr
descr := ""
applicationTime := .afterCompilation
add := fun src ref kind => match ref with
| `(attr| pp_dot) => do
logWarning "\
The @[pp_dot] attribute is deprecated now that dot notation is the default \
with the introduction of `pp.fieldNotation.generalized` in Lean v4.8.0."
if (kind != AttributeKind.global) then
throwError "`pp_dot` can only be used as a global attribute"
liftCommandElabM <| withRef ref <| mkExtendedFieldNotationUnexpander src
| _ => throwUnsupportedSyntax }
end Mathlib.ProjectionNotation
|
Tactic\Propose.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Lean.Meta.Tactic.TryThis
import Lean.Meta.Tactic.SolveByElim
import Mathlib.Lean.Expr.Basic
import Mathlib.Lean.Meta
import Mathlib.Lean.Meta.Basic
import Batteries.Util.Cache
import Mathlib.Tactic.Core
/-!
# Propose
This file defines a tactic `have? using a, b, c`
that tries to find a lemma which makes use of each of the local hypotheses `a, b, c`.
The variant `have? : t using a, b, c` restricts to lemmas with type `t` (which may contain `_`).
Note that in either variant `have?` does not look at the current goal at all.
It is a relative of `apply?` but for *forward reasoning* (i.e. looking at the hypotheses)
rather than backward reasoning.
```
import Batteries.Data.List.Basic
import Mathlib.Tactic.Propose
example (K L M : List Ξ±) (w : L.Disjoint M) (m : K β L) : True := by
have? using w, m -- Try this: `List.disjoint_of_subset_left m w`
trivial
```
-/
namespace Mathlib.Tactic.Propose
open Lean Meta Batteries.Tactic Tactic.TryThis
initialize registerTraceClass `Tactic.propose
/-- Configuration for `DiscrTree`. -/
def discrTreeConfig : WhnfCoreConfig := {}
initialize proposeLemmas : DeclCache (DiscrTree Name) β
DeclCache.mk "have?: init cache" failure {} fun name constInfo lemmas => do
if constInfo.isUnsafe then return lemmas
if β name.isBlackListed then return lemmas
withNewMCtxDepth do withReducible do
let (mvars, _, _) β forallMetaTelescope constInfo.type
let mut lemmas := lemmas
for m in mvars do
lemmas β lemmas.insertIfSpecific (β inferType m) name discrTreeConfig
pure lemmas
open Lean.Meta.SolveByElim in
/-- Shortcut for calling `solveByElim`. -/
def solveByElim (orig : MVarId) (goals : Array MVarId) (use : Array Expr) (required : Array Expr)
(depth) := do
let cfg : SolveByElimConfig :=
{ maxDepth := depth, exfalso := true, symm := true, intro := false }
let cfg := if !required.isEmpty then
cfg.testSolutions (fun _ => do
let r β instantiateMVars (.mvar orig)
pure <| required.all fun e => e.occurs r)
else
cfg
let cfg := cfg.synthInstance
_ β SolveByElim.solveByElim
cfg (use.toList.map pure) (fun _ => return (β getLocalHyps).toList) goals.toList
/--
Attempts to find lemmas which use all of the `required` expressions as arguments, and
can be unified with the given `type` (which may contain metavariables, which we avoid assigning).
We look up candidate lemmas from a discrimination tree using the first such expression.
Returns an array of pairs, containing the names of found lemmas and the resulting application.
-/
def propose (lemmas : DiscrTree Name) (type : Expr) (required : Array Expr)
(solveByElimDepth := 15) : MetaM (Array (Name Γ Expr)) := do
guard !required.isEmpty
let ty β whnfR (β instantiateMVars (β inferType required[0]!))
let candidates β lemmas.getMatch ty discrTreeConfig
candidates.filterMapM fun lem : Name =>
try
trace[Tactic.propose] "considering {lem}"
let Expr.mvar g β mkFreshExprMVar type | failure
let e β mkConstWithFreshMVarLevels lem
let (args, _, _) β forallMetaTelescope (β inferType e)
let .true β preservingMCtx <| withAssignableSyntheticOpaque <|
isDefEq type (β inferType (mkAppN e args)) | failure
g.assign (mkAppN e args)
let use := required.filterMap fun e => match e with | .fvar _ => none | _ => some e
solveByElim g (args.map fun a => a.mvarId!) use required solveByElimDepth
trace[Tactic.propose] "successfully filled in arguments for {lem}"
pure <| some (lem, β instantiateMVars (.mvar g))
catch _ => pure none
open Lean.Parser.Tactic
/--
* `have? using a, b, c` tries to find a lemma
which makes use of each of the local hypotheses `a, b, c`,
and reports any results via trace messages.
* `have? : h using a, b, c` only returns lemmas whose type matches `h` (which may contain `_`).
* `have?! using a, b, c` will also call `have` to add results to the local goal state.
Note that `have?` (unlike `apply?`) does not inspect the goal at all,
only the types of the lemmas in the `using` clause.
`have?` should not be left in proofs; it is a search tool, like `apply?`.
Suggestions are printed as `have := f a b c`.
-/
syntax (name := propose') "have?" "!"? (ident)? (" : " term)? " using " (colGt term),+ : tactic
open Elab.Tactic Elab Tactic in
elab_rules : tactic
| `(tactic| have?%$tk $[!%$lucky]? $[$h:ident]? $[ : $type:term]? using $[$terms:term],*) => do
let stx β getRef
let goal β getMainGoal
goal.withContext do
let required β terms.mapM (elabTerm Β· none)
let type β match type with
| some stx => elabTermWithHoles stx none (β getMainTag) true <&> (Β·.1)
| none => mkFreshTypeMVar
let proposals β propose (β proposeLemmas.get) type required
if proposals.isEmpty then
throwError "propose could not find any lemmas using the given hypotheses"
-- TODO we should have `proposals` return a lazy list, to avoid unnecessary computation here.
for p in proposals.toList.take 10 do
addHaveSuggestion tk (h.map (Β·.getId)) (β inferType p.2) p.2 stx
if lucky.isSome then
let mut g := goal
for p in proposals.toList.take 10 do
(_, g) β g.let p.1 p.2
replaceMainGoal [g]
@[inherit_doc propose'] syntax "have?!" (" : " term)? " using " (colGt term),+ : tactic
@[inherit_doc propose'] syntax "have!?" (" : " term)? " using " (colGt term),+ : tactic
macro_rules
| `(tactic| have?!%$tk $[: $type]? using $terms,*) =>
`(tactic| have?%$tk ! $[: $type]? using $terms,*)
| `(tactic| have!?%$tk $[: $type]? using $terms,*) =>
`(tactic| have?%$tk ! $[: $type]? using $terms,*)
|
Tactic\ProxyType.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Lean
import Mathlib.Tactic.Core
import Mathlib.Logic.Equiv.Defs
/-!
# Generating "proxy types"
This module gives tools to create an equivalence between a given inductive type and a
"proxy type" constructed from `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`.
It works for any non-recursive inductive type without indices.
The intended use case is for pulling typeclass instances across this equivalence. This
reduces the problem of generating typeclass instances to that of writing typeclass instances for
the above five types (and whichever additional types appear in the inductive type).
The main interface is the `proxy_equiv%` elaborator, where `proxy_equiv% t` gives an equivalence
between the proxy type for `t` and `t`. See the documentation for `proxy_equiv%` for an example.
For debugging information, do `set_option Elab.ProxyType true`.
It is possible to reconfigure the machinery to generate other types. See `ensureProxyEquiv`
and look at how it is used in `proxy_equiv%`.
## Implementation notes
For inductive types with `n` constructors, the `proxy_equiv%` elaborator creates a proxy
type of the form `Cβ β (Cβ β (β― β Cβ))`. The equivalence then needs to handle `n - 1` levels
of `Sum` constructors, which is a source of quadratic complexity.
An alternative design could be to generate a `C : Fin n β Type*` function for the proxy types
for each constructor and then use `(i : Fin n) Γ ULift (C i)` for the total proxy type. However,
typeclass inference is not good at finding instances for such a type even if there are instances
for each `C i`. One seems to need to add, for example, an explicit `[β i, Fintype (C i)]`
instance given `β i, Fintype (C i)`.
-/
namespace Mathlib.ProxyType
open Lean Elab Lean.Parser.Term
open Meta Command
initialize registerTraceClass `Elab.ProxyType
/-- Configuration used by `mkProxyEquiv`. -/
structure ProxyEquivConfig where
/-- Name to use for the declaration for a type that is `Equiv` to the given type. -/
proxyName : Name
/-- Name to use for the declaration for the equivalence `proxyType β type`. -/
proxyEquivName : Name
/-- Returns a proxy type for a constructor and a pattern to use to match against it,
given a list of fvars for the constructor arguments and pattern names to use for the arguments.
The proxy type is expected to be a `Type*`. -/
mkCtorProxyType : List (Expr Γ Name) β TermElabM (Expr Γ Term)
/-- Given (constructor name, proxy constructor type, proxy constructor pattern) triples
constructed using `mkCtorProxyType`, return (1) the total proxy type (a `Type*`),
(2) patterns to use for each constructor, and (3) a proof to use to prove `left_inv` for
`proxy_type β type` (this proof starts with `intro x`). -/
mkProxyType : Array (Name Γ Expr Γ Term) β TermElabM (Expr Γ Array Term Γ TSyntax `tactic)
/-- Returns a proxy type for a constructor and a pattern to use to match against it.
Input: a list of pairs associated to each argument of the constructor consisting
of (1) an fvar for this argument and (2) a name to use for this argument in patterns.
For example, given `#[(a, x), (b, y)]` with `x : Nat` and `y : Fin x`, then this function
returns `Sigma (fun x => Fin x)` and `β¨a, bβ©`.
Always returns a `Type*`. Uses `Unit`, `PLift`, and `Sigma`. Avoids using `PSigma` since
the `Fintype` instances for it go through `Sigma`s anyway.
The `decorateSigma` function is to wrap the `Sigma` a decorator such as `Lex`.
It should yield a definitionally equal type. -/
def defaultMkCtorProxyType (xs : List (Expr Γ Name))
(decorateSigma : Expr β TermElabM Expr := pure) :
TermElabM (Expr Γ Term) :=
match xs with
| [] => return (mkConst ``Unit, β `(term| ()))
| [(x, a)] => do
let xty β inferType x
if β Meta.isProp xty then
return (β mkAppM ``PLift #[xty], β `(term| β¨$(mkIdent a)β©))
else
return (xty, mkIdent a)
| (x, a) :: xs => do
let (xsty, patt) β defaultMkCtorProxyType xs
let xty β inferType x
if β Meta.isProp xty then
withLocalDeclD `x' (β mkAppM ``PLift #[xty]) fun x' => do
let xsty' := xsty.replaceFVar x (β mkAppM ``PLift.down #[x'])
let ty β decorateSigma (β mkAppM ``Sigma #[β mkLambdaFVars #[x'] xsty'])
return (ty, β `(term| β¨β¨$(mkIdent a)β©, $pattβ©))
else
let ty β decorateSigma (β mkAppM ``Sigma #[β mkLambdaFVars #[x] xsty])
return (ty, β `(term| β¨$(mkIdent a), $pattβ©))
/-- Create a `Sum` of types, mildly optimized to not have a trailing `Empty`.
The `decorateSum` function is to wrap the `Sum` with a function such as `Lex`.
It should yield a definitionally equal type. -/
def defaultMkProxyType (ctors : Array (Name Γ Expr Γ Term))
(decorateSum : Expr β TermElabM Expr := pure) :
TermElabM (Expr Γ Array Term Γ TSyntax `tactic) := do
let mut types := #[]
let mut patts := #[]
for i in [0:ctors.size] do
let (_ctorName, ty, patt) := ctors[i]!
types := types.push ty
patts := patts.push <| β wrapSumAccess i ctors.size patt
let (type, pf) β mkCType types.toList
return (type, patts, pf)
where
/-- Construct the `Sum` expression, using `decorateSum` to adjust each `Sum`. -/
mkCType (ctypes : List Expr) : TermElabM (Expr Γ TSyntax `tactic) :=
match ctypes with
| [] => return (mkConst ``Empty, β `(tactic| cases x))
| [x] => return (x, β `(tactic| rfl))
| x :: xs => do
let (ty, pf) β mkCType xs
let pf β `(tactic| cases x with | inl _ => rfl | inr x => $pf:tactic)
return (β decorateSum (β mkAppM ``Sum #[x, ty]), pf)
/-- Navigates into the sum type that we create in `mkCType` for the given constructor index. -/
wrapSumAccess (cidx nctors : Nat) (spatt : Term) : TermElabM Term :=
match cidx with
| 0 =>
if nctors = 1 then
return spatt
else
`(term| Sum.inl $spatt)
| cidx' + 1 => do
let spatt β wrapSumAccess cidx' (nctors - 1) spatt
`(term| Sum.inr $spatt)
/-- Default configuration. Defines `proxyType` and `proxyTypeEquiv` in the namespace
of the inductive type. Uses `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. -/
def ProxyEquivConfig.default (indVal : InductiveVal) : ProxyEquivConfig where
proxyName := indVal.name.mkStr "proxyType"
proxyEquivName := indVal.name.mkStr "proxyTypeEquiv"
mkCtorProxyType := defaultMkCtorProxyType
mkProxyType := defaultMkProxyType
/--
Generates a proxy type for the inductive type and an equivalence from the proxy type to the type.
If the declarations already exist, there is a check that they are correct.
-/
def ensureProxyEquiv (config : ProxyEquivConfig) (indVal : InductiveVal) : TermElabM Unit := do
if indVal.isRec then
throwError
"proxy equivalence: recursive inductive types are not supported (and are usually infinite)"
if 0 < indVal.numIndices then
throwError "proxy equivalence: inductive indices are not supported"
let levels := indVal.levelParams.map Level.param
forallBoundedTelescope indVal.type indVal.numParams fun params _sort => do
let mut cdata := #[]
for ctorName in indVal.ctors do
let ctorInfo β getConstInfoCtor ctorName
let ctorType β inferType <| mkAppN (mkConst ctorName levels) params
cdata := cdata.push <| β
forallBoundedTelescope ctorType ctorInfo.numFields fun xs _itype => do
let names β xs.mapM (fun _ => mkFreshUserName `a)
let (ty, ppatt) β config.mkCtorProxyType (xs.zip names).toList
let places := mkArray ctorInfo.numParams (β `(term| _))
let argNames := names.map mkIdent
let cpatt β `(term| @$(mkIdent ctorName) $places* $argNames*)
return (ctorName, ty, ppatt, cpatt)
let (ctype, ppatts, pf) β config.mkProxyType <|
cdata.map (fun (ctorName, ty, ppatt, _) => (ctorName, ty, ppatt))
let mut toFunAlts := #[]
let mut invFunAlts := #[]
for ppatt in ppatts, (_, _, _, cpatt) in cdata do
toFunAlts := toFunAlts.push <| β `(matchAltExpr| | $ppatt => $cpatt)
invFunAlts := invFunAlts.push <| β `(matchAltExpr| | $cpatt => $ppatt)
-- Create the proxy type definition
trace[Elab.ProxyType] "proxy type: {ctype}"
let ctype' β mkLambdaFVars params ctype
if let some const := (β getEnv).find? config.proxyName then
unless β isDefEq const.value! ctype' do
throwError "Declaration {config.proxyName} already exists and it is not the proxy type."
trace[Elab.ProxyType] "proxy type already exists"
else
addAndCompile <| Declaration.defnDecl
{ name := config.proxyName
levelParams := indVal.levelParams
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
type := β inferType ctype'
value := ctype' }
-- Set to be reducible so that typeclass inference can see it's a Fintype
setReducibleAttribute config.proxyName
setProtected config.proxyName
-- Add a docstring
addDocString config.proxyName s!"A \"proxy type\" equivalent to `{indVal.name}` that is \
constructed from `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. \
See `{config.proxyEquivName}` for the equivalence. \
(Generated by the `proxy_equiv%` elaborator.)"
trace[Elab.ProxyType] "defined {config.proxyName}"
-- Create the `Equiv`
let equivType β mkAppM ``Equiv #[ctype, mkAppN (mkConst indVal.name levels) params]
if let some const := (β getEnv).find? config.proxyEquivName then
unless β isDefEq const.type (β mkForallFVars params equivType) do
throwError "Declaration {config.proxyEquivName} already exists and has the wrong type."
trace[Elab.ProxyType] "proxy equivalence already exists"
else
trace[Elab.ProxyType] "constructing proxy equivalence"
let mut toFun β `(term| fun $toFunAlts:matchAlt*)
let mut invFun β `(term| fun $invFunAlts:matchAlt*)
if indVal.numCtors == 0 then
-- Empty matches don't elaborate, so use `nomatch` here.
toFun β `(term| fun x => nomatch x)
invFun β `(term| fun x => nomatch x)
let equivBody β `(term| { toFun := $toFun,
invFun := $invFun,
right_inv := by intro x; cases x <;> rfl
left_inv := by intro x; $pf:tactic })
let equiv β Term.elabTerm equivBody equivType
Term.synthesizeSyntheticMVarsNoPostponing
trace[Elab.ProxyType] "elaborated equivalence{indentExpr equiv}"
let equiv' β mkLambdaFVars params (β instantiateMVars equiv)
addAndCompile <| Declaration.defnDecl
{ name := config.proxyEquivName
levelParams := indVal.levelParams
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
type := β inferType equiv'
value := equiv' }
setProtected config.proxyEquivName
addDocString config.proxyEquivName s!"An equivalence between the \"proxy type\" \
`{config.proxyName}` and `{indVal.name}`. The proxy type is a reducible definition \
that represents the inductive type using `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum` \
(and whatever other inductive types appear within the inductive type), and the \
intended use is to define typeclass instances uses pre-existing instances on these. \
(Generated by the `proxy_equiv%` elaborator.)"
trace[Elab.ProxyType] "defined {config.proxyEquivName}"
/-- Helper function for `proxy_equiv% type : expectedType` elaborators.
Elaborate `type` and get its `InductiveVal`. Uses the `expectedType`, where the
expected type should be of the form `_ β type`. -/
def elabProxyEquiv (type : Term) (expectedType? : Option Expr) :
TermElabM (Expr Γ InductiveVal) := do
let type β Term.elabType type
if let some expectedType := expectedType? then
let equivType β Term.elabType (β `(_ β $(β Term.exprToSyntax type)))
unless β isDefEq expectedType equivType do
throwError
"Could not unify expected type{indentExpr expectedType}\nwith{indentExpr equivType}"
let type β Term.tryPostponeIfHasMVars type "In proxy_equiv% elaborator"
let type β whnf type
let .const declName _ := type.getAppFn
| throwError "{type} is not a constant or constant application"
return (type, β getConstInfoInduct declName)
/--
The term elaborator `proxy_equiv% Ξ±` for a type `Ξ±` elaborates to an equivalence `Ξ² β Ξ±`
for a "proxy type" `Ξ²` composed out of basic type constructors `Unit`, `PLift`, `Sigma`,
`Empty`, and `Sum`.
This only works for inductive types `Ξ±` that are neither recursive nor have indices.
If `Ξ±` is an inductive type with name `I`, then as a side effect this elaborator defines
`I.proxyType` and `I.proxyTypeEquiv`.
The elaborator makes use of the expected type, so `(proxy_equiv% _ : _ β Ξ±)` works.
For example, given this inductive type
```
inductive foo (n : Nat) (Ξ± : Type)
| a
| b : Bool β foo n Ξ±
| c (x : Fin n) : Fin x β foo n Ξ±
| d : Bool β Ξ± β foo n Ξ±
```
the proxy type it generates is `Unit β Bool β (x : Fin n) Γ Fin x β (_ : Bool) Γ Ξ±` and
in particular we have that
```
proxy_equiv% (foo n Ξ±) : Unit β Bool β (x : Fin n) Γ Fin x β (_ : Bool) Γ Ξ± β foo n Ξ±
```
-/
syntax (name := proxy_equiv) "proxy_equiv% " term : term
/-- Elaborator for `proxy_equiv%`. -/
@[term_elab proxy_equiv]
def elab_proxy_equiv : Elab.Term.TermElab := fun stx expectedType? =>
match stx with
| `(proxy_equiv% $t) => do
let (type, indVal) β elabProxyEquiv t expectedType?
let config : ProxyEquivConfig := ProxyEquivConfig.default indVal
ensureProxyEquiv config indVal
mkAppOptM config.proxyEquivName (type.getAppArgs.map .some)
| _ => throwUnsupportedSyntax
end Mathlib.ProxyType
|
Tactic\PushNeg.lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Simon Hudon, Alice Laroche, FrΓ©dΓ©ric Dupuis, Jireh Loreaux
-/
import Lean.Elab.Tactic.Location
import Mathlib.Logic.Basic
import Mathlib.Order.Defs
import Mathlib.Tactic.Conv
import Mathlib.Init.Set
import Lean.Elab.Tactic.Location
/-!
# The `push_neg` tactic
The `push_neg` tactic pushes negations inside expressions: it can be applied to goals as well
as local hypotheses and also works as a `conv` tactic.
-/
namespace Mathlib.Tactic.PushNeg
open Lean Meta Elab.Tactic Parser.Tactic
variable (p q : Prop) {Ξ± : Sort*} {Ξ² : Type*} (s : Ξ± β Prop)
theorem not_not_eq : (Β¬ Β¬ p) = p := propext not_not
theorem not_and_eq : (Β¬ (p β§ q)) = (p β Β¬ q) := propext not_and
theorem not_and_or_eq : (Β¬ (p β§ q)) = (Β¬ p β¨ Β¬ q) := propext not_and_or
theorem not_or_eq : (Β¬ (p β¨ q)) = (Β¬ p β§ Β¬ q) := propext not_or
theorem not_forall_eq : (Β¬ β x, s x) = (β x, Β¬ s x) := propext not_forall
theorem not_exists_eq : (Β¬ β x, s x) = (β x, Β¬ s x) := propext not_exists
theorem not_implies_eq : (Β¬ (p β q)) = (p β§ Β¬ q) := propext Classical.not_imp
theorem not_ne_eq (x y : Ξ±) : (Β¬ (x β y)) = (x = y) := ne_eq x y βΈ not_not_eq _
theorem not_iff : (Β¬ (p β q)) = ((p β§ Β¬ q) β¨ (Β¬ p β§ q)) := propext <|
_root_.not_iff.trans <| iff_iff_and_or_not_and_not.trans <| by rw [not_not, or_comm]
section LinearOrder
variable [LinearOrder Ξ²]
theorem not_le_eq (a b : Ξ²) : (Β¬ (a β€ b)) = (b < a) := propext not_le
theorem not_lt_eq (a b : Ξ²) : (Β¬ (a < b)) = (b β€ a) := propext not_lt
theorem not_ge_eq (a b : Ξ²) : (Β¬ (a β₯ b)) = (a < b) := propext not_le
theorem not_gt_eq (a b : Ξ²) : (Β¬ (a > b)) = (a β€ b) := propext not_lt
end LinearOrder
theorem not_nonempty_eq (s : Set Ξ²) : (Β¬ s.Nonempty) = (s = β
) := by
have A : β (x : Ξ²), Β¬(x β (β
: Set Ξ²)) := fun x β¦ id
simp only [Set.Nonempty, not_exists, eq_iff_iff]
exact β¨fun h β¦ Set.ext (fun x β¦ by simp only [h x, false_iff, A]), fun h β¦ by rwa [h]β©
theorem ne_empty_eq_nonempty (s : Set Ξ²) : (s β β
) = s.Nonempty := by
rw [ne_eq, β not_nonempty_eq s, not_not]
theorem empty_ne_eq_nonempty (s : Set Ξ²) : (β
β s) = s.Nonempty := by
rw [ne_comm, ne_empty_eq_nonempty]
/-- Make `push_neg` use `not_and_or` rather than the default `not_and`. -/
register_option push_neg.use_distrib : Bool :=
{ defValue := false
group := ""
descr := "Make `push_neg` use `not_and_or` rather than the default `not_and`." }
/-- Push negations at the top level of the current expression. -/
def transformNegationStep (e : Expr) : SimpM (Option Simp.Step) := do
-- Wrapper around `Simp.Step.visit`
let mkSimpStep (e : Expr) (pf : Expr) : Simp.Step :=
Simp.Step.visit { expr := e, proof? := some pf }
-- Try applying the inequality lemma and verify that we do get a defeq type.
-- Sometimes there might be the wrong LinearOrder available!
let handleIneq (eβ eβ : Expr) (notThm : Name) : SimpM (Option Simp.Step) := do
try
-- Allowed to fail if it can't synthesize an instance:
let thm β mkAppM notThm #[eβ, eβ]
let some (_, lhs, rhs) := (β inferType thm).eq? | failure -- this should never fail
-- Make sure the inferred instances are right:
guard <| β isDefEq e lhs
return some <| mkSimpStep rhs thm
catch _ => return none
let e_whnf β whnfR e
let some ex := e_whnf.not? | return Simp.Step.continue
let ex := (β instantiateMVars ex).cleanupAnnotations
match ex.getAppFnArgs with
| (``Not, #[e]) =>
return mkSimpStep e (β mkAppM ``not_not_eq #[e])
| (``And, #[p, q]) =>
match β getBoolOption `push_neg.use_distrib with
| false => return mkSimpStep (.forallE `_ p (mkNot q) default) (β mkAppM ``not_and_eq #[p, q])
| true => return mkSimpStep (mkOr (mkNot p) (mkNot q)) (β mkAppM ``not_and_or_eq #[p, q])
| (``Or, #[p, q]) =>
return mkSimpStep (mkAnd (mkNot p) (mkNot q)) (β mkAppM ``not_or_eq #[p, q])
| (``Iff, #[p, q]) =>
return mkSimpStep (mkOr (mkAnd p (mkNot q)) (mkAnd (mkNot p) q)) (β mkAppM ``not_iff #[p, q])
| (``Eq, #[ty, eβ, eβ]) =>
if ty.isAppOfArity ``Set 1 then
-- test if equality is of the form `s = β
`, and negate it to `s.Nonempty`
if eβ.isAppOfArity ``EmptyCollection.emptyCollection 2 then
let thm β mkAppM ``ne_empty_eq_nonempty #[eβ]
let some (_, _, rhs) := (β inferType thm).eq? | return none
return mkSimpStep rhs thm
-- test if equality is of the form `β
= s`, and negate it to `s.Nonempty`
if eβ.isAppOfArity ``EmptyCollection.emptyCollection 2 then
let thm β mkAppM ``empty_ne_eq_nonempty #[eβ]
let some (_, _, rhs) := (β inferType thm).eq? | return none
return mkSimpStep rhs thm
-- negate `a = b` to `a β b`
return Simp.Step.visit { expr := β mkAppM ``Ne #[eβ, eβ] }
| (``Ne, #[_ty, eβ, eβ]) =>
return mkSimpStep (β mkAppM ``Eq #[eβ, eβ]) (β mkAppM ``not_ne_eq #[eβ, eβ])
| (``LE.le, #[_ty, _inst, eβ, eβ]) => handleIneq eβ eβ ``not_le_eq
| (``LT.lt, #[_ty, _inst, eβ, eβ]) => handleIneq eβ eβ ``not_lt_eq
| (``GE.ge, #[_ty, _inst, eβ, eβ]) => handleIneq eβ eβ ``not_ge_eq
| (``GT.gt, #[_ty, _inst, eβ, eβ]) => handleIneq eβ eβ ``not_gt_eq
| (``Set.Nonempty, #[_ty, e]) =>
-- negate `s.Nonempty` to `s = β
`
let thm β mkAppM ``not_nonempty_eq #[e]
let some (_, _, rhs) := (β inferType thm).eq? | return none
return mkSimpStep rhs thm
| (``Exists, #[_, .lam n typ bo bi]) =>
return mkSimpStep (.forallE n typ (mkNot bo) bi)
(β mkAppM ``not_exists_eq #[.lam n typ bo bi])
| (``Exists, #[_, _]) =>
return none
| _ => match ex with
| .forallE name ty body binfo => do
if (β isProp ty) && !body.hasLooseBVars then
return mkSimpStep (β mkAppM ``And #[ty, mkNot body])
(β mkAppM ``not_implies_eq #[ty, body])
else
let body' : Expr := .lam name ty (mkNot body) binfo
let body'' : Expr := .lam name ty body binfo
return mkSimpStep (β mkAppM ``Exists #[body']) (β mkAppM ``not_forall_eq #[body''])
| _ => return none
/-- Recursively push negations at the top level of the current expression. This is needed
to handle e.g. triple negation. -/
partial def transformNegation (e : Expr) : SimpM Simp.Step := do
let Simp.Step.visit rβ β transformNegationStep e | return Simp.Step.continue
match rβ.proof? with
| none => return Simp.Step.continue rβ
| some _ => do
let Simp.Step.visit rβ β transformNegation rβ.expr | return Simp.Step.visit rβ
return Simp.Step.visit (β rβ.mkEqTrans rβ)
/-- Common entry point to `push_neg` as a conv. -/
def pushNegCore (tgt : Expr) : MetaM Simp.Result := do
let myctx : Simp.Context :=
{ config := { eta := true, zeta := false, proj := false },
simpTheorems := #[ ]
congrTheorems := (β getSimpCongrTheorems) }
(Β·.1) <$> Simp.main tgt myctx (methods := { pre := transformNegation })
/--
Push negations into the conclusion of an expression.
For instance, an expression `Β¬ β x, β y, x β€ y` will be transformed by `push_neg` into
`β x, β y, y < x`. Variable names are conserved.
This tactic pushes negations inside expressions. For instance, given a hypothesis
```lean
| Β¬ β Ξ΅ > 0, β Ξ΄ > 0, β x, |x - xβ| β€ Ξ΄ β |f x - yβ| β€ Ξ΅)
```
writing `push_neg` will turn the target into
```lean
| β Ξ΅, Ξ΅ > 0 β§ β Ξ΄, Ξ΄ > 0 β (β x, |x - xβ| β€ Ξ΄ β§ Ξ΅ < |f x - yβ|),
```
(The pretty printer does *not* use the abbreviations `β Ξ΄ > 0` and `β Ξ΅ > 0` but this issue
has nothing to do with `push_neg`).
Note that names are conserved by this tactic, contrary to what would happen with `simp`
using the relevant lemmas.
This tactic has two modes: in standard mode, it transforms `Β¬(p β§ q)` into `p β Β¬q`, whereas in
distrib mode it produces `Β¬p β¨ Β¬q`. To use distrib mode, use `set_option push_neg.use_distrib true`.
-/
syntax (name := pushNegConv) "push_neg" : conv
/-- Execute `push_neg` as a conv tactic. -/
@[tactic pushNegConv] def elabPushNegConv : Tactic := fun _ β¦ withMainContext do
Conv.applySimpResult (β pushNegCore (β instantiateMVars (β Conv.getLhs)))
/--
The syntax is `#push_neg e`, where `e` is an expression,
which will print the `push_neg` form of `e`.
`#push_neg` understands local variables, so you can use them to introduce parameters.
-/
macro (name := pushNeg) tk:"#push_neg " e:term : command => `(command| #conv%$tk push_neg => $e)
/-- Execute main loop of `push_neg` at the main goal. -/
def pushNegTarget : TacticM Unit := withMainContext do
let goal β getMainGoal
let tgt β instantiateMVars (β goal.getType)
let newGoal β applySimpResultToTarget goal tgt (β pushNegCore tgt)
if newGoal == goal then throwError "push_neg made no progress"
replaceMainGoal [newGoal]
/-- Execute main loop of `push_neg` at a local hypothesis. -/
def pushNegLocalDecl (fvarId : FVarId) : TacticM Unit := withMainContext do
let ldecl β fvarId.getDecl
if ldecl.isAuxDecl then return
let tgt β instantiateMVars ldecl.type
let goal β getMainGoal
let myres β pushNegCore tgt
let some (_, newGoal) β applySimpResultToLocalDecl goal fvarId myres False | failure
if newGoal == goal then throwError "push_neg made no progress"
replaceMainGoal [newGoal]
/--
Push negations into the conclusion of a hypothesis.
For instance, a hypothesis `h : Β¬ β x, β y, x β€ y` will be transformed by `push_neg at h` into
`h : β x, β y, y < x`. Variable names are conserved.
This tactic pushes negations inside expressions. For instance, given a hypothesis
```lean
h : Β¬ β Ξ΅ > 0, β Ξ΄ > 0, β x, |x - xβ| β€ Ξ΄ β |f x - yβ| β€ Ξ΅)
```
writing `push_neg at h` will turn `h` into
```lean
h : β Ξ΅, Ξ΅ > 0 β§ β Ξ΄, Ξ΄ > 0 β (β x, |x - xβ| β€ Ξ΄ β§ Ξ΅ < |f x - yβ|),
```
(The pretty printer does *not* use the abbreviations `β Ξ΄ > 0` and `β Ξ΅ > 0` but this issue
has nothing to do with `push_neg`).
Note that names are conserved by this tactic, contrary to what would happen with `simp`
using the relevant lemmas. One can also use this tactic at the goal using `push_neg`,
at every hypothesis and the goal using `push_neg at *` or at selected hypotheses and the goal
using say `push_neg at h h' β’` as usual.
This tactic has two modes: in standard mode, it transforms `Β¬(p β§ q)` into `p β Β¬q`, whereas in
distrib mode it produces `Β¬p β¨ Β¬q`. To use distrib mode, use `set_option push_neg.use_distrib true`.
-/
elab "push_neg" loc:(location)? : tactic =>
let loc := (loc.map expandLocation).getD (.targets #[] true)
withLocation loc
pushNegLocalDecl
pushNegTarget
(fun _ β¦ logInfo "push_neg couldn't find a negation to push")
|
Tactic\Qify.lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll, Mario Carneiro, Robert Y. Lewis
-/
import Mathlib.Algebra.Order.Ring.Cast
import Mathlib.Algebra.Order.Ring.Rat
import Mathlib.Data.Int.Cast.Lemmas
import Mathlib.Tactic.Basic
import Mathlib.Tactic.Zify
/-!
# `qify` tactic
The `qify` tactic is used to shift propositions from `β` or `β€` to `β`.
This is often useful since `β` has well-behaved division.
```
example (a b c x y z : β) (h : Β¬ x*y*z < 0) : c < a + 3*b := by
qify
qify at h
/-
h : Β¬βx * βy * βz < 0
β’ βc < βa + 3 * βb
-/
sorry
```
-/
namespace Mathlib.Tactic.Qify
open Lean
open Lean.Meta
open Lean.Parser.Tactic
open Lean.Elab.Tactic
/--
The `qify` tactic is used to shift propositions from `β` or `β€` to `β`.
This is often useful since `β` has well-behaved division.
```
example (a b c x y z : β) (h : Β¬ x*y*z < 0) : c < a + 3*b := by
qify
qify at h
/-
h : Β¬βx * βy * βz < 0
β’ βc < βa + 3 * βb
-/
sorry
```
`qify` can be given extra lemmas to use in simplification. This is especially useful in the
presence of nat subtraction: passing `β€` arguments will allow `push_cast` to do more work.
```
example (a b c : β€) (h : a / b = c) (hab : b β£ a) (hb : b β 0) : a = c * b := by
qify [hab] at h hb β’
exact (div_eq_iff hb).1 h
```
`qify` makes use of the `@[zify_simps]` and `@[qify_simps]` attributes to move propositions,
and the `push_cast` tactic to simplify the `β`-valued expressions. -/
syntax (name := qify) "qify" (simpArgs)? (location)? : tactic
macro_rules
| `(tactic| qify $[[$simpArgs,*]]? $[at $location]?) =>
let args := simpArgs.map (Β·.getElems) |>.getD #[]
`(tactic|
simp (config := {decide := false}) only [zify_simps, qify_simps, push_cast, $args,*]
$[at $location]?)
@[qify_simps] lemma intCast_eq (a b : β€) : a = b β (a : β) = (b : β) := by simp only [Int.cast_inj]
@[qify_simps] lemma intCast_le (a b : β€) : a β€ b β (a : β) β€ (b : β) := Int.cast_le.symm
@[qify_simps] lemma intCast_lt (a b : β€) : a < b β (a : β) < (b : β) := Int.cast_lt.symm
@[qify_simps] lemma intCast_ne (a b : β€) : a β b β (a : β) β (b : β) := by
simp only [ne_eq, Int.cast_inj]
@[deprecated (since := "2024-04-17")]
alias int_cast_ne := intCast_ne
end Qify
end Tactic
end Mathlib
|
Tactic\Recall.lean | /-
Copyright (c) 2023 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone, Kyle Miller
-/
import Lean.Elab.Command
import Lean.Elab.DeclUtil
/-!
# `recall` command
-/
namespace Mathlib.Tactic.Recall
/--
The `recall` command redeclares a previous definition for illustrative purposes.
This can be useful for files that give an expository account of some theory in Lean.
The syntax of the command mirrors `def`, so all the usual bells and whistles work.
```
recall List.cons_append (a : Ξ±) (as bs : List Ξ±) : (a :: as) ++ bs = a :: (as ++ bs) := rfl
```
Also, one can leave out the body.
```
recall Nat.add_comm (n m : Nat) : n + m = m + n
```
The command verifies that the new definition type-checks and that the type and value
provided are definitionally equal to the original declaration. However, this does not
capture some details (like binders), so the following works without error.
```
recall Nat.add_comm {n m : Nat} : n + m = m + n
```
-/
syntax (name := recall) "recall " ident ppIndent(optDeclSig) (declVal)? : command
open Lean Meta Elab Command Term
elab_rules : command
| `(recall $id $sig:optDeclSig $[$val?]?) => withoutModifyingEnv do
let declName := id.getId
let some info := (β getEnv).find? declName
| throwError "unknown constant '{declName}'"
let declConst : Expr := mkConst declName <| info.levelParams.map Level.param
discard <| liftTermElabM <| addTermInfo id declConst
let newId := mkIdentFrom id (β mkAuxName declName 1)
if let some val := val? then
let some infoVal := info.value?
| throwErrorAt val "constant '{declName}' has no defined value"
elabCommand <| β `(noncomputable def $newId $sig:optDeclSig $val)
let some newInfo := (β getEnv).find? newId.getId | return -- def already threw
liftTermElabM do
let mvs β newInfo.levelParams.mapM fun _ => mkFreshLevelMVar
let newType := newInfo.type.instantiateLevelParams newInfo.levelParams mvs
unless (β isDefEq info.type newType) do
throwTypeMismatchError none info.type newInfo.type declConst
let newVal := newInfo.value?.get!.instantiateLevelParams newInfo.levelParams mvs
unless (β isDefEq infoVal newVal) do
let err := m!"\
value mismatch{indentExpr declConst}\nhas value{indentExpr newVal}\n\
but is expected to have value{indentExpr infoVal}"
throwErrorAt val err
else
let (binders, type?) := expandOptDeclSig sig
if let some type := type? then
runTermElabM fun vars => do
withAutoBoundImplicit do
elabBinders binders.getArgs fun xs => do
let xs β addAutoBoundImplicits xs
let type β elabType type
Term.synthesizeSyntheticMVarsNoPostponing
let type β mkForallFVars xs type
let type β mkForallFVars vars type (usedOnly := true)
unless (β isDefEq info.type type) do
throwTypeMismatchError none info.type type declConst
else
unless binders.getNumArgs == 0 do
throwError "expected type after ':'"
|
Tactic\Recover.lean | /-
Copyright (c) 2022 Siddhartha Gadgil. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Siddhartha Gadgil, Jannis Limperg
-/
import Lean
/-!
# The `recover` tactic modifier
This defines the `recover` tactic modifier, which can be used to debug cases where goals
are not closed correctly. `recover tacs` for a tactic (or tactic sequence) `tacs`
applies the tactics and then adds goals
that are not closed, starting from the original goal.
-/
namespace Mathlib.Tactic
open Lean (HashSet)
open Lean Meta Elab Tactic
/--
Get all metavariables which `mvarId` depends on. These are the metavariables
which occur in the target or local context or delayed assignment (if any) of
`mvarId`, plus the metavariables which occur in these metavariables, etc.
-/
partial def getUnassignedGoalMVarDependencies (mvarId : MVarId) :
MetaM (HashSet MVarId) :=
return (β go mvarId |>.run {}).snd
where
/-- auxiliary function for `getUnassignedGoalMVarDependencies` -/
addMVars (e : Expr) : StateRefT (HashSet MVarId) MetaM Unit := do
let mvars β getMVars e
let mut s β get
set ({} : HashSet MVarId) -- Ensure that `s` is not shared.
for mvarId in mvars do
unless β mvarId.isDelayedAssigned do
s := s.insert mvarId
set s
mvars.forM go
/-- auxiliary function for `getUnassignedGoalMVarDependencies` -/
go (mvarId : MVarId) : StateRefT (HashSet MVarId) MetaM Unit :=
withIncRecDepth do
let mdecl β mvarId.getDecl
addMVars mdecl.type
for ldecl in mdecl.lctx do
addMVars ldecl.type
if let (some val) := ldecl.value? then
addMVars val
if let (some ass) β getDelayedMVarAssignment? mvarId then
let pendingMVarId := ass.mvarIdPending
unless β pendingMVarId.isAssigned <||> pendingMVarId.isDelayedAssigned do
modify (Β·.insert pendingMVarId)
go pendingMVarId
/-- Modifier `recover` for a tactic (sequence) to debug cases where goals are closed incorrectly.
The tactic `recover tacs` for a tactic (sequence) `tacs` applies the tactics and then adds goals
that are not closed, starting from the original goal. -/
elab "recover " tacs:tacticSeq : tactic => do
let originalGoals β getGoals
evalTactic tacs
let mut unassigned : HashSet MVarId := {}
for mvarId in originalGoals do
unless β mvarId.isAssigned <||> mvarId.isDelayedAssigned do
unassigned := unassigned.insert mvarId
let unassignedMVarDependencies β getUnassignedGoalMVarDependencies mvarId
unassigned := unassigned.insertMany unassignedMVarDependencies.toList
setGoals <| ((β getGoals) ++ unassigned.toList).eraseDups
|
Tactic\ReduceModChar.lean | /-
Copyright (c) 2023 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import Mathlib.Data.ZMod.Basic
import Mathlib.RingTheory.Polynomial.Basic
import Mathlib.Tactic.NormNum.DivMod
import Mathlib.Tactic.ReduceModChar.Ext
/-!
# `reduce_mod_char` tactic
Define the `reduce_mod_char` tactic, which traverses expressions looking for numerals `n`,
such that the type of `n` is a ring of (positive) characteristic `p`, and reduces these
numerals modulo `p`, to lie between `0` and `p`.
## Implementation
The main entry point is `ReduceModChar.derive`, which uses `simp` to traverse expressions and
calls `matchAndNorm` on each subexpression.
The type of each subexpression is matched syntactically to determine if it is a ring with positive
characteristic in `typeToCharP`. Using syntactic matching should be faster than trying to infer
a `CharP` instance on each subexpression.
The actual reduction happens in `normIntNumeral`. This is written to be compatible with `norm_num`
so it can serve as a drop-in replacement for some `norm_num`-based routines (specifically, the
intended use is as an option for the `ring` tactic).
In addition to the main functionality, we call `normNeg` and `normNegCoeffMul` to replace negation
with multiplication by `p - 1`, and simp lemmas tagged `@[reduce_mod_char]` to clean up the
resulting expression: e.g. `1 * X + 0` becomes `X`.
-/
open Lean Meta Simp
open Lean.Elab
open Tactic
open Qq
namespace Tactic
namespace ReduceModChar
open Mathlib.Meta.NormNum
variable {u : Level}
lemma CharP.intCast_eq_mod (R : Type _) [Ring R] (p : β) [CharP R p] (k : β€) :
(k : R) = (k % p : β€) := by
calc
(k : R) = β(k % p + p * (k / p)) := by rw [Int.emod_add_ediv]
_ = β(k % p) := by simp [CharP.cast_eq_zero R]
lemma CharP.isInt_of_mod {e' r : β€} {Ξ± : Type _} [Ring Ξ±] {n n' : β} (inst : CharP Ξ± n) {e : Ξ±}
(he : IsInt e e') (hn : IsNat n n') (hβ : IsInt (e' % n') r) : IsInt e r :=
β¨by rw [he.out, CharP.intCast_eq_mod Ξ± n, show n = n' from hn.out, hβ.out, Int.cast_id]β©
/-- Given an integral expression `e : t` such that `t` is a ring of characteristic `n`,
reduce `e` modulo `n`. -/
partial def normIntNumeral {Ξ± : Q(Type u)} (n : Q(β)) (e : Q($Ξ±)) (instRing : Q(Ring $Ξ±))
(instCharP : Q(CharP $Ξ± $n)) : MetaM (Result e) := do
let β¨ze, ne, peβ© β Result.toInt instRing (β Mathlib.Meta.NormNum.derive e)
let β¨n', pnβ© β deriveNat n q(instAddMonoidWithOneNat)
let rr β evalIntMod.go _ _ ze q(IsInt.raw_refl $ne) _ <|
.isNat q(instAddMonoidWithOne) _ q(isNat_natCast _ _ (IsNat.raw_refl $n'))
let β¨zr, nr, prβ© β rr.toInt q(Int.instRing)
return .isInt instRing nr zr q(CharP.isInt_of_mod $instCharP $pe $pn $pr)
lemma CharP.neg_eq_sub_one_mul {Ξ± : Type _} [Ring Ξ±] (n : β) (inst : CharP Ξ± n) (b : Ξ±)
(a : β) (a' : Ξ±) (p : IsNat (n - 1 : Ξ±) a) (pa : a = a') :
-b = a' * b := by
rw [β pa, β p.out, β neg_one_mul]
simp
/-- Given an expression `(-e) : t` such that `t` is a ring of characteristic `n`,
simplify this to `(n - 1) * e`.
This should be called only when `normIntNumeral` fails, because `normIntNumeral` would otherwise
be more useful by evaluating `-e` mod `n` to an actual numeral.
-/
@[nolint unusedHavesSuffices] -- the `=Q` is necessary for type checking
partial def normNeg {Ξ± : Q(Type u)} (n : Q(β)) (e : Q($Ξ±)) (_instRing : Q(Ring $Ξ±))
(instCharP : Q(CharP $Ξ± $n)) :
MetaM Simp.Result := do
let .app f (b : Q($Ξ±)) β whnfR e | failure
guard <|β withNewMCtxDepth <| isDefEq f q(Neg.neg (Ξ± := $Ξ±))
let r β (derive (Ξ± := Ξ±) q($n - 1))
match r with
| .isNat sΞ± a p => do
have : instAddMonoidWithOne =Q $sΞ± := β¨β©
let β¨a', pa'β© β mkOfNat Ξ± sΞ± a
let pf : Q(-$b = $a' * $b) := q(CharP.neg_eq_sub_one_mul $n $instCharP $b $a $a' $p $pa')
return { expr := q($a' * $b), proof? := pf }
| .isNegNat _ _ _ =>
throwError "normNeg: nothing useful to do in negative characteristic"
| _ => throwError "normNeg: evaluating `{n} - 1` should give an integer result"
lemma CharP.neg_mul_eq_sub_one_mul {Ξ± : Type _} [Ring Ξ±] (n : β) (inst : CharP Ξ± n) (a b : Ξ±)
(na : β) (na' : Ξ±) (p : IsNat ((n - 1) * a : Ξ±) na) (pa : na = na') :
-(a * b) = na' * b := by
rw [β pa, β p.out, β neg_one_mul]
simp
/-- Given an expression `-(a * b) : t` such that `t` is a ring of characteristic `n`,
and `a` is a numeral, simplify this to `((n - 1) * a) * b`. -/
@[nolint unusedHavesSuffices] -- the `=Q` is necessary for type checking
partial def normNegCoeffMul {Ξ± : Q(Type u)} (n : Q(β)) (e : Q($Ξ±)) (_instRing : Q(Ring $Ξ±))
(instCharP : Q(CharP $Ξ± $n)) :
MetaM Simp.Result := do
let .app neg (.app (.app mul (a : Q($Ξ±))) (b : Q($Ξ±))) β whnfR e | failure
guard <|β withNewMCtxDepth <| isDefEq neg q(Neg.neg (Ξ± := $Ξ±))
guard <|β withNewMCtxDepth <| isDefEq mul q(HMul.hMul (Ξ± := $Ξ±))
let r β (derive (Ξ± := Ξ±) q(($n - 1) * $a))
match r with
| .isNat sΞ± na np => do
have : AddGroupWithOne.toAddMonoidWithOne =Q $sΞ± := β¨β©
let β¨na', npa'β© β mkOfNat Ξ± sΞ± na
let pf : Q(-($a * $b) = $na' * $b) :=
q(CharP.neg_mul_eq_sub_one_mul $n $instCharP $a $b $na $na' $np $npa')
return { expr := q($na' * $b), proof? := pf }
| .isNegNat _ _ _ =>
throwError "normNegCoeffMul: nothing useful to do in negative characteristic"
| _ => throwError "normNegCoeffMul: evaluating `{n} - 1` should give an integer result"
/-- A `TypeToCharPResult Ξ±` indicates if `Ξ±` can be determined to be a ring of characteristic `p`.
-/
inductive TypeToCharPResult (Ξ± : Q(Type u))
| intLike (n : Q(β)) (instRing : Q(Ring $Ξ±)) (instCharP : Q(CharP $Ξ± $n))
| failure
instance {Ξ± : Q(Type u)} : Inhabited (TypeToCharPResult Ξ±) := β¨.failureβ©
/-- Determine the characteristic of a ring from the type.
This should be fast, so this pattern-matches on the type, rather than searching for a
`CharP` instance.
Use `typeToCharP (expensive := true)` to do more work in finding the characteristic,
in particular it will search for a `CharP` instance in the context. -/
partial def typeToCharP (expensive := false) (t : Q(Type u)) : MetaM (TypeToCharPResult t) :=
match Expr.getAppFnArgs t with
| (``ZMod, #[(n : Q(β))]) =>
return .intLike n
(q((ZMod.commRing _).toRing) : Q(Ring (ZMod $n)))
(q(ZMod.charP _) : Q(CharP (ZMod $n) $n))
| (``Polynomial, #[(R : Q(Type u)), _]) => do match β typeToCharP (expensive := expensive) R with
| (.intLike n _ _) =>
return .intLike n
(q(Polynomial.ring) : Q(Ring (Polynomial $R)))
(q(Polynomial.instCharP _) : Q(CharP (Polynomial $R) $n))
| .failure => return .failure
| _ => if ! expensive then return .failure else do
-- Fallback: run an expensive procedures to determine a characteristic,
-- by looking for a `CharP` instance.
withNewMCtxDepth do
/- If we want to support semirings, here we could implement the `natLike` fallback. -/
let .some instRing β trySynthInstanceQ q(Ring $t) | return .failure
let n β mkFreshExprMVarQ q(β)
let .some instCharP β findLocalDeclWithType? q(CharP $t $n) | return .failure
return .intLike (β instantiateMVarsQ n) instRing (.fvar instCharP)
/-- Given an expression `e`, determine whether it is a numeric expression in characteristic `n`,
and if so, reduce `e` modulo `n`.
This is not a `norm_num` plugin because it does not match on the syntax of `e`,
rather it matches on the type of `e`.
Use `matchAndNorm (expensive := true)` to do more work in finding the characteristic of
the type of `e`.
-/
partial def matchAndNorm (expensive := false) (e : Expr) : MetaM Simp.Result := do
let Ξ± β inferType e
let u_succ : Level β getLevel Ξ±
let (.succ u) := u_succ | throwError "expected {Ξ±} to be a `Type _`, not `Sort {u_succ}`"
have Ξ± : Q(Type u) := Ξ±
match β typeToCharP (expensive := expensive) Ξ± with
| (.intLike n instRing instCharP) =>
-- Handle the numeric expressions first, e.g. `-5` (which shouldn't become `-1 * 5`)
normIntNumeral n e instRing instCharP >>= Result.toSimpResult <|>
normNegCoeffMul n e instRing instCharP <|> -- `-(3 * X) β ((n - 1) * 3) * X`
normNeg n e instRing instCharP -- `-X β (n - 1) * X`
/- Here we could add a `natLike` result using only a `Semiring` instance.
This would activate only the less-powerful procedures
that cannot handle subtraction.
-/
| .failure =>
throwError "inferred type `{Ξ±}` does not have a known characteristic"
-- We use a few `simp` lemmas to preprocess the expression and clean up subterms like `0 * X`.
attribute [reduce_mod_char] sub_eq_add_neg
attribute [reduce_mod_char] zero_add add_zero zero_mul mul_zero one_mul mul_one
attribute [reduce_mod_char] eq_self_iff_true -- For closing non-numeric goals, e.g. `X = X`
/-- Reduce all numeric subexpressions of `e` modulo their characteristic.
Use `derive (expensive := true)` to do more work in finding the characteristic of
the type of `e`.
-/
partial def derive (expensive := false) (e : Expr) : MetaM Simp.Result := do
withTraceNode `Tactic.reduce_mod_char (fun _ => return m!"{e}") do
let e β instantiateMVars e
let config : Simp.Config := {
zeta := false
beta := false
eta := false
proj := false
iota := false
}
let congrTheorems β Meta.getSimpCongrTheorems
let ext? β getSimpExtension? `reduce_mod_char
let ext β match ext? with
| some ext => pure ext
| none => throwError "internal error: reduce_mod_char not registered as simp extension"
let ctx : Simp.Context := {
config := config,
congrTheorems := congrTheorems,
simpTheorems := #[β ext.getTheorems]
}
let discharge := Mathlib.Meta.NormNum.discharge ctx
let r : Simp.Result := {expr := e}
let pre := Simp.preDefault #[] >> fun e =>
try return (Simp.Step.done (β matchAndNorm (expensive := expensive) e))
catch _ => pure .continue
let post := Simp.postDefault #[]
let r β r.mkEqTrans (β Simp.main r.expr ctx (methods := { pre, post, discharge? := discharge })).1
return r
/-- Reduce all numeric subexpressions of the goal modulo their characteristic. -/
partial def reduceModCharTarget (expensive := false) : TacticM Unit := do
liftMetaTactic1 fun goal β¦ do
let tgt β instantiateMVars (β goal.getType)
let prf β derive (expensive := expensive) tgt
if prf.expr.consumeMData.isConstOf ``True then
match prf.proof? with
| some proof => goal.assign (β mkOfEqTrue proof)
| none => goal.assign (mkConst ``True.intro)
return none
else
applySimpResultToTarget goal tgt prf
/-- Reduce all numeric subexpressions of the given hypothesis modulo their characteristic. -/
partial def reduceModCharHyp (expensive := false) (fvarId : FVarId) : TacticM Unit :=
liftMetaTactic1 fun goal β¦ do
let hyp β instantiateMVars (β fvarId.getDecl).type
let prf β derive (expensive := expensive) hyp
return (β applySimpResultToLocalDecl goal fvarId prf false).map (Β·.snd)
open Parser.Tactic Elab.Tactic
/--
The tactic `reduce_mod_char` looks for numeric expressions in characteristic `p`
and reduces these to lie between `0` and `p`.
For example:
```
example : (5 : ZMod 4) = 1 := by reduce_mod_char
example : (X ^ 2 - 3 * X + 4 : (ZMod 4)[X]) = X ^ 2 + X := by reduce_mod_char
```
It also handles negation, turning it into multiplication by `p - 1`,
and similarly subtraction.
This tactic uses the type of the subexpression to figure out if it is indeed of positive
characteristic, for improved performance compared to trying to synthesise a `CharP` instance.
The variant `reduce_mod_char!` also tries to use `CharP R n` hypotheses in the context.
(Limitations of the typeclass system mean the tactic can't search for a `CharP R n` instance if
`n` is not yet known; use `have : CharP R n := inferInstance; reduce_mod_char!` as a workaround.)
-/
syntax (name := reduce_mod_char) "reduce_mod_char" (location)? : tactic
@[inherit_doc reduce_mod_char]
syntax (name := reduce_mod_char!) "reduce_mod_char!" (location)? : tactic
elab_rules : tactic
| `(tactic| reduce_mod_char $[$loc]?) => unsafe do
match expandOptLocation (Lean.mkOptionalNode loc) with
| Location.targets hyps target => do
(β getFVarIds hyps).forM reduceModCharHyp
if target then reduceModCharTarget
| Location.wildcard => do
(β (β getMainGoal).getNondepPropHyps).forM reduceModCharHyp
reduceModCharTarget
| `(tactic| reduce_mod_char! $[$loc]?) => unsafe do
match expandOptLocation (Lean.mkOptionalNode loc) with
| Location.targets hyps target => do
(β getFVarIds hyps).forM (reduceModCharHyp (expensive := true))
if target then reduceModCharTarget (expensive := true)
| Location.wildcard => do
(β (β getMainGoal).getNondepPropHyps).forM (reduceModCharHyp (expensive := true))
reduceModCharTarget (expensive := true)
end ReduceModChar
end Tactic
|
Tactic\Rename.lean | /-
Copyright (c) 2021 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean
/-!
# The `rename'` tactic
The `rename'` tactic renames one or several hypotheses.
-/
namespace Mathlib.Tactic
open Lean Elab.Tactic Meta
syntax renameArg := term " => " ident
/-- `rename' h => hnew` renames the hypothesis named `h` to `hnew`.
To rename several hypothesis, use `rename' hβ => hβnew, hβ => hβnew`.
You can use `rename' a => b, b => a` to swap two variables. -/
syntax (name := rename') "rename' " renameArg,+ : tactic
elab_rules : tactic
| `(tactic| rename' $[$as:term => $bs:ident],*) => do
let ids β getFVarIds as
liftMetaTactic1 fun goal β¦ do
let mut lctx β getLCtx
for fvar in ids, tgt in bs do
lctx := lctx.setUserName fvar tgt.getId
let mvarNew β mkFreshExprMVarAt lctx (β getLocalInstances)
(β goal.getType) MetavarKind.syntheticOpaque (β goal.getTag)
goal.assign mvarNew
pure mvarNew.mvarId!
withMainContext do
for fvar in ids, tgt in bs do
Elab.Term.addTermInfo' tgt (mkFVar fvar)
|
Tactic\RenameBVar.lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Patrick Massot
-/
import Lean
import Mathlib.Util.Tactic
import Mathlib.Lean.Expr.Basic
/-!
# The `rename_bvar` tactic
This file defines the `rename_bvar` tactic, for renaming bound variables.
-/
namespace Mathlib.Tactic
open Lean Parser Elab Tactic
/-- Renames a bound variable in a hypothesis. -/
def renameBVarHyp (mvarId : MVarId) (fvarId : FVarId) (old new : Name) :
MetaM Unit :=
modifyLocalDecl mvarId fvarId fun ldecl β¦
ldecl.setType <| ldecl.type.renameBVar old new
/-- Renames a bound variable in the target. -/
def renameBVarTarget (mvarId : MVarId) (old new : Name) : MetaM Unit :=
modifyTarget mvarId fun e β¦ e.renameBVar old new
/--
* `rename_bvar old new` renames all bound variables named `old` to `new` in the target.
* `rename_bvar old new at h` does the same in hypothesis `h`.
```lean
example (P : β β β β Prop) (h : β n, β m, P n m) : β l, β m, P l m := by
rename_bvar n q at h -- h is now β (q : β), β (m : β), P q m,
rename_bvar m n -- target is now β (l : β), β (n : β), P k n,
exact h -- Lean does not care about those bound variable names
```
Note: name clashes are resolved automatically.
-/
elab "rename_bvar " old:ident " β " new:ident loc?:(location)? : tactic => do
let mvarId β getMainGoal
match loc? with
| none => renameBVarTarget mvarId old.getId new.getId
| some loc =>
withLocation (expandLocation loc)
(fun fvarId β¦ renameBVarHyp mvarId fvarId old.getId new.getId)
(renameBVarTarget mvarId old.getId new.getId)
fun _ β¦ throwError "unexpected location syntax"
|
Tactic\Replace.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Mario Carneiro
-/
import Mathlib.Tactic.Have
/-!
# Extending `replace`
This file extends the `replace` tactic from `Batteries` to allow the addition of hypotheses to
the context without requiring their proofs to be provided immediately.
As a style choice, this should not be used in mathlib; but is provided for downstream users who
preferred the old style.
-/
namespace Mathlib.Tactic
open Lean Elab.Tactic
/--
Acts like `have`, but removes a hypothesis with the same name as
this one if possible. For example, if the state is:
Then after `replace h : Ξ²` the state will be:
```lean
case h
f : Ξ± β Ξ²
h : Ξ±
β’ Ξ²
f : Ξ± β Ξ²
h : Ξ²
β’ goal
```
whereas `have h : Ξ²` would result in:
```lean
case h
f : Ξ± β Ξ²
h : Ξ±
β’ Ξ²
f : Ξ± β Ξ²
hβ : Ξ±
h : Ξ²
β’ goal
```
-/
syntax (name := replace') "replace" haveIdLhs' : tactic
elab_rules : tactic
| `(tactic| replace $n:optBinderIdent $bs* $[: $t:term]?) => withMainContext do
let (goal1, goal2) β haveLetCore (β getMainGoal) n bs t false
let name := optBinderIdent.name n
let hId? := (β getLCtx).findFromUserName? name |>.map fun d β¦ d.fvarId
match hId? with
| some hId => replaceMainGoal [goal1, (β observing? <| goal2.clear hId).getD goal2]
| none => replaceMainGoal [goal1, goal2]
|
Tactic\RewriteSearch.lean | /-
Copyright (c) 2023 Lean FRO, LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Lean.Meta.Tactic.Rewrites
import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Data.List.EditDistance.Estimator
import Mathlib.Data.MLList.BestFirst
import Mathlib.Order.Interval.Finset.Nat
import Batteries.Data.MLList.Heartbeats
/-!
# The `rw_search` tactic
`rw_search` attempts to solve an equality goal
by repeatedly rewriting using lemmas from the library.
If no solution is found,
the best sequence of rewrites found before `maxHeartbeats` elapses is returned.
The search is a best-first search, minimising the Levenshtein edit distance between
the pretty-printed expressions on either side of the equality.
(The strings are tokenized at spaces,
separating delimiters `(`, `)`, `[`, `]`, and `,` into their own tokens.)
The implementation avoids completely computing edit distances where possible,
only computing lower bounds sufficient to decide which path to take in the search.
# Future improvements
We could call `simp` as an atomic step of rewriting.
The edit distance heuristic could be replaced by something else.
No effort has been made to choose the best tokenization scheme, and this should be investigated.
Moreover, the Levenshtein distance function is customizable with different weights for each token,
and it would be interesting to try optimizing these
(or dynamically updating them,
adding weight to tokens that persistently appear on one side of the equation but not the other.)
The `rw_search` tactic will rewrite by local hypotheses,
but will not use local hypotheses to discharge side conditions.
This limitation would need to be resolved in the `rw?` tactic first.
-/
namespace Mathlib.Tactic.RewriteSearch
open Lean Meta
open Lean.Meta.Rewrites
open Lean.Meta.LazyDiscrTree (ModuleDiscrTreeRef)
initialize registerTraceClass `rw_search
initialize registerTraceClass `rw_search.detail
/-- Separate a string into a list of strings by pulling off initial `(` or `]` characters,
and pulling off terminal `)`, `]`, or `,` characters. -/
partial def splitDelimiters (s : String) : List String :=
let rec /-- Pull off leading delimiters. -/ auxStart front pre :=
let head := s.get front
if head = '(' || head = '[' then
auxStart (s.next front) (head.toString :: pre)
else
(front, pre)
let rec /-- Pull off trailing delimiters. -/ auxEnd back suff :=
let last := s.get back
if last = ')' || last = ']' || last = ',' then
auxEnd (s.prev back) (last.toString :: suff)
else
(back, suff)
let (frontAfterStart, pre) := auxStart 0 []
let (backAfterEnd, suff) := auxEnd (s.prev s.endPos) []
pre.reverse ++ [s.extract frontAfterStart (s.next backAfterEnd)] ++ suff
/--
Tokenize a string at whitespace, and then pull off delimiters.
-/
-- `rw_search` seems to return better results if we tokenize
-- rather than just breaking the string into characters,
-- but more extensive testing would be great!
-- Tokenizing of course makes the edit distance calculations cheaper,
-- because the lists are significantly shorter.
-- On the other hand, because we currently use unweighted edit distance,
-- this makes it "cheap" to change one identifier for another.
def tokenize (e : Expr) : MetaM (List String) := do
let s := (β ppExpr e).pretty
return s.splitOn.map splitDelimiters |>.join
/--
Data structure containing the history of a rewrite search.
-/
structure SearchNode where mk' ::
/-- The lemmas used so far. -/
-- The first component is the index amongst successful rewrites at the previous node.
history : Array (Nat Γ Expr Γ Bool)
/-- The metavariable context after rewriting.
We carry this around so the search can safely backtrack. -/
mctx : MetavarContext
/-- The current goal. -/
goal : MVarId
/-- The type of the current goal. -/
type : Expr
/-- The pretty printed current goal. -/
ppGoal : String
/-- The tokenization of the left-hand-side of the current goal. -/
lhs : List String
/-- The tokenization of the right-hand-side of the current goal. -/
rhs : List String
/-- Whether the current goal can be closed by `rfl` (or `none` if this hasn't been test yet). -/
rfl? : Option Bool := none
/-- The edit distance between the tokenizations of the two sides
(or `none` if this hasn't been computed yet). -/
dist? : Option Nat := none
namespace SearchNode
/--
What is the cost for changing a token?
`Levenshtein.defaultCost` just uses constant cost `1` for any token.
It may be interesting to try others.
the only one I've experimented with so far is `Levenshtein.stringLogLengthCost`,
which performs quite poorly!
-/
def editCost : Levenshtein.Cost String String Nat := Levenshtein.defaultCost
/-- Check whether a goal can be solved by `rfl`, and fill in the `SearchNode.rfl?` field. -/
def compute_rfl? (n : SearchNode) : MetaM SearchNode := do
try
withoutModifyingState <| withMCtx n.mctx do
-- We use `withReducible` here to follow the behaviour of `rw`.
n.goal.refl
pure { n with mctx := β getMCtx, rfl? := some true }
catch _e =>
withMCtx n.mctx do
if (β try? n.goal.applyRfl).isSome then
pure { n with mctx := β getMCtx, rfl? := some true }
else
pure { n with rfl? := some false }
/-- Fill in the `SearchNode.dist?` field with the edit distance between the two sides. -/
def compute_dist? (n : SearchNode) : SearchNode :=
match n.dist? with
| some _ => n
| none =>
{ n with dist? := some (levenshtein editCost n.lhs n.rhs) }
/-- Represent a search node as string, solely for debugging. -/
def toString (n : SearchNode) : MetaM String := do
let n := n.compute_dist?
let tac β match n.history.back? with
| some (_, e, true) => do let pp β ppExpr e; pure s!"rw [β {pp}]"
| some (_, e, false) => do let pp β ppExpr e; pure s!"rw [{pp}]"
| none => pure ""
return s!"depth: {n.history.size}\n\
history: {n.history.map fun p => hash p % 10000}\n\
{tac}\n\
-- {n.ppGoal}\n\
distance: {n.dist?.get!}+{n.history.size}, {n.ppGoal.length}"
/-- Construct a `SearchNode`. -/
def mk (history : Array (Nat Γ Expr Γ Bool)) (goal : MVarId) (ctx : Option MetavarContext := none) :
MetaM (Option SearchNode) := goal.withContext do
let type β whnfR (β instantiateMVars (β goal.getType))
match type.eq? with
| none => return none
| some (_, lhs, rhs) =>
let lhsTokens β tokenize lhs
let rhsTokens β tokenize rhs
let r :=
{ history := history
mctx := β ctx.getDM getMCtx
goal := goal
type := type
ppGoal := (β ppExpr type).pretty
lhs := lhsTokens
rhs := rhsTokens }
return some r
/-- Construct an initial `SearchNode` from a goal. -/
def init (goal : MVarId) : MetaM (Option SearchNode) := mk #[] goal
/-- Add an additional step to the `SearchNode` history. -/
def push (n : SearchNode) (expr : Expr) (symm : Bool) (k : Nat) (g : MVarId)
(ctx : Option MetavarContext := none) : MetaM (Option SearchNode) :=
mk (n.history.push (k, expr, symm)) g ctx
/-- Report the index of the most recently applied lemma, in the ordering returned by `rw?`. -/
def lastIdx (n : SearchNode) : Nat :=
match n.history.back? with
| some (k, _) => k
| none => 0
instance : Ord SearchNode where
compare := compareOn fun n => toLex (toLex (n.ppGoal.length, n.lastIdx), n.ppGoal)
/--
A somewhat arbitrary penalty function.
Note that `n.lastIdx` penalizes using later lemmas from a particular call to `rw?` at a node,
but once we have moved on to the next node these penalties are "forgiven".
(You might in interpret this as encouraging
the algorithm to "trust" the ordering provided by `rw?`.)
I tried out a various (positive) linear combinations of
`.history.size`, `.lastIdx`, and `.ppGoal.length` (and also the `.log2`s of these).
* `.lastIdx.log2` is quite good, and the best coefficient is around 1.
* `.lastIdx / 10` is almost as good.
* `.history.size` makes things worse (similarly with `.log2`).
* `.ppGoal.length` makes little difference (similarly with `.log2`).
Here testing consisting of running the current `rw_search` test suite,
rejecting values for which any failed, and trying to minimize the run time reported by
```shell
lake build && \
time (lake env lean test/RewriteSearch/Basic.lean; \
lake env lean test/RewriteSearch/Polynomial.lean)
```
With a larger test suite it might be worth running this minimization again,
and considering other penalty functions.
(If you do this, please choose a penalty function which is in the interior of the region
where the test suite works.
I think it would be a bad idea to optimize the run time at the expense of fragility.)
-/
def penalty (n : SearchNode) : Nat := n.lastIdx.log2 + n.ppGoal.length.log2
/-- The priority function for search is Levenshtein distance plus a penalty. -/
abbrev prio (n : SearchNode) : Thunk Nat :=
(Thunk.pure n.penalty) + (Thunk.mk fun _ => levenshtein editCost n.lhs n.rhs)
/-- We can obtain lower bounds, and improve them, for the Levenshtein distance. -/
abbrev estimator (n : SearchNode) : Type :=
Estimator.trivial n.penalty Γ LevenshteinEstimator editCost n.lhs n.rhs
/-- Given a `RewriteResult` from the `rw?` tactic, create a new `SearchNode` with the new goal. -/
def rewrite (n : SearchNode) (r : Rewrites.RewriteResult) (k : Nat) :
MetaM (Option SearchNode) :=
withMCtx r.mctx do
let goal' β n.goal.replaceTargetEq r.result.eNew r.result.eqProof
n.push r.expr r.symm k goal' (β getMCtx)
/--
Given a pair of `DiscrTree` trees
indexing all rewrite lemmas in the imported files and the current file,
try rewriting the current goal in the `SearchNode` by one of them,
returning a `MLList MetaM SearchNode`, i.e. a lazy list of next possible goals.
-/
def rewrites (hyps : Array (Expr Γ Bool Γ Nat))
(lemmas : ModuleDiscrTreeRef (Name Γ RwDirection))
(forbidden : NameSet := β
) (n : SearchNode) : MLList MetaM SearchNode := .squash fun _ => do
if β isTracingEnabledFor `rw_search then do
trace[rw_search] "searching:\n{β toString n}"
let candidates β rewriteCandidates hyps lemmas n.type forbidden
-- Lift to a monadic list, so the caller can decide how much of the computation to run.
return MLList.ofArray candidates
|>.filterMapM (fun β¨lem, symm, weightβ© =>
rwLemma n.mctx n.goal n.type .solveByElim lem symm weight)
|>.enum
|>.filterMapM fun β¨k, rβ© => do n.rewrite r k
/--
Perform best first search on the graph of rewrites from the specified `SearchNode`.
-/
def search (n : SearchNode)
(stopAtRfl := true) (stopAtDistZero := true)
(forbidden : NameSet := β
) (maxQueued : Option Nat := none) :
MLList MetaM SearchNode := .squash fun _ => do
let hyps β localHypotheses
let moduleRef β createModuleTreeRef
let search := bestFirstSearchCore (maxQueued := maxQueued)
(Ξ² := String) (removeDuplicatesBy? := some SearchNode.ppGoal)
prio estimator (rewrites hyps moduleRef forbidden) n
let search β
if β isTracingEnabledFor `rw_search then do
pure <| search.mapM fun n => do trace[rw_search] "{β toString n}"; pure n
else
pure search
let search := if stopAtRfl then
search.mapM compute_rfl? |>.takeUpToFirst fun n => n.rfl? = some true
else
search
return if stopAtDistZero then
search.map (fun r => r.compute_dist?) |>.takeUpToFirst (fun r => r.dist? = some 0)
else
search
end SearchNode
open Elab Tactic Lean.Parser.Tactic
/--
`rw_search` attempts to solve an equality goal
by repeatedly rewriting using lemmas from the library.
If no solution is found,
the best sequence of rewrites found before `maxHeartbeats` elapses is returned.
The search is a best-first search, minimising the Levenshtein edit distance between
the pretty-printed expressions on either side of the equality.
(The strings are tokenized at spaces,
separating delimiters `(`, `)`, `[`, `]`, and `,` into their own tokens.)
You can use `rw_search [-my_lemma, -my_theorem]`
to prevent `rw_search` from using the names theorems.
-/
syntax "rw_search" (rewrites_forbidden)? : tactic
open Lean.Meta.Tactic.TryThis
elab_rules : tactic |
`(tactic| rw_search%$tk $[[ $[-$forbidden],* ]]?) => withMainContext do
let forbidden : NameSet :=
((forbidden.getD #[]).map Syntax.getId).foldl (init := β
) fun s n => s.insert n
let .some init β SearchNode.init (β getMainGoal) | throwError "Goal is not an equality."
let results := init.search (forbidden := forbidden) |>.whileAtLeastHeartbeatsPercent 20
let results β results.force
let min β match results with
| [] => failure
| h :: t =>
pure <| t.foldl (init := h) fun rβ rβ =>
if rβ.rfl? = some true then rβ
else if rβ.rfl? = some true then rβ
else if rβ.dist?.getD 0 β€ rβ.dist?.getD 0 then rβ else rβ
setMCtx min.mctx
replaceMainGoal [min.goal]
let type? β if min.rfl? = some true then pure none else do pure <| some (β min.goal.getType)
addRewriteSuggestion tk (min.history.toList.map (Β·.2))
type? (origSpan? := β getRef)
end RewriteSearch
end Tactic
end Mathlib
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.