The Mathlib Handbook

The volumes of the handbook are not written yet. This site shows the map of Mathlib that they will follow, at Mathlib 4472534b60.

The areas / V34. The tactics of Mathlib

Mathlib.Tactic.Translate.ToAdditive

13 declarations. Mathlib docs · Source

The @[to_additive] attribute.

The @[to_additive] attribute is used to translate multiplicative declarations to their additive equivalent. See the docstrings of to_additive for more information.

def Mathlib.Tactic.ToAdditive.to_additive_ignore_args E1 #

Lean.ParserDescr

This attribute has been deprecated.

def Mathlib.Tactic.ToAdditive.to_additive_do_translate E1 #

Lean.ParserDescr

The global do_translate/dont_translate attributes specify whether operations on a given type should be translated. dont_translate can be used for types that are translated, such as MonoidAlgebra -> AddMonoidAlgebra, or for fixed types, such as Fin n/ZMod n. do_translate is for types without arguments, like Unit and Empty, where the structure on it can be translated.

Note: The name generation is not aware of dont_translate, so if some part of a lemma is not translated thanks to this, you generally have to specify the translated name manually.

def Mathlib.Tactic.ToAdditive.to_additive_dont_translate E1 #

Lean.ParserDescr

The global do_translate/dont_translate attributes specify whether operations on a given type should be translated. dont_translate can be used for types that are translated, such as MonoidAlgebra -> AddMonoidAlgebra, or for fixed types, such as Fin n/ZMod n. do_translate is for types without arguments, like Unit and Empty, where the structure on it can be translated.

Note: The name generation is not aware of dont_translate, so if some part of a lemma is not translated thanks to this, you generally have to specify the translated name manually.

def Mathlib.Tactic.ToAdditive.to_additive E1 #

Lean.ParserDescr

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 -/
@[to_additive /-- Addition is commutative -/]
theorem 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 (reorder := ...) syntax to reorder the arguments in the generated additive declaration. This is specified using cycle notation. For example (reorder := α β, 5 6) swaps the arguments α and β 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 to_additive existing syntax to use an existing additive declaration, instead of automatically generating it. This attempts to autogenerate the (reorder := ...) argument.

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]
lemma 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.

The (rename := ...) syntax can be used for specifying the argument names of the generated declaration, overriding the automatic translation of names. For example, (rename := x → a, y ↔ z) will translate lemma mul_foo (x y z : α) ... to lemma add_foo (a z y : α) ....

Implementation notes

The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with to_additive. The dictionary is ToAdditive.nameDict and can be found in the Tactic.ToAdditive.GuessName file. If you introduce a new name which should be translated by to_additive you should add the translation to this dictionary.

In the mul_comm' example above, to_additive maps:

  • mul_comm' to add_comm',
  • CommSemigroup to AddCommSemigroup,
  • x * y to x + y and y * x to y + x, and
  • CommSemigroup.mul_comm' to AddCommSemigroup.add_comm'.

Heuristics

to_additive uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The heuristic looks at the argument that is determined by its relevant_arg option:

  • Only map an identifier to its additive version if its relevant_arg argument doesn't contain any unapplied identifiers.
  • relevant_arg is automatically inferred by to_additive, and this can be seen in to_additive?. It is usually the first argument.

Examples:

  • @Mul.mul Nat n m (i.e. (n * m : Nat)) will not change to +, since its relevant argument is Nat, an identifier not applied to any arguments.
  • @Mul.mul (α × β) x y will change to +. Its relevant argument contains the identifier Prod, but this is applied to α which is a free variable.
  • @Mul.mul (α × Int) x y will change to +, since its relevant argument is α × Int, and in Prod, α is the first argument. This would be bad, because we don't want to translate the order on Int, so one should use (dont_translate := α) to ensure the * stays a *.

The reasoning behind the heuristic is that the relevant argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type.

