Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/Lean/Mathlib/MathlibTest/Attribute/ToAdditive/     Datei vom 15.10.2026 mit Größe 39 kB image not shown  

Quelle  Basic.lean   Sprache: Lean

 

module

public import Mathlib.Algebra.Group.Defs
public meta import Mathlib.Lean.Exception
public import Mathlib.Tactic.ReduceModChar.Ext
public import Qq.MetaM

import all Init.Prelude
import all Mathlib.Tactic.Translate.Expr

open Qq Lean Meta Elab Command Mathlib Tactic Translate ToAdditive

public section

-- work in a namespace so that it doesn't matter if names clash
namespace Test

-- [note] use the below options for diagnostics:
-- set_option trace.translate true
-- set_option trace.translate_detail true
-- set_option pp.universes true
-- set_option pp.explicit true
-- set_option pp.notation false

/- ! Tests for namespaces of the resulting aliases -/
section

variable {G : Type*} [CommGroup G]
@[to_additive Bars.baz]
lemma Foo.Bar.baz (g h : G) : g * h = h * g := mul_comm g h
/-- info: Test.Foo.Bars.baz.{u_1} {G : Type u_1} [AddCommGroup G] (g h : G) : g + h = h + g -/
#guard_msgs in #check Foo.Bars.baz

@[to_additive Test.Baz.Bars.baz]
lemma Foo.Bar.baz' (g h : G) : g * h = h * g := mul_comm g h
/-- info: Test.Baz.Bars.baz.{u_1} {G : Type u_1} [AddCommGroup G] (g h : G) : g + h = h + g -/
#guard_msgs in #check Baz.Bars.baz

-- Specifying more components than the original lemma is fine.
@[to_additive Bar.Bars.Stars.Bazzz.b]
lemma Foo.Bar.baz'' (g h : G) : g * h = h * g := mul_comm g h
/-- info: Bar.Bars.Stars.Bazzz.b.{u_1} {G : Type u_1} [AddCommGroup G] (g h : G) : g + h = h + g -/
#guard_msgs in #check Bar.Bars.Stars.Bazzz.b

/--
warning: `to_additive` correctly autogenerated target name for CommGroup.foo.
You may remove the explicit argument AddCommGroup.foo.

Note: This linter can be disabled with `set_option linter.translate.generateName false`
-/

#guard_msgs in
@[to_additive AddCommGroup.foo]
lemma _root_.CommGroup.foo {g h : G} : g * h = h * g := mul_comm g h

#guard_msgs in
@[to_additive _root_.AddCommGroup.bar]
lemma _root_.CommGroup.Bar.foo {g h : G} : g * h = h * g := mul_comm g h
#guard_msgs(drop info) in #check AddCommGroup.bar

#guard_msgs in
@[to_additive _root_.fooz]
lemma _root_.CommGroup.Bar.bar {g h : G} : g * h = h * g := mul_comm g h
/-- info: fooz.{u_1} {G : Type u_1} [AddCommGroup G] {g h : G} : g + h = h + g -/
#guard_msgs in #check fooz
/-- error: Unknown constant `AddCommGroup._root_.fooz` -/
#guard_msgs in #check AddCommGroup._root_.fooz -- this name was previously generated, due to a bug

end

@[to_additive bar0]
def foo0 {α} [Mul α] [One α] (x y : α) : α := x * y * 1

theorem bar0_works : bar0 3 4 = 7 := by decide

run_meta guard <| (← getConstInfo `Test.bar0).all == [`Test.bar0]

/--
error: `to_additive` does not support mutually recursive declarations.
-/

#guard_msgs (error) in
mutual

@[to_additive bar0a]
theorem foo0a {α} [Monoid α] (n : ℕ) : True := by
  cases n with
  | zero => trivial
  | succ n => exact foo0b (α := α) n

theorem foo0b {α} [Monoid α] (n : ℕ) : True := by
  cases n with
  | zero => trivial
  | succ n => exact foo0a (α := α) n

end

class my_has_pow (α : Type u) (β : Type v) where
  pow : α → β → α

instance : my_has_pow Nat Nat := ⟨fun a b => a ^ b⟩

class my_has_scalar (M : Type u) (α : Type v) where
  smul : M → α → α

instance : my_has_scalar Nat Nat := ⟨fun a b => a * b⟩

set_option linter.translate.warnInvalid false in
attribute [to_additive (reorder := α β) my_has_scalar] my_has_pow
/--
error: `to_additive` validation failed: expected
  {α : Type _} → {β : Type _} → [self : my_has_scalar β α] → α → β → α
but `my_has_scalar.smul` has type
  {M : Type u} → {α : Type v} → [self : my_has_scalar M α] → M → α → α
-/

#guard_msgs in
attribute [to_additive existing smul] my_has_pow.pow
/--
error: `to_additive` validation failed: expected
  {β : Type _} → {α : Type _} → [self : my_has_scalar β α] → α → β → α
but `my_has_scalar.smul` has type
  {M : Type u} → {α : Type v} → [self : my_has_scalar M α] → M → α → α
-/

#guard_msgs in
attribute [to_additive existing (reorder := α β) smul] my_has_pow.pow
attribute [to_additive existing (reorder := α β, 4 5) smul] my_has_pow.pow

@[to_additive bar1]
def foo1 {α : Type u} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n

theorem foo1_works : foo1 3 4 = Nat.pow 3 4 := by decide
theorem bar1_works : bar1 3 4 = 3 * 4 := by decide

infix:80 " ^ " => my_has_pow.pow

instance dummy_pow : my_has_pow ℕ <| PLift ℤ := ⟨fun _ _ => 5⟩

@[to_additive bar2]
def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : PLift ℤ) : α := x ^ (n ^ m)

theorem foo2_works : foo2 2 3 (PLift.up 2) = Nat.pow 2 5 := by decide
theorem bar2_works : bar2 2 3 (PLift.up 2) = 2 * 5 := by decide

@[to_additive bar3]
def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x

theorem foo3_works : foo3 2 3 = Nat.pow 2 3 := by decide
theorem bar3_works : bar3 2 3 = 2 * 3 := by decide

