\[\begin{split}\newcommand{\as}{\kw{as}} \newcommand{\case}{\kw{case}} \newcommand{\cons}{\textsf{cons}} \newcommand{\consf}{\textsf{consf}} \newcommand{\emptyf}{\textsf{emptyf}} \newcommand{\End}{\kw{End}} \newcommand{\kwend}{\kw{end}} \newcommand{\even}{\textsf{even}} \newcommand{\evenO}{\textsf{even}_\textsf{O}} \newcommand{\evenS}{\textsf{even}_\textsf{S}} \newcommand{\Fix}{\kw{Fix}} \newcommand{\fix}{\kw{fix}} \newcommand{\for}{\textsf{for}} \newcommand{\forest}{\textsf{forest}} \newcommand{\Functor}{\kw{Functor}} \newcommand{\In}{\kw{in}} \newcommand{\ind}[3]{\kw{Ind}~[#1]\left(#2\mathrm{~:=~}#3\right)} \newcommand{\Indp}[4]{\kw{Ind}_{#4}[#1](#2:=#3)} \newcommand{\Indpstr}[5]{\kw{Ind}_{#4}[#1](#2:=#3)/{#5}} \newcommand{\injective}{\kw{injective}} \newcommand{\kw}[1]{\textsf{#1}} \newcommand{\length}{\textsf{length}} \newcommand{\letin}[3]{\kw{let}~#1:=#2~\kw{in}~#3} \newcommand{\List}{\textsf{list}} \newcommand{\lra}{\longrightarrow} \newcommand{\Match}{\kw{match}} \newcommand{\Mod}[3]{{\kw{Mod}}({#1}:{#2}\,\zeroone{:={#3}})} \newcommand{\ModImp}[3]{{\kw{Mod}}({#1}:{#2}:={#3})} \newcommand{\ModA}[2]{{\kw{ModA}}({#1}=={#2})} \newcommand{\ModS}[2]{{\kw{Mod}}({#1}:{#2})} \newcommand{\ModType}[2]{{\kw{ModType}}({#1}:={#2})} \newcommand{\mto}{.\;} \newcommand{\nat}{\textsf{nat}} \newcommand{\Nil}{\textsf{nil}} \newcommand{\nilhl}{\textsf{nil\_hl}} \newcommand{\nO}{\textsf{O}} \newcommand{\node}{\textsf{node}} \newcommand{\nS}{\textsf{S}} \newcommand{\odd}{\textsf{odd}} \newcommand{\oddS}{\textsf{odd}_\textsf{S}} \newcommand{\ovl}[1]{\overline{#1}} \newcommand{\Pair}{\textsf{pair}} \newcommand{\plus}{\mathsf{plus}} \newcommand{\SProp}{\textsf{SProp}} \newcommand{\Prop}{\textsf{Prop}} \newcommand{\return}{\kw{return}} \newcommand{\Set}{\textsf{Set}} \newcommand{\Sort}{\mathcal{S}} \newcommand{\Str}{\textsf{Stream}} \newcommand{\Struct}{\kw{Struct}} \newcommand{\subst}[3]{#1\{#2/#3\}} \newcommand{\tl}{\textsf{tl}} \newcommand{\tree}{\textsf{tree}} \newcommand{\trii}{\triangleright_\iota} \newcommand{\Type}{\textsf{Type}} \newcommand{\WEV}[3]{\mbox{$#1[] \vdash #2 \lra #3$}} \newcommand{\WEVT}[3]{\mbox{$#1[] \vdash #2 \lra$}\\ \mbox{$ #3$}} \newcommand{\WF}[2]{{\mathcal{W\!F}}(#1)[#2]} \newcommand{\WFE}[1]{\WF{E}{#1}} \newcommand{\WFT}[2]{#1[] \vdash {\mathcal{W\!F}}(#2)} \newcommand{\WFTWOLINES}[2]{{\mathcal{W\!F}}\begin{array}{l}(#1)\\\mbox{}[{#2}]\end{array}} \newcommand{\with}{\kw{with}} \newcommand{\WS}[3]{#1[] \vdash #2 <: #3} \newcommand{\WSE}[2]{\WS{E}{#1}{#2}} \newcommand{\WT}[4]{#1[#2] \vdash #3 : #4} \newcommand{\WTE}[3]{\WT{E}{#1}{#2}{#3}} \newcommand{\WTEG}[2]{\WTE{\Gamma}{#1}{#2}} \newcommand{\WTM}[3]{\WT{#1}{}{#2}{#3}} \newcommand{\zeroone}[1]{[{#1}]} \end{split}\]

# Implicit Coercions

Author:

  Amokrane Saïbi

## General Presentation

This section describes the inheritance mechanism of Coq. In Coq with inheritance, we are not interested in adding any expressive power to our theory, but only convenience. Given a term, possibly not typable, we are interested in the problem of determining if it can be well typed modulo insertion of appropriate coercions. We allow to write:

> - `f a` where `f:(forall x:A,B)` and `a:A'` when `A'` can be seen in some sense as a subtype of `A`.

> - `x:A` when `A` is not a type, but can be seen in a certain sense as a type: set, group, category etc.

> - `f a` when `f` is not a function, but can be seen in a certain sense as a function: bijection, functor, any structure morphism etc.

## Coercion Classes

A class with \(n\) parameters is any defined name with a type `forall (ident1 : type1)..(identn:typen), sort`. Thus a class with parameters is considered as a single class and not as a family of classes. An object of a coercion class is any term of type `coercion_class term1 .. termn`. In addition to these user-defined classes, we have two built-in classes:

> - `Sortclass`, the class of sorts; its objects are the terms whose type is a sort (e.g. `Prop` or `Type`).

> - `Funclass`, the class of functions; its objects are all the terms with a functional type, i.e. of form `forall x:A,B`.

Formally, the syntax of classes is defined as:

> coercion_class`::=`Funclass`````|`Sortclass`````|`reference``

Note

Don't confuse coercion classes with typeclasses, which are records with special properties defined with the `Class` command.

## Coercions

A name `f` can be declared as a coercion between a source user-defined class `C` with \(n\) parameters and a target class `D` if one of these conditions holds:

> - `D` is a user-defined class, then the type of `f` must have the form `forall (x₁:A₁)..(xₖ:Aₖ)(y:C v₁..vₙ), D u₁..uₘ` where \(m\) is the number of parameters of `D`.

> - `D` is `Funclass`, then the type of `f` must have the form `forall (x₁:A₁)..(xₖ:Aₖ)(y:C v₁..vₙ)(x:A), B`.

> - `D` is `Sortclass`, then the type of `f` must have the form `forall (x₁:A₁)..(xₖ:Aₖ)(y:C v₁..vₙ), s` with `s` a sort.

We then write `f : C >-> D`.

When you declare a new coercion (e.g. with `Coercion`), new coercion paths with the same classes as existing ones are ignored. Coq will generate a warning when the two paths may be non convertible. When the `x₁..xₖ` are exactly the `v₁..vₙ` (in the same order), the coercion is said to satisfy the uniform inheritance condition. When possible, we recommend using coercions that satisfy this condition. This guarantees that no spurious warning will be generated.

Note

The built-in class `Sortclass` can be used as a source class, but the built-in class `Funclass` cannot.

To coerce an object `t:C t₁..tₙ` of `C` towards `D`, we have to apply the coercion `f` to it; the obtained term `f _.._ t` is then an object of `D`.

## Reversible Coercions

When a term cannot be coerced (directly) to its expected type, Coq tries to use a reversible coercion (see the `reversible` attribute). Intuitively, Coq synthesizes a new term of the right type that can be coerced to the original one. The new term is obtained by reversing the coercion, that is guessing its input given the output.

More precisely, in order to coerce a term `a : A` to type `B`, Coq finds a reversible coercion `f : B >-> A`, then synthesizes some `?x : B` such that `f ?x = a` (typically through Canonical Structures or Typeclasses) and finally replaces `a` with the value of `?x`.

If Coq doesn't find a reversible coercion `f : B >-> A`, then it looks for a coercion class `C` equipped with an incoming reversible coercion `g : B >-> C` and a coercion `h : A >-> C` (not necessarily reversible), then synthesizes some `?x : B` such that `g ?x = h a`, and finally replaces `a` with the value of `?x`. If there's another class `D` with a coercion from `C` to `D` and incoming coercions from `A` and `B`, Coq tries `C` before `D`. This ordering is well defined only if the coercion graph happens to be a semi lattice. The intuition behind this ordering is that since coercions forget information, `D` has less information that `C`, and hence inferring `?x : B` from `h a : D` would be harder.

See the example below.

## Identity Coercions

To make coercions work for both a named class and for `Sortclass` or `Funclass`, use the `Identity Coercion` command. There is an example here.

## Inheritance Graph

Coercions form an inheritance graph with classes as nodes. We call coercion path an ordered list of coercions between two nodes of the graph. A class `C` is said to be a subclass of `D` if there is a coercion path in the graph from `C` to `D`; we also say that `C` inherits from `D`. Our mechanism supports multiple inheritance since a class may inherit from several classes, contrary to simple inheritance where a class inherits from at most one class. However there must be at most one path between two classes. If this is not the case, only the oldest one is valid and the others are ignored. So the order of declaration of coercions is important.

We extend notations for coercions to coercion paths. For instance `[f₁;..;fₖ] : C >-> D` is the coercion path composed by the coercions `f₁..fₖ`. The application of a coercion path to a term consists of the successive application of its coercions.

## Coercion Classes

Command Coercion reference : coercion_class >-> coercion_class?
Command Coercion ident_decl def_body

  The first form declares the construction denoted by `reference` as a coercion between the two given classes. The second form defines `ident_decl` just like `Definition` `ident_decl def_body` and then declares `ident_decl` as a coercion between it source and its target. Both forms support the `local` attribute, which makes the coercion local to the current section.

  `: coercion_class >-> coercion_class?`

    The source and target classes of the coercion. If unspecified, `reference` must already be a coercion, which enables modifying the `reversible` attribute of `reference`. See the example below.

  Attribute reversible= yes​no?

    This attribute allows the coercion to be used as a reversible coercion. By default coercions are not reversible except for `Record` fields specified using `:>`.

  Attribute nonuniform

    Silence the non uniform inheritance warning.

    Deprecated since version 8.18: Use the `warnings` attribute instead with "-uniform-inheritance".

  Error qualid not declared.

    `qualid` is not defined globally.

  Error qualid is already a coercion.

    `qualid` is already registered as a coercion.

  Error Funclass cannot be a source class.

    Funclass as a source class is currently not supported. This may change in the future.

  Error qualid is not a function.

    `qualid` is not a function, so it cannot be used as a coercion.

  Error Cannot find the source class of qualid.

    Coq can not infer a valid source class.

  Error Cannot recognize coercion_class as a source class of qualid.

    The inferred source class of the coercion differs from the one specified.

  Error Cannot find the target class

    The target class of the coercion is not specified and cannot be inferred. Make sure that the target is not a variable.

  Error Found target class coercion_class instead of coercion_class

    The inferred target class of the coercion differs from the one specified.

  Warning qualid does not respect the uniform inheritance condition.

    The test for ambiguous coercion paths may yield false positives involving the coercion `qualid`. Use the `warnings` attribute with "-uniform-inheritance" to silence this warning.

  Warning New coercion path ... is ambiguous with existing ...

    The check for ambiguous paths failed. The paths for which this check fails are displayed by a warning in the form `[f₁;..;fₙ] : C >-> D`.

    The convertibility checking procedure for coercion paths is complete for paths consisting of coercions satisfying the uniform inheritance condition, but some coercion paths could be reported as ambiguous even if they are convertible with existing ones when they have coercions that don't satisfy this condition.

  Warning ... is not definitionally an identity function.

    If a coercion path has the same source and target class, that is said to be circular. When a new circular coercion path is not convertible with the identity function, it will be reported as ambiguous.

Some objects can be declared as coercions when they are defined. This applies to assumptions and constructors of inductive types and record fields. Use `:>` instead of `:` before the type of the assumption to do so. See `of_type`.

Command Identity Coercion ident : coercion_classsrc >-> coercion_classdest

  Checks that `coercion_classsrc` is a constant with a body of the form `fun (x₁:T₁)..(xₙ:Tₙ) => coercion_classdest t₁..tₘ` where `m` is the number of parameters of `coercion_classdest`. Then we define an identity function with type `forall (x₁:T₁)..(xₙ:Tₙ)(y:C x₁..xₙ),D t₁..tₘ`, and we declare it as an identity coercion between `C` and `D`. See below for an example.

  This command supports the `local` attribute, which makes the coercion local to the current section.

  Error coercion_class must be a transparent constant.
  Command SubClass ident_decl def_body

    If `type` is a coercion class `ident'` applied to some arguments then `ident` is defined and an identity coercion of name `Id_ident_ident'` is declared. In other words, this is an abbreviation for

    `Definition ident := type.` `Identity Coercion Id_ident_ident' : ident >-> ident'`.

    This command supports the `local` attribute, which makes the coercion local to the current section.

## Displaying Available Coercions

Command Print Classes

  Print the list of declared coercion classes in the current context.

Command Print Coercions

  Print the list of declared coercions in the current context.

Command Print Graph

  Print the list of valid coercion paths in the current context.

Command Print Coercion Paths coercion_class coercion_class

  Print the list of valid coercion paths between the two given classes.

## Activating the Printing of Coercions

Flag Printing Coercions

  When on, this flag forces all the coercions to be printed. By default, coercions are not printed.

Table Printing Coercion qualid

  This table specifies a set of qualids for which coercions are always displayed. Use the `Add` and `Remove` commands to update the set of qualids.

## Classes as Records

Structures with Inheritance may be defined using the `Record` command.

Use `>` before the record name to declare the constructor name as a coercion from the class of the last field type to the record name. See `record_definition`.

Use `:>` in the field type to declare the field as a coercion from the record name to the class of the field type. For these coercions, the `reversible` attribute defaults to `yes`. See `of_type`.

## Coercions and Sections

The inheritance mechanism is compatible with the section mechanism. The global classes and coercions defined inside a section are redefined after its closing, using their new value and new type. The classes and coercions which are local to the section are simply forgotten. Coercions with a local source class or a local target class are also forgotten.

## Coercions and Modules

The coercions present in a module are activated only when the module is explicitly imported.

## Examples

There are three situations:

Example: Coercion at function application

`f a` is ill-typed where `f:forall x:A,B` and `a:A'`. If there is a coercion path between `A'` and `A`, then `f a` is transformed into `f a'` where `a'` is the result of the application of this coercion path to `a`.

We first give an example of coercion between atomic inductive types

Definition bool_in_nat (b:bool) := if b then 0 else 1.
  bool_in_nat is defined
Coercion bool_in_nat : bool >-> nat.
  bool_in_nat is now a coercion
Check (0 = true).
  0 = true : Prop
Set Printing Coercions.
Check (0 = true).
  0 = bool_in_nat true : Prop
Unset Printing Coercions.

Warning

Note that `Check (true = O)` would fail. This is "normal" behavior of coercions. To validate `true=O`, the coercion is searched from `nat` to `bool`. There is none.

We give an example of coercion between classes with parameters.

Parameters (C : nat -> Set) (D : nat -> bool -> Set) (E : bool -> Set).
  C is declared D is declared E is declared
Parameter f : forall n:nat, C n -> D (S n) true.
  f is declared
Coercion f : C >-> D.
  f is now a coercion
Parameter g : forall (n:nat) (b:bool), D n b -> E b.
  g is declared
Coercion g : D >-> E.
  g is now a coercion
Parameter c : C 0.
  c is declared
Parameter T : E true -> nat.
  T is declared
Check (T c).
  T c : nat
Set Printing Coercions.
Check (T c).
  T (g 1 true (f 0 c)) : nat
Unset Printing Coercions.

In the case of functional arguments, we use the monotonic rule of sub-typing. To coerce `t : forall x : A, B` towards `forall x : A', B'`, we have to coerce `A'` towards `A` and `B` towards `B'`. An example is given below:

Parameters (A B : Set) (h : A -> B).
  A is declared B is declared h is declared
Coercion h : A >-> B.
  h is now a coercion
Parameter U : (A -> E true) -> nat.
  U is declared
Parameter t : B -> C 0.
  t is declared
Check (U t).
  U (fun x : A => t x) : nat
Set Printing Coercions.
Check (U t).
  U (fun x : A => g 1 true (f 0 (t (h x)))) : nat
Unset Printing Coercions.

Remark the changes in the result following the modification of the previous example.

Parameter U' : (C 0 -> B) -> nat.
  U' is declared
Parameter t' : E true -> A.
  t' is declared
Check (U' t').
  U' (fun x : C 0 => t' x) : nat
Set Printing Coercions.
Check (U' t').
  U' (fun x : C 0 => h (t' (g 1 true (f 0 x)))) : nat
