fact stringlengths 6 3.84k | type stringclasses 11 values | library stringclasses 32 values | imports listlengths 1 14 | filename stringlengths 20 95 | symbolic_name stringlengths 1 90 | docstring stringlengths 7 20k ⌀ |
|---|---|---|---|---|---|---|
FactorsHelper.singleton (n : ℕ) {a : ℕ} (h₁ : Nat.blt a n) (h₂ : IsNat (minFac n) n) :
FactorsHelper n a [n] :=
FactorsHelper.nil.cons _ ⟨mul_one _⟩ h₁ h₂ | theorem | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | FactorsHelper.singleton | null |
FactorsHelper.cons_self {n m : ℕ} (a : ℕ) {l : List ℕ}
(h : IsNat (a * m) n) (H : FactorsHelper m a l) :
FactorsHelper n a (a :: l) := fun pa =>
H.cons_of_le _ h le_rfl (Nat.prime_def_minFac.1 pa).2 pa | theorem | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | FactorsHelper.cons_self | null |
FactorsHelper.singleton_self (a : ℕ) : FactorsHelper a a [a] :=
FactorsHelper.nil.cons_self _ ⟨mul_one _⟩ | theorem | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | FactorsHelper.singleton_self | null |
FactorsHelper.primeFactorsList_eq {n : ℕ} {l : List ℕ} (H : FactorsHelper n 2 l) :
Nat.primeFactorsList n = l :=
let ⟨h₁, h₂, h₃⟩ := H Nat.prime_two
have := List.isChain_iff_pairwise.1 (@List.IsChain.tail _ _ (_ :: _) h₁)
(List.eq_of_perm_of_sorted
(Nat.primeFactorsList_unique h₃ h₂) this (Nat.primeFactorsList_sorted _)).symm
open Lean Elab Tactic Qq | theorem | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | FactorsHelper.primeFactorsList_eq | null |
private partial evalPrimeFactorsListAux
{en enl : Q(ℕ)} {ea eal : Q(ℕ)} (ehn : Q(IsNat $en $enl)) (eha : Q(IsNat $ea $eal)) :
MetaM ((l : Q(List ℕ)) × Q(FactorsHelper $en $ea $l)) := do
/-
In this function we will use the convention that all `e` prefixed variables (proofs or otherwise)
contain `Expr`s. The variables starting with `h` are proofs about the _meta_ code;
these will not actually be used in the construction of the proof, and are simply used to help the
reader reason about why the proof construction is correct.
-/
let n := enl.natLit!
let ⟨hn0⟩ ← if h : 0 < n then pure <| PLift.up h else
throwError m!"{enl} must be positive"
let a := eal.natLit!
let b := n.minFac
let ⟨hab⟩ ← if h : a ≤ b then pure <| PLift.up h else
throwError m!"{q($eal < $(enl).minFac)} does not hold"
if h_bn : b < n then
let m := n / b
have em : Q(ℕ) := mkRawNatLit m
have ehm : Q(IsNat (OfNat.ofNat $em) $em) := q(⟨rfl⟩)
if h_ba_eq : b = a then
have eh : Q($eal * $em = $en) :=
have : a * m = n := by simp [m, b, ← h_ba_eq, Nat.mul_div_cancel' (minFac_dvd _)]
(q(Eq.refl $en) : Expr)
let ehp₁ := q(isNat_mul rfl $eha $ehm $eh)
let ⟨el, ehp₂⟩ ← evalPrimeFactorsListAux ehm eha
pure ⟨q($ea :: $el), q(($ehp₂).cons_self _ $ehp₁)⟩
else
have eb : Q(ℕ) := mkRawNatLit b
have ehb : Q(IsNat (OfNat.ofNat $eb) $eb) := q(⟨rfl⟩)
have ehbm : Q($eb * $em = $en) :=
have : b * m = n := Nat.mul_div_cancel' (minFac_dvd _)
(q(Eq.refl $en) : Expr)
have ehp₁ := q(isNat_mul rfl $ehb $ehm $ehbm)
have ehp₂ : Q(Nat.blt $ea $eb = true) :=
have : a < b := lt_of_le_of_ne' hab h_ba_eq
(q(Eq.refl (true)) : Expr)
let .isNat _ lit ehp₃ ← evalMinFac.core q($eb) q(inferInstance) q($eb) ehb b | failure
assertInstancesCommute
have : $lit =Q $eb := ⟨⟩
let ⟨l, p₄⟩ ← evalPrimeFactorsListAux ehm ehb
pure ⟨q($eb :: $l), q(($p₄).cons _ $ehp₁ $ehp₂ $ehp₃ )⟩
else
have hbn_eq : b = n := (minFac_le hn0).eq_or_lt.resolve_right h_bn
if hba : b = a then
have eh : Q($en = $ea) :=
have : n = a := hbn_eq.symm.trans hba
(q(Eq.refl $en) : Expr)
pure ⟨q([$ea]), q($eh ▸ FactorsHelper.singleton_self $ea)⟩
else do
let eh_a_lt_n : Q(Nat.blt $ea $en = true) :=
... | def | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | evalPrimeFactorsListAux | Given `n` and `a` (in expressions `en` and `ea`) corresponding to literal numerals
(in `enl` and `eal`), returns `(l, ⊢ factorsHelper n a l)`. |
evalPrimeFactorsList
{en enl : Q(ℕ)} (hn : Q(IsNat $en $enl)) :
MetaM ((l : Q(List ℕ)) × Q(Nat.primeFactorsList $en = $l)) := do
match enl.natLit! with
| 0 =>
have _ : $enl =Q nat_lit 0 := ⟨⟩
have hen : Q($en = 0) := q($(hn).out)
return ⟨_, q($hen ▸ Nat.primeFactorsList_zero)⟩
| 1 =>
let _ : $enl =Q nat_lit 1 := ⟨⟩
have hen : Q($en = 1) := q($(hn).out)
return ⟨_, q($hen ▸ Nat.primeFactorsList_one)⟩
| _ => do
have h2 : Q(IsNat 2 (nat_lit 2)) := q(⟨Eq.refl (nat_lit 2)⟩)
let ⟨l, p⟩ ← evalPrimeFactorsListAux hn h2
return ⟨l, q(($p).primeFactorsList_eq)⟩ | def | Tactic | [
"Mathlib.Data.Nat.Factors",
"Mathlib.Tactic.NormNum.Prime"
] | Mathlib/Tactic/Simproc/Factors.lean | evalPrimeFactorsList | Given a natural number `n`, returns `(l, ⊢ Nat.primeFactorsList n = l)`. |
private NameStruct where
/-- The namespace that the final name will reside in. -/
parent : Name
/-- A list of pieces to be joined by `toName`. -/
components : List String | structure | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | NameStruct | An internal representation of a name to be used for a generated lemma. |
private NameStruct.toName (n : NameStruct) : Name :=
Name.mkStr n.parent <|
match n.components with
| [] => ""
| [x] => s!"{x}_def"
| e => "_".intercalate e | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | NameStruct.toName | Join the components with `_`, or append `_def` if there is only one component. |
private NameStruct.update (nm : NameStruct) (s : String) (isPrefix : Bool := false) :
NameStruct :=
{ nm with components := if isPrefix then s :: nm.components else nm.components ++ [s] } | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | NameStruct.update | `update nm s isPrefix` adds `s` to the last component of `nm`,
either as prefix or as suffix (specified by `isPrefix`).
Used by `simps_add_projections`. |
mkSimpContextResult (cfg : Meta.Simp.Config := {}) (simpOnly := false) (kind := SimpKind.simp)
(dischargeWrapper := DischargeWrapper.default) (hasStar := false) :
MetaM MkSimpContextResult := do
match dischargeWrapper with
| .default => pure ()
| _ =>
if kind == SimpKind.simpAll then
throwError "'simp_all' tactic does not support 'discharger' option"
if kind == SimpKind.dsimp then
throwError "'dsimp' tactic does not support 'discharger' option"
let simpTheorems ← if simpOnly then
simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems)
else
getSimpTheorems
let simprocs := #[← if simpOnly then pure {} else Simp.getSimprocs]
let congrTheorems ← getSimpCongrTheorems
let ctx : Simp.Context ← Simp.mkContext cfg
(simpTheorems := #[simpTheorems])
(congrTheorems := congrTheorems)
if !hasStar then
return { ctx, simprocs, dischargeWrapper }
else
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.setSimpTheorems simpTheorems
return { ctx, simprocs, dischargeWrapper } | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | mkSimpContextResult | Make `MkSimpContextResult` giving data instead of Syntax. Doesn't support arguments.
Intended to be very similar to `Lean.Elab.Tactic.mkSimpContext`
Todo: support arguments. |
mkSimpContext (cfg : Meta.Simp.Config := {}) (simpOnly := false) (kind := SimpKind.simp)
(dischargeWrapper := DischargeWrapper.default) (hasStar := false) :
MetaM Simp.Context := do
let data ← mkSimpContextResult cfg simpOnly kind dischargeWrapper hasStar
return data.ctx | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | mkSimpContext | Make `Simp.Context` giving data instead of Syntax. Doesn't support arguments.
Intended to be very similar to `Lean.Elab.Tactic.mkSimpContext`
Todo: support arguments. |
ProjectionData where
/-- The name used in the generated `simp` lemmas -/
name : Name
/-- An Expression used by simps for the projection. It must be definitionally equal to an original
projection (or a composition of multiple projections).
These Expressions can contain the universe parameters specified in the first argument of
`structureExt`. -/
expr : Expr
/-- A list of natural numbers, which is the projection number(s) that have to be applied to the
Expression. For example the list `[0, 1]` corresponds to applying the first projection of the
structure, and then the second projection of the resulting structure (this assumes that the
target of the first projection is a structure with at least two projections).
The composition of these projections is required to be definitionally equal to the provided
Expression. -/
projNrs : List Nat
/-- A Boolean specifying whether `simp` lemmas are generated for this projection by default. -/
isDefault : Bool
/-- A Boolean specifying whether this projection is written as prefix. -/
isPrefix : Bool
deriving Inhabited | structure | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | ProjectionData | An `(attr := ...)` option for `simps`. -/
syntax simpsOptAttrOption := atomic(" (" &"attr" " := " Parser.Term.attrInstance,* ")")?
/-- Arguments to `@[simps]` attribute.
Currently, a potential `(attr := ...)` argument has to come before other configuration options. -/
syntax simpsArgsRest := simpsOptAttrOption Tactic.optConfig (ppSpace ident)*
/-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this
declaration.
Example:
```lean
@[simps] def foo : ℕ × ℤ := (1, 2)
```
derives two `simp` lemmas:
```lean
@[simp] lemma foo_fst : foo.fst = 1
@[simp] lemma foo_snd : foo.snd = 2
```
* It does not derive `simp` lemmas for the prop-valued projections.
* It will automatically reduce newly created beta-redexes, but will not unfold any definitions.
* If the structure has a coercion to either sorts or functions, and this is defined to be one
of the projections, then this coercion will be used instead of the projection.
* If the structure is a class that has an instance to a notation class, like `Neg` or `Mul`,
then this notation is used instead of the corresponding projection.
* You can specify custom projections, by giving a declaration with name
`{StructureName}.Simps.{projectionName}`. See Note [custom simps projection].
Example:
```lean
def Equiv.Simps.invFun (e : α ≃ β) : β → α := e.symm
@[simps] def Equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩
```
generates
```
@[simp] lemma Equiv.trans_toFun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a
@[simp] lemma Equiv.trans_invFun : ∀ {α β γ} (e₁ e₂) (a : γ),
⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a
```
* You can specify custom projection names, by specifying the new projection names using
`initialize_simps_projections`.
Example: `initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply)`.
See `initialize_simps_projections` for more information.
* If one of the fields itself is a structure, this command will recursively create
`simp` lemmas for all fields in that structure.
* Exception: by default it will not recursively create `simp` lemmas for fields in the structures
`Prod`, `PProd`, and `Opposite`. You can give explicit projection names or change the value of
`Simps.Config.notRecursive` to override this behavior.
Example:
```lean
structure MyProd (α β : Type*) := (fst : α) (snd : β)
@[simps] def foo : Prod ℕ ℕ × MyProd ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_snd_fst : foo.snd.fst = 3
@[simp] lemma foo_snd_snd : foo.snd.snd = 4
```
* You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified
projections.
* Recursive projection names can be specified using `proj1_proj2_proj3`.
This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`.
Example:
```lean
structure MyProd (α β : Type*) := (fst : α) (snd : β)
@[simps fst fst_fst snd] def foo : Prod ℕ ℕ × MyProd ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_fst_fst : foo.fst.fst = 1
@[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4}
```
* If one of the values is an eta-expanded structure, we will eta-reduce this structure.
Example:
```lean
structure EquivPlusData (α β) extends α ≃ β where
data : Bool
@[simps] def EquivPlusData.rfl {α} : EquivPlusData α α := { Equiv.refl α with data := true }
```
generates the following:
```lean
@[simp] lemma bar_toEquiv : ∀ {α : Sort*}, bar.toEquiv = Equiv.refl α
@[simp] lemma bar_data : ∀ {α : Sort*}, bar.data = true
```
This is true, even though Lean inserts an eta-expanded version of `Equiv.refl α` in the
definition of `bar`.
* You can add additional attributes to all lemmas generated by `simps` using e.g.
`@[simps (attr := grind =)]`.
* For configuration options, see the doc string of `Simps.Config`.
* The precise syntax is `simps (attr := a) config ident*`, where `a` is a list of attributes,
`config` declares configuration options and `ident*` is a list of desired projection names.
* Configuration options can be given using `(config := e)` where `e : Simps.Config`,
or by specifying options directly, like `-fullyApplied` or `(notRecursive := [])`.
* `@[simps]` reduces let-expressions where necessary.
* When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the
lemmas it generates. The same can be achieved by using `@[simps?]`.
* Use `@[to_additive (attr := simps)]` to apply both `to_additive` and `simps` to a definition
This will also generate the additive versions of all `simp` lemmas.
-/
/- If one of the fields is a partially applied constructor, we will eta-expand it
(this likely never happens, so is not included in the official doc). -/
syntax (name := simps) "simps" "!"? "?"? simpsArgsRest : attr
@[inherit_doc simps] macro "simps?" rest:simpsArgsRest : attr => `(attr| simps ? $rest)
@[inherit_doc simps] macro "simps!" rest:simpsArgsRest : attr => `(attr| simps ! $rest)
@[inherit_doc simps] macro "simps!?" rest:simpsArgsRest : attr => `(attr| simps ! ? $rest)
@[inherit_doc simps] macro "simps?!" rest:simpsArgsRest : attr => `(attr| simps ! ? $rest)
end Attr
/-- Linter to check that `simps!` is used when needed -/
register_option linter.simpsNoConstructor : Bool := {
defValue := true
descr := "Linter to check that `simps!` is used" }
/-- Linter to check that no unused custom declarations are declared for simps. -/
register_option linter.simpsUnusedCustomDeclarations : Bool := {
defValue := true
descr := "Linter to check that no unused custom declarations are declared for simps" }
namespace Command
/-- Syntax for renaming a projection in `initialize_simps_projections`. -/
syntax simpsRule.rename := ident " → " ident
/-- Syntax for making a projection non-default in `initialize_simps_projections`. -/
syntax simpsRule.erase := "-" ident
/-- Syntax for making a projection default in `initialize_simps_projections`. -/
syntax simpsRule.add := "+" ident
/-- Syntax for making a projection prefix. -/
syntax simpsRule.prefix := &"as_prefix " ident
/-- Syntax for a single rule in `initialize_simps_projections`. -/
syntax simpsRule := simpsRule.prefix <|> simpsRule.rename <|> simpsRule.erase <|> simpsRule.add
/-- Syntax for `initialize_simps_projections`. -/
syntax simpsProj := ppSpace ident (" (" simpsRule,+ ")")?
/--
This command allows customisation of the lemmas generated by `simps`.
By default, tagging a definition of an element `myObj` of a structure `MyStruct` with `@[simps]`
generates one `@[simp]` lemma `myObj_myProj` for each projection `myProj` of `MyStruct`. There are a
few exceptions to this general rule:
* For algebraic structures, we will automatically use the notation (like `Mul`)
for the projections if such an instance is available.
* By default, the projections to parent structures are not default projections,
but all the data-carrying fields are (including those in parent structures).
This default behavior is customisable as such:
* You can disable a projection by default by running
`initialize_simps_projections MulEquiv (-invFun)`
This will ensure that no simp lemmas are generated for this projection,
unless this projection is explicitly specified by the user (as in
`@[simps invFun] def myEquiv : MulEquiv _ _ := _`).
* Conversely, you can enable a projection by default by running
`initialize_simps_projections MulEquiv (+toEquiv)`.
* You can specify custom names by writing e.g.
`initialize_simps_projections MulEquiv (toFun → apply, invFun → symm_apply)`.
* If you want the projection name added as a prefix in the generated lemma name, you can use
`as_prefix fieldName`:
`initialize_simps_projections MulEquiv (toFun → coe, as_prefix coe)`
Note that this does not influence the parsing of projection names: if you have a declaration
`foo` and you want to apply the projections `snd`, `coe` (which is a prefix) and `fst`, in that
order you can run `@[simps snd_coe_fst] def foo ...` and this will generate a lemma with the
name `coe_foo_snd_fst`.
Here are a few extra pieces of information:
* Run `initialize_simps_projections?` (or `set_option trace.simps.verbose true`)
to see the generated projections.
* Running `initialize_simps_projections MyStruct` without arguments is not necessary, it has the
same effect if you just add `@[simps]` to a declaration.
* It is recommended to call `@[simps]` or `initialize_simps_projections` in the same file as the
structure declaration. Otherwise, the projections could be generated multiple times in different
files.
Some common uses:
* If you define a new homomorphism-like structure (like `MulHom`) you can just run
`initialize_simps_projections` after defining the `DFunLike` instance (or instance that implies
a `DFunLike` instance).
```
instance {mM : Mul M} {mN : Mul N} : FunLike (MulHom M N) M N := ...
initialize_simps_projections MulHom (toFun → apply)
```
This will generate `foo_apply` lemmas for each declaration `foo`.
* If you prefer `coe_foo` lemmas that state equalities between functions, use
`initialize_simps_projections MulHom (toFun → coe, as_prefix coe)`
In this case you have to use `@[simps -fullyApplied]` whenever you call `@[simps]`.
* You can also initialize to use both, in which case you have to choose which one to use by default,
by using either of the following
```
initialize_simps_projections MulHom (toFun → apply, toFun → coe, as_prefix coe, -coe)
initialize_simps_projections MulHom (toFun → apply, toFun → coe, as_prefix coe, -apply)
```
In the first case, you can get both lemmas using `@[simps, simps -fullyApplied coe]` and in
the second case you can get both lemmas using `@[simps -fullyApplied, simps apply]`.
* If you declare a new homomorphism-like structure (like `RelEmbedding`),
then `initialize_simps_projections` will automatically find any `DFunLike` coercions
that will be used as the default projection for the `toFun` field.
```
initialize_simps_projections relEmbedding (toFun → apply)
```
* If you have an isomorphism-like structure (like `Equiv`) you often want to define a custom
projection for the inverse:
```
def Equiv.Simps.symm_apply (e : α ≃ β) : β → α := e.symm
initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply)
```
-/
syntax (name := initialize_simps_projections)
"initialize_simps_projections" "?"? simpsProj : command
@[inherit_doc «initialize_simps_projections»]
macro "initialize_simps_projections?" rest:simpsProj : command =>
`(initialize_simps_projections ? $rest)
end Command
end Lean.Parser
initialize registerTraceClass `simps.verbose
initialize registerTraceClass `simps.debug
namespace Simps
/-- Projection data for a single projection of a structure |
ParsedProjectionData where
/-- name for this projection used in the structure definition -/
strName : Name
/-- syntax that might have provided `strName` -/
strStx : Syntax := .missing
/-- name for this projection used in the generated `simp` lemmas -/
newName : Name
/-- syntax that provided `newName` -/
newStx : Syntax := .missing
/-- will simp lemmas be generated for with (without specifically naming this?) -/
isDefault : Bool := true
/-- is the projection name a prefix? -/
isPrefix : Bool := false
/-- projection expression -/
expr? : Option Expr := none
/-- the list of projection numbers this expression corresponds to -/
projNrs : Array Nat := #[]
/-- is this a projection that is changed by the user? -/
isCustom : Bool := false | structure | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | ParsedProjectionData | The `Simps.structureExt` environment extension specifies the preferred projections of the given
structure, used by the `@[simps]` attribute.
- You can generate this with the command `initialize_simps_projections`.
- If not generated, the `@[simps]` attribute will generate this automatically.
- To change the default value, see Note [custom simps projection].
- The first argument is the list of names of the universe variables used in the structure
- The second argument is an array that consists of the projection data for each projection.
-/
initialize structureExt : NameMapExtension (List Name × Array ProjectionData) ←
registerNameMapExtension (List Name × Array ProjectionData)
/-- Projection data used internally in `getRawProjections`. |
ParsedProjectionData.toProjectionData (p : ParsedProjectionData) : ProjectionData :=
{ p with name := p.newName, expr := p.expr?.getD default, projNrs := p.projNrs.toList } | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | ParsedProjectionData.toProjectionData | Turn `ParsedProjectionData` into `ProjectionData`. |
ProjectionRule where
/-- A renaming rule `before→after` or
Each name comes with the syntax used to write the rule,
which is used to declare hover information. -/
| rename (oldName : Name) (oldStx : Syntax) (newName : Name) (newStx : Syntax) :
ProjectionRule
/-- An adding rule `+fieldName` -/
| add : Name → Syntax → ProjectionRule
/-- A hiding rule `-fieldName` -/
| erase : Name → Syntax → ProjectionRule
/-- A prefix rule `prefix fieldName` -/
| prefix : Name → Syntax → ProjectionRule | inductive | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | ProjectionRule | The type of rules that specify how metadata for projections in changes.
See `initialize_simps_projections`. |
projectionsInfo (l : List ProjectionData) (pref : String) (str : Name) : MessageData :=
let ⟨defaults, nondefaults⟩ := l.partition (·.isDefault)
let toPrint : List MessageData :=
defaults.map fun s ↦
let prefixStr := if s.isPrefix then "(prefix) " else ""
m!"Projection {prefixStr}{s.name}: {s.expr}"
let print2 : MessageData :=
String.join <| (nondefaults.map fun nm : ProjectionData ↦ toString nm.1).intersperse ", "
let toPrint :=
toPrint ++
if nondefaults.isEmpty then [] else
[("No lemmas are generated for the projections: " : MessageData) ++ print2 ++ "."]
let toPrint := MessageData.joinSep toPrint ("\n" : MessageData)
m!"{pref} {str}:\n{toPrint}" | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | projectionsInfo | Returns the projection information of a structure. |
findProjectionIndices (strName projName : Name) : MetaM (List Nat) := do
let env ← getEnv
let some baseStr := findField? env strName projName |
throwError "{strName} has no field {projName} in parent structure"
let some fullProjName := getProjFnForField? env baseStr projName |
throwError "no such field {projName}"
let some pathToField := getPathToBaseStructure? env baseStr strName |
throwError "no such field {projName}"
let allProjs := pathToField ++ [fullProjName]
return allProjs.map (env.getProjectionFnInfo? · |>.get!.i) | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | findProjectionIndices | Find the indices of the projections that need to be applied to elaborate `$e.$projName`.
Example: If `e : α ≃+ β` and ``projName = `invFun`` then this returns `[0, 1]`, because the first
projection of `MulEquiv` is `toEquiv` and the second projection of `Equiv` is `invFun`. |
private dropPrefixIfNotNumber? (s : String) (pre : String) : Option Substring := do
let ret ← s.dropPrefix? pre
let flag := ret.toString.data.head?.elim false Char.isDigit
if flag then none else some ret | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | dropPrefixIfNotNumber | A variant of `Substring.dropPrefix?` that does not consider `toFoo` to be a prefix to `toFoo_1`.
This is checked by inspecting whether the first character of the remaining part is a digit.
We use this variant because the latter is often a different field with an auto-generated name. |
private isPrefixOfAndNotNumber (s p : String) : Bool := (dropPrefixIfNotNumber? p s).isSome | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | isPrefixOfAndNotNumber | A variant of `String.isPrefixOf` that does not consider `toFoo` to be a prefix to `toFoo_1`. |
private splitOnNotNumber (s delim : String) : List String :=
(process (s.splitOn delim).reverse "").reverse where
process (arr : List String) (tail : String) := match arr with
| [] => []
| (x :: xs) =>
let flag := x.data.head?.elim false Char.isDigit
if flag then
process xs (tail ++ delim ++ x)
else
List.cons (x ++ tail) (process xs "") | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | splitOnNotNumber | A variant of `String.splitOn` that does not split `toFoo_1` into `toFoo` and `1`. |
partial getCompositeOfProjectionsAux (proj : String) (e : Expr) (pos : Array Nat)
(args : Array Expr) : MetaM (Expr × Array Nat) := do
let env ← getEnv
let .const structName _ := (← whnf (← inferType e)).getAppFn |
throwError "{e} doesn't have a structure as type"
let projs := getStructureFieldsFlattened env structName
let projInfo := projs.toList.map fun p ↦ do
((← dropPrefixIfNotNumber? proj (p.lastComponentAsString ++ "_")).toString, p)
let some (projRest, projName) := projInfo.reduceOption.getLast? |
throwError "Failed to find constructor {proj.dropRight 1} in structure {structName}."
let newE ← mkProjection e projName
let newPos := pos ++ (← findProjectionIndices structName projName)
if projRest.isEmpty then
let newE ← mkLambdaFVars args newE
return (newE, newPos)
let type ← inferType newE
forallTelescopeReducing type fun typeArgs _tgt ↦ do
getCompositeOfProjectionsAux projRest (mkAppN newE typeArgs) newPos (args ++ typeArgs) | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | getCompositeOfProjectionsAux | Auxiliary function of `getCompositeOfProjections`. |
getCompositeOfProjections (structName : Name) (proj : String) : MetaM (Expr × Array Nat) := do
let strExpr ← mkConstWithLevelParams structName
let type ← inferType strExpr
forallTelescopeReducing type fun typeArgs _ ↦
withLocalDeclD `x (mkAppN strExpr typeArgs) fun e ↦
getCompositeOfProjectionsAux (proj ++ "_") e #[] <| typeArgs.push e | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | getCompositeOfProjections | Suppose we are given a structure `str` and a projection `proj`, that could be multiple nested
projections (separated by `_`), where each projection could be a projection of a parent structure.
This function returns an expression that is the composition of these projections and a
list of natural numbers, that are the projection numbers of the applied projections.
Note that this function is similar to elaborating dot notation, but it can do a little more.
Example: if we do
```
structure gradedFun (A : ℕ → Type*) where
toFun := ∀ i j, A i →+ A j →+ A (i + j)
initialize_simps_projections (toFun_toFun_toFun → myMul)
```
we will be able to generate the "projection"
`fun {A} (f : gradedFun A) (x : A i) (y : A j) ↦ ↑(↑(f.toFun i j) x) y`,
which projection notation cannot do. |
mkParsedProjectionData (structName : Name) : CoreM (Array ParsedProjectionData) := do
let env ← getEnv
let projs := getStructureFields env structName
if projs.size == 0 then
throwError "Declaration {structName} is not a structure."
let projData := projs.map fun fieldName ↦ {
strName := fieldName, newName := fieldName,
isDefault := isSubobjectField? env structName fieldName |>.isNone }
let parentProjs := getStructureFieldsFlattened env structName false
let parentProjs := parentProjs.filter (!projs.contains ·)
let parentProjData := parentProjs.map fun nm ↦
{strName := nm, newName := nm}
return projData ++ parentProjData | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | mkParsedProjectionData | Get the default `ParsedProjectionData` for structure `str`.
It first returns the direct fields of the structure in the right order, and then
all (non-subobject fields) of all parent structures. The subobject fields are precisely the
non-default fields. |
applyProjectionRules (projs : Array ParsedProjectionData) (rules : Array ProjectionRule) :
CoreM (Array ParsedProjectionData) := do
let projs : Array ParsedProjectionData := rules.foldl (init := projs) fun projs rule ↦
match rule with
| .rename strName strStx newName newStx =>
if (projs.map (·.newName)).contains strName then
projs.map fun proj ↦ if proj.newName == strName then
{ proj with
newName,
newStx,
strStx := if proj.strStx.isMissing then strStx else proj.strStx } else
proj else
projs.push {strName, strStx, newName, newStx}
| .erase nm stx =>
if (projs.map (·.newName)).contains nm then
projs.map fun proj ↦ if proj.newName = nm then
{ proj with
isDefault := false,
strStx := if proj.strStx.isMissing then stx else proj.strStx } else
proj else
projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx, isDefault := false}
| .add nm stx =>
if (projs.map (·.newName)).contains nm then
projs.map fun proj ↦ if proj.newName = nm then
{ proj with
isDefault := true,
strStx := if proj.strStx.isMissing then stx else proj.strStx } else
proj else
projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx}
| .prefix nm stx =>
if (projs.map (·.newName)).contains nm then
projs.map fun proj ↦ if proj.newName = nm then
{ proj with
isPrefix := true,
strStx := if proj.strStx.isMissing then stx else proj.strStx } else
proj else
projs.push {strName := nm, newName := nm, strStx := stx, newStx := stx, isPrefix := true}
trace[simps.debug] "Projection info after applying the rules: {projs}."
unless (projs.map (·.newName)).toList.Nodup do throwError "\
Invalid projection names. Two projections have the same name.\n\
This is likely because a custom composition of projections was given the same name as an \
existing projection. Solution: rename the existing projection (before naming the \
custom projection)."
pure projs | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | applyProjectionRules | Execute the projection renamings (and turning off projections) as specified by `rules`. |
findProjection (str : Name) (proj : ParsedProjectionData)
(rawUnivs : List Level) : CoreM ParsedProjectionData := do
let env ← getEnv
let (rawExpr, nrs) ← MetaM.run' <|
getCompositeOfProjections str proj.strName.lastComponentAsString
if !proj.strStx.isMissing then
_ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.strStx rawExpr
trace[simps.debug] "Projection {proj.newName} has default projection {rawExpr} and
uses projection indices {nrs}"
let customName := str ++ `Simps ++ proj.newName
match env.find? customName with
| some d@(.defnInfo _) =>
let customProj := d.instantiateValueLevelParams! rawUnivs
trace[simps.verbose] "found custom projection for {proj.newName}:{indentExpr customProj}"
match (← MetaM.run' <| isDefEq customProj rawExpr) with
| true =>
_ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.newStx <|
← mkConstWithLevelParams customName
pure { proj with expr? := some customProj, projNrs := nrs, isCustom := true }
| false =>
let customProjType ← MetaM.run' (inferType customProj)
let rawExprType ← MetaM.run' (inferType rawExpr)
if (← MetaM.run' (isDefEq customProjType rawExprType)) then
throwError "Invalid custom projection:{indentExpr customProj}\n\
Expression is not definitionally equal to {indentExpr rawExpr}"
else
throwError "Invalid custom projection:{indentExpr customProj}\n\
Expression has different type than {str ++ proj.strName}. Given type:\
{indentExpr customProjType}\nExpected type:{indentExpr rawExprType}\n\
Note: make sure order of implicit arguments is exactly the same."
| _ =>
_ ← MetaM.run' <| TermElabM.run' <| addTermInfo proj.newStx rawExpr
pure {proj with expr? := some rawExpr, projNrs := nrs} | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | findProjection | Auxiliary function for `getRawProjections`.
Generates the default projection, and looks for a custom projection declared by the user,
and replaces the default projection with the custom one, if it can find it. |
checkForUnusedCustomProjs (stx : Syntax) (str : Name) (projs : Array ParsedProjectionData) :
CoreM Unit := do
let nrCustomProjections := projs.toList.countP (·.isCustom)
let env ← getEnv
let customDeclarations := env.constants.map₂.foldl (init := #[]) fun xs nm _ =>
if (str ++ `Simps).isPrefixOf nm && !nm.isInternalDetail && !isReservedName env nm then
xs.push nm
else
xs
if nrCustomProjections < customDeclarations.size then
Linter.logLintIf linter.simpsUnusedCustomDeclarations stx m!"\
Not all of the custom declarations {customDeclarations} are used. Double check the \
spelling, and use `?` to get more information." | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | checkForUnusedCustomProjs | Checks if there are declarations in the current file in the namespace `{str}.Simps` that are
not used. |
findAutomaticProjectionsAux (str : Name) (proj : ParsedProjectionData) (args : Array Expr) :
TermElabM <| Option (Expr × Name) := do
if let some ⟨className, isNotation, findArgs⟩ :=
notationClassAttr.find? (← getEnv) proj.strName then
let findArgs ← unsafe evalConst findArgType findArgs
let classArgs ← try findArgs str className args
catch ex =>
trace[simps.debug] "Projection {proj.strName} is likely unrelated to the projection of \
{className}:\n{ex.toMessageData}"
return none
let classArgs ← classArgs.mapM fun e => match e with
| none => mkFreshExprMVar none
| some e => pure e
let classArgs := classArgs.map Arg.expr
let projName := (getStructureFields (← getEnv) className)[0]!
let projName := className ++ projName
let eStr := mkAppN (← mkConstWithLevelParams str) args
let eInstType ←
try withoutErrToSorry (elabAppArgs (← Term.mkConst className) #[] classArgs none true false)
catch ex =>
trace[simps.debug] "Projection doesn't have the right type for the automatic projection:\n\
{ex.toMessageData}"
return none
return ← withLocalDeclD `self eStr fun instStr ↦ do
trace[simps.debug] "found projection {proj.strName}. Trying to synthesize {eInstType}."
let eInst ← try synthInstance eInstType
catch ex =>
trace[simps.debug] "Didn't find instance:\n{ex.toMessageData}"
return none
let projExpr ← elabAppArgs (← Term.mkConst projName) #[] (classArgs.push <| .expr eInst)
none true false
let projExpr ← mkLambdaFVars (if isNotation then args.push instStr else args) projExpr
let projExpr ← instantiateMVars projExpr
return (projExpr, projName)
return none | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | findAutomaticProjectionsAux | If a structure has a field that corresponds to a coercion to functions or sets, or corresponds
to notation, find the custom projection that uses this coercion or notation.
Returns the custom projection and the name of the projection used.
We catch most errors this function causes, so that we don't fail if an unrelated projection has
an applicable name. (e.g. `Iso.inv`)
Implementation note: getting rid of TermElabM is tricky, since `Expr.mkAppOptM` doesn't allow to
keep metavariables around, which are necessary for `OutParam`. |
findAutomaticProjections (str : Name) (projs : Array ParsedProjectionData) :
CoreM (Array ParsedProjectionData) := do
let strDecl ← getConstInfo str
trace[simps.debug] "debug: {projs}"
MetaM.run' <| TermElabM.run' (s := {levelNames := strDecl.levelParams}) <|
forallTelescope strDecl.type fun args _ ↦ do
let projs ← projs.mapM fun proj => do
if let some (projExpr, projName) := ← findAutomaticProjectionsAux str proj args then
unless ← isDefEq projExpr proj.expr?.get! do
throwError "The projection {proj.newName} is not definitionally equal to an application \
of {projName}:{indentExpr proj.expr?.get!}\nvs{indentExpr projExpr}"
if proj.isCustom then
trace[simps.verbose] "Warning: Projection {proj.newName} is given manually by the user, \
but it can be generated automatically."
return proj
trace[simps.verbose] "Using {indentExpr projExpr}\nfor projection {proj.newName}."
return { proj with expr? := some projExpr }
return proj
return projs | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | findAutomaticProjections | Auxiliary function for `getRawProjections`.
Find custom projections, automatically found by simps.
These come from `DFunLike` and `SetLike` instances. |
getRawProjections (stx : Syntax) (str : Name) (traceIfExists : Bool := false)
(rules : Array ProjectionRule := #[]) (trc := false) :
CoreM (List Name × Array ProjectionData) := do
withOptions (· |>.updateBool `trace.simps.verbose (trc || ·)) <| do
let env ← getEnv
if let some data := (structureExt.getState env).find? str then
withOptions (· |>.updateBool `trace.simps.verbose (traceIfExists || ·)) <| do
trace[simps.verbose]
projectionsInfo data.2.toList "The projections for this structure have already been \
initialized by a previous invocation of `initialize_simps_projections` or `@[simps]`.\n\
Generated projections for" str
return data
trace[simps.verbose] "generating projection information for structure {str}."
trace[simps.debug] "Applying the rules {rules}."
let strDecl ← getConstInfo str
let rawLevels := strDecl.levelParams
let rawUnivs := rawLevels.map Level.param
let projs ← mkParsedProjectionData str
let projs ← applyProjectionRules projs rules
let projs ← projs.mapM fun proj ↦ findProjection str proj rawUnivs
checkForUnusedCustomProjs stx str projs
let projs ← findAutomaticProjections str projs
let projs := projs.map (·.toProjectionData)
let projs ← projs.mapM fun proj ↦ do
match (← MetaM.run' <| isProof proj.expr) with
| true => pure { proj with isDefault := false }
| false => pure proj
trace[simps.verbose] projectionsInfo projs.toList "generated projections for" str
structureExt.add str (rawLevels, projs)
trace[simps.debug] "Generated raw projection data:{indentD <| toMessageData (rawLevels, projs)}"
pure (rawLevels, projs)
library_note "custom simps projection" /--
You can specify custom projections for the `@[simps]` attribute.
To do this for the projection `MyStructure.originalProjection` by adding a declaration
`MyStructure.Simps.myProjection` that is definitionally equal to
`MyStructure.originalProjection` but has the projection in the desired (simp-normal) form.
Then you can call
```
initialize_simps_projections (originalProjection → myProjection, ...)
```
to register this projection. See `elabInitializeSimpsProjections` for more information.
You can also specify custom projections that are definitionally equal to a composite of multiple
projections. This is often desirable when extending structures (without `oldStructureCmd`).
`CoeFun` and notation class (like `Mul`) instances will be automatically used, if they
are definitionally equal to a projection of the structure (but not when they are equal to the
composite of multiple projections).
-/ | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | getRawProjections | Get the projections used by `simps` associated to a given structure `str`.
The returned information is also stored in the environment extension `Simps.structureExt`, which
is given to `str`. If `str` already has this attribute, the information is read from this
extension instead. See the documentation for this extension for the data this tactic returns.
The returned universe levels are the universe levels of the structure. For the projections there
are three cases
* If the declaration `{StructureName}.Simps.{projectionName}` has been declared, then the value
of this declaration is used (after checking that it is definitionally equal to the actual
projection. If you rename the projection name, the declaration should have the *new* projection
name.
* You can also declare a custom projection that is a composite of multiple projections.
* Otherwise, for every class with the `notation_class` attribute, and the structure has an
instance of that notation class, then the projection of that notation class is used for the
projection that is definitionally equal to it (if there is such a projection).
This means in practice that coercions to function types and sorts will be used instead of
a projection, if this coercion is definitionally equal to a projection. Furthermore, for
notation classes like `Mul` and `Zero` those projections are used instead of the
corresponding projection.
Projections for coercions and notation classes are not automatically generated if they are
composites of multiple projections (for example when you use `extend` without the
`oldStructureCmd` (does this exist?)).
* Otherwise, the projection of the structure is chosen.
For example: ``getRawProjections env `Prod`` gives the default projections.
```
([u, v], [(`fst, `(Prod.fst.{u v}), [0], true, false),
(`snd, `(@Prod.snd.{u v}), [1], true, false)])
```
Optionally, this command accepts three optional arguments:
* If `traceIfExists` the command will always generate a trace message when the structure already
has an entry in `structureExt`.
* The `rules` argument specifies whether projections should be added, renamed, used as prefix, and
not used by default.
* if `trc` is true, this tactic will trace information just as if
`set_option trace.simps.verbose true` was set. |
elabSimpsRule : Syntax → CommandElabM ProjectionRule
| `(simpsRule| $id1 → $id2) => return .rename id1.getId id1.raw id2.getId id2.raw
| `(simpsRule| - $id) => return .erase id.getId id.raw
| `(simpsRule| + $id) => return .add id.getId id.raw
| `(simpsRule| as_prefix $id) => return .prefix id.getId id.raw
| _ => Elab.throwUnsupportedSyntax | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | elabSimpsRule | Parse a rule for `initialize_simps_projections`. It is `<name>→<name>`, `-<name>`, `+<name>`
or `as_prefix <name>`. |
@[command_elab «initialize_simps_projections»] elabInitializeSimpsProjections : CommandElab
| stx@`(initialize_simps_projections $[?%$trc]? $id $[($stxs,*)]?) => do
let stxs := stxs.getD <| .mk #[]
let rules ← stxs.getElems.raw.mapM elabSimpsRule
let nm ← resolveGlobalConstNoOverload id
_ ← liftTermElabM <| addTermInfo id.raw <| ← mkConstWithLevelParams nm
_ ← liftCoreM <| getRawProjections stx nm true rules trc.isSome
| _ => throwUnsupportedSyntax | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | elabInitializeSimpsProjections | Function elaborating `initialize_simps_projections`. |
Config where
/-- Make generated lemmas simp lemmas -/
isSimp := true
/-- Other attributes to apply to generated lemmas. -/
attrs : Array Syntax := #[]
/-- simplify the right-hand side of generated simp-lemmas using `dsimp, simp`. -/
simpRhs := false
/-- TransparencyMode used to reduce the type in order to detect whether it is a structure. -/
typeMd := TransparencyMode.instances
/-- TransparencyMode used to reduce the right-hand side in order to detect whether it is a
constructor. Note: was `none` in Lean 3 -/
rhsMd := TransparencyMode.reducible
/-- Generated lemmas that are fully applied, i.e. generates equalities between applied functions.
Set this to `false` to generate equalities between functions. -/
fullyApplied := true
/-- List of types in which we are not recursing to generate simplification lemmas.
E.g. if we write `@[simps] def e : α × β ≃ β × α := ...` we will generate `e_apply` and not
`e_apply_fst`. -/
notRecursive := [`Prod, `PProd, `Opposite, `PreOpposite]
/-- Output debug messages. Not used much, use `set_option simps.debug true` instead. -/
debug := false
/-- The stem to use for the projection names. If `none`, the default, use the suffix of the
current declaration name, or the empty string if the declaration is an instance and the instance
is named according to the `inst` convention. -/
nameStem : Option String := none
deriving Inhabited | structure | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | Config | Configuration options for `@[simps]` |
@[deprecated "use `-fullyApplied` instead" (since := "2025-03-10")]
Config.asFn : Simps.Config where
fullyApplied := false | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | Config.asFn | Function elaborating `Config` -/
declare_command_config_elab elabSimpsConfig Config
/-- A common configuration for `@[simps]`: generate equalities between functions instead equalities
between fully applied Expressions. Replaced by `@[simps -fullyApplied]`. |
@[deprecated "use `-isSimp` instead" (since := "2025-03-10")]
Config.lemmasOnly : Config where
isSimp := false | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | Config.lemmasOnly | A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`.
Replaced by `@[simps -isSimp]`. |
partial _root_.Lean.Expr.instantiateLambdasOrApps (es : Array Expr) (e : Expr) : Expr :=
e.betaRev es.reverse true -- check if this is what I want | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | _root_.Lean.Expr.instantiateLambdasOrApps | `instantiateLambdasOrApps es e` instantiates lambdas in `e` by expressions from `es`.
If the length of `es` is larger than the number of lambdas in `e`,
then the term is applied to the remaining terms.
Also reduces head let-expressions in `e`, including those after instantiating all lambdas.
This is very similar to `expr.substs`, but this also reduces head let-expressions. |
getProjectionExprs (stx : Syntax) (tgt : Expr) (rhs : Expr) (cfg : Config) :
MetaM <| Array <| Expr × ProjectionData := do
let params := tgt.getAppArgs
if cfg.debug && !(← (params.zip rhs.getAppArgs).allM fun ⟨a, b⟩ ↦ isDefEq a b) then
throwError "unreachable code: parameters are not definitionally equal"
let str := tgt.getAppFn.constName?.getD default
let rhsArgs := rhs.getAppArgs.toList.drop params.size
let (rawUnivs, projDeclata) ← getRawProjections stx str
projDeclata.mapM fun proj ↦ do
let expr := proj.expr.instantiateLevelParams rawUnivs tgt.getAppFn.constLevels!
let proj := if ← isProof expr
then { proj with isDefault := false }
else proj
return (rhsArgs.getD (fallback := default) proj.projNrs.head!,
{ proj with
expr := expr.instantiateLambdasOrApps params
projNrs := proj.projNrs.tail })
variable (ref : Syntax) (univs : List Name) | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | getProjectionExprs | Get the projections of a structure used by `@[simps]` applied to the appropriate arguments.
Returns a list of tuples
```
(corresponding right-hand-side, given projection name, projection Expression,
future projection numbers, used by default, is prefix)
```
(where all fields except the first are packed in a `ProjectionData` structure)
one for each projection. The given projection name is the name for the projection used by the user
used to generate (and parse) projection names. For example, in the structure
Example 1: ``getProjectionExprs env `(α × β) `(⟨x, y⟩)`` will give the output
```
[(`(x), `fst, `(@Prod.fst.{u v} α β), [], true, false),
(`(y), `snd, `(@Prod.snd.{u v} α β), [], true, false)]
```
Example 2: ``getProjectionExprs env `(α ≃ α) `(⟨id, id, fun _ ↦ rfl, fun _ ↦ rfl⟩)``
will give the output
```
[(`(id), `apply, (Equiv.toFun), [], true, false),
(`(id), `symm_apply, (fun e ↦ e.symm.toFun), [], true, false),
...,
...]
``` |
addProjection (declName : Name) (type lhs rhs : Expr) (args : Array Expr)
(cfg : Config) : MetaM Unit := do
trace[simps.debug] "Planning to add the equality{indentD m!"{lhs} = ({rhs} : {type})"}"
let env ← getEnv
let lvl ← getLevel type
let mut (rhs, prf) := (rhs, mkAppN (mkConst `Eq.refl [lvl]) #[type, lhs])
if cfg.simpRhs then
let ctx ← mkSimpContext
let (rhs2, _) ← dsimp rhs ctx
if rhs != rhs2 then
trace[simps.debug] "`dsimp` simplified rhs to{indentExpr rhs2}"
else
trace[simps.debug] "`dsimp` failed to simplify rhs"
let (result, _) ← simp rhs2 ctx
if rhs2 != result.expr then
trace[simps.debug] "`simp` simplified rhs to{indentExpr result.expr}"
else
trace[simps.debug] "`simp` failed to simplify rhs"
rhs := result.expr
prf := result.proof?.getD prf
let eqAp := mkApp3 (mkConst `Eq [lvl]) type lhs rhs
let declType ← mkForallFVars args eqAp
let declValue ← mkLambdaFVars args prf
if (env.find? declName).isSome then -- diverging behavior from Lean 3
throwError "simps tried to add lemma{indentD m!"{.ofConstName declName} : {declType}"}\n\
to the environment, but it already exists."
trace[simps.verbose] "adding projection {declName}:{indentExpr declType}"
prependError "Failed to add projection lemma {declName}:" do
addDecl <| .thmDecl {
name := declName
levelParams := univs
type := declType
value := declValue }
inferDefEqAttr declName
addDeclarationRangesFromSyntax declName (← getRef) ref
TermElabM.run' do
_ ← addTermInfo (isBinder := true) ref <| ← mkConstWithLevelParams declName
if cfg.isSimp then
addSimpTheorem simpExtension declName true false .global <| eval_prio default
let attrs ← elabAttrs cfg.attrs
Elab.Term.applyAttributes declName attrs | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | addProjection | Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`,
`args` is the list of local constants occurring, and `univs` is the list of universe variables. |
partial headStructureEtaReduce (e : Expr) : MetaM Expr := do
let env ← getEnv
let (ctor, args) := e.getAppFnArgs
let some (.ctorInfo { induct := struct, numParams, ..}) := env.find? ctor | pure e
let some { fieldNames, .. } := getStructureInfo? env struct | pure e
let (params, fields) := args.toList.splitAt numParams -- fix if `Array.take` / `Array.drop` exist
trace[simps.debug]
"rhs is constructor application with params{indentD params}\nand fields {indentD fields}"
let field0 :: fieldsTail := fields | return e
let fieldName0 :: fieldNamesTail := fieldNames.toList | return e
let (fn0, fieldArgs0) := field0.getAppFnArgs
unless fn0 == struct ++ fieldName0 do
trace[simps.debug] "{fn0} ≠ {struct ++ fieldName0}"
return e
let (params', reduct :: _) := fieldArgs0.toList.splitAt numParams | unreachable!
unless params' == params do
trace[simps.debug] "{params'} ≠ {params}"
return e
trace[simps.debug] "Potential structure-eta-reduct:{indentExpr e}\nto{indentExpr reduct}"
let allArgs := params.toArray.push reduct
let isEta ← (fieldsTail.zip fieldNamesTail).allM fun (field, fieldName) ↦
if field.getAppFnArgs == (struct ++ fieldName, allArgs) then pure true else isProof field
unless isEta do return e
trace[simps.debug] "Structure-eta-reduce:{indentExpr e}\nto{indentExpr reduct}"
headStructureEtaReduce reduct | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | headStructureEtaReduce | Perform head-structure-eta-reduction on expression `e`. That is, if `e` is of the form
`⟨f.1, f.2, ..., f.n⟩` with `f` definitionally equal to `e`, then
`headStructureEtaReduce e = headStructureEtaReduce f` and `headStructureEtaReduce e = e` otherwise. |
partial addProjections (nm : NameStruct) (type lhs rhs : Expr)
(args : Array Expr) (mustBeStr : Bool) (cfg : Config)
(todo : List (String × Syntax)) (toApply : List Nat) : MetaM (Array Name) := do
trace[simps.debug] "Type of the Expression before normalizing: {type}"
withTransparency cfg.typeMd <| forallTelescopeReducing type fun typeArgs tgt ↦ withDefault do
trace[simps.debug] "Type after removing pi's: {tgt}"
let tgt ← whnfD tgt
trace[simps.debug] "Type after reduction: {tgt}"
let newArgs := args ++ typeArgs
let lhsAp := lhs.instantiateLambdasOrApps typeArgs
let rhsAp := rhs.instantiateLambdasOrApps typeArgs
let str := tgt.getAppFn.constName
trace[simps.debug] "todo: {todo}, toApply: {toApply}"
let todoNext := todo.filter (·.1 ≠ "")
let env ← getEnv
let stx? := todo.find? (·.1 == "") |>.map (·.2)
/- The syntax object associated to the projection we're making now (if any).
Note that we use `ref[0]` so that with `simps (config := ...)` we associate it to the word `simps`
instead of the application of the attribute to arguments. -/
let stxProj := stx?.getD ref[0]
let strInfo? := getStructureInfo? env str
/- Don't recursively continue if `str` is not a structure or if the structure is in
`notRecursive`. -/
if strInfo?.isNone ||
(todo.isEmpty && str ∈ cfg.notRecursive && !mustBeStr && toApply.isEmpty) then
if mustBeStr then
throwError "Invalid `simps` attribute. Target {str} is not a structure"
if !todoNext.isEmpty && str ∉ cfg.notRecursive then
let firstTodo := todoNext.head!.1
throwError "Invalid simp lemma {nm.update firstTodo false |>.toName}.\nProjection \
{(splitOnNotNumber firstTodo "_")[1]!} doesn't exist, \
because target {str} is not a structure."
if cfg.fullyApplied then
addProjection stxProj univs nm.toName tgt lhsAp rhsAp newArgs cfg
else
addProjection stxProj univs nm.toName type lhs rhs args cfg
return #[nm.toName]
let some (.inductInfo { isRec := false, ctors := [ctor], .. }) := env.find? str | unreachable!
trace[simps.debug] "{str} is a structure with constructor {ctor}."
let rhsEta ← headStructureEtaReduce rhsAp
let addThisProjection := stx?.isSome && toApply.isEmpty
if addThisProjection then
if cfg.fullyApplied then
addProjection stxProj univs nm.toName tgt lhsAp rhsEta newArgs cfg
else
addProjection stxProj univs nm.toName type lhs rhs args cfg
let rhsWhnf ← withTransparency cfg.rhsMd <| whnf rhsEta
trace[simps.debug] "The right-hand-side {indentExpr rhsAp}\n reduces to {indentExpr rhsWhnf}"
if !rhsWhnf.getAppFn.isConstOf ctor then
if cfg.rhsMd == .reducible && (mustBeStr || !todoNext.isEmpty || !toApply.isEmpty) then
trace[simps.debug] "Using relaxed reducibility."
... | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | addProjections | Derive lemmas specifying the projections of the declaration.
`nm`: name of the lemma
If `todo` is non-empty, it will generate exactly the names in `todo`.
`toApply` is non-empty after a custom projection that is a composition of multiple projections
was just used. In that case we need to apply these projections before we continue changing `lhs`.
`simpLemmas`: names of the simp lemmas added so far.(simpLemmas : Array Name) |
simpsTac (ref : Syntax) (nm : Name) (cfg : Config := {})
(todo : List (String × Syntax) := []) (trc := false) : AttrM (Array Name) :=
withOptions (· |>.updateBool `trace.simps.verbose (trc || ·)) <| do
let env ← getEnv
let some d := env.find? nm | throwError "Declaration {nm} doesn't exist."
let lhs : Expr := mkConst d.name <| d.levelParams.map Level.param
let todo := todo.eraseDups |>.map fun (proj, stx) ↦ (proj ++ "_", stx)
let mut cfg := cfg
let nm : NameStruct :=
{ parent := nm.getPrefix
components :=
if let some n := cfg.nameStem then
if n == "" then [] else [n]
else
let s := nm.lastComponentAsString
if (← isInstance nm) ∧ s.startsWith "inst" then [] else [s]}
MetaM.run' <| addProjections ref d.levelParams
nm d.type lhs (d.value?.getD default) #[] (mustBeStr := true) cfg todo [] | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | simpsTac | `simpsTac` derives `simp` lemmas for all (nested) non-Prop projections of the declaration.
If `todo` is non-empty, it will generate exactly the names in `todo`.
If `shortNm` is true, the generated names will only use the last projection name.
If `trc` is true, trace as if `trace.simps.verbose` is true. |
simpsTacFromSyntax (nm : Name) (stx : Syntax) : AttrM (Array Name) :=
match stx with
| `(attr| simps $[!%$bang]? $[?%$trc]? $attrs:simpsOptAttrOption $c:optConfig $[$ids]*) => do
let extraAttrs := match attrs with
| `(Attr.simpsOptAttrOption| (attr := $[$stxs],*)) => stxs
| _ => #[]
let cfg ← liftCommandElabM <| elabSimpsConfig c
let cfg := if bang.isNone then cfg else { cfg with rhsMd := .default, simpRhs := true }
let cfg := { cfg with attrs := cfg.attrs ++ extraAttrs }
let ids := ids.map fun x => (x.getId.eraseMacroScopes.lastComponentAsString, x.raw)
simpsTac stx nm cfg ids.toList trc.isSome
| _ => throwUnsupportedSyntax | def | Tactic | [
"Lean.Elab.Tactic.Simp",
"Lean.Elab.App",
"Mathlib.Tactic.Simps.NotationClass",
"Mathlib.Lean.Expr.Basic"
] | Mathlib/Tactic/Simps/Basic.lean | simpsTacFromSyntax | elaborate the syntax and run `simpsTac`. |
findArgType : Type := Name → Name → Array Expr → MetaM (Array (Option Expr)) | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | findArgType | The `@[notation_class]` attribute specifies that this is a notation class,
and this notation should be used instead of projections by `@[simps]`.
* This is only important if the projection is written differently using notation, e.g.
`+` uses `HAdd.hAdd`, not `Add.add` and `0` uses `OfNat.ofNat` not `Zero.zero`.
We also add it to non-heterogeneous notation classes, like `Neg`, but it doesn't do much for any
class that extends `Neg`.
* `@[notation_class* <projName> Simps.findCoercionArgs]` is used to configure the
`SetLike` and `DFunLike` coercions.
* The first name argument is the projection name we use as the key to search for this class
(default: name of first projection of the class).
* The second argument is the name of a declaration that has type
`findArgType` which is defined to be `Name → Name → Array Expr → MetaM (Array (Option Expr))`.
This declaration specifies how to generate the arguments of the notation class from the
arguments of classes that use the projection. -/
syntax (name := notation_class) "notation_class" "*"? (ppSpace ident)? (ppSpace ident)? : attr
open Lean Meta Elab Term
namespace Simps
/-- The type of methods to find arguments for automatic projections for `simps`.
We partly define this as a separate definition so that the unused arguments linter doesn't complain. |
defaultfindArgs : findArgType := fun _ className args ↦ do
let some classExpr := (← getEnv).find? className | throwError "no such class {className}"
let arity := classExpr.type.getNumHeadForalls
if arity == args.size then
return args.map some
else if h : args.size = 1 then
return .replicate arity args[0]
else
throwError "initialize_simps_projections cannot automatically find arguments for class \
{className}" | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | defaultfindArgs | Find arguments for a notation class |
copyFirst : findArgType := fun _ _ args ↦ return (args.push <| args[0]?.getD default).map some | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | copyFirst | Find arguments by duplicating the first argument. Used for `pow`. |
copySecond : findArgType := fun _ _ args ↦ return (args.push <| args[1]?.getD default).map some | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | copySecond | Find arguments by duplicating the first argument. Used for `smul`. |
nsmulArgs : findArgType := fun _ _ args ↦
return #[Expr.const `Nat [], args[0]?.getD default] ++ args |>.map some | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | nsmulArgs | Find arguments by prepending `ℕ` and duplicating the first argument. Used for `nsmul`. |
zsmulArgs : findArgType := fun _ _ args ↦
return #[Expr.const `Int [], args[0]?.getD default] ++ args |>.map some | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | zsmulArgs | Find arguments by prepending `ℤ` and duplicating the first argument. Used for `zsmul`. |
findZeroArgs : findArgType := fun _ _ args ↦
return #[some <| args[0]?.getD default, some <| mkRawNatLit 0] | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | findZeroArgs | Find arguments for the `Zero` class. |
findOneArgs : findArgType := fun _ _ args ↦
return #[some <| args[0]?.getD default, some <| mkRawNatLit 1] | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | findOneArgs | Find arguments for the `One` class. |
findCoercionArgs : findArgType := fun str className args ↦ do
let some classExpr := (← getEnv).find? className | throwError "no such class {className}"
let arity := classExpr.type.getNumHeadForalls
let eStr := mkAppN (← mkConstWithLevelParams str) args
let classArgs := .replicate (arity - 1) none
return #[some eStr] ++ classArgs | def | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | findCoercionArgs | Find arguments of a coercion class (`DFunLike` or `SetLike`) |
AutomaticProjectionData where
/-- `className` is the name of the class we are looking for. -/
className : Name
/-- `isNotation` is a Boolean that specifies whether this is notation
(false for the coercions `DFunLike` and `SetLike`). If this is set to true, we add the current
class as hypothesis during type-class synthesis. -/
isNotation := true
/-- The method to find the arguments of the class. -/
findArgs : Name := `Simps.defaultfindArgs
deriving Inhabited | structure | Tactic | [
"Mathlib.Init",
"Lean.Elab.Exception",
"Batteries.Lean.NameMapAttribute",
"Batteries.Tactic.Lint"
] | Mathlib/Tactic/Simps/NotationClass.lean | AutomaticProjectionData | Data needed to generate automatic projections. This data is associated to a name of a projection
in a structure that must be used to trigger the search. |
private TerminalReplacementOutcome where
| success (stx : TSyntax `tactic)
| remainingGoals (stx : TSyntax `tactic) (goals : List MessageData)
| error (stx : TSyntax `tactic) (msg : MessageData)
open Elab.Command | inductive | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | TerminalReplacementOutcome | Helper structure for the return type of the `test` function in `terminalReplacement`. |
terminalReplacement (oldTacticName newTacticName : String) (oldTacticKind : SyntaxNodeKind)
(newTactic : Syntax → MVarId → MetaM (TSyntax `tactic))
(reportFailure : Bool := true) (reportSuccess : Bool := false)
(reportSlowdown : Bool := false) (maxSlowdown : Float := 1) :
TacticAnalysis.Config := .ofComplex {
out := TerminalReplacementOutcome
ctx := Syntax
trigger _ stx := if stx.getKind == oldTacticKind
then .accept stx else .skip
test stx goal := do
let tac ← newTactic stx goal
try
let (goals, _) ← Lean.Elab.runTactic goal tac
match goals with
| [] => return .success tac
| _ => do
let goalsMessages ← goals.mapM fun g => do
let e ← instantiateMVars (← g.getType)
pure m!"⊢ {MessageData.ofExpr e}\n"
return .remainingGoals tac goalsMessages
catch _e =>
let name ← mkAuxDeclName `extracted
let ((sig, _, modules), _) ← (Mathlib.Tactic.ExtractGoal.goalSignature name goal).run
let imports := modules.toList.map (s!"import {·}")
return .error tac m!"{"\n".intercalate imports}\n\ntheorem {sig} := by\n fail_if_success {tac}\n {stx}"
tell stx _ oldHeartbeats new newHeartbeats :=
match new with
| .error _ msg =>
if reportFailure then
let msg :=
m!"`{newTacticName}` failed where `{oldTacticName}` succeeded.\n" ++
m!"Original tactic:{indentD stx}\n" ++
m!"Counterexample:{indentD msg}"
return msg
else
return none
| .remainingGoals newStx goals =>
if reportFailure then
let msg :=
m!"`{newTacticName}` left unsolved goals where `{oldTacticName}` succeeded.\n" ++
m!"Original tactic:{indentD stx}\n" ++
m!"Replacement tactic:{indentD newStx}\n" ++
m!"Unsolved goals:{indentD goals}"
return msg
else
return none
| .success newStx => do
let msg := if (← liftCoreM <| PrettyPrinter.ppTactic newStx).pretty = newTacticName then
m!"`{newTacticName}` can replace `{stx}`"
else
m!"`{newTacticName}` can replace `{stx}` using `{newStx}`"
... | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | terminalReplacement | Define a pass that tries replacing one terminal tactic with another.
`newTacticName` is a human-readable name for the tactic, for example "linarith".
This can be used to group messages together, so that `ring`, `ring_nf`, `ring1`, ...
all produce the same message.
`oldTacticKind` is the `SyntaxNodeKind` for the tactic's main parser,
for example `Mathlib.Tactic.linarith`.
`newTactic stx goal` selects the new tactic to try, which may depend on the old tactic invocation
in `stx` and the current `goal`. |
grindReplacementWith (tacticName : String) (tacticKind : SyntaxNodeKind)
(reportFailure : Bool := true) (reportSuccess : Bool := false)
(reportSlowdown : Bool := false) (maxSlowdown : Float := 1) :
TacticAnalysis.Config :=
terminalReplacement tacticName "grind" tacticKind (fun _ _ => `(tactic| grind))
reportFailure reportSuccess reportSlowdown maxSlowdown | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | grindReplacementWith | Define a pass that tries replacing a specific tactic with `grind`.
`tacticName` is a human-readable name for the tactic, for example "linarith".
This can be used to group messages together, so that `ring`, `ring_nf`, `ring1`, ...
all produce the same message.
`tacticKind` is the `SyntaxNodeKind` for the tactic's main parser,
for example `Mathlib.Tactic.linarith`. |
@[tacticAnalysis linter.tacticAnalysis.regressions.linarithToGrind,
inherit_doc linter.tacticAnalysis.regressions.linarithToGrind]
linarithToGrindRegressions := grindReplacementWith "linarith" `Mathlib.Tactic.linarith | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | linarithToGrindRegressions | null |
@[tacticAnalysis linter.tacticAnalysis.regressions.ringToGrind,
inherit_doc linter.tacticAnalysis.regressions.ringToGrind]
ringToGrindRegressions := grindReplacementWith "ring" `Mathlib.Tactic.RingNF.ring | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | ringToGrindRegressions | null |
@[tacticAnalysis linter.tacticAnalysis.regressions.omegaToCutsat,
inherit_doc linter.tacticAnalysis.regressions.omegaToCutsat]
omegaToCutsatRegressions :=
terminalReplacement "omega" "cutsat" ``Lean.Parser.Tactic.omega (fun _ _ => `(tactic| cutsat))
(reportSuccess := false) (reportFailure := true) | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | omegaToCutsatRegressions | null |
@[tacticAnalysis linter.tacticAnalysis.omegaToCutsat,
inherit_doc linter.tacticAnalysis.omegaToCutsat]
omegaToCutsat :=
terminalReplacement "omega" "cutsat" ``Lean.Parser.Tactic.omega (fun _ _ => `(tactic| cutsat))
(reportSuccess := true) (reportFailure := false) | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | omegaToCutsat | null |
@[tacticAnalysis linter.tacticAnalysis.rwMerge, inherit_doc linter.tacticAnalysis.rwMerge]
rwMerge : TacticAnalysis.Config := .ofComplex {
out := (List MVarId × Array Syntax)
ctx := (Array (Array Syntax))
trigger ctx stx :=
match stx with
| `(tactic| rw [$args,*]) => .continue ((ctx.getD #[]).push args)
| _ => if let some args := ctx then if args.size > 1 then .accept args else .skip else .skip
test ctx goal := withOptions (fun opts => opts.set `grind.warning false) do
let ctxT : Array (TSyntax `Lean.Parser.Tactic.rwRule) := ctx.flatten.map (⟨·⟩)
let tac ← `(tactic| rw [$ctxT,*])
try
let (goals, _) ← Lean.Elab.runTactic goal tac
return (goals, ctxT.map (↑·))
catch _e => -- rw throws an error if it fails to pattern-match.
return ([goal], ctxT.map (↑·))
tell _stx _old _oldHeartbeats new _newHeartbeats := pure <|
if new.1.isEmpty then
m!"Try this: rw {new.2}"
else none } | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | rwMerge | null |
@[tacticAnalysis linter.tacticAnalysis.mergeWithGrind,
inherit_doc linter.tacticAnalysis.mergeWithGrind]
mergeWithGrind : TacticAnalysis.Config where
run seq := do
if let #[(preCtx, preI), (_postCtx, postI)] := seq[0:2].array then
if postI.stx.getKind == ``Lean.Parser.Tactic.grind then
if let [goal] := preI.goalsBefore then
let goals ← try
preCtx.runTacticCode preI goal postI.stx
catch _e =>
pure [goal]
if goals.isEmpty then
logWarningAt preI.stx m!"'{preI.stx}; grind' can be replaced with 'grind'" | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | mergeWithGrind | null |
@[tacticAnalysis linter.tacticAnalysis.terminalToGrind,
inherit_doc linter.tacticAnalysis.terminalToGrind]
terminalToGrind : TacticAnalysis.Config where
run seq := do
let threshold := 3
let mut replaced : List (TSyntax `tactic) := []
let mut success := false
let mut oldHeartbeats := 0
let mut newHeartbeats := 0
for (ctx, i) in seq.reverse do
if replaced.length >= threshold - 1 && i.stx.getKind != ``Lean.Parser.Tactic.grind then
if let [goal] := i.goalsBefore then
let suffix := ⟨i.stx⟩ :: replaced
let seq ← `(tactic| $suffix.toArray;*)
let (oldGoals, heartbeats) ← withHeartbeats <|
try
ctx.runTacticCode i goal seq
catch _e =>
pure [goal]
if !oldGoals.isEmpty then
logWarningAt i.stx m!"Original tactics failed to solve the goal: {seq}"
oldHeartbeats := heartbeats
let tac ← `(tactic| grind)
let (newGoals, heartbeats) ← withHeartbeats <|
try
ctx.runTacticCode i goal tac
catch _e =>
pure [goal]
newHeartbeats := heartbeats
if newGoals.isEmpty then
success := true
else
break
else
break
replaced := ⟨i.stx⟩ :: replaced
if h : replaced.length >= threshold ∧ success then
let stx := replaced[0]
let seq ← `(tactic| $replaced.toArray;*)
logWarningAt stx m!"replace the proof with 'grind': {seq}"
if oldHeartbeats * 2 < newHeartbeats then
logWarningAt stx m!"'grind' is slower than the original: {oldHeartbeats} -> {newHeartbeats}" | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | terminalToGrind | null |
@[tacticAnalysis linter.tacticAnalysis.introMerge, inherit_doc linter.tacticAnalysis.introMerge]
introMerge : TacticAnalysis.Config := .ofComplex {
out := Option (TSyntax `tactic)
ctx := Array (Array Term)
trigger ctx stx :=
match stx with
| `(tactic| intro%$x $args*) => .continue ((ctx.getD #[]).push
<| if args.size = 0 then #[⟨mkHole x⟩] else args)
| _ => if let some args := ctx then if args.size > 1 then .accept args else .skip else .skip
test ctx goal := do
let ctxT := ctx.flatten
let tac ← `(tactic| intro $ctxT*)
try
let _ ← Lean.Elab.runTactic goal tac
return some tac
catch _e => -- if for whatever reason we can't run `intro` here.
return none
tell _stx _old _oldHeartbeats new _newHeartbeats := pure <|
if let some tac := new then m!"Try this: {tac}" else none} | def | Tactic | [
"Mathlib.Tactic.TacticAnalysis",
"Mathlib.Tactic.ExtractGoal",
"Mathlib.Tactic.MinImports",
"Lean.Elab.Tactic.Meta",
"Lean.Elab.Command"
] | Mathlib/Tactic/TacticAnalysis/Declarations.lean | introMerge | null |
@[to_additive /-- Addition is commutative -/]
mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := CommSemigroup.mul_comm
```
The transport tries to do the right thing in most cases using several
heuristics described below. However, in some cases it fails, and
requires manual intervention.
Use the `to_additive existing` syntax to use an existing additive declaration, instead of
automatically generating it.
Use the `(reorder := ...)` syntax to reorder the arguments in the generated additive declaration.
This is specified using cycle notation. For example `(reorder := 1 2, 5 6)` swaps the first two
arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move
the fifth argument before the third argument. This is mostly useful to translate declarations using
`Pow` to those using `SMul`.
Use the `(attr := ...)` syntax to apply attributes to both the multiplicative and the additive
version:
```
@[to_additive (attr := simp)] lemma mul_one' {G : Type*} [Group G] (x : G) : x * 1 = x := mul_one x
```
For `simps` this also ensures that some generated lemmas are added to the additive dictionary.
`@[to_additive (attr := to_additive)]` is a special case, where the `to_additive`
attribute is added to the generated lemma only, to additivize it again.
This is useful for lemmas about `Pow` to generate both lemmas about `SMul` and `VAdd`. Example:
```
@[to_additive (attr := to_additive VAdd_lemma, simp) SMul_lemma] | theorem | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | mul_comm' | An attribute that tells `@[to_additive]` that certain arguments of this definition are not
involved when using `@[to_additive]`.
This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another
fixed type occurs as one of these arguments. -/
syntax (name := to_additive_ignore_args) "to_additive_ignore_args" (ppSpace num)* : attr
/-- This attribute is deprecated. Use `to_additive (relevant_arg := ...)` instead. -/
syntax (name := to_additive_relevant_arg) "to_additive_relevant_arg " num : attr
/-- An attribute that stores all the declarations that deal with numeric literals on variable types.
Numeral literals occur in expressions without type information, so in order to decide whether `1`
needs to be changed to `0`, the context around the numeral is relevant.
Most numerals will be in an `OfNat.ofNat` application, though tactics can add numeral literals
inside arbitrary functions. By default we assume that we do not change numerals, unless it is
in a function application with the `to_additive_change_numeral` attribute.
`@[to_additive_change_numeral n₁ ...]` should be added to all functions that take one or more
numerals as argument that should be changed if `additiveTest` succeeds on the first argument,
i.e. when the numeral is only translated if the first argument is a variable
(or consists of variables).
The arguments `n₁ ...` are the positions of the numeral arguments (starting counting from 1). -/
syntax (name := to_additive_change_numeral) "to_additive_change_numeral" (ppSpace num)* : attr
/-- The `to_additive_dont_translate` attribute, used to specify types that should be translated by
`to_additive`, but its operations should remain multiplicative.
Usage notes:
* Apply this together with the `to_additive` attribute.
* The name generation of `to_additive` is not aware that the operations on this type should not be
translated, so you generally have to specify the name itself, if the name should remain
multiplicative.
-/
syntax (name := to_additive_dont_translate) "to_additive_dont_translate" : attr
/-- An `attr := ...` option for `to_additive`. -/
syntax toAdditiveAttrOption := &"attr" " := " Parser.Term.attrInstance,*
/--
`reorder := ...` reorders the arguments/hypotheses in the generated declaration.
It uses cycle notation. For example `(reorder := 1 2, 5 6)` swaps the first two
arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move
the fifth argument before the third argument. This is used in `to_dual` to swap the arguments in
`≤`, `<` and `⟶`. It is also used in `to_additive` to translate from `^` to `•`.
-/
syntax toAdditiveReorderOption := &"reorder" " := " (num+),+
/--
the `relevant_arg := ...` option tells which argument is a type where this declaration uses the
multiplicative structure. This is inferred automatically using the function `findMultiplicativeArg`,
but it can also be overwritten using this syntax.
If there are multiple arguments with a multiplicative structure, we typically tag the first one.
If this argument contains a fixed type, this declaration will not be additivized.
See the Heuristics section of the `to_additive` doc-string for more details.
If a declaration is not tagged, it is presumed that the first argument is relevant.
To indicate that there is no relevant argument, set it to a number that is out of bounds,
i.e. larger than the number of arguments, e.g. `(relevant_arg := 100)`.
Implementation note: we only allow exactly 1 relevant argument, even though some declarations
(like `Prod.instGroup`) have multiple arguments with a multiplicative structure on it.
The reason is that whether we additivize a declaration is an all-or-nothing decision, and
we will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α`
anyway.
-/
syntax toAdditiveRelevantOption := &"relevant_arg" " := " num
/--
`dont_translate := ...` takes a list of type variables (separated by spaces) that should not be
considered for translation. For example in
```
lemma foo {α β : Type} [Group α] [Group β] (a : α) (b : β) : a * a⁻¹ = 1 ↔ b * b⁻¹ = 1
```
we can choose to only additivize `α` by writing `to_additive (dont_translate := β)`.
-/
syntax toAdditiveDontTranslateOption := &"dont_translate" " := " ident+
/-- Options to `to_additive`. -/
syntax toAdditiveOption := "(" toAdditiveAttrOption <|> toAdditiveReorderOption <|>
toAdditiveRelevantOption <|> toAdditiveDontTranslateOption ")"
/-- An `existing` or `self` name hint for `to_additive`. -/
syntax toAdditiveNameHint := (ppSpace (&"existing" <|> &"self"))?
/-- Remaining arguments of `to_additive`. -/
syntax toAdditiveRest :=
toAdditiveNameHint (ppSpace toAdditiveOption)* (ppSpace ident)? (ppSpace (str <|> docComment))?
/-- The attribute `to_additive` can be used to automatically transport theorems
and definitions (but not inductive types and structures) from a multiplicative
theory to an additive theory.
To use this attribute, just write:
```
@[to_additive]
theorem mul_comm' {α} [CommSemigroup α] (x y : α) : x * y = y * x := mul_comm x y
```
This code will generate a theorem named `add_comm'`. It is also
possible to manually specify the name of the new declaration:
```
@[to_additive add_foo]
theorem foo := sorry
```
An existing documentation string will _not_ be automatically used, so if the theorem or definition
has a doc string, a doc string for the additive version should be passed explicitly to
`to_additive`.
```
/-- Multiplication is commutative |
Pow_lemma ... :=
```
In the above example, the `simp` is added to all 3 lemmas. All other options to `to_additive`
(like the generated name or `(reorder := ...)`) are not passed down,
and can be given manually to each individual `to_additive` call. | lemma | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | Pow_lemma | null |
findTranslation? (env : Environment) : Name → Option Name :=
(ToAdditive.translations.getState env).find? | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | findTranslation | Linter, mostly used by `@[to_additive]`, that checks that the source declaration doesn't have
certain attributes -/
register_option linter.existingAttributeWarning : Bool := {
defValue := true
descr := "Linter, mostly used by `@[to_additive]`, that checks that the source declaration \
doesn't have certain attributes" }
/-- Linter to check that the `to_additive` attribute is not given manually -/
register_option linter.toAdditiveGenerateName : Bool := {
defValue := true
descr := "Linter used by `@[to_additive]` that checks if `@[to_additive]` automatically \
generates the user-given name" }
/-- Linter to check whether the user correctly specified that the additive declaration already
exists -/
register_option linter.toAdditiveExisting : Bool := {
defValue := true
descr := "Linter used by `@[to_additive]` that checks whether the user correctly specified that
the additive declaration already exists" }
/-- Linter to check that the `relevant_arg` attribute is not given manually -/
register_option linter.toAdditiveRelevantArg : Bool := {
defValue := true
descr := "Linter to check that the `relevant_arg` attribute is not given manually." }
@[inherit_doc to_additive_ignore_args]
initialize ignoreArgsAttr : NameMapExtension (List Nat) ←
registerNameMapAttribute {
name := `to_additive_ignore_args
descr :=
"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized."
add := fun _ stx ↦ do
let ids ← match stx with
| `(attr| to_additive_ignore_args $[$ids:num]*) => pure <| ids.map (·.1.isNatLit?.get!)
| _ => throwUnsupportedSyntax
return ids.toList }
/-- An extension that stores all the declarations that need their arguments reordered when
applying `@[to_additive]`. It is applied using the `to_additive (reorder := ...)` syntax. -/
initialize reorderAttr : NameMapExtension (List (List Nat)) ←
registerNameMapExtension _
@[inherit_doc to_additive_relevant_arg]
initialize relevantArgAttr : NameMapExtension Nat ←
registerNameMapAttribute {
name := `to_additive_relevant_arg
descr := "Auxiliary attribute for `to_additive` stating \
which arguments are the types with a multiplicative structure."
add := fun
| _, stx@`(attr| to_additive_relevant_arg $id) => do
Linter.logLintIf linter.toAdditiveRelevantArg stx
m!"This attribute is deprecated. Use `@[to_additive (relevant_arg := ...)]` instead."
pure <| id.getNat.pred
| _, _ => throwUnsupportedSyntax }
@[inherit_doc to_additive_dont_translate]
initialize dontTranslateAttr : NameMapExtension Unit ←
registerNameMapAttribute {
name := `to_additive_dont_translate
descr := "Auxiliary attribute for `to_additive` stating \
that the operations on this type should not be translated."
add := fun
| _, `(attr| to_additive_dont_translate) => return
| _, _ => throwUnsupportedSyntax }
@[inherit_doc to_additive_change_numeral]
initialize changeNumeralAttr : NameMapExtension (List Nat) ←
registerNameMapAttribute {
name := `to_additive_change_numeral
descr :=
"Auxiliary attribute for `to_additive` that stores functions that have numerals as argument."
add := fun
| _, `(attr| to_additive_change_numeral $[$arg]*) =>
pure <| arg.map (·.1.isNatLit?.get!.pred) |>.toList
| _, _ => throwUnsupportedSyntax }
/-- Maps multiplicative names to their additive counterparts. -/
initialize translations : NameMapExtension Name ← registerNameMapExtension _
/-- Get the multiplicative → additive translation for the given name. |
findPrefixTranslation (env : Environment) (nm : Name) : Name :=
nm.mapPrefix (findTranslation? env) | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | findPrefixTranslation | Get the multiplicative → additive translation for the given name,
falling back to translating a prefix of the name if the full name can't be translated.
This allows translating automatically generated declarations such as `IsRegular.casesOn`. |
insertTranslation (src tgt : Name) (failIfExists := true) : CoreM Unit := do
if let some tgt' := findTranslation? (← getEnv) src then
if failIfExists then
throwError "The translation {src} ↦ {tgt'} already exists"
else
trace[to_additive] "The translation {src} ↦ {tgt'} already exists"
return
modifyEnv (ToAdditive.translations.addEntry · (src, tgt))
trace[to_additive] "Added translation {src} ↦ {tgt}" | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | insertTranslation | Add a (multiplicative → additive) name translation to the translations map. |
ArgInfo where
/-- The arguments that should be reordered by `to_additive`, using cycle notation. -/
reorder : List (List Nat) := []
/-- The argument used to determine whether this constant should be translated. -/
relevantArg : Nat := 0 | structure | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | ArgInfo | `ArgInfo` stores information about how a constant should be translated. |
insertTranslationAndInfo (src tgt : Name) (argInfo : ArgInfo) (failIfExists := true) :
CoreM Unit := do
insertTranslation src tgt failIfExists
if argInfo.reorder != [] then
trace[to_additive] "@[to_additive] will reorder the arguments of {tgt} by {argInfo.reorder}."
reorderAttr.add src argInfo.reorder
if argInfo.relevantArg != 0 then
trace[to_additive_detail] "Setting relevant_arg for {src} to be {argInfo.relevantArg}."
relevantArgAttr.add src argInfo.relevantArg | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | insertTranslationAndInfo | Add a name translation to the translations map and add the `argInfo` information to `src`. |
Config : Type where
/-- View the trace of the to_additive procedure.
Equivalent to `set_option trace.to_additive true`. -/
trace : Bool := false
/-- The name of the target (the additive declaration). -/
tgt : Name := Name.anonymous
/-- An optional doc string. -/
doc : Option String := none
/-- If `allowAutoName` is `false` (default) then
`@[to_additive]` will check whether the given name can be auto-generated. -/
allowAutoName : Bool := false
/-- The arguments that should be reordered by `to_additive`, using cycle notation. -/
reorder : List (List Nat) := []
/-- The argument used to determine whether this constant should be translated. -/
relevantArg? : Option Nat := none
/-- The attributes which we want to give to both the multiplicative and additive versions.
For `simps` this will also add generated lemmas to the translation dictionary. -/
attrs : Array Syntax := #[]
/-- A list of type variables that should not be translated by `to_additive`. -/
dontTranslate : List Ident := []
/-- The `Syntax` element corresponding to the original multiplicative declaration
(or the `to_additive` attribute if it is added later),
which we need for adding definition ranges. -/
ref : Syntax
/-- An optional flag stating that the additive declaration already exists.
If this flag is wrong about whether the additive declaration exists, `to_additive` will
raise a linter error.
Note: the linter will never raise an error for inductive types and structures. -/
existing : Bool := false
/-- An optional flag stating that the target of the translation is the target itself.
This can be used to reorder arguments, such as in
`attribute [to_dual self (reorder := 3 4)] LE.le`.
It can also be used to give a hint to `additiveTest`, such as in
`attribute [to_additive self] Unit`.
If `self := true`, we should also have `existing := true`. -/
self : Bool := false
deriving Repr
attribute [nolint unusedArguments] instReprConfig.repr | structure | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | Config | `Config` is the type of the arguments that can be provided to `to_additive`. |
etaExpandN (n : Nat) (e : Expr) : MetaM Expr := do
forallBoundedTelescope (← inferType e) (some n) fun xs _ ↦ mkLambdaFVars xs (mkAppN e xs) | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | etaExpandN | Eta expands `e` at most `n` times. |
expand (e : Expr) : MetaM Expr := do
let env ← getEnv
let reorderFn : Name → List (List ℕ) := fun nm ↦ (reorderAttr.find? env nm |>.getD [])
let e₂ ← Lean.Meta.transform (input := e) (skipConstInApp := true)
(post := fun e => return .done e) fun e ↦
e.withApp fun f args ↦ do
match f with
| .proj n i s =>
let some info := getStructureInfo? (← getEnv) n | return .continue -- e.g. if `n` is `Exists`
let some projName := info.getProjFn? i | unreachable!
if findTranslation? env projName |>.isNone then
return .continue
return .visit <| (← whnfD (← inferType s)).withApp fun sf sargs ↦
mkAppN (mkApp (mkAppN (.const projName sf.constLevels!) sargs) s) args
| .const c _ =>
let reorder := reorderFn c
if reorder.isEmpty then
return .continue
let needed_n := reorder.flatten.foldr Nat.max 0 + 1
if needed_n ≤ args.size then
return .continue
else
let e' ← etaExpandN (needed_n - args.size) e
trace[to_additive_detail] "expanded {e} to {e'}"
return .continue e'
| _ => return .continue
if e != e₂ then
trace[to_additive_detail] "expand:\nBefore: {e}\nAfter: {e₂}"
return e₂ | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | expand | `e.expand` eta-expands all expressions that have as head a constant `n` in `reorder`.
They are expanded until they are applied to one more argument than the maximum in `reorder.find n`.
It also expands all kernel projections that have as head a constant `n` in `reorder`. |
unsafe additiveTestUnsafe (env : Environment) (e : Expr) (dontTranslate : Array FVarId) :
Option (Name ⊕ FVarId) :=
let rec visit (e : Expr) (inApp := false) : OptionT (StateM (PtrSet Expr)) (Name ⊕ FVarId) := do
if e.isConst then
if (dontTranslateAttr.find? env e.constName).isNone &&
(inApp || (findTranslation? env e.constName).isSome) then
failure
else
return .inl e.constName
if (← get).contains e then
failure
modify fun s => s.insert e
match e with
| x@(.app e a) =>
visit e true <|> do
guard !x.isConstantApplication
if let some n := e.getAppFn.constName? then
if let some l := ignoreArgsAttr.find? env n then
if e.getAppNumArgs + 1 ∈ l then
failure
visit a
| .lam _ _ t _ => visit t
| .forallE _ _ t _ => visit t
| .letE _ _ e body _ => visit e <|> visit body
| .mdata _ b => visit b
| .proj _ _ b => visit b
| .fvar fvarId => if dontTranslate.contains fvarId then return .inr fvarId else failure
| _ => failure
Id.run <| (visit e).run' mkPtrSet | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | additiveTestUnsafe | Implementation function for `additiveTest`.
Failure means that in that subexpression there is no constant that blocks `e` from being translated.
We cache previous applications of the function, using an expression cache using ptr equality
to avoid visiting the same subexpression many times. Note that we only need to cache the
expressions without taking the value of `inApp` into account, since `inApp` only matters when
the expression is a constant. However, for this reason we have to make sure that we never
cache constant expressions, so that's why the `if`s in the implementation are in this order.
Note that this function is still called many times by `applyReplacementFun`
and we're not remembering the cache between these calls. |
additiveTest (env : Environment) (e : Expr) (dontTranslate : Array FVarId := #[]) :
Option (Name ⊕ FVarId) :=
unsafe additiveTestUnsafe env e dontTranslate | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | additiveTest | `additiveTest e` tests whether the expression `e` contains a constant
`nm` that is not applied to any arguments, and such that `translations.find?[nm] = none`.
This is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform
constants if `additiveTest` applied to their relevant argument returns `true`.
This means we will replace expression applied to e.g. `α` or `α × β`, but not when applied to
e.g. `ℕ` or `ℝ × α`.
We ignore all arguments specified by the `ignore` `NameMap`. |
_root_.List.swapFirstTwo {α : Type _} : List α → List α
| [] => []
| [x] => [x]
| x::y::l => y::x::l | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | _root_.List.swapFirstTwo | Swap the first two elements of a list |
changeNumeral : Expr → Expr
| .lit (.natVal 1) => mkRawNatLit 0
| e => e | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | changeNumeral | Change the numeral `nat_lit 1` to the numeral `nat_lit 0`.
Leave all other expressions unchanged. |
applyReplacementFun (e : Expr) (dontTranslate : Array FVarId := #[]) : MetaM Expr := do
let e' := aux (← getEnv) (← getBoolOption `trace.to_additive_detail) (← expand e)
e'.forEach fun
| .const n .. => do
if !(← hasConst (skipRealize := false) n) && isReservedName (← getEnv) n then
executeReservedNameAction n
| _ => pure ()
return e'
where /-- Implementation of `applyReplacementFun`. -/
aux (env : Environment) (trace : Bool) : Expr → Expr :=
let reorderFn : Name → List (List ℕ) := fun nm ↦ (reorderAttr.find? env nm |>.getD [])
let relevantArg : Name → ℕ := fun nm ↦ (relevantArgAttr.find? env nm).getD 0
Lean.Expr.replaceRec fun r e ↦ Id.run do
if trace then
dbg_trace s!"replacing at {e}"
match e with
| .const n₀ ls₀ => do
let n₁ := findPrefixTranslation env n₀
let ls₁ : List Level := if 0 ∈ (reorderFn n₀).flatten then ls₀.swapFirstTwo else ls₀
if trace then
if n₀ != n₁ then
dbg_trace s!"changing {n₀} to {n₁}"
if 0 ∈ (reorderFn n₀).flatten then
dbg_trace s!"reordering the universe variables from {ls₀} to {ls₁}"
return some <| .const n₁ ls₁
| .app g x => do
let mut gf := g.getAppFn
if gf.isBVar && x.isLit then
if trace then
dbg_trace s!"applyReplacementFun: Variables applied to numerals are not changed {g.app x}"
return some <| g.app x
let mut gAllArgs := e.getAppArgs
let some nm := gf.constName? | return mkAppN (← r gf) (← gAllArgs.mapM r)
/- Test if the head should not be replaced. -/
let relevantArgId := relevantArg nm
if h : relevantArgId < gAllArgs.size then
if let some fxd := additiveTest env gAllArgs[relevantArgId] dontTranslate then
if trace then
match fxd with
| .inl fxd => dbg_trace s!"The application of {nm} contains the fixed type \
{fxd}, so it is not changed."
| .inr _ => dbg_trace s!"The application of {nm} contains a fixed \
variable so it is not changed."
else
gf ← r gf
/- Test if arguments should be reordered. -/
let reorder := reorderFn nm
if !reorder.isEmpty then
gAllArgs := gAllArgs.permute! reorder
if trace then
dbg_trace s!"reordering the arguments of {nm} using the cyclic permutations {reorder}"
... | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | applyReplacementFun | `applyReplacementFun e` replaces the expression `e` with its additive counterpart.
It translates each identifier (inductive type, defined function etc) in an expression, unless
* The identifier occurs in an application with first argument `arg`; and
* `test arg` is false.
However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`
is tested, instead of the first argument.
It will also reorder arguments of certain functions, using `reorderFn`:
e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorderFn g = some [1]`. |
renameBinderNames (src : Expr) : Expr :=
src.mapForallBinderNames fun
| .str p s => .str p (guessName s)
| n => n | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | renameBinderNames | Rename binder names in pi type. |
reorderForall (reorder : List (List Nat)) (src : Expr) : MetaM Expr := do
if let some maxReorder := reorder.flatten.max? then
forallBoundedTelescope src (some (maxReorder + 1)) fun xs e => do
if xs.size = maxReorder + 1 then
mkForallFVars (xs.permute! reorder) e
else
throwError "the permutation\n{reorder}\nprovided by the `(reorder := ...)` option is \
out of bounds, the type{indentExpr src}\nhas only {xs.size} arguments"
else
return src | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | reorderForall | Reorder pi-binders. See doc of `reorderAttr` for the interpretation of the argument |
reorderLambda (reorder : List (List Nat)) (src : Expr) : MetaM Expr := do
if let some maxReorder := reorder.flatten.max? then
let maxReorder := maxReorder + 1
lambdaBoundedTelescope src maxReorder fun xs e => do
if xs.size = maxReorder then
mkLambdaFVars (xs.permute! reorder) e
else
forallBoundedTelescope (← inferType e) (maxReorder - xs.size) fun ys _ => do
mkLambdaFVars ((xs ++ ys).permute! reorder) (mkAppN e ys)
else
return src | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | reorderLambda | Reorder lambda-binders. See doc of `reorderAttr` for the interpretation of the argument |
applyReplacementForall (dontTranslate : List Nat) (e : Expr) :
MetaM Expr := do
if let some maxDont := dontTranslate.max? then
forallBoundedTelescope e (some (maxDont + 1)) fun xs e => do
let xs := xs.map (·.fvarId!)
let dontTranslate := dontTranslate.filterMap (xs[·]?) |>.toArray
let mut e ← applyReplacementFun e dontTranslate
for x in xs.reverse do
let decl ← x.getDecl
let xType ← applyReplacementFun decl.type dontTranslate
e := .forallE decl.userName xType (e.abstract #[.fvar x]) decl.binderInfo
return e
else
applyReplacementFun e #[] | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | applyReplacementForall | Run `applyReplacementFun` on an expression `∀ x₁ .. xₙ, e`,
making sure not to translate type-classes on `xᵢ` if `i` is in `dontTranslate`. |
applyReplacementLambda (dontTranslate : List Nat) (e : Expr) :
MetaM Expr := do
if let some maxDont := dontTranslate.max? then
lambdaBoundedTelescope e (maxDont + 1) fun xs e => do
let xs := xs.map (·.fvarId!)
let dontTranslate := dontTranslate.filterMap (xs[·]?) |>.toArray
let mut e ← applyReplacementFun e dontTranslate
for x in xs.reverse do
let decl ← x.getDecl
let xType ← applyReplacementFun decl.type dontTranslate
e := .lam decl.userName xType (e.abstract #[.fvar x]) decl.binderInfo
return e
else
applyReplacementFun e #[] | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | applyReplacementLambda | Run `applyReplacementFun` on an expression `fun x₁ .. xₙ ↦ e`,
making sure not to translate type-classes on `xᵢ` if `i` is in `dontTranslate`. |
declUnfoldAuxLemmas (decl : ConstantInfo) : MetaM ConstantInfo := do
let mut decl := decl
decl := decl.updateType <| ← unfoldAuxLemmas decl.type
if let some v := decl.value? then
trace[to_additive] "value before unfold:{indentExpr v}"
decl := decl.updateValue <| ← unfoldAuxLemmas v
trace[to_additive] "value after unfold:{indentExpr decl.value!}"
else if let .opaqueInfo info := decl then -- not covered by `value?`
decl := .opaqueInfo { info with value := ← unfoldAuxLemmas info.value }
return decl | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | declUnfoldAuxLemmas | Unfold auxlemmas in the type and value. |
getDontTranslates (given : List Ident) (type : Expr) : MetaM (List Nat) := do
forallTelescope type fun xs _ => do
given.mapM fun id => withRef id.raw <| do
let fvarId ← getFVarFromUserName id.getId
return (xs.idxOf? fvarId).get! | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | getDontTranslates | Given a list of variable local identifiers that shouldn't be translated,
determine the arguments that shouldn't be translated.
TODO: Currently, this function doesn't deduce any `dont_translate` types from `type`.
In the future we would like that the presence of `MonoidAlgebra k G` will automatically
flag `k` as a type to not be translated. |
updateDecl (tgt : Name) (srcDecl : ConstantInfo) (reorder : List (List Nat))
(dont : List Ident) : MetaM ConstantInfo := do
let mut decl := srcDecl.updateName tgt
if 0 ∈ reorder.flatten then
decl := decl.updateLevelParams decl.levelParams.swapFirstTwo
let dont ← getDontTranslates dont srcDecl.type
decl := decl.updateType <| ← reorderForall reorder <| ← applyReplacementForall dont <|
renameBinderNames decl.type
if let some v := decl.value? then
decl := decl.updateValue <| ← reorderLambda reorder <| ← applyReplacementLambda dont v
else if let .opaqueInfo info := decl then -- not covered by `value?`
decl := .opaqueInfo { info with
value := ← reorderLambda reorder <| ← applyReplacementLambda dont info.value }
return decl | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | updateDecl | Run applyReplacementFun on the given `srcDecl` to make a new declaration with name `tgt` |
declAbstractNestedProofs (decl : ConstantInfo) : MetaM ConstantInfo := do
if decl matches .defnInfo _ then
return decl.updateValue <| ← withDeclNameForAuxNaming decl.name do
Meta.abstractNestedProofs decl.value!
else
return decl | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | declAbstractNestedProofs | Abstracts the nested proofs in the value of `decl` if it is a def. |
findTargetName (env : Environment) (src pre tgt_pre : Name) : CoreM Name :=
/- This covers auxiliary declarations like `match_i` and `proof_i`. -/
if let some post := pre.isPrefixOf? src then
return tgt_pre ++ post
/- This covers equation lemmas (for other declarations). -/
else if let some post := privateToUserName? src then
match findTranslation? env post.getPrefix with
| none => return src
| some addName => return src.updatePrefix <| mkPrivateName env addName
else if src.hasMacroScopes then
mkFreshUserName src.eraseMacroScopes
else
throwError "internal @[to_additive] error." | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | findTargetName | Find the target name of `pre` and all created auxiliary declarations. |
findAuxDecls (e : Expr) (pre : Name) : NameSet :=
e.foldConsts ∅ fun n l ↦
if n.getPrefix == pre || isPrivateName n || n.hasMacroScopes then
l.insert n
else
l | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | findAuxDecls | Returns a `NameSet` of all auxiliary constants in `e` that might have been generated
when adding `pre` to the environment.
Examples include `pre.match_5` and
`_private.Mathlib.MyFile.someOtherNamespace.someOtherDeclaration._eq_2`.
The last two examples may or may not have been generated by this declaration.
The last example may or may not be the equation lemma of a declaration with the `@[to_additive]`
attribute. We will only translate it if it has the `@[to_additive]` attribute.
Note that this function would return `proof_nnn` aux lemmas if
we hadn't unfolded them in `declUnfoldAuxLemmas`. |
partial transformDeclAux
(cfg : Config) (pre tgt_pre : Name) : Name → CoreM Unit := fun src ↦ do
let env ← getEnv
trace[to_additive_detail] "visiting {src}"
if (findTranslation? env src).isSome && src != pre then
return
if src != pre && !src.isInternalDetail then
throwError "The declaration {pre} depends on the declaration {src} which is in the namespace \
{pre}, but does not have the `@[to_additive]` attribute. This is not supported.\n\
Workaround: move {src} to a different namespace."
let tgt ← findTargetName env src pre tgt_pre
if env.contains tgt then
if tgt == src then
trace[to_additive_detail] "Auxiliary declaration {src} will be translated to itself."
else
trace[to_additive_detail] "Already visited {tgt} as translation of {src}."
return
let srcDecl ← getConstInfo src
let srcDecl ← MetaM.run' do declUnfoldAuxLemmas srcDecl
for n in findAuxDecls srcDecl.type pre do
transformDeclAux cfg pre tgt_pre n
if let some value := srcDecl.value? then
for n in findAuxDecls value pre do
transformDeclAux cfg pre tgt_pre n
if let .opaqueInfo {value, ..} := srcDecl then
for n in findAuxDecls value pre do
transformDeclAux cfg pre tgt_pre n
if !pre.isPrefixOf src then
insertTranslation src tgt
let trgDecl : ConstantInfo ← MetaM.run' <|
if src == pre then
updateDecl tgt srcDecl cfg.reorder cfg.dontTranslate
else
updateDecl tgt srcDecl [] []
let value ← match trgDecl with
| .thmInfo { value, .. } | .defnInfo { value, .. } | .opaqueInfo { value, .. } => pure value
| _ => throwError "Expected {tgt} to have a value."
trace[to_additive] "generating\n{tgt} : {trgDecl.type} :=\n {value}"
try
MetaM.run' <| check value
catch
| Exception.error _ msg => throwError "@[to_additive] failed. \
The translated value is not type correct. For help, see the docstring \
of `to_additive.attr`, section `Troubleshooting`. \
Failed to add declaration\n{tgt}:\n{msg}"
| _ => panic! "unreachable"
let trgDecl ← MetaM.run' <| declAbstractNestedProofs trgDecl
/- If `src` is explicitly marked as `noncomputable`, then add the new decl as a declaration but
do not compile it, and mark is as noncomputable. Otherwise, only log errors in compiling if `src`
has executable code.
Note that `noncomputable section` does not explicitly mark noncomputable definitions as
... | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | transformDeclAux | Transform the declaration `src` and all declarations `pre._proof_i` occurring in `src`
using the transforms dictionary.
`replace_all`, `trace`, `ignore` and `reorder` are configuration options.
`pre` is the declaration that got the `@[to_additive]` attribute and `tgt_pre` is the target of this
declaration. |
copyInstanceAttribute (src tgt : Name) : CoreM Unit := do
if let some prio ← getInstancePriority? src then
let attr_kind := (← getInstanceAttrKind? src).getD .global
trace[to_additive_detail] "Making {tgt} an instance with priority {prio}."
addInstance tgt attr_kind prio |>.run' | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | copyInstanceAttribute | Copy the instance attribute in a `to_additive`
[todo] it seems not to work when the `to_additive` is added as an attribute later. |
warnAttrCore (stx : Syntax) (f : Environment → Name → Bool)
(thisAttr attrName src tgt : Name) : CoreM Unit := do
if f (← getEnv) src then
Linter.logLintIf linter.existingAttributeWarning stx <|
m!"The source declaration {src} was given attribute {attrName} before calling @[{thisAttr}]. \
The preferred method is to use `@[{thisAttr} (attr := {attrName})]` to apply the \
attribute to both {src} and the target declaration {tgt}." ++
if thisAttr == `to_additive then
m!"\nSpecial case: If this declaration was generated by @[to_additive] \
itself, you can use @[to_additive (attr := to_additive, {attrName})] on the original \
declaration."
else "" | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | warnAttrCore | Warn the user when the multiplicative declaration has an attribute. |
warnAttr {α β : Type} [Inhabited β] (stx : Syntax) (attr : SimpleScopedEnvExtension α β)
(f : β → Name → Bool) (thisAttr attrName src tgt : Name) : CoreM Unit :=
warnAttrCore stx (f <| attr.getState ·) thisAttr attrName src tgt | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | warnAttr | Warn the user when the multiplicative declaration has a simple scoped attribute. |
warnParametricAttr {β : Type} [Inhabited β] (stx : Syntax) (attr : ParametricAttribute β)
(thisAttr attrName src tgt : Name) : CoreM Unit :=
warnAttrCore stx (attr.getParam? · · |>.isSome) thisAttr attrName src tgt | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | warnParametricAttr | Warn the user when the multiplicative declaration has a parametric attribute. |
additivizeLemmas {m : Type → Type} [Monad m] [MonadError m] [MonadLiftT CoreM m]
(names : Array Name) (argInfo : ArgInfo) (desc : String) (t : Name → m (Array Name)) :
m Unit := do
let auxLemmas ← names.mapM t
let nLemmas := auxLemmas[0]!.size
for (nm, lemmas) in names.zip auxLemmas do
unless lemmas.size == nLemmas do
throwError "{names[0]!} and {nm} do not generate the same number of {desc}."
for (srcLemmas, tgtLemmas) in auxLemmas.zip <| auxLemmas.eraseIdx! 0 do
for (srcLemma, tgtLemma) in srcLemmas.zip tgtLemmas do
insertTranslationAndInfo srcLemma tgtLemma argInfo | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | additivizeLemmas | `additivizeLemmas names argInfo desc t` runs `t` on all elements of `names`
and adds translations between the generated lemmas (the output of `t`).
`names` must be non-empty. |
findMultiplicativeArg (nm : Name) : MetaM Nat := do
forallTelescopeReducing (← getConstInfo nm).type fun xs ty ↦ do
let env ← getEnv
let multArg? (tgt : Expr) : Option Nat := do
let c ← tgt.getAppFn.constName?
guard (findTranslation? env c).isSome
let relevantArg := (relevantArgAttr.find? env c).getD 0
let arg ← tgt.getArg? relevantArg
xs.findIdx? (arg.containsFVar ·.fvarId!)
let arg ← OptionT.run <| xs.firstM fun x ↦ OptionT.mk do
forallTelescope (← inferType x) fun _ys tgt ↦ return multArg? tgt
let arg := arg <|> multArg? ty
trace[to_additive_detail] "findMultiplicativeArg: {arg}"
return arg.getD 0 | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | findMultiplicativeArg | Find the argument of `nm` that appears in the first multiplicative (type-class) argument.
Returns 1 if there are no types with a multiplicative class as arguments.
E.g. `Prod.instGroup` returns 1, and `Pi.instOne` returns 2.
Note: we only consider the relevant argument (`(relevant_arg := ...)`) of each type-class.
E.g. `[Pow A N]` is a multiplicative type-class on `A`, not on `N`. |
targetName (cfg : Config) (src : Name) : CoreM Name := do
if cfg.self then
if cfg.tgt != .anonymous then
throwError m!"`to_additive self` ignores the provided name {cfg.tgt}"
return src
let .str pre s := src | throwError "to_additive: can't transport {src}"
trace[to_additive_detail] "The name {s} splits as {s.splitCase}"
let tgt_auto := guessName s
let depth := cfg.tgt.getNumParts
let pre := findPrefixTranslation (← getEnv) pre
let (pre1, pre2) := pre.splitAt (depth - 1)
let res := if cfg.tgt == .anonymous then pre.str tgt_auto else pre1 ++ cfg.tgt
if res == src then
throwError "to_additive: the generated additivised name equals the original name '{src}', \
meaning that no part of the name was additivised.\n\
If this is intentional, use the `@[to_additive self]` syntax.\n\
Otherwise, check that your declaration name is correct \
(if your declaration is an instance, try naming it)\n\
or provide an additivised name using the `@[to_additive my_add_name]` syntax."
if cfg.tgt == pre2.str tgt_auto && !cfg.allowAutoName then
Linter.logLintIf linter.toAdditiveGenerateName cfg.ref m!"\
to_additive correctly autogenerated target name for {src}.\n\
You may remove the explicit argument {cfg.tgt}."
if cfg.tgt != .anonymous then
trace[to_additive_detail] "The automatically generated name would be {pre.str tgt_auto}"
return res | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | targetName | Return the provided target name or autogenerate one if one was not provided. |
proceedFieldsAux (src tgt : Name) (argInfo : ArgInfo) (f : Name → Array Name) : CoreM Unit := do
let srcFields := f src
let tgtFields := f tgt
if srcFields.size != tgtFields.size then
throwError "Failed to map fields of {src}, {tgt} with {srcFields} ↦ {tgtFields}.\n \
Lengths do not match."
for srcField in srcFields, tgtField in tgtFields do
insertTranslationAndInfo srcField tgtField argInfo | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | proceedFieldsAux | if `f src = #[a_1, ..., a_n]` and `f tgt = #[b_1, ... b_n]` then `proceedFieldsAux src tgt f`
will insert translations from `a_i` to `b_i`. |
proceedFields (src tgt : Name) (argInfo : ArgInfo) : CoreM Unit := do
let env ← getEnv
let aux := proceedFieldsAux src tgt argInfo
aux fun declName ↦
if isStructure env declName then
let info := getStructureInfo env declName
Array.ofFn (n := info.fieldNames.size) (info.getProjFn? · |>.get!)
else
#[]
aux fun declName ↦
if isStructure env declName then
getStructureInfo env declName |>.parentInfo
|>.filterMap fun c ↦ if !c.subobject then c.projFn else none
else
#[]
aux fun declName ↦ match env.find? declName with
| some (ConstantInfo.inductInfo { ctors, .. }) => ctors.toArray
| _ => #[] | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | proceedFields | Add the structure fields of `src` to the translations dictionary
so that future uses of `to_additive` will map them to the corresponding `tgt` fields. |
elabToAdditive : Syntax → CoreM Config
| `(attr| to_additive%$tk $[?%$trace]? $existing?
$[$opts:toAdditiveOption]* $[$tgt]? $[$doc]?) => do
let mut attrs := #[]
let mut reorder := []
let mut relevantArg? := none
let mut dontTranslate := []
for opt in opts do
match opt with
| `(toAdditiveOption| (attr := $[$stxs],*)) =>
attrs := attrs ++ stxs
| `(toAdditiveOption| (reorder := $[$[$reorders:num]*],*)) =>
for cycle in reorders do
if h : cycle.size = 1 then
throwErrorAt cycle[0] "\
invalid cycle `{cycle[0]}`, a cycle must have at least 2 elements.\n\
`(reorder := ...)` uses cycle notation to specify a permutation.\n\
For example `(reorder := 1 2, 5 6)` swaps the first two arguments with each other \
and the fifth and the sixth argument and `(reorder := 3 4 5)` will move \
the fifth argument before the third argument."
let cycle ← cycle.toList.mapM fun n => match n.getNat with
| 0 => throwErrorAt n "invalid position `{n}`, positions are counted starting from 1."
| n+1 => pure n
reorder := cycle :: reorder
| `(toAdditiveOption| (relevant_arg := $n)) =>
if let some arg := relevantArg? then
throwErrorAt opt "cannot specify `relevant_arg` multiple times"
else
relevantArg? := n.getNat.pred
| `(toAdditiveOption| (dont_translate := $[$types:ident]*)) =>
dontTranslate := dontTranslate ++ types.toList
| _ => throwUnsupportedSyntax
let (existing, self) := match existing? with
| `(toAdditiveNameHint| existing) => (true, false)
| `(toAdditiveNameHint| self) => (true, true)
| _ => (false, false)
if self && !attrs.isEmpty then
throwError "invalid `(attr := ...)` after `self`, \
as there is only one declaration for the attributes.\n\
Instead, you can write the attributes in the usual way."
trace[to_additive_detail] "attributes: {attrs}; reorder arguments: {reorder}"
let doc ← doc.mapM fun
| `(str|$doc:str) => open Linter in do
if getLinterValue linter.deprecated (← getLinterOptions) then
let hintSuggestion := {
diffGranularity := .none
toTryThisSuggestion := { suggestion := "/-- " ++ doc.getString.trim ++ " -/" }
}
let sugg ← Hint.mkSuggestionsMessage #[hintSuggestion] doc
(codeActionPrefix? := "Update to: ") (forceList := false)
logWarningAt doc <| .tagged ``Linter.deprecatedAttr
... | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | elabToAdditive | Elaboration of the configuration options for `to_additive`. |
partial applyAttributes (stx : Syntax) (rawAttrs : Array Syntax) (thisAttr src tgt : Name)
(argInfo : ArgInfo) : TermElabM (Array Name) := do
copyInstanceAttribute src tgt
if src != tgt && linter.existingAttributeWarning.get (← getOptions) then
let appliedAttrs ← getAllSimpAttrs src
if appliedAttrs.size > 0 then
let appliedAttrs := ", ".intercalate (appliedAttrs.toList.map toString)
Linter.logLintIf linter.existingAttributeWarning stx m!"\
The source declaration {src} was given the simp-attribute(s) {appliedAttrs} before \
calling @[{thisAttr}].\nThe preferred method is to use something like \
`@[{thisAttr} (attr := {appliedAttrs})]`\nto apply the attribute to both \
{src} and the target declaration {tgt}."
warnAttr stx Lean.Elab.Tactic.Ext.extExtension
(fun b n => (b.tree.values.any fun t => t.declName = n)) thisAttr `ext src tgt
warnAttr stx Lean.Meta.Rfl.reflExt (·.values.contains ·) thisAttr `refl src tgt
warnAttr stx Lean.Meta.Symm.symmExt (·.values.contains ·) thisAttr `symm src tgt
warnAttr stx Batteries.Tactic.transExt (·.values.contains ·) thisAttr `trans src tgt
warnAttr stx Lean.Meta.coeExt (·.contains ·) thisAttr `coe src tgt
warnParametricAttr stx Lean.Linter.deprecatedAttr thisAttr `deprecated src tgt
warnParametricAttr stx simpsAttr thisAttr `simps src tgt
warnAttrCore stx Term.elabAsElim.hasTag thisAttr `elab_as_elim src tgt
let attrs ← elabAttrs rawAttrs
let (additiveAttrs, attrs) := attrs.partition (·.name == `to_additive)
let nestedDecls ←
match additiveAttrs.size with
| 0 => pure #[]
| 1 => addToAdditiveAttr tgt (← elabToAdditive additiveAttrs[0]!.stx) additiveAttrs[0]!.kind
| _ => throwError "cannot apply {thisAttr} multiple times."
let allDecls := #[src, tgt] ++ nestedDecls
if attrs.size > 0 then
trace[to_additive_detail] "Applying attributes {attrs.map (·.stx)} to {allDecls}"
for attr in attrs do
withRef attr.stx do withLogging do
if attr.name == `simps then
additivizeLemmas allDecls argInfo "simps lemmas" (simpsTacFromSyntax · attr.stx)
return
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
let runAttr := do
for decl in allDecls do
attrImpl.add decl attr.stx attr.kind
let elaborator := attrImpl.ref
if (← getInfoState).enabled && (← getEnv).contains elaborator then
withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do
try runAttr
finally if attr.stx[0].isIdent || attr.stx[0].isAtom then
pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] }
else
runAttr
... | def | Tactic | [
"Batteries.Tactic.Trans",
"Lean.Compiler.NoncomputableAttr",
"Lean.Elab.Tactic.Ext",
"Lean.Meta.Tactic.Rfl",
"Lean.Meta.Tactic.Symm",
"Lean.Meta.Tactic.TryThis",
"Mathlib.Data.Array.Defs",
"Mathlib.Data.Nat.Notation",
"Mathlib.Lean.Expr.ReplaceRec",
"Mathlib.Lean.Meta.Simp",
"Mathlib.Lean.Name",... | Mathlib/Tactic/ToAdditive/Frontend.lean | applyAttributes | Apply attributes to the multiplicative and additive declarations. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.