Identifiers that have the @[to_additive] attribute are ignored. For example, multiplication in ↥Semigroup is replaced by addition in ↥AddSemigroup. You can turn this behavior off by also adding the @[to_additive_dont_translate] attribute.

Troubleshooting

If @[to_additive] fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what @[to_additive] did wrong by looking at the type mismatch error.

  • Option 1: The most common case is that it didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like ℕ or ℝ. However, the heuristic misfires on some other declarations. Solutions:
    • First figure out what the fixed type is in the first argument of the declaration that didn't get additivized. Note that this fixed type can occur in implicit arguments. If manually finding it is hard, you can run set_option trace.translate_detail true and search the output for the fragment "contains the fixed type" to find what the fixed type is.
    • If the fixed type has an additive counterpart (like ↥Semigroup), give it the @[to_additive] attribute.
    • If the fixed type has nothing to do with algebraic operations (like TopCat), add the attribute @[to_additive_do_translate] to the fixed type Foo.
    • If the fixed type occurs inside the relevant argument of a declaration d, but this argument is not connected to the multiplicative structure on d, consider adding attribute [to_additive self (relevant_arg := n)] to d, where n is different from k. If none of the arguments have a multiplicative structure, then the heuristic should not apply at all. This can be achieved with (relevant_arg := _).
  • Option 2: It additivized a declaration d that should remain multiplicative. Solution:
    • Make sure the relevant_arg of d is a type with a multiplicative structure. You can see the value of relevant_arg using to_additive? on d. The reason is that @[to_additive] doesn't additivize declarations if their relevant_arg contains fixed types like ℕ or ℝ. See section Heuristics. The expected output of to_additive? is (relevant_arg := n) where the n-th argument is a type (family) with a multiplicative structure on it. If the relevant_arg is wrong, you should add the attribute @[to_additive (relevant_arg := α)] manually, where α is the name of an argument with a multiplicative structure.
  • Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves pow/^. Solutions:
    • Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. NPow.npow n x corresponds to x ^ n, but it is convenient that NPow.npow has this argument order, since it matches NSMul.nsmul n x.
    • If this is not possible, add (reorder := ...) argument to to_additive.

If neither of these solutions work, and to_additive is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to multiplicative G. Afterwards, apply the attribute manually:

attribute [to_additive foo_add_bar] foo_bar

This will allow future uses of to_additive to recognize that foo_bar should be replaced with foo_add_bar.

Handling of hidden definitions

Before transporting the “main” declaration src, to_additive first scans its type and value for names starting with src, and transports them. This includes auxiliary definitions like src._match_1

In addition to transporting the “main” declaration, to_additive transports its equational lemmas and tags them as equational lemmas for the new declaration.

Structure fields and constructors

If src is a structure, then the additive version has to be already written manually. In this case to_additive adds all structure fields to its mapping.

Name generation

  • If @[to_additive] is called without a name argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to to_additive, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.

  • You can add a namespace translation using the following command:

    insert_to_additive_translation QuotientGroup QuotientAddGroup
    

    Later uses of @[to_additive] on declarations in the QuotientGroup namespace will be created in the QuotientAddGroup namespace. This is not necessary if there is already a declaration with name QuotientGroup.

  • If @[to_additive] is called with a name argument new_name /without a dot/, then to_additive updates the prefix as described above, then replaces the last part of the name with new_name.

  • If @[to_additive] is called with a name argument NewNamespace.new_name /with a dot/, then to_additive uses this new name as is.

As a safety check, in the first case to_additive double checks that the new name differs from the original one.

def Mathlib.Tactic.ToAdditive.attrTo_additive?_ E1 #

Lean.ParserDescr

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 -/
@[to_additive /-- Addition is commutative -/]
theorem 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 (reorder := ...) syntax to reorder the arguments in the generated additive declaration. This is specified using cycle notation. For example (reorder := α β, 5 6) swaps the arguments α and β 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 to_additive existing syntax to use an existing additive declaration, instead of automatically generating it. This attempts to autogenerate the (reorder := ...) argument.

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]
lemma 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.