@[to_additive bar4]
def foo4 {α : Type u} : Type v → Type (max u v) := @my_has_pow α

@[to_additive bar4_test]
lemma foo4_test {α β : Type u} : @foo4 α β = @my_has_pow α β := (rfl)

set_option linter.defProp false in
set_option linter.concreteInstances false in
@[to_additive bar5]
def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : True := True.intro

@[to_additive bar6]
def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _

-- fails because of workaround in `transform`. Not sure if this will show up in practice
-- @[to_additive bar7]
-- def foo7 := @my_has_pow.pow

-- theorem foo7_works : foo7 2 3 = Nat.pow 2 3 := by decide
-- theorem bar7_works : bar7 2 3 = 2 * 3 := by decide

/-- Check that we don't additivize `Nat` expressions. -/
@[to_additive bar8]
def foo8 (a b : ℕ) := a * b

theorem bar8_works : bar8 2 3 = 6 := by decide

/-- Check that we don't additivize `Nat` numerals. -/
@[to_additive bar9]
def foo9 := 1

theorem bar9_works : bar9 = 1 := by decide

@[to_additive bar10]
def foo10 (n m : ℕ) := HPow.hPow n m + n * m * 2 + 1 * 0 + 37 * 1 + 2

theorem bar10_works : bar10 = foo10 := (rfl)

@[to_additive bar11]
def foo11 (n : ℕ) (m : ℤ) := n * m * 2 + 1 * 0 + 37 * 1 + 2

theorem bar11_works : bar11 = foo11 := (rfl)

@[to_additive bar12]
def foo12 (_ : Nat) (_ : Int) : Fin 37 := ⟨2, by decide⟩

@[to_additive (reorder := α β, 4 5) bar13]
lemma foo13 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : x ^ y = x ^ y := rfl

@[to_additive (reorder := α β, 4 5) bar14]
def foo14 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : α := (x ^ y) ^ y

@[to_additive (reorder := α β, 4 5) bar15]
lemma foo15 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := (rfl)

@[to_additive (reorder := α β, 4 5) bar16]
lemma foo16 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := foo15 x y

@[to_additive bar17]
def foo17 [Group α] (x : α) : α := x * 1

@[to_additive (attr := simp) bar18]
lemma foo18 [Group α] (x : α) : foo17 x = x ∧ foo17 x = 1 * x :=
  ⟨mul_one x, mul_one x |>.trans <| one_mul x |>.symm⟩

example [Group α] (x : α) : foo17 x = 1 * x := by simp
example [Group α] (x : α) : foo17 x = x := by simp
example [AddGroup α] (x : α) : bar17 x = 0 + x := by simp
example [AddGroup α] (x : α) : bar17 x = x := by simp

run_meta guard <| (← getConstInfo `Test.bar18).all == [`Test.bar18]

/- Testing nested to_additive calls -/
@[to_additive (attr := simp, to_additive baz19) bar19]
def foo19 := 1

example {x} (h : 1 = x) : foo19 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : bar19 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : baz19 = x := by simp; guard_target = 1 = x; exact h

/- Testing that the order of the attributes doesn't matter -/
@[to_additive (attr := to_additive baz20, simp) bar20]
def foo20 := 1

example {x} (h : 1 = x) : foo20 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : bar20 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : baz20 = x := by simp; guard_target = 1 = x; exact h

@[to_additive bar21]
def foo21 {N} {A} [Pow A N] (a : A) (n : N) : A := a ^ n

run_meta guard <| translations.find? (← getEnv) `Test.foo21
  matches some ⟨`Test.bar21, ⟨[], ⟨[], #[]⟩⟩, .arg 1, false⟩

@[to_additive bar22]
abbrev foo22 {α} [Monoid α] (a : α) : ℕ → α
  | 0 => 1
  | _ => a

run_meta do
  -- make `abbrev` definition `reducible` automatically
  guard <| (← getReducibilityStatus `Test.bar22) == .reducible
  -- make `abbrev` definition `inline` automatically
  guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22) == some .inline
  -- some auxiliary definitions are also `abbrev` but not `reducible`
  guard <| (← getReducibilityStatus `Test.bar22.match_1) != .reducible
  guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22.match_1) == some .inline
  guard <| (← getConstInfo `Test.bar22.match_1).all == [`Test.bar22.match_1]

run_cmd do
  -- test that we cannot transport a declaration to itself
  successIfFail <| liftCoreM <| addTranslationAttr ToAdditive.data `bar11_works { ref := ← getRef }

/- Test on inductive types -/
inductive AddInd : ℕ → Prop where
  | basic : AddInd 2
  | zero : AddInd 1

@[to_additive (relevant_arg := _)]
inductive MulInd : ℕ → Prop where
  | basic : MulInd 2
  | one : MulInd 1

run_cmd do
  unless findTranslationName? (← getEnv) ToAdditive.data `Test.MulInd.one == some `Test.AddInd.zero do throwError "1"
  unless findTranslationName? (← getEnv) ToAdditive.data `Test.MulInd.basic == some `Test.AddInd.basic do throwError "2"
  unless findTranslationName? (← getEnv) ToAdditive.data `Test.MulInd == some `Test.AddInd do throwError "3"

@[to_additive addFixedNumeralTest]
def fixedNumeralTest {α} [One α] :=
  @OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 _

@[to_additive addFixedNumeralTest2]
def fixedNumeralTest2 {α} [One α] :=
  @OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 (@One.toOfNat1 ((fun _ => ℕ) (1 : α)) _)

/-! Test the namespace bug (https://github.com/leanprover-community/mathlib4/pull/8733).
This code should *not* generate a lemma
  `add_some_def.in_namespace`. -/

def some_def.in_namespace : Bool := false

def some_def {α : Type u} [Mul α] (x : α) : α :=
  if some_def.in_namespace then x * x else x

@[expose]
def myFin (_ : ℕ) := ℕ

instance : One (myFin n) := ⟨(1 : ℕ)⟩

@[to_additive bar]
def myFin.foo : myFin (n + 1) := 1

/-- We can pattern-match with `1`, which creates a term with a pure nat literal.
See https://github.com/leanprover-community/mathlib4/pull/2046 -/

@[to_additive]
def mul_foo {α} [Monoid α] (a : α) : ℕ → α
  | 0 => 1
  | 1 => 1
  | (_ + 2) => a


-- cannot apply `@[to_additive]` to `some_def` if `some_def.in_namespace` doesn't have the attribute
run_cmd liftCoreM <| successIfFail <|
  transformDeclRec ToAdditive.data { ref := ← getRef} `Test.some_def `Test.add_some_def `Test.some_def