Unset Printing Coercions.

Example: Coercion to a type

An assumption `x:A` when `A` is not a type, is ill-typed. It is replaced by `x:A'` where `A'` is the result of the application to `A` of the coercion path between the class of `A` and `Sortclass` if it exists. This case occurs in the abstraction `fun x:A => t`, universal quantification `forall x:A,B`, global variables and parameters of (co)inductive definitions and functions. In `forall x:A,B`, such a coercion path may also be applied to `B` if necessary.

Parameter Graph : Type.
  Graph is declared
Parameter Node : Graph -> Type.
  Node is declared
Coercion Node : Graph >-> Sortclass.
  Node is now a coercion
Parameter G : Graph.
  G is declared
Parameter Arrows : G -> G -> Type.
  Arrows is declared
Check Arrows.
  Arrows : G -> G -> Type
Parameter fg : G -> G.
  fg is declared
Check fg.
  fg : G -> G
Set Printing Coercions.
Check fg.
  fg : Node G -> Node G
Unset Printing Coercions.

Example: Coercion to a function

`f a` is ill-typed because `f:A` is not a function. The term `f` is replaced by the term obtained by applying to `f` the coercion path between `A` and `Funclass` if it exists.

Parameter bij : Set -> Set -> Set.
  bij is declared
Parameter ap : forall A B:Set, bij A B -> A -> B.
  ap is declared