The (rename := ...) syntax can be used for specifying the argument names of the generated declaration, overriding the automatic translation of names. For example, (rename := x → a, y ↔ z) will translate lemma mul_foo (x y z : α) ... to lemma add_foo (a z y : α) ....

Implementation notes

The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with to_additive. The dictionary is ToAdditive.nameDict and can be found in the Tactic.ToAdditive.GuessName file. If you introduce a new name which should be translated by to_additive you should add the translation to this dictionary.

In the mul_comm' example above, to_additive maps:

  • mul_comm' to add_comm',
  • CommSemigroup to AddCommSemigroup,
  • x * y to x + y and y * x to y + x, and
  • CommSemigroup.mul_comm' to AddCommSemigroup.add_comm'.

Heuristics

to_additive uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The heuristic looks at the argument that is determined by its relevant_arg option:

  • Only map an identifier to its additive version if its relevant_arg argument doesn't contain any unapplied identifiers.
  • relevant_arg is automatically inferred by to_additive, and this can be seen in to_additive?. It is usually the first argument.

Examples:

  • @Mul.mul Nat n m (i.e. (n * m : Nat)) will not change to +, since its relevant argument is Nat, an identifier not applied to any arguments.
  • @Mul.mul (α × β) x y will change to +. Its relevant argument contains the identifier Prod, but this is applied to α which is a free variable.
  • @Mul.mul (α × Int) x y will change to +, since its relevant argument is α × Int, and in Prod, α is the first argument. This would be bad, because we don't want to translate the order on Int, so one should use (dont_translate := α) to ensure the * stays a *.

The reasoning behind the heuristic is that the relevant argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type.

Identifiers that have the @[to_additive] attribute are ignored. For example, multiplication in ↥Semigroup is replaced by addition in ↥AddSemigroup. You can turn this behavior off by also adding the @[to_additive_dont_translate] attribute.

Troubleshooting

If @[to_additive] fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what @[to_additive] did wrong by looking at the type mismatch error.

  • Option 1: The most common case is that it didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like ℕ or ℝ. However, the heuristic misfires on some other declarations. Solutions:
    • First figure out what the fixed type is in the first argument of the declaration that didn't get additivized. Note that this fixed type can occur in implicit arguments. If manually finding it is hard, you can run set_option trace.translate_detail true and search the output for the fragment "contains the fixed type" to find what the fixed type is.
    • If the fixed type has an additive counterpart (like ↥Semigroup), give it the @[to_additive] attribute.
    • If the fixed type has nothing to do with algebraic operations (like TopCat), add the attribute @[to_additive_do_translate] to the fixed type Foo.
    • If the fixed type occurs inside the relevant argument of a declaration d, but this argument is not connected to the multiplicative structure on d, consider adding attribute [to_additive self (relevant_arg := n)] to d, where n is different from k. If none of the arguments have a multiplicative structure, then the heuristic should not apply at all. This can be achieved with (relevant_arg := _).
  • Option 2: It additivized a declaration d that should remain multiplicative. Solution:
    • Make sure the relevant_arg of d is a type with a multiplicative structure. You can see the value of relevant_arg using to_additive? on d. The reason is that @[to_additive] doesn't additivize declarations if their relevant_arg contains fixed types like ℕ or ℝ. See section Heuristics. The expected output of to_additive? is (relevant_arg := n) where the n-th argument is a type (family) with a multiplicative structure on it. If the relevant_arg is wrong, you should add the attribute @[to_additive (relevant_arg := α)] manually, where α is the name of an argument with a multiplicative structure.
  • Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves pow/^. Solutions:
    • Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. NPow.npow n x corresponds to x ^ n, but it is convenient that NPow.npow has this argument order, since it matches NSMul.nsmul n x.
    • If this is not possible, add (reorder := ...) argument to to_additive.