attribute [to_additive some_other_name] some_def.in_namespace
attribute [to_additive add_some_def] some_def

run_cmd do liftCoreM <| successIfFail (getConstInfo `Test.add_some_def.in_namespace)

set_option linter.defProp false in
set_option linter.unusedVariables false in
def foo_mul {I J K : Type} (n : ℕ) {f : I → Type} (L : Type) [∀ i, One (f i)]
  [Add I] [Mul L] : true := by trivial


@[to_additive]
instance pi.has_one {I : Type} {f : I → Type} [(i : I) → One <| f i] : One ((i : I) → f i) :=
  ⟨fun _ => 1⟩

set_option warn.classDefReducibility false in
@[to_additive]
def nat_pi_has_one {α : Type} [One α] : One ((x : Nat) → α) := by infer_instance

set_option warn.classDefReducibility false in
@[to_additive]
def pi_nat_has_one {I : Type} : One ((x : I) → Nat)  := pi.has_one

example : @pi_nat_has_one = @pi_nat_has_zero := rfl

section instances

class FooClass (α) : Prop where
  refle : ∀ a : α, a = a

@[to_additive]
instance FooClass_one [One α] : FooClass α := ⟨fun _ ↦ rfl⟩

lemma one_fooClass [One α] : FooClass α := by infer_instance

lemma zero_fooClass [Zero α] : FooClass α := by infer_instance

end instances

/- Test that we can rewrite with definitions with the `@[to_additive]` attribute. -/
@[to_additive]
lemma npowRec_zero [One M] [Mul M] (x : M) : npowRec 0 x = 1 := by
  rw [npowRec]

set_option linter.translate.redundant false in
/- Test that we can rewrite with definitions without the `@[to_additive]` attribute. -/
@[to_additive addoptiontest]
lemma optiontest (x : Option α) : x.elim none some = x := by
  cases x <;> rw [Option.elim]

/- Check that `to_additive` works if a `_match` aux declaration is created. -/
@[to_additive]
def IsUnit [Mul M] (a : M) : Prop := a ≠ a

@[to_additive]
theorem isUnit_iff_exists_inv [Mul M] {a : M} : IsUnit a ↔ ∃ _ : α, a ≠ a :=
  ⟨fun h => absurd rfl h, fun ⟨_, hab⟩ => hab⟩

@[to_additive (dont_translate := R)]
def mulMatchAux {R A} [Mul A] (_ : R) (_ : A) : Nat := 5

@[to_additive (dont_translate := R)]
theorem mulMatchThm {R A} (r : R) (a : A) [Mul A] : True := by
  have ⟨_, _⟩ : mulMatchAux r a = mulMatchAux r a ∧ True := ⟨rfl, trivial⟩
  exact trivial

/-! Test that `@[to_additive]` correctly translates auxiliary declarations that do not have the
original declaration name as prefix. -/

@[to_additive]
def IsUnit' [Monoid M] (a : M) : Prop := ∃ b : M, a * b = 1

@[to_additive]
theorem isUnit'_iff_exists_inv [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, a * b = 1 := Iff.rfl

@[to_additive]
theorem isUnit'_iff_exists_inv' [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, b * a = 1 := by
  simp [isUnit'_iff_exists_inv, mul_comm]

/-! Test a permutation with a cycle of length > 2. -/
@[to_additive (reorder := x y z)]
def reorderMulThree {α : Type _} [Mul α] (x y z : α) : α := x * y * z

/-! Test a permutation that is too big for the list of arguments. -/
/-- error: index `51` is out of bounds, there are only `5` arguments -/
#guard_msgs in
@[to_additive (reorder := 3 4 51)]
def reorderMulThree' {α : Type _} [Mul α] (x y z : α) : α := x * y * z

/-! Test `(reorder := ...)` when the proof needs to be eta-expanded. -/
set_option linter.translate.warnInvalid false in
@[to_additive (reorder := 3 4 5)]
alias reorderMulThree_alias := reorderMulThree

set_option linter.translate.warnInvalid false in
@[to_additive (reorder := 3 4 2)]
alias reorderMulThree_alias' := reorderMulThree

@[to_additive (reorder := 3 4 5)]
def reorderMulThree_alias'' {α : Type _} [Mul α] (x y : α) : α → α := reorderMulThree x y

/--
error: Invalid cycle `04`, a cycle must have at least 2 elements.
See the docstring of `reorder` for how to specify reorders.
-/

#guard_msgs in
@[to_additive (reorder := 04)]
example (a b c d e : Nat) : True := trivial

/--
error: Please remove the duplicate entries from the disjoint cycle representation.
See the docstring of `reorder` for how to specify reorders.
-/

#guard_msgs in
@[to_additive (reorder := 1 2, 2 3)]
example (a b c d e : Nat) : True := trivial

/--
error: Please remove the duplicate entries from the disjoint cycle representation.
See the docstring of `reorder` for how to specify reorders.
-/

#guard_msgs in
@[to_additive (reorder := 1 2 2 3)]
example (a b c d e : Nat) : True := trivial

/--
error: The reorder within argument 1 has been set to both `3 4` and `1 2`. Please specify it only once.
-/

#guard_msgs in
@[to_additive (reorder := 1 (1 2), 1 (3 4))]
example (h : ∀ a b c d : Nat, True) : True := trivial

/-- error: invalid index `00`, arguments are counted starting from 1. -/
#guard_msgs in
@[to_additive (reorder := 00 100 200)]
example : True := trivial

/-- error: invalid argument `x`, it is not an argument of `_example`. -/
#guard_msgs in
@[to_additive (reorder := x y z)]
example : True := trivial

example {α : Type _} [Add α] (x y z : α) : reorderAddThree z x y = x + y + z := rfl


def Ones : ℕ → Q(Nat)
  | 0     => q(1)
  | (n + 1) => q($(Ones n) + $(Ones n))


-- This test just exists to see if this finishes in finite time. It should take <100ms.
-- #time
run_cmd do
  let e : Expr := Ones 300
  let _ ← liftCoreM <| MetaM.run' <| (applyReplacementFun ToAdditive.data e).run #[] #[]

@[expose, to_additive, to_additive_dont_translate] def MonoidEnd : Type := Unit
def Unit' : Type := Unit
@[to_additive_do_translate] def Unit'' : Type := Unit

run_meta do
  guard !(← shouldTranslate ToAdditive.data q(Semigroup MonoidEnd) |>.run #[] #[]).1
  guard !(← shouldTranslate ToAdditive.data q(Semigroup Unit') |>.run #[] #[]).1
  guard (← shouldTranslate ToAdditive.data q(Semigroup Unit'') |>.run #[] #[]).1


@[to_additive instSemiGroupAddMonoidEnd]
instance : Semigroup MonoidEnd where
  mul _ _ := ()
  mul_assoc _ _ _ := rfl

@[to_additive]
lemma monoidEnd_lemma (x y z : MonoidEnd) : x * (y * z) = (x * y) * z := mul_assoc .. |>.symm

/-- info: Test.addMonoidEnd_lemma (x y z : AddMonoidEnd) : x * (y * z) = x * y * z -/
#guard_msgs in
#check addMonoidEnd_lemma

/-!
Some arbitrary tests to check whether additive names are guessed correctly.
-/

section guessName

meta def checkGuessName (s t : String) : Elab.Command.CommandElabM Unit :=
  unless (GuessName.guessName { nameDict, abbreviationDict } s) == t do
    throwError "failed: {GuessName.guessName { nameDict, abbreviationDict } s} != {t}"

run_cmd
  checkGuessName "HMul_Eq_LEOne_Conj₂MulLT'" "HAdd_Eq_Nonpos_Conj₂AddLT'"
  checkGuessName "OneMulSMulInvDivPow"       "ZeroAddVAddNegSubNSMul"
  checkGuessName "ProdFinprodNPowZPow"       "SumFinsumNSMulZSMul"

  -- The current design swaps all instances of `Comm`+`Add` in order to have
  -- `AddCommMonoid` instead of `CommAddMonoid`.
  checkGuessName "comm_mul_CommMul_commMul" "comm_add_AddComm_addComm"
  checkGuessName "mul_comm_MulComm_mulComm" "add_comm_AddComm_addComm"

  checkGuessName "CommMonoid" "AddCommMonoid"
  checkGuessName "commMonoid" "addCommMonoid"

  checkGuessName "CancelCommMonoid" "AddCancelCommMonoid"
  checkGuessName "cancelCommMonoid" "addCancelCommMonoid"
  checkGuessName "CancelMonoid" "AddCancelMonoid"
  checkGuessName "cancelMonoid" "addCancelMonoid"
  checkGuessName "RightCancelMonoid" "AddRightCancelMonoid"
  checkGuessName "rightCancelMonoid" "addRightCancelMonoid"
  checkGuessName "LeftCancelMonoid" "AddLeftCancelMonoid"
  checkGuessName "leftCancelMonoid" "addLeftCancelMonoid"

  checkGuessName "IsLeftRegular" "IsAddLeftRegular"
  checkGuessName "isRightRegular" "isAddRightRegular"
  checkGuessName "IsRegular" "IsAddRegular"

  checkGuessName "LTOne_LEOne_OneLE_OneLT" "Neg_Nonpos_Nonneg_Pos"
  checkGuessName "LTHMulHPowLEHDiv" "LTHAddHSMulLEHSub"
  checkGuessName "OneLEHMul" "NonnegHAdd"
  checkGuessName "OneLTHPow" "PosHSMul"
  checkGuessName "OneLTPow" "PosNSMul"
  checkGuessName "instCoeTCOneHom" "instCoeTCZeroHom"
  checkGuessName "instCoeTOneHom" "instCoeTZeroHom"
  checkGuessName "instCoeOneHom" "instCoeZeroHom"
  checkGuessName "invFun_eq_symm" "invFun_eq_symm"
  checkGuessName "MulEquiv.symmInvFun" "AddEquiv.symmInvFun"
  checkGuessName "IsScalarTower" "VAddAssocClass"
  checkGuessName "isScalarTower" "vaddAssocClass"
  checkGuessName "eventuallyLE_one_mul_atBot" "eventuallyLE_zero_add_atBot"

end guessName

end Test

insert_to_additive_translation localize add_localize

@[to_additive] def localize.r := Nat
set_option linter.translate.overwrite false in
@[to_additive add_localize] def localize := Nat
@[to_additive] def localize.s := Nat

run_cmd do
  unless findTranslationName? (← getEnv) ToAdditive.data `localize.r == some `add_localize.r do throwError "1"
  unless findTranslationName? (← getEnv) ToAdditive.data `localize   == some `add_localize   do throwError "2"
  unless findTranslationName? (← getEnv) ToAdditive.data `localize.s == some `add_localize.s do throwError "3"

/--
warning: The source declaration one_eq_one was given the simp-attribute(s) simp, reduce_mod_char before calling @[to_additive].
The preferred method is to use something like `@[to_additive (attr := simp, reduce_mod_char)]`
to apply the attribute to both one_eq_one and the target declaration zero_eq_zero.

Note: This linter can be disabled with `set_option linter.existingAttributeWarning false`
-/

#guard_msgs in
@[simp, reduce_mod_char, to_additive]
lemma one_eq_one {α : Type*} [One α] : (1 : α) = 1 := rfl

@[to_additive (attr := reduce_mod_char, simp)]
lemma one_eq_one' {α : Type*} [One α] : (1 : α) = 1 := rfl

section
-- Test the error message for a name that cannot be additivised.

/--
error: to_additive: the generated translated name equals the original name `foo`.
If this is intentional, use the `@[to_additive self]` syntax.
Otherwise, check that your declaration name is correct (if your declaration is an instance, try naming it)
or provide a translated name using the `@[to_additive my_add_name]` syntax.
---
warning: declaration uses `sorry`
-/

#guard_msgs in
@[to_additive]
local instance foo {α : Type*} [Semigroup α] : Monoid α := sorry

end

-- Test the error message for a wrong `to_additive existing`.

/--
error: `to_additive` validation failed:
  expected 1 universe levels, but `Nat.le_trans` has 0 universe levels
-/

#guard_msgs in
@[to_additive existing Nat.le_trans]
lemma one_eq_one'' {α : Type*} [One α] : (1 : α) = 1 := rfl


/--
error: `to_additive` validation failed: expected
  ∀ {α : Type _} [inst : Zero α], 0 = 0
but `Eq.trans` has type
  ∀ {α : Sort u} {a b c : α}, a = b → b = c → a = c
-/

#guard_msgs in
@[to_additive existing Eq.trans]
lemma one_eq_one''' {α : Type*} [One α] : (1 : α) = 1 := rfl

/-!
Test that @[to_additive] can reorder arguments of raw kernel projections.
-/

open Lean in
elab "unfold%" e:term : term => do
  let e ← Elab.Term.elabTerm e none
  Meta.unfoldDefinition e

@[to_additive]
def myPow {α β : Type} [i : Pow α β] (a : α) := unfold% i.1 a

/--
info: def myPow : {α β : Type} → [i : Pow α β] → α → β → α :=
fun {α β} [i : Pow α β] a => i.1 a
-/

#guard_msgs in
#print myPow
/--
info: def myNSMul : {α β : Type} → [i : SMul β α] → α → β → α :=
fun {α β} [SMul β α] a a_1 => SMul.smul a_1 a
-/

#guard_msgs in
#print myNSMul

@[to_additive]
def myMul {α : Type} [i : Mul α] (a : α) := unfold% i.1 a

/--
info: def myMul : {α : Type} → [i : Mul α] → α → α → α :=
fun {α} [i : Mul α] a => i.1 a
-/

#guard_msgs in
#print myMul
/--
info: def myAdd : {α : Type} → [i : Add α] → α → α → α :=
fun {α} [Add α] a => Add.add a
-/

#guard_msgs in
#print myAdd

/-! Test that the `existingAttributeWarning` linter doesn't fire for `to_additive self`. -/
/--
warning: `to_additive self` is redundant when none of the arguments are reordered and no `(relevant_arg := ...)` is provided.
Please remove the attribute, or provide an explicit `(reorder := ...)` or `(relevant_arg := ...)` argument.
If you need to give a hint to `to_additive` to translate expressions involving `test1`,
use `to_additive_do_translate` instead

Note: This linter can be disabled with `set_option linter.translate.redundant false`
-/

#guard_msgs in
@[simp, to_additive self]
theorem test1 : 5 = 5 := rfl

/-! Test that the `existingAttributeWarning` linter doesn't fire for `to_additive none`. -/
/--
warning: `to_additive` did not change the type of theorem `test1'`. Please remove the attribute.

Note: This linter can be disabled with `set_option linter.translate.redundant false`
-/

#guard_msgs in
@[simp, to_additive none]
theorem test1' : 5 = 5 := rfl

/-! Test that we can't write `to_additive self (attr := ..)`. -/

/--
error: invalid `(attr := ...)` after `self` or `none`, as there is no other declaration for the attributes.
Instead, you can write the attributes in the usual way.
-/

#guard_msgs in
@[to_additive self (attr := simp)]
theorem test2 : 5 = 5 := rfl

/-! Previously, An application that isn't a constant, such as `(no_index Add) α`, would be seen as
multiplicative, hence `α` would be set as the `to_additive_relevant_arg`. -/


@[to_additive]
def fooMul {α β : Type} (_ : (no_index Add) α) [Mul β] (x y : β) : β := x * y

@[to_additive] -- this would not translate `fooMul`
def barMul {β : Type} [Mul β] (x y : β) : β := fooMul instAddNat x y

/-! Test that additive docstrings work -/
section doc

set_option linter.translate.redundant false

/-- I am a multiplicative docstring! -/
@[to_additive /-- I am an additive docstring! -/]
theorem mulTrivial : True := trivial

@[to_additive (attr := inherit_doc mulTrivial)]
theorem mulTrivial' : True := trivial

/--
info: some (I am an additive docstring!)
---
info: some (I am a multiplicative docstring!)
---
info: some (I am an additive docstring!)
-/

#guard_msgs in
run_cmd
  logInfo m!"{← findDocString? (← getEnv) ``addTrivial}"
  logInfo m!"{← findDocString? (← getEnv) ``mulTrivial'}"
  logInfo m!"{← findDocString? (← getEnv) ``addTrivial'}"

end doc

/-! Test handling of noncomputability -/

elab "#computability " decl:ident : command => do
  let name ← liftCoreM (realizeGlobalConstNoOverloadWithInfo decl)
  let markedNonComp := isNoncomputable (← getEnv) name
  let hasNoExec := (IR.findEnvDecl (← getEnv) name).isNone
  let desc :=
    if markedNonComp then "is marked noncomputable"
    else if hasNoExec then "has no executable code"
    else "is computable"
  logInfo m!"`{name}` {desc}"

/- Both should be computable -/

@[to_additive]
def mulComputableTest : Nat := 0

/-- info: `mulComputableTest` is computable -/
#guard_msgs in #computability mulComputableTest
/-- info: `addComputableTest` is computable -/
#guard_msgs in #computability addComputableTest

/- Both should be marked noncomputable -/

@[to_additive]
noncomputable def mulMarkedNoncomputable : Nat := 0

/-- info: `mulMarkedNoncomputable` is marked noncomputable -/
#guard_msgs in #computability mulMarkedNoncomputable
/-- info: `addMarkedNoncomputable` is marked noncomputable -/
#guard_msgs in #computability addMarkedNoncomputable

noncomputable section

/- Compilation should succeed despite `noncomputable section` -/

@[to_additive]
def mulComputableTest' : Nat := 0

/-- info: `mulComputableTest'` is computable -/
#guard_msgs in #computability mulComputableTest'
/-- info: `addComputableTest'` is computable -/
#guard_msgs in #computability addComputableTest'

/- Both should be marked noncomputable -/

@[to_additive]
noncomputable def mulMarkedNoncomputable' : Nat := 0

/-- info: `mulMarkedNoncomputable'` is marked noncomputable -/
#guard_msgs in #computability mulMarkedNoncomputable'
/-- info: `addMarkedNoncomputable'` is marked noncomputable -/
#guard_msgs in #computability addMarkedNoncomputable'

/- Both should be marked noncomputable -/

@[to_additive]
def mulNoExec {G} (n : Nonempty G) : G := Classical.choice n

/-- info: `mulNoExec` is marked noncomputable -/
#guard_msgs in #computability mulNoExec
/-- info: `addNoExec` is marked noncomputable -/
#guard_msgs in #computability addNoExec

end

/-! Test structures with a private constructor and private fields -/

structure MyPrivateAdd where
  private mk ::
  private add : Nat

@[to_additive]
structure MyPrivateMul where
  private mk ::
  private mul : Nat

@[to_additive]
def MyPrivateMul.mk' (a : Nat) := MyPrivateMul.mk a

@[to_additive]
def MyPrivateMul.mul' (x : MyPrivateMul) := x.mul

/-! Test the `(dont_translate := ...)` framework -/

class MyRing (α : Type*) extends Group α

@[to_additive (dont_translate := β γ) add_neg_iff_mul_inv]
lemma mul_inv_iff_mul_inv {α β γ : Type} [Group α] [MyRing β] [MyRing γ] (a : α) (b : β) (c : γ) :
    a * a⁻¹ = 1 ↔ b * b⁻¹ = 1 ∨ c * c⁻¹ = 1 := by
  simp

/--
info: add_neg_iff_mul_inv {α β γ : Type} [AddGroup α] [MyRing β] [MyRing γ] (a : α) (b : β) (c : γ) :
  a + -a = 0 ↔ b * b⁻¹ = 1 ∨ c * c⁻¹ = 1
-/

#guard_msgs in
#check add_neg_iff_mul_inv

@[to_additive (dont_translate := β) add_neg_iff_mul_inv]
def Subtype.mul_inv_iff_mul_inv {α β : Type} [Group α] [MyRing β] (a : α) (b : β) :
    {a : α // a * a⁻¹ = 1 ↔ b * b⁻¹ = 1} := by
  exists a
  simp

set_option linter.auxLemma false in
/--
info: Subtype.mul_inv_iff_mul_inv._proof_1 {α β : Type} [Group α] [MyRing β] (a : α) (b : β) : a * a⁻¹ = 1 ↔ b * b⁻¹ = 1
-/

#guard_msgs in
#check Subtype.mul_inv_iff_mul_inv._proof_1
set_option linter.auxLemma false in
/--
info: Subtype.add_neg_iff_mul_inv._proof_1 {α β : Type} [AddGroup α] [MyRing β] (a : α) (b : β) : a + -a = 0 ↔ b * b⁻¹ = 1
-/

#guard_msgs in
#check Subtype.add_neg_iff_mul_inv._proof_1

/-!
Test that `relevant_arg` and `reorder` are passed to `simps` and `.eq_1`, and to
structure fields/constructors.
-/


structure SimpleNSMul (β : Type 1) (α : Type) where
  x : Nat

@[to_additive (reorder := α β) (relevant_arg := β)]
structure SimplePow (α : Type) (β : Type 1) where
  x : Nat

@[expose, to_additive (reorder := α β) (attr := simps)]
def simplePowZero (α β) : SimplePow α β where
  x := 0

@[to_additive]
lemma simplePowZero_x' {β} : (simplePowZero Nat β).x = 0 := by
  rw [simplePowZero_x]

@[to_additive]
lemma simplePowZero_x'' {β} : (simplePowZero Nat β).x = 0 := by
  rw [simplePowZero.eq_1]

/-- info: simpleNSMulZero_x' {β : Type 1} : (simpleNSMulZero β ℕ).x = 0 -/
#guard_msgs in
#check simpleNSMulZero_x'
/-- info: simpleNSMulZero_x'' {β : Type 1} : (simpleNSMulZero β ℕ).x = 0 -/
#guard_msgs in
#check simpleNSMulZero_x''


structure AddMonoidAlgebra (k G : Type) where
  x : G → k

@[to_additive (relevant_arg := G)]
structure MonoidAlgebra (k G : Type) where
  x : G → k

variable {G : Type} [Monoid G]

@[to_additive]
instance : Mul (MonoidAlgebra Nat G) where
  mul a b := ⟨fun i => a.1 i * b.1 1⟩

-- `relevant_arg` information is inherited from the base translation in `*.casesOn`:
@[to_additive]
instance : Mul (MonoidAlgebra Nat G) where
  mul | ⟨a⟩, ⟨b⟩ => ⟨fun i => a i * b 1⟩

-- `to_additive` can automatically determine that `G` is the relevant argument,
-- because `G` is relevant to the translation of `MonoidAlgebra`
@[to_additive (dont_translate := k)]
def monoidAlgebraFoo {k G : Type} [Inhabited k] : MonoidAlgebra k G × Nat :=
  (⟨fun _ ↦ default⟩, 2)

run_meta guard <|
  translations.find? (← getEnv) ``monoidAlgebraFoo
    matches some ⟨``addMonoidAlgebraFoo, ⟨[], ⟨[], #[]⟩⟩, .arg 1, false⟩

/--
warning: `to_additive` correctly autogenerated `(relevant_arg := 2)` for `monoidAlgebraFoo₁`.
You may remove the option.

Note: This linter can be disabled with `set_option linter.translate.relevantArg false`
-/

#guard_msgs in
@[to_additive (dont_translate := k) (relevant_arg := G)]
def monoidAlgebraFoo₁ {k G : Type} [Inhabited k] : MonoidAlgebra k G × Nat :=
  (⟨fun _ ↦ default⟩, 2)

/--
warning: `to_additive` determined that `(relevant_arg := 2)` is the right option for `monoidAlgebraFoo₂`, rather than `(relevant_arg := 1)`.
You may remove the option.

Note: This linter can be disabled with `set_option linter.translate.relevantArg false`
---
warning: @[to_additive] failed to add a translation from `monoidAlgebraFoo₂.eq_1` to any of `[addMonoidAlgebraFoo₂.eq_1]`.
Please silence this warning and add a translation manually. Errors:

`to_additive` validation failed: expected
  ∀ {k G : Type} [inst : Inhabited k], monoidAlgebraFoo₂ = ({ x := fun x => default }, 2)
but `addMonoidAlgebraFoo₂.eq_1` has type
  ∀ {k G : Type} [inst : Inhabited k], addMonoidAlgebraFoo₂ = ({ x := fun x => default }, 2)

Note: This linter can be disabled with `set_option linter.translate.warnInvalid false`
-/

#guard_msgs in
@[expose, to_additive (dont_translate := k) (relevant_arg := k)]
def monoidAlgebraFoo₂ {k G : Type} [Inhabited k] : MonoidAlgebra k G × Nat :=
  (⟨fun _ ↦ default⟩, 2)

-- Proofs in types aren't abstracted:
set_option linter.defProp false in
@[to_additive]
def abstractMul : Function.const _ True (id Nat.zero_lt_one) := trivial

set_option pp.proofs true in
/-- info: abstractMul : Function.const (0 < 1) True (id Nat.zero_lt_one) -/
#guard_msgs in
#check abstractMul
set_option pp.proofs true in
/-- info: abstractAdd : Function.const (0 < 1) True (id Nat.zero_lt_one) -/
#guard_msgs in
#check abstractAdd

-- We give a warning if an existing translation is overwritten:
/--
warning: `abstractMul` was already translated to `abstractAdd` instead of `someOtherTranslation`.
Unless the original translation was wrong, please remove this `to_additive` attribute.

Note: This linter can be disabled with `set_option linter.translate.overwrite false`
-/

#guard_msgs in
attribute [to_additive someOtherTranslation] abstractMul

-- Test that we don't blindly translate the prefix of a name.
def Mul.test : Nat := 5
@[to_additive] def Mul.test' := Mul.test

-- Test that arguments of free variables aren't considered by `shouldTranslate`
@[to_additive_dont_translate]
def dontTranslateId {α} : α → α := id

@[to_additive]
theorem functionTypeMonoid {ι : Type*} {R : ι → Type*} [(i : ι) → Monoid (R i)] (i : ι)
  (a : R (dontTranslateId i)) : a * a = a * a := rfl

class AddClass (α : Type) extends Add α where
class MulClass (α : Type) extends Mul α where
-- Test that the reserved `MulClass.mk.congr_simp` can be translated to `AddClass.mk.congr_cimp`
attribute [to_additive existing] MulClass MulClass.mk.congr_simp

/-- error: `to_additive` cannot translate `MulAxiom` because it has no value. -/
#guard_msgs in
@[to_additive]
axiom MulAxiom {α} : Mul α

/-! Docstring on `alias` -/

@[to_additive] alias HMulAlias := HMul

/--
info: **Alias** of `HAdd`.

---

The notation typeclass for heterogeneous addition.
This enables the notation `a + b : γ` where `a : α`, `b : β`.
-/

#guard_msgs in
run_cmd
  let some doc ← findDocString? (← getEnv) ``HAddAlias
    | throwError "no `docComment` docstring found"
  logInfo doc

@[to_additive /-- Overriding docstring -/] alias HMulAlias' := HMul

/-- info: Overriding docstring -/
#guard_msgs in
run_cmd
  let some doc ← findDocString? (← getEnv) ``HAddAlias'
    | throwError "no `docComment` docstring found"
  logInfo doc

/-! Deprecated attribute -/

@[to_additive (attr := deprecated mul_comm +typeChanged (since := "today"))]
theorem old_mul_comm {α} [CommMagma α] (b a : α) : a * b = b * a := mul_comm a b

/--
warning: `old_mul_comm` has been deprecated: Use `mul_comm` instead

Note: The updated constant has a different type:
  ∀ {G : Type u_1} [inst : CommMagma G] (a b : G), a * b = b * a
instead of
  ∀ {α : Type u_1} [inst : CommMagma α] (b a : α), a * b = b * a
---
info: @old_mul_comm : ∀ {α : Type u_1} [inst : CommMagma α] (b a : α), a * b = b * a
-/

#guard_msgs in
#check @old_mul_comm

/--
warning: `old_add_comm` has been deprecated: Use `add_comm` instead

Note: The updated constant has a different type:
  ∀ {G : Type u_1} [inst : AddCommMagma G] (a b : G), a + b = b + a
instead of
  ∀ {α : Type u_1} [inst : AddCommMagma α] (b a : α), a + b = b + a
---
info: @old_add_comm : ∀ {α : Type u_1} [inst : AddCommMagma α] (b a : α), a + b = b + a
-/

#guard_msgs in
#check @old_add_comm

@[to_additive (attr := deprecated (since := "today"))]
alias mul_comm_alias := mul_comm

/--
warning: `mul_comm_alias` has been deprecated: Use `mul_comm` instead

Hint: Replace the deprecated name:
  mul_comm_̵a̵l̵i̵a̵s̵
---
info: @mul_comm_alias : ∀ {G : Type u_1} [inst : CommMagma G] (a b : G), a * b = b * a
-/

#guard_msgs in
#check @mul_comm_alias

/--
warning: `add_comm_alias` has been deprecated: Use `add_comm` instead

Hint: Replace the deprecated name:
  add_comm_̵a̵l̵i̵a̵s̵
---
info: @add_comm_alias : ∀ {G : Type u_1} [inst : AddCommMagma G] (a b : G), a + b = b + a
-/

#guard_msgs in
#check @add_comm_alias

/-! Warning when adding docstrings to existing declarations -/

namespace ExistingDeclDocstring

/-- Existing docstring -/
opaque add (G : Type*) [AddGroup G] : Prop

/-- warning: The target declaration `add` already has a docstring. -/
#guard_msgs in
@[to_additive existing /-- New docstring -/]
opaque mul (G : Type*) [Group G] : Prop

/-- warning: The target declaration `self` already has a docstring. -/
#guard_msgs in
/-- Existing docstring -/
@[to_additive self (reorder := x y) /-- New docstring -/]
opaque self (x y : Nat) : Prop

/-- Existing docstring -/
structure addStruct (G : Type*) [AddGroup G] where

/-- warning: The target declaration `addStruct` already has a docstring. -/
#guard_msgs in
@[to_additive /-- New docstring -/]
structure mulStruct (G : Type*) [Group G] where

-- Examples with no pre-existing docstring

opaque add' (G : Type*) [AddGroup G] : Prop

/-- warning: This docstring should be added directly to `add'`. -/
#guard_msgs in
@[to_additive existing /-- New docstring -/]
opaque mul' (G : Type*) [Group G] : Prop

/-- warning: This docstring should be added directly to `self'`. -/
#guard_msgs in
@[to_additive self (reorder := x y) /-- New docstring -/]
opaque self' (x y : Nat) : Prop

structure addStruct' (G : Type*) [AddGroup G] where

/-- warning: This docstring should be added directly to `addStruct'`. -/
#guard_msgs in
@[to_additive /-- New docstring -/]
structure mulStruct' (G : Type*) [Group G] where

end ExistingDeclDocstring

section errors

abbrev FakeMul (α : Type) := Mul α

variable {α : Type}

/--
error: `@[to_additive]` failed to add declaration `add_rfl`.
  The translated type is not type correct.
Application type mismatch: The argument
  inst✝
has type
  Add α
but is expected to have type
  FakeMul α
in the application
  @inferInstance (FakeMul α) inst✝

For help, see the docstring of `to_additive`, section `Troubleshooting`.
-/

#guard_msgs in
@[to_additive]
theorem mul_rfl [Mul α] (a b : α) : haveI : FakeMul α := inferInstance; a * b = a * b := Eq.refl (a * b)

/--
error: `@[to_additive]` failed to add declaration `instFakeAddOfAddGroup`.
  The translated value does not have the translated type.
The value
  fun {α} [AddGroup α] => { add := fun x1 x2 => x1 + x2 }
has type
  {α : Type} → [AddGroup α] → Add α
but is expected to have type
  {α : Type} → [AddGroup α] → FakeMul α

For help, see the docstring of `to_additive`, section `Troubleshooting`.
-/

#guard_msgs in
@[to_additive]
local instance [Group α] : FakeMul α := ⟨(· * ·)⟩

/--
error: `@[to_additive]` failed to add declaration `instAddOfAddGroup_mathlibTest`.
  The translated value is not type correct.
Application type mismatch: The argument
  inst✝
has type
  AddGroup α
but is expected to have type
  Group α
in the application
  @instFakeMulOfGroup α inst✝

For help, see the docstring of `to_additive`, section `Troubleshooting`.
-/

#guard_msgs in
@[to_additive]
instance [Group α] : Mul α := ⟨(· * ·)⟩

end errors

namespace ModuleSystem
-- Test that `private` and `exposed` are translated correctly.

variable {α : Type} [Mul α] (a b : α)

@[to_additive]
private def mul_1 := a * b

@[to_additive]
def mul_2 := match 0 with | 0 | 1 | _ + 1 => a * b

@[expose, to_additive]
def mul_3 := match 0 with | 0 | 1 | 2 | _ + 1 => a * b

/--
info: private def ModuleSystem.add_1 : {α : Type} → [Add α] → α → α → α :=
fun {α} [Add α] a b => a + b
-/

#guard_msgs in
#print add_1
/--
info: def ModuleSystem.add_2 : {α : Type} → [Add α] → α → α → α :=
fun {α} [Add α] a b =>
  match 0 with
  | 0 => a + b
  | 1 => a + b
  | n.succ => a + b
-/

#guard_msgs in
#print add_2
/--
info: @[expose] def ModuleSystem.add_3 : {α : Type} → [Add α] → α → α → α :=
fun {α} [Add α] a b =>
  match 0 with
  | 0 => a + b
  | 1 => a + b
  | 2 => a + b
  | n.succ => a + b
-/

#guard_msgs in #print add_3

set_option linter.auxLemma false
/--
info: private def ModuleSystem.add_2.match_1.{u_1} : (motive : ℕ → Sort u_1) →
  (x : ℕ) → (Unit → motive 0) → (Unit → motive 1) → ((n : ℕ) → motive n.succ) → motive x :=
fun motive x h_1 h_2 h_3 => Nat.casesOn x (h_1 ()) fun n => dite (n = 0) (Eq.ndrec_symm (h_2 ())) fun h_1 => h_3 n
-/

#guard_msgs in
#print add_2.match_1
/--
info: @[expose] def ModuleSystem.add_3.match_1.{u_1} : (motive : ℕ → Sort u_1) →
  (x : ℕ) → (Unit → motive 0) → (Unit → motive 1) → (Unit → motive 2) → ((n : ℕ) → motive n.succ) → motive x :=
fun motive x h_1 h_2 h_3 h_4 =>
  Nat.casesOn x (h_1 ()) fun n =>
    dite (n = 0) (Eq.ndrec_symm (h_2 ())) fun h_1 => dite (n = 1) (Eq.ndrec_symm (h_3 ())) fun h_2 => h_4 n
-/

#guard_msgs in
#print add_3.match_1

end ModuleSystem

Messung
CHZG
9310010097

¤ Dauer der Verarbeitung: 0.11 Sekunden  (vorverarbeitet am  2026-11-24) ¤

*© Formatika GbR, Deutschland