Coercion ap : bij >-> Funclass.
  ap is now a coercion
Parameter b : bij nat nat.
  b is declared
Check (b 0).
  b 0 : nat
Set Printing Coercions.
Check (b 0).
  ap nat nat b 0 : nat
Unset Printing Coercions.

Example: Reversible coercions

Notice the `:>` on `ssort` making it a reversible coercion.

Structure S := { ssort :> Type; sstuff : ssort; }.
  S is defined ssort is defined sstuff is defined
Definition test (s : S) := sstuff s.
  test is defined
Canonical Structure S_nat := {| ssort := nat; sstuff := 0; |}.
  S_nat is defined

Check test (nat : Type).
  test (nat : Type) : nat

Example: Reversible coercions using the `reversible` attribute

Notice there is no `:>` on `ssort'` and the added `Coercion` compared to the previous example.

Structure S' := { ssort' : Type; sstuff' : ssort'; }.
  S' is defined ssort' is defined sstuff' is defined
Coercion ssort' : S' >-> Sortclass.
  ssort' is now a coercion
Definition test' (s : S') := sstuff' s.
  test' is defined
Canonical Structure S_nat' := {| ssort' := nat; sstuff' := 0; |}.
  S_nat' is defined

Since there's no `:>` on the definition of `ssort'`, the `reversible` attribute is not set:

Fail Check test' (nat : Type).
  The command has indeed failed with message: The term "nat : Type" has type "Type" while it is expected to have type "S'".

The attribute can be set after declaring the coercion:

#[reversible] Coercion ssort'.
Check test' (nat : Type).
  test' (nat : Type) : nat

Example: Identity coercions.

Definition fct := nat -> nat.
  fct is defined
Parameter incr_fct : Set.
  incr_fct is declared
Parameter fct_of_incr_fct : incr_fct -> fct.
  fct_of_incr_fct is declared

Fail Coercion fct_of_incr_fct : incr_fct >-> Funclass.
  The command has indeed failed with message: Found target class Funclass instead of fct.

Coercion fct_of_incr_fct : incr_fct >-> fct.
  fct_of_incr_fct is now a coercion
Parameter f' : incr_fct.
  f' is declared

Check f' : fct.
  f' : fct : fct
Fail Check f' 0.
  The command has indeed failed with message: Illegal application (Non-functional construction): The expression "f'" of type "incr_fct" cannot be applied to the term "0" : "nat"
Identity Coercion Id_fct_Funclass : fct >-> Funclass.
Check f' 0.
  f' 0 : nat

Example: Inheritance Graph

Let us see the resulting graph after all these examples.

Print Graph.
  [h] : A >-> B [f] : C >-> D [f; g] : C >-> E [g] : D >-> E [Node] : Graph >-> Sortclass [reverse_coercion] : ReverseCoercionSource >-> ReverseCoercionTarget [ap] : bij >-> Funclass [Id_fct_Funclass] : fct >-> Funclass (reversible) [fct_of_incr_fct; Id_fct_Funclass] : incr_fct >-> Funclass [fct_of_incr_fct] : incr_fct >-> fct [ssort] : S >-> Sortclass (reversible) [ssort'] : S' >-> Sortclass (reversible) [bool_in_nat] : bool >-> nat

Other versions v: 8.20.0

Versions
  dev
  stable
  8.20
  8.19
  8.18
  8.17
  8.16
  8.15
  8.14
  8.13
  8.12
  8.11
  8.10
  8.9
  8.8
  8.7
  8.6
  8.5
  8.4
  8.3
  8.2
  8.1
  8.0

Downloads
  PDF