If neither of these solutions work, and to_additive is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to multiplicative G. Afterwards, apply the attribute manually:

attribute [to_additive foo_add_bar] foo_bar

This will allow future uses of to_additive to recognize that foo_bar should be replaced with foo_add_bar.

Handling of hidden definitions

Before transporting the “main” declaration src, to_additive first scans its type and value for names starting with src, and transports them. This includes auxiliary definitions like src._match_1

In addition to transporting the “main” declaration, to_additive transports its equational lemmas and tags them as equational lemmas for the new declaration.

Structure fields and constructors

If src is a structure, then the additive version has to be already written manually. In this case to_additive adds all structure fields to its mapping.

Name generation

  • If @[to_additive] is called without a name argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to to_additive, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.

  • You can add a namespace translation using the following command:

    insert_to_additive_translation QuotientGroup QuotientAddGroup
    

    Later uses of @[to_additive] on declarations in the QuotientGroup namespace will be created in the QuotientAddGroup namespace. This is not necessary if there is already a declaration with name QuotientGroup.

  • If @[to_additive] is called with a name argument new_name /without a dot/, then to_additive updates the prefix as described above, then replaces the last part of the name with new_name.

  • If @[to_additive] is called with a name argument NewNamespace.new_name /with a dot/, then to_additive uses this new name as is.

As a safety check, in the first case to_additive double checks that the new name differs from the original one.

opaque Mathlib.Tactic.ToAdditive.dontTranslateAttr E1 #

Lean.NameMapExtension Unit

The global do_translate/dont_translate attributes specify whether operations on a given type should be translated. dont_translate can be used for types that are translated, such as MonoidAlgebra -> AddMonoidAlgebra, or for fixed types, such as Fin n/ZMod n. do_translate is for types without arguments, like Unit and Empty, where the structure on it can be translated.

Note: The name generation is not aware of dont_translate, so if some part of a lemma is not translated thanks to this, you generally have to specify the translated name manually.

opaque Mathlib.Tactic.ToAdditive.translations E1 #

Lean.NameMapExtension Mathlib.Tactic.Translate.TranslationInfo

Maps multiplicative names to their additive counterparts.

def Mathlib.Tactic.ToAdditive.nameDict E1 #

Std.HashMap String (List String)

Dictionary used by guessName to autogenerate names. This only transforms single name components, unlike abbreviationDict.

Note: guessName capitalizes the output according to the capitalization of the input. In order for this to work, the input should always start with a lower case letter, and the output should always start with an upper case letter.

def Mathlib.Tactic.ToAdditive.abbreviationDict E1 #

Std.HashMap String String

We need to fix a few abbreviations after applying nameDict, i.e. replacing ZeroLE by Nonneg. This dictionary contains these fixes. The input should contain entries that is in lowerCamelCase (e.g. ltzero; the initial sequence of capital letters should be lower-cased) and the output should be in UpperCamelCase (e.g. LTZero). When applying the dictionary, we lower-case the output if the input was also given in lower-case.

opaque Mathlib.Tactic.ToAdditive.guessNameExt E1 #

Mathlib.Tactic.GuessName.GuessNameExt

Environment extension used for guessing the translation of a name.

def Mathlib.Tactic.ToAdditive.data E1 #

Mathlib.Tactic.Translate.TranslateData

The bundle of environment extensions for to_additive

def Mathlib.Tactic.ToAdditive.commandInsert_to_additive_translation__ E1 #

Lean.ParserDescr

insert_to_additive_translation mulName addName inserts the translation mulName ↦ addName into the to_additive dictionary. This is useful for translating namespaces that don't (yet) have a corresponding translated declaration.

def Mathlib.Tactic.ToAdditive.commandTo_additive_name_hint__ E1 #

Lean.ParserDescr

to_additive_name_hint src tgt lets to_additive translate the name segment src to tgt for the rest of the file current. src and tgt should both be capitalized.