\[\begin{split}\newcommand{\as}{\kw{as}} \newcommand{\Assum}[3]{\kw{Assum}(#1)(#2:#3)} \newcommand{\case}{\kw{case}} \newcommand{\cons}{\textsf{cons}} \newcommand{\consf}{\textsf{consf}} \newcommand{\Def}[4]{\kw{Def}(#1)(#2:=#3:#4)} \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}[4]{\kw{Ind}[#2](#3:=#4)} \newcommand{\ind}[3]{\kw{Ind}~[#1]\left(#2\mathrm{~:=~}#3\right)} \newcommand{\Indp}[5]{\kw{Ind}_{#5}(#1)[#2](#3:=#4)} \newcommand{\Indpstr}[6]{\kw{Ind}_{#5}(#1)[#2](#3:=#4)/{#6}} \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{\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}\]

Polymorphic Universes

Author

Matthieu Sozeau

General Presentation

Warning

The status of Universe Polymorphism is experimental.

This section describes the universe polymorphic extension of Coq. Universe polymorphism makes it possible to write generic definitions making use of universes and reuse them at different and sometimes incompatible universe levels.

A standard example of the difference between universe polymorphic and monomorphic definitions is given by the identity function:

Definition identity {A : Type} (a : A) := a.
identity is defined

By default, constant declarations are monomorphic, hence the identity function declares a global universe (say Top.1) for its domain. Subsequently, if we try to self-apply the identity, we will get an error:

Fail Definition selfid := identity (@identity).
The command has indeed failed with message: The term "@identity" has type "forall A : Type, A -> A" while it is expected to have type "?A" (unable to find a well-typed instantiation for "?A": cannot ensure that "Type@{identity.u0+1}" is a subtype of "Type@{identity.u0}").

Indeed, the global level Top.1 would have to be strictly smaller than itself for this self-application to type check, as the type of (@identity) is forall (A : Type@{Top.1}), A -> A whose type is itself Type@{Top.1+1}.

A universe polymorphic identity function binds its domain universe level at the definition level instead of making it global.

Polymorphic Definition pidentity {A : Type} (a : A) := a.
pidentity is defined
About pidentity.
pidentity@{Top.2} : forall {A : Type}, A -> A pidentity is universe polymorphic Arguments pidentity {A}%type_scope pidentity is transparent Expands to: Constant Top.pidentity

It is then possible to reuse the constant at different levels, like so:

Definition selfpid := pidentity (@pidentity).
selfpid is defined

Of course, the two instances of pidentity in this definition are different. This can be seen when the Printing Universes flag is on:

Set Printing Universes.
Print selfpid.
selfpid = pidentity@{selfpid.u0} (@pidentity@{selfpid.u1}) : forall A : Type@{selfpid.u1}, A -> A (* {selfpid.u1 selfpid.u0} |= selfpid.u1 < selfpid.u0 *) Arguments selfpid _%type_scope

Now pidentity is used at two different levels: at the head of the application it is instantiated at Top.3 while in the argument position it is instantiated at Top.4. This definition is only valid as long as Top.4 is strictly smaller than Top.3, as shown by the constraints. Note that this definition is monomorphic (not universe polymorphic), so the two universes (in this case Top.3 and Top.4) are actually global levels.

When printing pidentity, we can see the universes it binds in the annotation @{Top.2}. Additionally, when Printing Universes is on we print the "universe context" of pidentity consisting of the bound universes and the constraints they must verify (for pidentity there are no constraints).

Inductive types can also be declared universes polymorphic on universes appearing in their parameters or fields. A typical example is given by monoids:

Polymorphic Record Monoid := { mon_car :> Type; mon_unit : mon_car;   mon_op : mon_car -> mon_car -> mon_car }.
Monoid is defined mon_car is defined mon_unit is defined mon_op is defined
Print Monoid.
Record Monoid : Type@{Top.6+1} := Build_Monoid { mon_car : Type@{Top.6}; mon_unit : mon_car; mon_op : mon_car -> mon_car -> mon_car } (* Top.6 |= *) Arguments Build_Monoid _%type_scope _ _%function_scope

The Monoid's carrier universe is polymorphic, hence it is possible to instantiate it for example with Monoid itself. First we build the trivial unit monoid in Set:

Definition unit_monoid : Monoid :=   {| mon_car := unit; mon_unit := tt; mon_op x y := tt |}.
unit_monoid is defined

From this we can build a definition for the monoid of Set-monoids (where multiplication would be given by the product of monoids).

Polymorphic Definition monoid_monoid : Monoid.
1 subgoal ============================ Monoid@{Top.9}
  refine (@Build_Monoid Monoid unit_monoid (fun x y => x)).
No more subgoals.
Defined.
Print monoid_monoid.
monoid_monoid@{Top.9} = {| mon_car := Monoid@{Set}; mon_unit := unit_monoid; mon_op := fun x _ : Monoid@{Set} => x |} : Monoid@{Top.9} (* Top.9 |= Set < Top.9 *)

As one can see from the constraints, this monoid is “large”, it lives in a universe strictly higher than Set.

Polymorphic, Monomorphic

Attribute universes(polymorphic)

This attribute can be used to declare universe polymorphic definitions and inductive types. There is also a legacy syntax using the Polymorphic prefix (see legacy_attr) which, as shown in the examples, is more commonly used.

Flag Universe Polymorphism

This flag is off by default. When it is on, new declarations are polymorphic unless the universes(monomorphic) attribute is used.

Attribute universes(monomorphic)

This attribute can be used to declare universe monomorphic definitions and inductive types (i.e. global universe constraints are produced), even when the Universe Polymorphism flag is on. There is also a legacy syntax using the Monomorphic prefix (see legacy_attr).

Many other commands can be used to declare universe polymorphic or monomorphic constants depending on whether the Universe Polymorphism flag is on or the universes(polymorphic) or universes(monomorphic) attributes are used:

Cumulative, NonCumulative

Attribute universes(cumulative)

Polymorphic inductive types, coinductive types, variants and records can be declared cumulative using this attribute or the legacy Cumulative prefix (see legacy_attr) which, as shown in the examples, is more commonly used.

This means that two instances of the same inductive type (family) are convertible based on the universe variances; they do not need to be equal.

Error The cumulative and noncumulative attributes can only be used in a polymorphic context.

Using this attribute requires being in a polymorphic context, i.e. either having the Universe Polymorphism flag on, or having used the universes(polymorphic) attribute as well.

Note

#[ universes(polymorphic), universes(cumulative) ] can be abbreviated into #[ universes(polymorphic, cumulative) ].

Flag Polymorphic Inductive Cumulativity

When this flag is on (it is off by default), it makes all subsequent polymorphic inductive definitions cumulative, unless the universes(noncumulative) attribute is used. It has no effect on monomorphic inductive definitions.

Attribute universes(noncumulative)

Declares the inductive type as non-cumulative even if the Polymorphic Inductive Cumulativity flag is on. There is also a legacy syntax using the NonCumulative prefix (see legacy_attr).

This means that two instances of the same inductive type (family) are convertible only if all the universes are equal.

Consider the examples below.

Polymorphic Cumulative Inductive list {A : Type} := | nil : list | cons : A -> list -> list.
list is defined list_rect is defined list_ind is defined list_rec is defined list_sind is defined
Print list.
Inductive list@{Top.12} (A : Type@{Top.12}) : Type@{max(Set,Top.12)} := nil : list@{Top.12} | cons : A -> list@{Top.12} -> list@{Top.12} (* *Top.12 |= *) Arguments list {A}%type_scope Arguments nil {A}%type_scope Arguments cons {A}%type_scope

When printing list, the universe context indicates the subtyping constraints by prefixing the level names with symbols.

Because inductive subtypings are only produced by comparing inductives to themselves with universes changed, they amount to variance information: each universe is either invariant, covariant or irrelevant (there are no contravariant subtypings in Coq), respectively represented by the symbols =, + and *.

Here we see that list binds an irrelevant universe, so any two instances of list are convertible: \(E[Γ] ⊢ \mathsf{list}@\{i\}~A =_{βδιζη} \mathsf{list}@\{j\}~B\) whenever \(E[Γ] ⊢ A =_{βδιζη} B\) and this applies also to their corresponding constructors, when they are comparable at the same type.

See Conversion rules for more details on convertibility and subtyping. The following is an example of a record with non-trivial subtyping relation:

Polymorphic Cumulative Record packType := {pk : Type}.
packType is defined pk is defined

packType binds a covariant universe, i.e.

\[E[Γ] ⊢ \mathsf{packType}@\{i\} =_{βδιζη} \mathsf{packType}@\{j\}~\mbox{ whenever }~i ≤ j\]

An example of a proof using cumulativity

Set Universe Polymorphism.
Set Polymorphic Inductive Cumulativity.
Inductive eq@{i} {A : Type@{i}} (x : A) : A -> Type@{i} := eq_refl : eq x x.
eq is defined eq_rect is defined eq_ind is defined eq_rec is defined eq_sind is defined
Definition funext_type@{a b e} (A : Type@{a}) (B : A -> Type@{b}) := forall f g : (forall a, B a),                 (forall x, eq@{e} (f x) (g x))                 -> eq@{e} f g.
funext_type is defined
Section down.
   Universes a b e e'.
   Constraint e' < e.
   Lemma funext_down {A B}      (H : @funext_type@{a b e} A B) : @funext_type@{a b e'} A B.
1 subgoal A : Type B : A -> Type H : funext_type A B ============================ funext_type A B
   Proof.
     exact H.
No more subgoals.
   Defined.
End down.

Cumulativity Weak Constraints

Flag Cumulativity Weak Constraints

When set, which is the default, causes "weak" constraints to be produced when comparing universes in an irrelevant position. Processing weak constraints is delayed until minimization time. A weak constraint between u and v when neither is smaller than the other and one is flexible causes them to be unified. Otherwise the constraint is silently discarded.

This heuristic is experimental and may change in future versions. Disabling weak constraints is more predictable but may produce arbitrary numbers of universes.

Global and local universes

Each universe is declared in a global or local environment before it can be used. To ensure compatibility, every global universe is set to be strictly greater than Set when it is introduced, while every local (i.e. polymorphically quantified) universe is introduced as greater or equal to Set.

Conversion and unification

The semantics of conversion and unification have to be modified a little to account for the new universe instance arguments to polymorphic references. The semantics respect the fact that definitions are transparent, so indistinguishable from their bodies during conversion.

This is accomplished by changing one rule of unification, the first- order approximation rule, which applies when two applicative terms with the same head are compared. It tries to short-cut unfolding by comparing the arguments directly. In case the constant is universe polymorphic, we allow this rule to fire only when unifying the universes results in instantiating a so-called flexible universe variables (not given by the user). Similarly for conversion, if such an equation of applicative terms fail due to a universe comparison not being satisfied, the terms are unfolded. This change implies that conversion and unification can have different unfolding behaviors on the same development with universe polymorphism switched on or off.

Minimization

Universe polymorphism with cumulativity tends to generate many useless inclusion constraints in general. Typically at each application of a polymorphic constant f, if an argument has expected type Type@{i} and is given a term of type Type@{j}, a \(j ≤ i\) constraint will be generated. It is however often the case that an equation \(j = i\) would be more appropriate, when f's universes are fresh for example. Consider the following example:

Polymorphic Definition pidentity {A : Type} (a : A) := a.
pidentity is defined
Set Printing Universes.
Definition id0 := @pidentity nat 0.
id0 is defined
Print id0.
id0@{} = pidentity@{Set} 0 : nat

This definition is elaborated by minimizing the universe of id0 to level Set while the more general definition would keep the fresh level i generated at the application of id and a constraint that Set \(≤ i\). This minimization process is applied only to fresh universe variables. It simply adds an equation between the variable and its lower bound if it is an atomic universe (i.e. not an algebraic max() universe).

Flag Universe Minimization ToSet

Turning this flag off (it is on by default) disallows minimization to the sort Set and only collapses floating universes between themselves.

Explicit Universes

|
Set
|
Prop
::=
Set
|
Prop
|
Type
|
_
|
::=
@{ ident* +? | univ_constraint*, +?? }

The syntax has been extended to allow users to explicitly bind names to universes and explicitly instantiate polymorphic definitions.

Command Universe ident+

In the monomorphic case, declares new global universes with the given names. Global universe names live in a separate namespace. The command supports the universes(polymorphic) attribute (or the Polymorphic legacy attribute) only in sections, meaning the universe quantification will be discharged for each section definition independently.

Error Polymorphic universes can only be declared inside sections, use Monomorphic Universe instead.
Command Constraint univ_constraint+,

Declares new constraints between named universes.

If consistent, the constraints are then enforced in the global environment. Like Universe, it can be used with the universes(polymorphic) attribute (or the Polymorphic legacy attribute) in sections only to declare constraints discharged at section closing time. One cannot declare a global constraint on polymorphic universes.

Error Undeclared universe ident.
Error Universe inconsistency.
Error Polymorphic universe constraints can only be declared inside sections, use Monomorphic Constraint instead

Printing universes

Flag Printing Universes

Turn this flag on to activate the display of the actual level of each occurrence of Type. See Sorts for details. This wizard flag, in combination with Printing All can help to diagnose failures to unify terms apparently identical but internally different in the Calculus of Inductive Constructions.

Command Print Sorted? Universes Subgraph ( qualid* )? string?

This command can be used to print the constraints on the internal level of the occurrences of \(\Type\) (see Sorts).

The Subgraph clause limits the printed graph to the requested names (adjusting constraints to preserve the implied transitive constraints between kept universes).

The Sorted clause makes each universe equivalent to a numbered label reflecting its level (with a linear ordering) in the universe hierarchy.

string is an optional output filename. If string ends in .dot or .gv, the constraints are printed in the DOT language, and can be processed by Graphviz tools. The format is unspecified if string doesn’t end in .dot or .gv.

Polymorphic definitions

For polymorphic definitions, the declaration of (all) universe levels introduced by a definition uses the following syntax:

Polymorphic Definition le@{i j} (A : Type@{i}) : Type@{j} := A.
le is defined
Print le.
le@{i j} = fun A : Type@{i} => A : Type@{i} -> Type@{j} (* i j |= i <= j *) Arguments le _%type_scope

During refinement we find that j must be larger or equal than i, as we are using A : Type@{i} <= Type@{j}, hence the generated constraint. At the end of a definition or proof, we check that the only remaining universes are the ones declared. In the term and in general in proof mode, introduced universe names can be referred to in terms. Note that local universe names shadow global universe names. During a proof, one can use Show Universes to display the current context of universes.

It is possible to provide only some universe levels and let Coq infer the others by adding a + in the list of bound universe levels:

Fail Definition foobar@{u} : Type@{u} := Type.
The command has indeed failed with message: Universe {Top.48} is unbound.
Definition foobar@{u +} : Type@{u} := Type.
foobar is defined
Set Printing Universes.
Print foobar.
foobar@{u Top.50} = Type@{Top.50} : Type@{u} (* u Top.50 |= Top.50 < u *)

This can be used to find which universes need to be explicitly bound in a given definition.

Definitions can also be instantiated explicitly, giving their full instance:

Check (pidentity@{Set}).
pidentity@{Set} : ?A -> ?A where ?A : [ |- Set]
Monomorphic Universes k l.
Check (le@{k l}).
le@{k l} : Type@{k} -> Type@{l} (* {} |= k <= l *)

User-named universes and the anonymous universe implicitly attached to an explicit Type are considered rigid for unification and are never minimized. Flexible anonymous universes can be produced with an underscore or by omitting the annotation to a polymorphic definition.

Check (fun x => x) : Type -> Type.
(fun x : Type@{Top.53} => x) : Type@{Top.53} -> Type@{Top.54} : Type@{Top.53} -> Type@{Top.54} (* {Top.54 Top.53} |= Top.53 <= Top.54 *)
Check (fun x => x) : Type -> Type@{_}.
(fun x : Type@{Top.55} => x) : Type@{Top.55} -> Type@{Top.55} : Type@{Top.55} -> Type@{Top.55} (* {Top.55} |= *)
Check le@{k _}.
le@{k k} : Type@{k} -> Type@{k}
Check le.
le@{Top.58 Top.58} : Type@{Top.58} -> Type@{Top.58} (* {Top.58} |= *)
Flag Strict Universe Declaration

Turning this flag off allows one to freely use identifiers for universes without declaring them first, with the semantics that the first use declares it. In this mode, the universe names are not associated with the definition or proof once it has been defined. This is meant mainly for debugging purposes.

Flag Private Polymorphic Universes

This flag, on by default, removes universes which appear only in the body of an opaque polymorphic definition from the definition's universe arguments. As such, no value needs to be provided for these universes when instantiating the definition. Universe constraints are automatically adjusted.

Consider the following definition:

Lemma foo@{i} : Type@{i}.
1 subgoal ============================ Type@{i}
Proof. exact Type. Qed.
No more subgoals.
Print foo.
foo@{i} = Type@{Top.61} : Type@{i} (* Public universes: i |= Set < i Private universes: {Top.61} |= Top.61 < i *)

The universe Top.xxx for the Type in the body cannot be accessed, we only care that one exists for any instantiation of the universes appearing in the type of foo. This is guaranteed when the transitive constraint Set <= Top.xxx < i is verified. Then when using the constant we don't need to put a value for the inner universe:

Check foo@{_}.
foo@{Top.62} : Type@{Top.62} (* {Top.62} |= Set < Top.62 *)

and when not looking at the body we don't mention the private universe:

About foo.
foo@{i} : Type@{i} (* i |= Set < i *) foo is universe polymorphic foo is opaque Expands to: Constant Top.foo

To recover the same behaviour with regard to universes as Defined, the Private Polymorphic Universes flag may be unset:

Unset Private Polymorphic Universes.
Lemma bar : Type. Proof. exact Type. Qed.
1 subgoal ============================ Type@{Top.63} No more subgoals.
About bar.
bar@{Top.63 Top.64} : Type@{Top.63} (* Top.63 Top.64 |= Top.64 < Top.63 *) bar is universe polymorphic bar is opaque Expands to: Constant Top.bar
Fail Check bar@{_}.
The command has indeed failed with message: Universe instance should have length 2.
Check bar@{_ _}.
bar@{Top.66 Top.67} : Type@{Top.66} (* {Top.67 Top.66} |= Top.67 < Top.66 *)

Note that named universes are always public.

Set Private Polymorphic Universes.
Unset Strict Universe Declaration.
Lemma baz : Type@{outer}. Proof. exact Type@{inner}. Qed.
1 subgoal ============================ Type@{outer} No more subgoals.
About baz.
baz@{outer inner} : Type@{outer} (* outer inner |= inner < outer *) baz is universe polymorphic baz is opaque Expands to: Constant Top.baz

Universe polymorphism and sections

Variables, Context, Universe and Constraint in a section support polymorphism. This means that the universe variables and their associated constraints are discharged polymorphically over definitions that use them. In other words, two definitions in the section sharing a common variable will both get parameterized by the universes produced by the variable declaration. This is in contrast to a “mononorphic” variable which introduces global universes and constraints, making the two definitions depend on the same global universes associated to the variable.

It is possible to mix universe polymorphism and monomorphism in sections, except in the following ways:

  • no monomorphic constraint may refer to a polymorphic universe:

    Section Foo.
      Polymorphic Universe i.
      Fail Constraint i = i.
    The command has indeed failed with message: Cannot add monomorphic constraints which refer to section polymorphic universes.

    This includes constraints implicitly declared by commands such as Variable, which may need to be used with universe polymorphism activated (locally by attribute or globally by option):

    Fail Variable A : (Type@{i} : Type).
    The command has indeed failed with message: Cannot add monomorphic constraints which refer to section polymorphic universes.
    Polymorphic Variable A : (Type@{i} : Type).
    A is declared

    (in the above example the anonymous Type constrains polymorphic universe i to be strictly smaller.)

  • no monomorphic constant or inductive may be declared if polymorphic universes or universe constraints are present.

These restrictions are required in order to produce a sensible result when closing the section (the requirement on constants and inductives is stricter than the one on constraints, because constants and inductives are abstracted by all the section's polymorphic universes and constraints).