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