Gabriel Scherer

Didier Rémy

GADT meet subtyping

Keywords: subtyping, datatypes, variance sous-typage, types de données, variance

While generalized abstract datatypes (GADT) are now considered well-understood, adding them to a language with a notion of subtyping comes with a few surprises. What does it mean for a GADT parameter to be covariant? The answer turns out to be quite subtle. It involves fine-grained properties of the subtyping relation that raise interesting design questions. We allow variance annotations in GADT definitions, study their soundness, and present a sound and complete algorithm to check them. Our work may be applied to real-world ML-like languages with explicit subtyping such as OCaml, or to languages with general subtyping constraints.

Motivation

In languages that have a notion of subtyping, the interface of parametrized types usually specifies a variance. It defines the subtyping relation between two instances of a parametrized type from the subtyping relations that hold between their parameters. For example, the type α list of immutable lists is expected to be covariant : we wish σ list ≤ σ ′ list as soon as σ ≤ σ ′ .

Variance is essential in languages whose programming idioms rely on subtyping, in particular object-oriented languages. Another reason to care about variance is its use in the relaxed value restriction [START_REF] Garrigue | Relaxing the value restriction[END_REF]: while a possibly-effectful expression, also called an expansive expression, cannot be soundly generalized in ML-unless some sophisticated enhancement of the type system keeps track of effectful expressions-it is always sound to generalize type variables that only appear in covariant positions, which may not classify mutable values. This relaxation uses an intuitive subtyping argument: all occurrences of such type variables can be specialized to ⊥, and anytime later, all covariant occurrences of the same variable (which are now ⊥) can be simultaneously replaced by the same arbitrary type τ , which is always a supertype of ⊥. This relaxation of the value-restriction is implemented in OCaml, where it is surprisingly useful. Therefore, it is important for extensions of type definitions, such as GADT, to support it as well through a clear and expressive definition of parameter covariance.

For example, consider the following GADT of well-typed expressions: Is it safe to say that expr is covariant in its type parameter? It turns out that, using the subtyping relation of the OCaml type system, the answer is "yes". But, surprisingly to us, in a type system with a top type ⊤, the answer would be "no". The aim of this article is to present a sound and complete criterion to check soundness of parameter variance annotations, for use in a type-checker. We also discuss the apparent fragility of this criterion with respect to changes to the subtyping relation (e.g. the presence or absence of a top type, private types, etc.), and a different, more robust way to combine GADT and subtyping.

Examples

Let us first explain why it is reasonable to say that α expr is covariant. Informally, if we are able to coerce a value of type α into one of type α ′ (we write (v :> α ′ ) to explicitly cast a value v of type α to a value of type α ′ ), then we are also able to transform a value of type α expr into one of type α ′ expr. Here is some pseudocode1 for the coercion function: In the Prod case, we make an informal use of something we know about the OCaml type system: the supertypes of a tuple are all tuples. By entering the branch, we gain the knowledge that α must be equal to some type of the form β * γ. So from α ≤ α ′ we know that β * γ ≤ α ′ . Therefore, α ′ must itself be a pair of the form β ′ * γ ′ . By covariance of the product, we deduce that β ≤ β ′ and γ ≤ γ ′ . This allows to conclude by casting at types β ′ expr and γ ′ expr, recursively.

Similarly, in the Int case, we know that α must be an int and therefore an int expr is returned. This is because we know that, in OCaml, no type is above int: if int ≤ τ , then τ must be int.

What we use in both cases is reasoning of the form2 : "if T [β] ≤ α ′ , then I know that α ′ is of the form T [β ′ ] for some β ′ ". We call this an upward closure property: when we "go up" from a T [β], we only find types that also have the structure of T . Similarly, for contravariant parameters, we would need a downward closure property:

T is downward-closed if T [β] ≥ α ′ entails that α ′ is of the form T [β ′ ].
Before studying a more troubling example, we define the classic equality type (α, β) eq, and the corresponding casting function cast : ∀αβ.(α, β) eq → α → β: type (α, β) eq = | Refl : ∀γ. (γ, γ) eq let cast (eqab : (α, β) eq) : α → β = match eqab with | Refl -> (fun x -> x)

Notice that it would be unsound 3 to define eq as covariant, even in only one parameter. For example, if we had type (+α, =β) eq, from any σ ≤ τ we could subtype (σ, σ) eq into (τ, σ) eq, allowing to cast any value of type τ back into one of type σ, which is unsound in general. As a counter-example, the following declaration is incorrect: the type α t cannot be declared covariant.

type +α t = | K : < m : int > → < m : int > t let v = (K (object method m = 1 end) :> < > t)

This declaration uses the OCaml object type < m : int >, which qualifies objects having a method m returning an integer. It is a subtype of object types with fewer methods, in this case the empty object type < >, so the alleged covariance of t, if accepted by the compiler, would allow us to cast a value of type < m : int > t into one of type < > t. However, from such a value, we could wrongly deduce an equality witness (< >, <m : int>) eq that allows to cast any empty object of type < > into an object of type < m : int >, but this is unsound, of course! let get_eq : α t → (α, < m : int >) eq = function | K _ -> Refl (* locally α = < m : int > *) let wrong : < > -> < m : int > = let eq : (< >, < m : int >) eq = get_eq v in cast eq

It is possible to reproduce this example using a different feature of the OCaml type system named private type abbreviation 4 : a module using a type type t = τ internally may describe its interface as type t = private τ . This is a compromise between a type abbreviation and an abstract type: it is possible to cast a value of type t into one of type τ , but not, conversely, to construct a value of type t from one of type τ . In other words, t is a strict subtype of τ : we have t ≤ τ but not t ≥ τ . Take for example type file_descr = private int: this semiabstraction is useful to enforce invariants by restricting the construction of values of type file_descr, while allowing users to conveniently and efficiently destruct them for inspection at type int.

Unsound GADT covariance declarations would defeat the purpose of such private types: as soon as the user gets one element of the private type, she could forge values of this type, as illustrated by the code below. The difference between the former, correct Prod case and those two latter situations with unsound variance is the notion of upward closure. The types α * β and int used in the correct example were upward-closed. On the contrary, the private type M.file_descr has a distinct supertype int, and similarly the object type < m:int > has a supertype < > with a different structure (no method m).

In this article, we formally show that these notions of upward and downwardclosure are the key to a sound variance check for GADT. We start from the formal development of Simonet and Pottier [START_REF] Simonet | A constraint-based approach to guarded algebraic data types[END_REF], which provides a general soundness proof for a language with subtyping and a very general notion of GADT expressing arbitrary constraints-rather than only type equalities. By specializing their correctness criterion, we can express it in terms of syntactic checks for closure and variance, that are simple to implement in a type-checker.

The problem of non-monotonicity

There is a problem with those upward or downward closure assumptions: while they hold in core ML, with strong inversion theorems, they are non-monotonic properties: they are not necessarily preserved by extensions of the subtyping lattice. For example, OCaml has a concept of private types: a type specified by type t = private τ is a new semi-abstract type smaller than τ (t ≤ τ but t τ ), that can be defined a posteriori for any type. Hence, no type is downward-closed forever. That is, for any type τ , a new, strictly smaller type may always be defined in the future.

This means that closure properties of the OCaml type system are relatively weak: no type is downward-closed 5 (so instantiated GADT parameters cannot be contravariant), and arrow types are not upward-closed as their domain should be downward-closed. Only purely positive algebraic datatypes are upward-closed. The subset of GADT declarations that can be declared covariant today is small, yet, we think, large enough to capture a lot of useful examples, such as α expr above.

Giving back the freedom of subtyping

It is disturbing that the type system should rely on non-monotonic properties: if we adopt the correctness criterion above, we must be careful in the future not to enrich the subtyping relation too much. Consider private types for example: one could imagine a symmetric concept of a type that would be strictly above a given type τ ; we will name those types invisible types (they can be constructed, but not observed). Invisible types and GADT covariance seem to be working against each other: if the designer adds one, adding the other later will be difficult.

A solution to this tension is to allow the user to locally guarantee negative properties about subtyping (what is not a subtype), at the cost of selectively abandoning the corresponding flexibility. Just as object-oriented languages have final classes that cannot be extended any more, we would like to be able to define some types as public (respectively visible), that cannot later be made private (resp. invisible). Such declarations would be rejected if the defining type already has subtypes (e.g. an object type), and would forbid further declarations of types below (resp. above) the defined type, effectively guaranteeing downward (resp. upward) closure. Finally, upward or downward closure is a semantic aspect of a type that we must have the freedom to publish through an interface: abstract types could optionally be declared public or visible.

Another approach: subtyping constraints

Getting fine variance properties out of GADT is difficult because they correspond to type equalities which, to a first approximation, use their two operands both positively and negatively. One way to get an easy variance check is to encourage users to change their definitions into different ones that are easier to check. For example, consider the following redefinition of α expr (in a speculative extension of OCaml with subtyping constraints):

type +α expr = | Val : ∀α.α → α expr | Int : ∀α[α≥int].int → α expr | Thunk : ∀β. β expr * (β → α) → α expr | Prod : ∀αβγ[α≥β * γ]. (β expr * γ expr) → α expr
It is now quite easy to check that this definition is covariant, since all type equalities α = T i [β] have been replaced by inequalities α ≥ T i [β] which are preserved when replacing α by a subtype α ′ ≥ α-we explain this more formally in §4.3. This variation on GADT, using subtyping instead of equality constraints, has been studied by Emir et al [START_REF] Emir | Variance and generalized constraints for C# generics[END_REF] in the context of the C♯ programming language.

But isn't such a type definition less useful than the previous one, which had a stronger constraint? We will discuss this choice in more detail in §4.3.

a "closed world" and we can check, for example, that they are never used in a private type definition.

On the importance of variance annotations

Being able to specify the variance of a parametrized datatype is important at abstraction boundaries: one may wish to define a program component relying on an abstract type, but still make certain subtyping assumptions on this type. Variance assignments provide a framework to specify such a semantic interface with respect to subtyping. When this abstract type dependency is provided by an encapsulated implementation, the system must check that the provided implementation indeed matches the claimed variance properties.

Assume the user specifies an abstract type the right hand-side is not a value, and is therefore not generalized in presence of the value restriction; we get a monomorphic type, ?α t, where ?α is a yet-undetermined type variable. The relaxed value restriction [START_REF] Garrigue | Relaxing the value restriction[END_REF] indicates that it is sound to generalize ?α, as it only appears in covariant positions. Informally, one may unify ?α with ⊥, add an innocuous quantification over α, and then generalize ∀α.⊥ t into ∀α.α t by covariance-assuming a lifting of subtyping to polymorphic type schemes.

The definition of nil will therefore get generalized in presence of the relaxed value restriction, which would not be the case if the interface S had specified an invariant type.

Related work

When we encountered the question of checking variance annotations on GADT, we expected to find it already discussed in the literature. The work of Simonet and Pottier [START_REF] Simonet | A constraint-based approach to guarded algebraic data types[END_REF] is the closest we could find. It was done in the context of finding good specification for type inference of code using GADT, and in this context it is natural to embed some form of constraint solving in the type inference problem. From there, Simonet and Pottier generalized to a rich notion of GADT defined over arbitrary constraints, in presence of a subtyping relation, justified in their setting by potential applications to information flow checking.

They do not describe a particular type system, but a parametrized framework HMG(X), in the spirit of the inference framework HM(X). In this setting, they prove a general soundness result, applicable to all type systems which satisfy their model requirements. We directly reuse this soundness result, by checking that we respect these requirements and proving that their condition for soundness is met. This allows us to concentrate purely on the static semantics, without having to define our own dynamic semantics to formulate subject reduction and progress results.

Their soundness requirement is formulated in terms of a general constraint entailment problem involving arbitrary constraints. Specializing this to our setting is simple, but expressing it in a form that is amenable to mechanical verification is surprisingly harder-this is the main result of this paper. Furthermore, at their level of generality, the design issues related to subtyping of GADT, in particular the notion of upward and downward-closed type constructors, were not apparent. Our article is therefore not only a specialized, more practical instance of their framework, but also raises new design issues.

The other major related work, by Emir, Kennedy, Russo and Yu [START_REF] Emir | Variance and generalized constraints for C# generics[END_REF], studies the soundness of having subtyping constraints on classes and methods of an object-oriented type system with generics (parametric polymorphism). Previous work [START_REF] Kennedy | Generalized algebraic data types and object-oriented programming[END_REF] had already established the relation between the GADT style of having type equality constraints on data constructors and the desirable object-oriented feature of having type equality constraints on object methods. This work extends it to general subtyping constraints and develops a syntactic soundness proof in the context of a core type system for an object-oriented languages with generics.

The general duality between the "sums of data" prominent in functional programming and "record of operations" omnipresent in object-oriented programming is now well-understood. Yet, it is surprisingly difficult to reason on the correspondence between GADT and generalized method constraints; an application that is usually considered to require GADT in a functional style (for example a stronglytyped eval α expr datatype and its associated eval function) is simply expressed in idiomatic object-oriented style without specific constraints6 , while the simple flatten : ∀α, α list list → α list requires an equality or subtyping constraint when expressed in object-oriented style. These important differences of style and applications make it difficult to compare our present work with this one. Our understanding of this system is that a subtyping constraint of the form X ≤ Y is considered to be a negative occurrence of X, and a positive occurrence of Y ; this means that equality constraints (which are conjunctions of a (≤) constraint and a (≥) constraints) always impose invariance on their arguments. Checking correctness of constraints with this notion of variance is simpler than with our upward and downward-closure criterion, but also not as expressive. It corresponds, in our work, to the idea of GADT with subtyping constraint mentioned in the introduction and that we detail in §4.3.

The design trade-off in this related work is different from our setting; the reason why we do not focus on this solution is that it requires explicit annotations at the GADT definition site, and more user annotations in pattern matching in our system where subtyping is explicitly annotated, while convertibility is implicitly inferred by unification. On the contrary, in an OOP system with explicit constraints and implicit subtyping, this solution has the advantage of user convenience.

We can therefore see our present work as a different choice in the design space: we want to allow a richer notion of variance assignment for type equalities, at the cost a higher complexity for those checks. Note that the two directions are complementary and are both expressed in our formal framework.

σ ≤ σ σ 1 ≤ σ 2 σ 2 ≤ σ 3 σ 1 ≤ σ 3 b c b ≤ c σ ≥ σ ′ τ ≤ τ ′ σ → τ ≤ σ ′ → τ ′ σ ≤ σ ′ τ ≤ τ ′ σ * τ ≤ σ ′ * τ ′ type vα t ∀i, σ i ≺ vi σ ′ i σ t ≤ σ ′ t

A formal setting

We define a core language for Algebraic Datatypes (ADT) and, later, Generalized Algebraic Datatypes (GADT), that is an instance of the parametrized HMG(X) system of Simonet and Pottier [START_REF] Simonet | A constraint-based approach to guarded algebraic data types[END_REF]. We refine their framework by using variances to define subtyping, but rely on their formal description for most of the system, in particular the static and dynamic semantics. We ultimately rely on their type soundness proof, by rigorously showing (in the next section) that their requirements on datatype definitions for this proof to hold are met in our extension with variances.

Atomic subtyping

Our type system defines a subtyping relation between ground types, parametrized by a reflexive transitive relation between base constant types (int, bool, etc.). Ground types consist of a set of base types b, function types τ 1 → τ 2 , product types τ 1 * τ 2 , and a set of algebraic datatypes σ t. (We write σ for a sequence of types (σ i ) i∈I .) We use prefix notation for datatype parameters, as is the usage in ML. Datatypes may be user-defined by toplevel declarations of the form:

type vα t = | K 1 of τ 1 [α] | ... | K n of τ n [α]
This is a disjoint sum: the constructors K c represent all possible cases and each type τ c [α] is the domain of the constructor K c . Applying it to an argument e of a corresponding ground type τ [σ] constructs a term of type σ t. Values of this type are deconstructed using pattern matching clauses of the form K c x → e, one for each constructor.

The sequence vα is a binding list of type variables α i along with their variance annotation v i , which is a marker among the set {+, -, =, ⋊ ⋉}. We may associate a relation a relation (≺ v ) between types to each variance v:

• ≺ + is the covariant relation (≤);
• ≺ -is the contravariant relation (≥), the symmetric of (≤);

• ≺ = is the invariant relation (=), defined as the intersection of (≤) and (≥);

• ≺ ⋊ ⋉ , is the irrelevant relation (⋊ ⋉), the full relation such that σ ⋊ ⋉ τ holds for all types σ and τ .

Given a reflexive transitive relation ( ) on base types, the subtyping relation on ground types (≤) is defined by the inference rules of Figure 1, which, in particular, give their meaning to the variance annotations vα. The judgment type vα t simply means that the type constructor t has been previously defined with the variance annotation vα. Notice that the rules for arrow and product types can be subsumed by the rule for datatypes, if one consider them as special datatypes (with a specific dynamic semantics) of variance (-, +) and (+, +), respectively. For this reason, the following definitions will not explicitly detail the cases for arrows and products.

Finally, it is routine to show that the rules for reflexivity and transitivity are admissible, by pushing them up in the derivation until the base cases b c, where they can be removed as ( ) is assumed to be reflexive and transitive. Removing reflexivity and transitivity provides us with an equivalent syntax-directed judgment having powerful inversion principles: if σ t ≤ σ ′ t and type vα t, then one can deduce that for each i, σ i ≺ vi σ ′ i . We insist that our equality relation (=) is here a derived concept, defined from the subtyping relation (≤) as the "equiconvertibility" relation (≤ ∩ ≥); in particular, it is not defined as the usual syntactic equality. On the restriction of atomic subtyping The subtyping system demonstrated above is called "atomic". If two head constructors are in the subtyping relation, they are either identical or constant (no parameters). Structure-changing subtyping occurs only at the leaves of the subtyping derivations.

While this simplifies the meta-theoretic study of the subtyping relation, this is too simplifying for real-world type systems that use non-atomic subtyping relations.

In our examples using the OCaml type system, private type were a source of nonatomic subtyping: if you define type α t 2 = private α t 1 , the head constructors t 1 and t 2 are distinct yet in a subtyping relation. If we want to apply our formal results to the design of such languages, we must be careful to isolate any assumption on this atomic nature of our core formal calculus.

The aspect of non-atomic subtype relations we are interested in is the notion of v-closed constructor. We have used this notion informally in the first section (in OCaml, product types are +-closed); we now defined it formally.

Definition 1 (Constructor closure) A type constructor α t is v-closed if, for any type sequence σ and type τ such that σ t ≺ v τ hold, then τ is necessarily equal to σ ′ t for some σ ′ .

In our core calculus, all type constructors are v-closed for any v = ⋊ ⋉, but we will still mark this hypothesis explicitly when it appears in typing judgments; this let the formal results be adapted more easily to a non-atomic type system.

It would have been even more convincing to start from a non-atomic subtyping relation. However, the formal system of Simonet and Pottier, whose soundness proof we ultimately reuse, restricts subtyping relations between (G)ADT type to atomic subtyping. We are confident their proof (and then our formal setting) can be extended to cover the non-atomic case, but we have left this extension to future work.

The algebra of variances

If we know that σ t ≤ σ ′ t, that is σ t ≺ + σ ′ t, and the constructor t has variable vα, an inversion principle tells us that for each i,

σ i ≺ vi σ ′ i .
But what if we only know σ t ≺ u σ ′ t for some variance u different from (+)? If u is (-), we get the reverse relation

σ i ≻ vi σ ′ i . If u is (⋊ ⋉), we get σ i ⋊ ⋉ σ ′ i , that is, nothing. This outlines a composition operation on variances u.v i , such that if σ t ≺ u σ ′ t then σ i ≺ u.vi σ ′ i holds. It is defined by the following table: v.w = + -⋊ ⋉ w = = = = ⋊ ⋉ + = + -⋊ ⋉ - = -+ ⋊ ⋉ ⋊ ⋉ ⋊ ⋉ ⋊ ⋉ ⋊ ⋉ ⋊ ⋉ v
This operation is associative and commutative. Such an operator, and the algebraic properties of variances explained below, have already been used by other authors, for example [START_REF] Abel | Polarized subtyping for sized types[END_REF].

There is a natural order relation between variances, which is the coarser-than order between the corresponding relations: v ≤ w if and only if (≺ v ) ⊇ (≺ w ); i.e. if and only if, for all σ and τ , σ ≺ w τ implies σ ≺ v τ .7 This reflexive, partial order is described by the following lattice diagram:

= C C + { { A A - ⋊ ⋉ } }
That is, all variances are smaller than = and bigger than ⋊ ⋉.

From the order lattice on variances we can define join ∨ and meet ∧ of variances: v ∨ w is the biggest variance such that v ∨ w ≤ v and v ∨ w ≤ v; conversely, v ∧ w is the lowest variance such that v ≤ v ∧ w and w ≤ v ∧ w. Finally, the composition operation is monotonous: if v ≤ v ′ then w.v ≤ w.v ′ (and v.w ≤ v ′ .w).

We will frequently manipulate vectors vα, of variable associated with variances, which correpond to the "context" Γ of a type declaration. We extend our operation pairwise on those contexts: Γ ∨ Γ ′ and Γ ∧ Γ ′ , and the ordering between contexts Γ ≤ Γ ′ . We also extend the variance-dependent subtyping relation (≺ v ), which becomes an order (≺ Γ ) between vectors of type of the same length: σ ≺ vα σ ′ holds when for all i we have σ i ≺ vi σ ′ i .

Variance assignment in ADTs

A counter-example To have a sound type system, some datatype declarations must be rejected. Assume (only for this example) that we have two base types int and bool such that bool int and int bool. Consider the following type declaration:

type (+α, +β) t = | Fun of α → β
If it were accepted, we could build type the following program that deduces from the (+α) variance that (bool, bool) t ≤ (int, bool) t; that is, we could turn the identity function of type bool → bool into one of type int → bool and then turns an integer into a boolean:

let three_as_bool : bool = match (Fun (fun x -> x) : (bool, bool) t :> (int, bool) t) with | Fun (danger : int → bool) -> danger 3 vc-Var wα ∈ Γ w ≥ v Γ ⊢ α : v vc-Constr Γ ⊢ type wα t ∀i, Γ ⊢ σ i : v.w i Γ ⊢ σ t : v
K c of τ c [α]) c∈C is well-signed if ∀c ∈ C, ∀σ, ∀σ ′ , σ t ≤ σ ′ t =⇒ τ c [σ] ≤ τ c [σ ′ ]
The definition of (+α, +β) t is not well-signed because we have (⊥, ⊥) t ≤ (int, ⊥) t according to the variance declaration, but we do not have the corresponding con-

clusion (int → ⊥) ≤ (⊥ → ⊥).
This is a simplified version, specialized to simple algebraic datatypes, of the soundness criterion of Simonet and Pottier. They proved that this condition is sufficient8 for soundness: if all datatype definitions accepted by the type-checker are well-signed, then both subject reduction and progress hold-for their static and dynamic semantics, using the subtyping relation (≤) we have defined.

A judgment for variance assignment When reformulating the well-signedness requirement of Simonet and Pottier for simple ADT, in our specific case where the subtyping relation is defined by variance, it becomes a simple check on the variance of type definitions. Our example above is unsound as its claims α covariant while it in fact appears in negative position in the definition.

In the context of higher-order subtyping [START_REF] Abel | Polarized subtyping for sized types[END_REF], where type abstractions are first-class and annotated with a variance (λvα.τ ), it is natural to present this check as a kind checking of the form Γ ⊢ τ : κ, where Γ is a context vα of type variables associated with variances. For example, if +α ⊢ τ : ⋆ is provable, it is sound to consider α covariant in τ . In the context of a simple first-order monomorphic type calculus, this amounts to a monotonicity check on the type τ as defined by [START_REF] Emir | Variance and generalized constraints for C# generics[END_REF]. Both approaches use judgments of a peculiar form where the context changes when going under a type constructor: to check Γ ⊢ σ → τ , one checks Γ ⊢ τ but (Γ/-) ⊢ σ, where Γ/-reverses all the variances in the context Γ (turns (-) into (+) and conversely). Abel gives an elegant presentation of this inversion / as an algebraic operation on variances, a quasi-inverse such that u/v ≤ w if and only if u ≤ w.v. This context change is also reminiscent of the context resurrection operation of the literature on proof irrelevance (in the style of [START_REF] Pfenning | Intensionality, extensionality, and proof irrelevance in modal type theory[END_REF] for example).

We chose an equivalent but more conventional style where the context of subderivation does not change: instead of a judgment Γ ⊢ τ that becomes (Γ/u) ⊢ σ when moving to a subterm of variance u, we define a judgment of the form Γ ⊢ τ : v, that evolves into Γ ⊢ σ : (v.u). The two styles are equally expressive: our judgment Γ ⊢ τ : v holds if and only if (Γ/v) ⊢ τ holds in Abel's system-but we found that this one extends more naturally to checking decomposability, as will later be necessary. The inference rules for the judgment Γ ⊢ τ : v are defined on Figure 2.

A semantics for variance assignment This syntactic judgment Γ ⊢ τ : v corresponds to a semantics property about the types and context involved, which formalizes our intuition of "when the variables vary along Γ, the expression τ varies along v". We also give a few formal results about this judgment.

Definition 2 (Interpretation of the variance checking judgment)

We write Γ ⊢ τ : v for the property:

∀σ, σ ′ , σ ≺ Γ σ ′ =⇒ τ [σ] ≺ v τ [σ ′ ].
Lemma 1 (Correctness of variance checking) Γ ⊢ τ : v is provable if and only if Γ ⊢ τ : v holds.

Proof:

Soundness: Γ ⊢ τ : v implies Γ ⊢ τ : v By induction on the derivation. In the variable case this is direct. In the σ t case, for ρ, ρ ′ such that ρ ≺ Γ ρ ′ , we get ∀i,

σ i [ρ] ≺ v.wi σ i [ρ ′ ] by inductive hypothesis, which allows to conclude, by definition of variance composition, that (σ t)[ρ] ≺ v (σ t)[ρ ′ ].
Completeness: Γ ⊢ τ : v implies Γ ⊢ τ : v By induction on τ ; in the variable case this is again direct. In the σ t case, given ρ

≺ Γ ρ ′ such that (σ t)[ρ] ≺ v (σ t)[ρ ′ ]
we can deduce by inversion that for each variable α i of variance

w i in τ [α] we have σ i [ρ] ≺ v.wi σ i [ρ ′ ], which allows us to inductively build the subderivations Γ ⊢ σ i : v.w i . Lemma 2 (Monotonicity) If Γ ⊢ τ : v is provable and Γ ≤ Γ ′ then Γ ′ ⊢ τ : v is provable. Lemma 3 If Γ ⊢ τ : v and Γ ′ ⊢ τ : v both hold, then (Γ ∨ Γ ′ ) ⊢ τ : v also holds.
Corollary 1 (Principality) For any type τ and any variance v, there exists a minimal context ∆ such that ∆ ⊢ τ : v holds. That is, for any other context Γ such that Γ ⊢ τ : v, we have ∆ ≤ Γ.

Inversion of subtyping

We have mentioned in 2.1 the inversion properties of our subtyping relation. From σ t ≤ σ ′ t we can deduce subtyping relations on the type parameters σ i , σ ′ i . This can be generalized to any type expression τ [α]:

Theorem 1 (Inversion) For any type τ [α], variance v, and type sequences σ and σ ′ , the subtyping relation τ

[σ] ≺ v τ [σ ′ ] holds if and only if the judgment Γ ⊢ τ : v holds for some context Γ such that σ ≺ Γ σ ′ .
Proof: The reverse implication, is a direct application of the soundness of the variance judgment.

The direct implication is proved by induction on τ

[α]. The variable case is direct: if α[σ] ≺ v α[σ ′ ] holds then for Γ equal to (vα) we indeed have vα ⊢ α : v and σ ≺ Γ σ ′ .
In the τ t case, we have that

(τ t)[σ] ≺ v (τ t)[σ ′ ].
Suppose the variance of α t is wα: by inversion on the head type constructor t we deduce that for each i,

τ i [σ] ≺ v.wi τ i [σ ′ ].
Our induction hypothesis then gives us a family of contexts (Γ i ) i∈I such that for each i we have Γ i ⊢ τ i : v.w i . Furthermore, σ ≺ Γi σ ′ holds for all Γ i , which means that σ ≺ ∧i∈I Γi bs ′ . Let's define Γ as ∧ i∈I Γ i . By construction we have Γ ≥ Γ i , so by monotonicity (Lemma 2) we have Γ ⊢ τ i : v.w i for each i. This allows us to conclude Γ ⊢ τ t : v as desired.

Note that this would work even for type constructors that are not v-closed: we are not comparing a τ [σ] to any type τ ′ , but to a type τ [σ ′ ] sharing the same structure-the head constructors are always the same.

For any given pair σ, σ

′ such that τ [σ] ≺ v τ [σ ′ ] we can produce a context Γ such that σ ≺ Γ σ ′ .
But is there a common context that would work for any pair? Indeed, that is the lowest possible context, the principal context Γ such that Γ ⊢ τ : v.

Corollary 2 (Principal inversion) If ∆ is principal for ∆ ⊢ τ : v, then for any type sequences σ and σ ′ , the subtyping relation τ

[σ] ≺ v τ [σ ′ ] implies σ ≺ ∆ σ ′ . Proof: Let ∆ be the principal context such that ∆ ⊢ τ : v holds. For any σ, σ ′ such that τ [σ] ≺ v τ [σ ′ ], by inversion (Theorem 1) we have some Γ such that Γ ⊢ τ : v and σ ≺ Γ σ ′ . By definition of ∆, ∆ ≤ Γ so σ ≺ ∆ σ ′ also holds. That is, σ ≺ ∆ σ ′ holds for any σ, σ ′ such that τ [σ] ≺ v τ [σ ′ ].

Checking variance of type definitions

We have all the machinery in place to explain the checking of ADT variance declarations. The well-signedness criterion of Simonet and Pottier gives us a general semantic characterization of which definitions are correct: a definition type vα t = (K c of (τ c [α]) c∈C is correct if, for each constructor c, we have:

∀σ, ∀σ ′ , σ t ≤ σ ′ t =⇒ τ [σ] ≤ τ [σ ′ ] By inversion of subtyping, σ t ≤ σ ′ t implies σ i ≺ vi σ ′
i for all i. Therefore, it suffices to check that:

∀σ, ∀σ ′ , (∀i, σ i ≺ vi σ ′ i ) =⇒ τ [σ] ≤ τ [σ ′
] This is exactly the semantic property corresponding to the judgment vα ⊢ τ : (+)! That is, we have reduced soundness verification of an algebraic type definition to a mechanical syntactic check on the constructor argument type. This syntactic criterion is very close to the one implemented in actual type checkers, which do not need to decide general subtyping judgments-or worse solve general subtyping constraints-to check variance of datatype parameters. Our aim is now to find a similar syntactic criterion for the soundness of variance annotations on guarded algebraic datatypes, rather than simple algebraic datatypes.

Variance annotations in GADT

A general description of GADT When used to build terms of type α t, a constructor K of τ behaves like a function of type ∀α.(τ → α t). Remark that the codomain is exactly α t, the type t instantiated with parametric variables. GADT arise by relaxing this restriction, allowing to specify constructors with richer types of the form ∀α.(τ → σ t). See for example the declaration of constructor Prod in the introduction:

| Prod : ∀βγ. β expr * γ expr → (β * γ) expr
Instead of being just α expr, the codomain is now (β * γ) expr. We moved from simple algebraic datatypes to so-called generalized algebraic datatypes. This approach is natural and convenient for the users, so it is exactly the syntax chosen in languages with explicit GADT support, such as Haskell and OCaml, and is reminiscent of the inductive datatype definitions of dependently typed languages.

However, for formal study of GADT, a different formulation based on equality constraints is preferred. The idea is that we will force again the codomain to be exactly α expr, but allow additional type equations such as α = β * γ in this example: In the general case, a GADT definition for α t is composed of a set of constructor declarations, each of the form:

| K : ∀α. (∃β[α = σ[β]]. τ [α, β]) → α t or, reusing the classic notation, | K of ∃β[α = σ[β]]. τ [α, β]
Without loss of generality, we can conveniently assume that the variables α do not appear in the parameter type τ anymore: if some α i appears in τ , one may always pick a fresh existential variable β, add the constraint α = β to D, and consider τ [β/α]. Let us re-express the introductory example in this form, that is,

K of ∃β[α = σ[β]]. τ [β]: type α expr = | Val of ∃β[α = β]. β | Int of [α = int]. int | Thunk of ∃βγ[α = γ]. β expr * (β → γ) | Prod of ∃βγ[α = β * γ]. β expr * γ expr
If all constraints between brackets are of the simple form α i = β i (for distinct variables α i and β i ), as for the constructor Thunk, then we have a constructor with existential types as described by Laüfer and Odersky [START_REF] Odersky | An extension of ML with first-class abstract types[END_REF]. If furthermore there are no other existential variables than those equated with a type parameter, as in the Val case, we have an usual algebraic type constructor; of course the whole type is "simply algebraic" only if each of its constructors is algebraic.

In the rest of the paper, we extend our former core language with such guarded algebraic datatypes. This impacts the typing rules (which are precisely defined in Simonet and Pottier), but not the notion of subtyping, which is defined on (GADT) type constructors with variance type vα t just as it previously was on simple datatypes. What needs to be changed, however, is the soundness criterion for checking the variance of type definitions.

The correctness criterion Simonet and Pottier [START_REF] Simonet | A constraint-based approach to guarded algebraic data types[END_REF] define a general framework HMG(X) to study type systems with GADT where the type equalities in bounded quantification are generalized to an arbitrary constraint language. They make few assumptions on the type system used, mostly that it has function types σ → τ , user-definable (guarded) algebraic datatypes α t, and a subtyping relation σ ≤ τ (which may be just equality, in languages without subtyping).

They use this general type system to give static semantics (typing rules) to a fixed untyped lambda-calculus equipped with datatype construction and pattern matching operations. They are able to prove a type soundness result under just some general assumptions on the particular subtyping relation (≤). Here are the three requirements to get their soundness result:

1. Incomparability of distinct types: for all types τ 1 , τ 2 , σ, σ ′ and distinct datatypes α t, α ′ t ′ , the types (τ 1 → τ 2 ), τ 1 * τ 2 , σ t and σ ′ t ′ must be pairwise incomparable (both and ) -this is where our restriction to an atomic subtyping relation, discussed in §2.1, comes from.

Decomposability of function and product types

: if τ 1 → τ 2 ≤ σ 1 → σ 2 (re- spectively τ 1 * τ 2 ≤ σ 1 * σ 2 ), we must have τ 1 ≥ σ 1 (resp. τ 1 ≤ σ 1 ) and τ 2 ≤ σ 2 .
3. Decomposability of datatypes9 : for each datatype α t and all type vectors σ and σ ′ such that σ t ≤ σ ′ t, we must have (∃β

[D[σ]]τ ) ≤ (∃β[D[σ ′ ]]τ ) for each constructor K of ∃β[D[β, α]]. τ [β].
Those three criteria are necessary for the soundness proof. We will now explain how variance of type parameters impact those requirements, that is, how to match a GADT implementation against a variance specification. With our definition of subtyping based on variance, and the assumption that the datatype vα t we are defining indeed has variance vα, is the GADT decomposability requirement (item 3 above) satisfied by all its constructors? If so, then the datatype definition is sound and can be accepted. Otherwise, the datatype definition does not match the specified variance, and should be rejected by the type checker.

Checking variances of GADT

For every type definition, we need to check that the decomposability requirement of Simonet and Pottier holds. Remark that it is expressed for each GADT constructor independently of the other constructors for the same type: we can check one constructor at a time. Assume we check a fixed constructor

K of argument type ∃β[D[α, β]]. τ [β].
Simonet and Pottier prove that their requirement is equivalent to the following formula, which is more convenient to manipulate:

∀σ, σ ′ , ρ, σ t ≤ σ ′ t ∧ D[σ, ρ] =⇒ ∃ρ ′ , D[σ ′ , ρ ′ ] ∧ τ [ρ] ≤ τ [ρ ′ ] (req-SP)
The purpose of this section is to extract a practical criterion equivalent to this requirement. It should not be expressed as a general constraint satisfaction problem, but rather as a syntax-directed and decidable algorithm that can be used in a typechecker-without having to implement a full-blown constraint solver.

A remark on the non-completeness Note that while the criterion req-SP is sound, it is not complete-even in the simple ADT case. For a constructor K of τ of σ t, the justification for the fact that, under the hypothesis σ t ≤ σ ′ t, we should have τ [σ] ≤ τ [σ ′ ] is the following: given a value v of type τ [σ], we can build the value K v at type σ t, and coerce it to σ ′ t. We can then deconstruct this value by matching the constructor K, whose argument is of type τ [σ ′ ]. But this whole computation, (match (K v :> σ ′ t) with K x → x), reduces to v, so for value reduction to hold we need to also have v :

τ [σ ′ ].
For this whole argument to work we need a value at type τ [σ]. In fact, if the type τ [σ] is not inhabited, it can fail to satisfy req-SP and still be sound: this criterion is not complete. See the following example in a consistent system with an uninhabited type ⊥:

type +α t = | T of int | Empty of ⊥ * (α → bool)
Despite α occurring in a contravariant position in the dead Empty branch (which violates the soundness criterion of Simonet and Pottier), under the assumption that the ⊥ type really is uninhabited we know that this Empty constructor will never be used in closed code, and the contravariant occurrence will therefore never make a program "go wrong". The definition is correct, yet rejected by req-SP, which is therefore incomplete.

Deciding type inhabitation in the general case is a very complex question, which is mostly orthogonal to the presence and design of GADT in the type system. There is, however, one clear interaction between the type inhabitation question and GADT. If a GADT α t is instantiated with type variables σ that satisfy none of the constraints D[α] of its constructors K of ∃β [D].τ , then we know that σ t is not inhabited. This is related to the idea of "domain information" that we discuss in the Future Work section ( §5).

Expressing decomposability

If we specialize req-SP to the Prod constructor of the α expr example datatype, i.e. Prod of ∃βγ[α = β * γ]β expr * γ expr, we get:

∀σ, σ ′ , ρ 1 , ρ 2 , σ expr ≤ σ ′ expr ∧ σ = ρ 1 * ρ 2 =⇒ ∃ρ ′ 1 , ρ ′ 2 , (σ ′ = ρ ′ 1 * ρ ′ 2 ∧ ρ 1 * ρ 2 ≤ ρ ′ 1 * ρ ′ 2 )
We can substitute equalities and use the (assumed) covariance to simplify the subtyping constraint σ expr ≤ σ ′ expr into σ ≤ σ ′ :

∀σ ′ , ρ 1 , ρ 2 , ρ 1 * ρ 2 ≤ σ ′ =⇒ ∃ρ ′ 1 , ρ ′ 2 , (σ ′ = ρ ′ 1 * ρ ′ 2 ∧ ρ 1 ≤ ρ ′ 1 ∧ ρ 2 ≤ ρ ′ 2 ) (1)
This is the upward closure property mentioned in the introduction. This transformation is safe only if any supertype σ ′ of a product ρ 1 * ρ 2 is itself a product, i.e. is of the form ρ ′ 1 * ρ ′ 2 for some ρ ′ 1 and ρ ′ 2 . More generally, for a type Γ ⊢ σ and a variance v, we are interested in a closure property of the form

∀(ρ : Γ), σ ′ , σ[ρ] ≺ v σ ′ =⇒ ∃(ρ ′ : Γ), σ ′ = σ[ρ ′ ]
Here, the context Γ represents the set of existential variables of the constructor (β and γ in our example). We can easily express the condition ρ 1 ≤ ρ ′ 1 and ρ 2 ≤ ρ ′ 2 on the right-hand side of the implication by considering a context Γ annotated with variances (+β, +γ), and using the context ordering (≺ Γ ). Then, (1) is equivalent to:

∀(ρ : Γ), σ ′ , σ[ρ] ≺ v σ ′ =⇒ ∃(ρ ′ : Γ), ρ ≺ Γ ρ ′ ∧ σ ′ = σ[ρ ′ ]
Our aim is now to find a set of inference rules to check decomposability; we will later reconnect it to req-SP. In fact, we study a slightly more general relation, where the equality σ[ρ ′ ] = σ ′ on the right-hand side is relaxed to an arbitrary relation σ

[ρ ′ ] ≺ v ′ σ ′ :
Definition 3 (Decomposability) Given a context Γ, a type expression σ[β] and two variances v and v ′ , we say that σ is decomposable under Γ from variance v to variance v ′ , which we write Γ σ : v v ′ , if the property

∀(ρ : Γ), σ ′ , σ[ρ] ≺ v σ ′ =⇒ ∃(ρ ′ : Γ), ρ ≺ Γ ρ ′ ∧ σ[ρ ′ ] ≺ v ′ σ ′ holds.
We use the symbol rather than ⊢ to highlight the fact that this is just a logic formula, not the semantics criterion corresponding to an inductive judgment, nor a syntactic judgment-we will introduce one later in section 3.4.

Remark that, due to the positive occurrence of the relation ≺ Γ in the proposition Γ τ : v v ′ and the anti-monotonicity of ≺ Γ , this formula is "anti-monotonous" with respect to the context ordering Γ ≤ Γ ′ . This corresponds to saying that we can still decompose, but with less information on the existential witness ρ ′ . Lemma 4 (Anti-monotonicity) If Γ τ : v v ′ holds and Γ ′ ≤ Γ, then Γ ′ τ : v v ′ also holds.

Our final decomposability criterion, given below in Figure 3, requires both correct variances and a decomposability property, so it will be neither monotonous nor anti-monotonous with respect to the context argument.

In the following subsections, we study the subtleties of decomposability.

Variable occurrences

In the Prod case, the type whose decomposability was considered is β * γ (in the context β, γ). In this very simple case, decomposability depends only on the type constructor for the product. In the present type system, with very strong invertibility principles on the subtyping relation, both upward and downward closures hold for products-and any other head type constructor. In the general case, we require that this specific type constructor be upward-closed.

In the general case, the closure of the head type constructor alone is not enough to ensure decomposability of the whole type. For example, in a complex type expression with subterms, we should consider the closure of the type constructors appearing in the subterms as well. Besides, there are subtleties when a variable occurs several times.

For example, while β * γ is decomposable from (+) to (=), β * β is not: ⊥ * ⊥ is an instantiation of β * β, and a subtype of, e.g., int * bool, but it is not equal to (β * β)[γ ′ ] for any γ ′ . The same variable occurring twice in covariant position (or having one covariant and one invariant or contravariant occurence) breaks decomposability.

On the other hand, two invariant occurrences are possible: Finally, a variable may appear in irrelevant positions without affecting closure properties; β * (β irr) (where irr is an upward-closed irrelevant type, defined for example as type

β
α irr = int) is upward closed: if σ * (σ irr) ≤ σ ′ , then σ ′ is of the form σ ′ 1 * (σ ′ 2 irr) with σ ≤ σ ′ 1 and σ ⋊ ⋉ σ ′ 2 , which is equiconvertible to σ ′ 1 * (σ ′ 1
irr) by irrelevance, an instance of β * (β irr).

Context zipping

The intuition to think about these different cases is to consider that, for any σ ′ , we are looking for a way to construct a "witness" σ ′ such that τ [σ ′ ] = σ ′ from the hypothesis τ [σ] ≺ v σ ′ . When a type variable appears only once, its witness can be determined by inspecting the corresponding position in the type σ ′ . For example in α * β ≤ bool * int, the mapping α → bool, β → int gives the witness pair bool, int.

However, when a variable appears twice, the two witnesses corresponding to the two occurrences may not coincide. (Consider for example β * β ≤ bool * int.) If a variable β i appears in several invariant occurrences, the witness of each occurrence is forced to be equal to the corresponding subterm of τ [σ], that is σ i , and therefore the various witnesses are themselves equal, hence compatible. On the contrary, for two covariant occurrences (as in the β * β case), it is possible to pick a σ ′ such that the two witnesses are incompatible-and similarly for one covariant and one invariant occurrence. Finally, an irrelevant occurrence will never break closure properties, as all witnesses (forced by another occurrence) are compatible.

To express these merging properties, we define a "zip" 11 operation v 1 v 2 , that formally expresses which combinations of variances are possible for several occurrences of the same variable; it is a partial operation (for example, it is not defined in the covariant-covariant case, which breaks the closure properties) with the following table:

v w = + -⋊ ⋉ w = = = + + - - ⋊ ⋉ = + -⋊ ⋉ v
The following lemma uses zipping to merge together the results of the decomposition of several subterms (σ i ) i into a "simultaneous decomposition". Definition 4 (Simultaneous decomposition) Given a context Γ, and families of type expressions (σ i ) i∈I and variances (v i ) i∈I and (v ′ i ) i∈I , we define the following "simultaneous closure property" Γ (T i : v i v ′ i ) i∈I defined as :

∀(ρ : Γ), σ ′ , (∀i ∈ I, σ i [ρ] ≺ vi σ ′ i ) =⇒ ∃(ρ ′ : Γ), ρ ≺ Γ ρ ′ ∧ (∀i ∈ I, σ i [ρ ′ ] ≺ v ′ i σ ′ i )
Lemma 5 (Soundness of zipping) Suppose we have families of type expressions (T i [β]) i∈I , contexts (Γ i ) i∈I and variances (v i ) i∈I and (v ′ i ) i∈I such that i∈I Γ i exists and for all i we have both Γ i ⊢ T i : v i and Γ i T i : v i v ′ i . Then, we have

( i∈I Γ i ) (σ i : v i v ′ i ) i∈I .
Proof: Without loss of generality, we can consider that there are only two type expressions T 1 [β] and T 2 [β], and that the free variables β is reduced to a single variable β. Let w 1 , w 2 be the respective variances of β in Γ 1 , Γ 2 . We know that (w 1 w 2 ) exists and is equal to the variance w of the variable β in Γ 1 Γ 2 .

Our further assumptions are Γ i ⊢ T i : v i (1) and Γ i T i :

v i v ′ i (2) for i in {1, 2}. The expansion of (2) is: ∀i ∈ I, ∀ρ, σ ′ i , T i [ρ] ≺ vi σ ′ i =⇒ ∃ρ ′ , ρ ≺ Γi ρ ′ ∧ T i [ρ ′ ] ≺ v ′ i σ ′ i (3) Our goal is to prove Γ 1 Γ 2 (σ i : v i v ′ i ) i∈I , which is equivalent to: ∀ρ, σ ′ , (∀i ∈ I, (T i [ρ] ≺ vi σ ′ i )) =⇒ ∃ρ ′ , ρ ≺ Γ ρ ′ ∧ ∀i ∈ I, T i [ρ ′ ] ≺ v ′ i σ ′ i (4) Assume given ρ and (σ ′ 1 , σ ′ 2 ) such that T 1 [ρ] ≺ v1 σ ′ 1 (5) and T 2 [ρ] ≺ v2 σ ′ 2 (
6). Applying (3) with i equal to 1 and (5) ensures the existence of a ρ ′ 1 such that ρ ≺ w1 ρ ′ 1 (7) and

T 1 [ρ ′ 1 ] ≺ v1 σ ′ 1 (8). Similarly, there exists ρ ′ 2 such that ρ ≺ w2 ρ ′ 2 (9) and T 2 [ρ ′ 2 ] ≺ v2 σ ′ 2 (
10). To establish (4), it remains to build a single ρ ′ that satisfies

ρ ≺ w ρ ′ (11), T 1 [ρ ′ ] ≺ v1 σ ′ 1 (12) and T 2 [ρ ′ ] ≺ v2 σ ′ 2 (
13), simultaneously. We reason by case analysis on w 1 and w 2 (restricted to the cases where the zip exists).

If both w 1 and w 2 are (⋊ ⋉), we take either ρ ′ 1 or ρ ′ 2 for: since w is ⋊ ⋉, we (11) trivially holds; Furthermore,

T [ρ ′ ] = T [ρ ′ 1 ] = T [ρ ′ 2 ]
by irrelevance of v i and (1); therefore (12) and (13) follow from ( 8) and ( 10).

If only one of the w i is (⋊ ⋉), we'll suppose that it is w 1 . We then take ρ 2 for ρ ′ . Since ⋊ ⋉ 1 w 2 is w 2 , (11) follows from (9); Furthermore,

T [ρ ′ ] = T [ρ ′
1 ] by irrelevance of 11 The idea of context merging and the term "zipping" are inspired by Montagu and Remy [START_REF] Montagu | Modeling abstract types in modules with open existential types[END_REF] sc-Triv

v ≥ v ′ Γ ⊢ τ : v Γ ⊢ τ : v ⇒ v ′ sc-Var wα ∈ Γ w = v Γ ⊢ α : v ⇒ v ′ sc-Constr Γ ⊢ type wα t : v-closed Γ = i Γ i ∀i, Γ i ⊢ σ i : v.w i ⇒ v ′ .w i Γ ⊢ σ t : v ⇒ v ′ Figure 3: Syntactic decomposablity v 1 and (1) while T 2 [ρ ′ ] = T 2 [ρ ′
2 ] holds by construction; Hence, as in the previous case, ( 12) and (13) follow from ( 8) and (10).

Finally, if both w 1 and w 2 are (=), then (7) and ( 9) implies ρ ′ 1 = ρ = ρ ′ 2 . We take ρ for ρ ′ and all three conditions are obviously satisfied. This lemma admits a kind of converse lemma stating completeness of zipping, that says that if Γ (T i : v i v ′ i ) i holds, then Γ is indeed related to a zip of contexts (Γ i ) i that pairwise decompose each of the (T i ) i . However, the proof of completeness is more delicate and we prove it separately in §3.5.

Syntactic decomposability

Equipped with the zipping operation, we introduce a judgment Γ ⊢ τ : v ⇒ v ′ to express decomposability, syntactically, defined by the inference rules on Figure 3.

We rely on the zip soundness (Lemma 5) to merge sub-derivations into larger ones, so in addition to decomposability, the judgments simultaneously ensures that v is a correct variance for τ under Γ. Actually, in order to understand the details of this judgment, it is quite instructive to compare it with the variance-checking judgment Γ ⊢ τ : v defined on Figure 2.

Rule sc-Var is very similar to vc-Var, except that the condition w ≥ v is replaced by a stronger equality w = v. The reason why the variance-checking judgment has an inequality w ≥ v is to make it monotonous in the environment-as requested by its corresponding semantics criterion (Definition 2). Therefore, the condition w ≥ v is necessary for completeness-and admissible. On the contrary, the present judgment ensures, according the semantic criterion (Definition 5), that both the variance is correct (monotonous in the environment) and the type is decomposable, a property which is anti-monotonic in the environment (Lemma 4). Therefore, the semantics criterion Γ ⊢ τ : v ⇒ v ′ is invariant in Γ and, correspondingly, the variable rule must use a strict equality.

The most interesting rule is sc-Constr. It checks first that the head type constructor is v-closed (according to Definition 1); then, it checks each subtype for decomposability from v to v ′ with compatible witnesses, that is, in an environment family Γ i that can be zipped into a unique environment Γ.

In order to connect the syntactic and semantics versions of decomposability, we define the interpretation Γ ⊢ τ : v ⇒ v ′ of syntactic decomposability.

Definition 5 (Interpretation of syntactic decomposability)

We write Γ ⊢ τ : v ⇒ v ′ for the conjunction of properties Γ ⊢ τ : v and Γ τ : v v ′ .

Note that our interpretation Γ ⊢ τ : v ⇒ v ′ does not coincide with our previous decomposability formula Γ τ : v v ′ , because of the additional variance-checking hypothesis that makes it composable. The distinction between those two notions of decomposition is not useful to have a sound criterion, but is crucial to be complete with respect to the criterion of Simonet and Pottier, which imposes no variance checking condition.

Lemma 6 (Soundness of syntactic decomposability)

If the judgment Γ ⊢ τ : v ⇒ v ′ holds, then Γ ⊢ τ : v ⇒ v ′ is holds. Proof: The proof is by induction on the derivation Γ ⊢ τ : v ⇒ v ′ (1). Expanding Γ ⊢ τ : v ⇒ v ′ , we must show both Γ ⊢ τ : v , or equivalently Γ ⊢ τ : v (2) and Γ τ : v v ′ (3)
, which itself expands to: [START_REF][END_REF]. Cases where the derivation of (1) ends with sc-Triv and sc-Var cases are direct: take ρ and (. . . , σ ′ , . . . ) for ρ ′ , respectively.

∀(ρ : Γ), σ ′ , σ[ρ] ≺ v σ ′ =⇒ ∃(ρ ′ : Γ), ρ ≺ Γ ρ ′ ∧ σ[ρ ′ ] ≺ v ′ σ ′ Let ρ, τ ′ be such that τ [ρ] ≺ v τ ′ . We must exhibit a sequence ρ ′ such that ρ ≺ Γ ρ ′ (4) and τ [ρ ′ ] ≺ v ′ τ ′ (
In the remaining cases, the derivation ends with Rule sc-Constr and τ is of the form σ t.

• The v-closure assumption of the left premise ensures that τ ′ is itself of the form σ ′ t for some sequence of closed types σ ′ . By inversion on the variance wα of the head constructor t, we deduce σ i [ρ] ≺ v.wi σ ′ i for all i (6). • The middle premise is the zipping assumption on the contexts Γ = i∈I Γ i (7).

• The right premises gives us subderivations Γ i ⊢ σ i : v.w i ⇒ v ′ .w i . This implies Γ i ⊢ σ i : v.w i , for all i, which implies Γ ⊢ σ t : v, i.e. (2). By induction hypothesis, this also implies Γ i ⊢ σ i : v.w i (8) and Γ i σ i : v.w i ⇒ v ′ .w i for all i (9).

We may now apply zip soundness (Lemma 5) with hypotheses (7), (8) and (9), which gives us the simultaneous decomposition Γ (σ ′ i : v.w i v ′ .w i ) i∈I . Expanding this property (Definition 4), we may apply to (6) to get to get a witness ρ ′ such that both ρ ′ ≺ Γ ρ, i.e. our first goal (4), and (∀i

∈ I, σ i [ρ ′ ] ≺ v ′ .wi σ ′ i ), which implies (σ t)[ρ ′ ] ≺ v ′ σ ′ t, i.e. our second goal (5).
Completeness is the general case is however much more difficult and we only prove it when the right-hand side variance v ′ is (=). In other words, we take back the generality that we have introduced in §3.1 when defining decomposability. The proof requires several auxiliary lemmas; it is the subject of the next subsection.

Completeness of syntactic decomposability

We first show a few auxiliary results that will serve in the proof of zip completeness, and later, to reconnect our closure-checking criterion (Definition 5) with the full criterion of Simonet and Pottier (req-SP).

Lemma 7 (Intermediate value) Let τ [α] be a type expression and ρ 1 , ρ 2 , ρ 3 three type families such that τ [ρ 1 ] ≤ τ [ρ 2 ] ≤ τ [ρ 3 ] and ρ 1 ≺ Γ ρ 3 holds for some Γ. Then, there exists a type family ρ ′ 2 such that both

ρ 1 ≺ Γ ρ ′ 2 ≺ Γ ρ 3 and τ [ρ ′ 2 ] = τ [ρ 2 ] hold.
Proof: We reuse the notations of the definition and assume τ

[ρ 1 ] ≤ τ [ρ 2 ] ≤ τ [ρ 3 ] (1) and ρ 1 ≺ Γ ρ 3 (2). We just have to exhibit ρ ′ 2 such that both ρ 1 ≺ Γ ρ ′ 2 ≺ Γ ρ 3 (3) and τ [ρ ′ 2 ] = τ [ρ 2 ] (4) hold.
Let ∆ be the most general variance of τ , i.e. the lowest context such that ∆ ⊢ τ : + (5) holds. By principal inversion (Corollary 2) applied to (1) twice thanks to (5), we have

ρ 1 ≺ ∆ ρ 2 ≺ ∆ ρ 3 (6).
If ∆ ≥ Γ, the result is immediate, as ρ 1 ≺ Γ ρ 2 ≺ Γ ρ 3 follows from (6) by antimonotonicity and both (3) and ( 4) hold when we take ρ 2 for ρ ′ 2 . Otherwise, we reason on each variable of the context Γ independently. We may assume, w.l.o.g., that τ is defined over a single free variable α, and Γ and ∆ are single variances v ∆ , v Γ with v ∆ v Γ . We reason by case analysis on the possible variances for (v ∆ , v Γ ), which are {( , =), (+, -), (-, +), (⋊ ⋉, )}. 3) and (4), as above. Finally, the cases (+, -) and (-, +) are symmetric and we will only work out the first one, i.e. v ∆ is (+) and v Γ is (-). From τ [ρ 1 ] ≤ τ [ρ 3 ] (which follows from (1) by transitivity) and ( 5), we have ρ 1 ≺ v∆ ρ 3 , i.e. ρ 1 ≤ ρ 3 . Since the hypothesis (2) becomes ρ 1 ≥ ρ 3 , we have ρ 1 = ρ 3 . Then, taking ρ 1 for ρ ′ 2 , (3) trivially holds while (4) follows from (1).

If v Γ is (=), the hypotheses (2) and (1) become ρ 1 = ρ 3 and τ [ρ 1 ] ≤ τ [ρ 2 ] ≤ τ [ρ 1 ], which implies τ [ρ 1 ] = τ [ρ 2 ]. Thus, taking ρ 1 for ρ ′ 2 satisfies (3) and (4). If v ∆ is (⋊ ⋉), then by irrelevant of ⋊ ⋉ and (5), we have τ [ρ 1 ] = τ [ρ 2 ]. Thus, taking ρ 1 for ρ ′ 2 satisfies (
The next lemma connects the monotonicity of the variance-checking judgment (checking variance at a lower context provides more information, and is therefore harder) and the anti-monotonicity of the decomposability formula (decomposing to a higher context provides more information, and is therefore harder): for a fixed type expression, the contexts at which you can check variance are higher than the contexts at which you can decompose. This property, however, only holds for nontrivial decomposability results (otherwise any context can decompose): we must decompose from a v to a v ′ that do not verify v ≥ v ′ , and no variable of the typing context must be irrelevant.

Lemma 8 Let τ [α] be a type and v and v ′ be variances such that v v ′ . If Γ τ : v v ′ and ∆ is the most general context such that ∆ ⊢ τ : v, then, for each non-irrelevant variable α of ∆, we have Γ(α) ≤ ∆(α).

Proof: We show that the Γ is lower than the lowest possible ∆, i.e. it is the most general context such that ∆ ⊢ τ : v holds. Without loss of generality, we consider the case where τ has a single, non-irrelevant variable α, and Γ and ∆ are singleton contexts over a single variance, respectively w Γ and w ∆ , with w ∆ = (⋊ ⋉).

Therefore, we assume (w Γ α) τ : v v ′ (1) and (w ∆ α) ⊢ τ : v (2). We prove that w Γ ≤ w ∆ . We actually show that for any ρ 1 , ρ 2 such that ρ 1 ≺ ∆ ρ 2 we also have

ρ 1 ≺ Γ ρ 2 (3). From ρ 1 ≺ Γ ρ 2 , we can deduce τ [ρ 1 ] ≺ v τ [ρ 2 ] (4). Applying (1), we get a ρ ′ such that ρ 1 ≺ Γ ρ ′ (5) and τ [ρ ′ ] ≺ v ′ τ [ρ 2 ] (6).
We then reason by case analysis on v v ′ , considering the different cases {(⋊ ⋉, ), (+, -), (-, +), ( , =)}.

If v is (⋊ ⋉), the most general w ∆ is ⋊ ⋉, a case we explicitly ruled out: there is nothing to prove.

If v ′ is (=), then (6) implies τ [ρ ′ ] = τ [ρ 2 ]
, and in particular ρ ′ = ρ 2 ; our goal (3) follows from [START_REF][END_REF].

If (v, v ′ ) is (+, -) (we won't repeat the symmetric case (-, +)), then (4) and ( 6

) becomes τ [ρ 1 ] ≤ τ [ρ 2 ] and τ [ρ 2 ] ≤ τ [ρ ′ ]. Given (5), the intermediate value lemma (Lemma 7) ensures the existence of a ρ ′′ such that ρ ≺ Γ ρ ′′ ≺ Γ ρ ′ and τ [ρ ′′ ] = τ [ρ 2 ].
From there, we deduce ρ ′′ = ρ 2 , our goal (3) follows from [START_REF][END_REF], as in the previous case.

Finally, the following auxiliary lemmas will be useful in the proof of completeness.

We construct a family of contexts (Γ i ) i∈I such that the following holds:

Γ ≤ i Γ i∈I (2) ∀i, Γ i ⊢ T i : v i (3) ∀i, Γ i T i : v i (=) (4)
where ( 4) is equivalent to

∀i, ∀σ ′ i , ρ, T i [ρ] ≺ vi σ ′ i =⇒ ∃ρ ′ , ρ ≺ Γi ρ ′ ∧ T i [ρ ′ ] = σ ′ i (5)
The first step is to move from the entailment (1) of the form ∀ρ, (∀i ∈ I, . . . ) =⇒ (∃ρ ′ , (∀i ∈ I, . . . )) to the weaker form (∀i ∈ I, ∀ρ, . . . =⇒ ∃ρ ′ , . . . ), but closer to [START_REF][END_REF]. More precisely, we show that

∀i, ∀σ ′ i , ρ, T i [ρ] ≺ vi σ ′ i =⇒ ∃ρ ′ , ρ ≺ Γ ρ ′ ∧ T i [ρ ′ ] = σ ′ i (6)
that is, ∀i, Γ T i : v i (=) (7). Let i, σ ′ i , and ρ be such that T i [ρ] ≺ vi σ ′ i (8). We show that there exists a ρ ′ such that T i [ρ] = σ ′ i (9) and ρ ≺ Γ ρ ′ (10). Let us extend our type σ ′ i to a family σ ′ , defined by taking σ ′ j equal to T j [ρ] for j in I \ {i}. By construction, we have (∀j ∈ I, T j [ρ] ≺ vj σ ′ j ). Therefore, we may apply (1) to get a ρ ′ such that ρ ≺ Γ ρ ′ , i.e. our first goal (10), and (∀j, T j [ρ ′ ] = σ ′ i ), which implies our second goal (9) when j is i. This proves (6).

We now prove that we can refine this to have ρ ≺ Γi ρ ′ for (Γ i ) i∈I such that Γ ≤ i Γ i .

Let ∆ 1 and ∆ 2 be the most general contexts such both that ∆ 1 ⊢ T 1 : v 1 and ∆ 2 ⊢ T 2 : v 2 hold (11). Let (2)', (3)', and (4)' be obtained by replacing Γ i 's by ∆ i 's in our three goals (2), (3), and (4). In fact (3)' is just (11). By Lemma 10 applied to (7) twice, given (11), we have both ∆ 1 T 1 : v 1 (=) and ∆ 2 T 2 : v 2 (=), that is, (4).

Hence ∆ 1 and ∆ 2 are correct choices for Γ 1 and Γ 2 if they also satisfy the goal (2)', i.e. ∆ 1 ∆ 2 ≥ Γ. We now study when remaining goal (2)' holds and, when it does not, propose a different choice for Γ 1 and Γ 2 that respect all three goals. Therefore, the only remaining case is when w 1 and w 2 are both (=). Then ∆ 1 ∆ 2 is (=β), which is the highest single-variable context. So our goal (2)' trivially holds.

Of these several cases, one (⋊ ⋉, ⋊ ⋉) has Γ 1 Γ 2 = Γ directly, and in the others Γ 1 and Γ 2 were defined as the most general contexts such that Γ 1 ⊢ T 1 : v 1 and Γ 2 ⊢ T 2 : v 2 . If we add the further hypothesis that for each i, Γ ⊢ T i : v i holds, then by principality of the Γ i , we have that Γ i ≤ Γ for each i. This implies that we have ( i∈I Γ i ) ≤ Γ (when it is defined, coincides with the lowest upper bound ∧). By combination with (2), we get ( i∈I Γ i ) = Γ.

Lemma 12 (Completeness of syntactic decomposability)

If Γ ⊢ τ : v ⇒ v ′ holds for v ′ ∈ {=, ⋊ ⋉}, then Γ ⊢ τ : v ⇒ v ′ is provable. Proof: Assume Γ ⊢ τ : v ⇒ v ′ holds for v ′ ∈ {=, ⋊ ⋉}, i.e. Γ ⊢ τ : v (1) and Γ τ : v v ′ (2)
, which expands to

∀(ρ : Γ), τ ′ , τ [ρ] ≺ v τ ′ =⇒ ∃(ρ ′ : Γ), ρ ≺ Γ ρ ′ ∧ τ [ρ ′ ] ≺ v ′ τ ′ (3)
We show Γ ⊢ τ : v ⇒ v ′ (4) by structural induction on τ

If v ≥ v ′ holds, then (4) directly follows from Rule sc-Triv. This applies in particular when v ′ = ⋊ ⋉. Hence, we only need to consider the remaining cases where v ′ is (=) and v ≥ v ′

We now reason by cases on τ .

Case τ is a variable α.

(3) becomes

∀ρ, τ ′ , ρ ≺ v τ ′ =⇒ ∃ρ ′ , ρ ≺ Γ ρ ′ ∧ ρ ′ = τ ′
This means that if ρ ≺ v τ ′ holds then ρ ≺ Γ τ ′ also holds: the variance wα ∈ Γ satisfies v ≥ w. Since, the hypothesis (1) implies v ≤ w, we have v = w. Therefore, (4) follows by Rule sc-Var.

Case τ is of the form σ t. By inversion, the derivation of (1) must end with rule vc-Constr, hence we have Γ ⊢ σ i : v.w i (5) for each i ∈ I with Γ ⊢ type wα t (6).

Let us show that Γ (σ i : v.w i =.w i ) i∈I (7), i.e.

∀ρ, σ ′ , (∀i ∈ I, σ i [ρ] ≺ vi σ ′ i ) =⇒ ∃ρ ′ , ρ ≺ Γ ρ ′ ∧ (∀i ∈ I, σ i [ρ ′ ] ≺ v ′ i σ ′ i )
Let ρ and σ ′ be such that σ i [ρ] ≺ vi σ ′ i holds for all i in I. From this and (5), we have (σ t)[ρ] ≺ v σ ′ t. By applitcation of (2), there exists ρ ′ such that ρ ≺ Γ ρ ′ and (σ t)[ρ ′ ] ≺ = σ ′ t. By inversion of subtyping , this implies σ i [ρ ′ ] ≺ =.wi σ ′ i , for all i in I. This proves (7). We also note that the constructor t is v-closed (8).

To prove our goal (4), we construct a family (Γ i ) i∈I of contexts that satisfies i∈I Γ i = Γ (9) and subderivations Γ i ⊢ σ i : v.w i ⇒ =.w i (10), since then the conclusion (4) follows by an application of rule sc-Constr with (6), (9), and (10).

We will handle separately the arguments σ j that are irrelevant, i.e. when w j is ⋊ ⋉, from the rest. Let I ⋊ ⋉ be the set of indices with irrelevant variances and I ⋊ ⋉ the others.

For any i ∈ I ⋊ ⋉ , v.w i and =.w i are both ⋊ ⋉ so the condition (10), which becomes

Γ i ⊢ σ i : ⋊ ⋉ ⇒ ⋊ ⋉, is void of content (σ i [ρ] ≺ ⋊ ⋉ σ ′ i =⇒ ∃ρ ′ , σ i [ρ ′ ] ≺ ⋊ ⋉ σ ′
i is always true). More precisely, let Γ i be the irrelevant context having only irrelevant variances. Then (10) follows by Rule sc-Triv.

Since the decomposability constraints for i ∈ I ⋊ ⋉ such that w i = ⋊ ⋉ are trivial, ( 7) is equivalent to Γ (σ i : v.w i =.w i ) i∈I ⋊ ⋉ (11).

For each i ∈ I ⋊ ⋉ , (=.w i ) equals (=), so (11) becomes Γ (σ i : v.w i (=)) i∈I ⋊ ⋉ . By zip completeness (Theorem 2), there is a family (Γ i ) i∈I ⋊ ⋉ such that Γ ≤ i∈I ⋊ ⋉ Γ i and both Γ i ⊢ σ i : v.w i and Γ i σ i : v.w i (=), i.e. Γ i ⊢ σ i : v.w i ⇒ (=) (12) hold for any i ∈ I ⋊ ⋉ , Furthermore, since we also have [START_REF][END_REF], we can strengthen our result into i∈I ⋊ ⋉ Γ i = Γ. By induction hypothesis applied to (12), we have (10) for i ∈ I ⋊ ⋉ .

We have two families of contexts over domains I ⋊ ⋉ and I ⋊ ⋉ that partition I; we can union them in a family (Γ i ) i∈I that has subderivations ∀i ∈ I, Γ i ⊢ σ i : v.w i ⇒ v ′ .w i . As the contexts in I ⋊ ⋉ are all irrelevant, they are neutral for the zipping operation:

i∈I Γ i is equal to i∈I ⋊ ⋉ Γ i
, that is Γ. This proves (9) while (10) has already been proved separately for i ∈ I ⋊ ⋉ and i ∈ I ⋊ ⋉ .

Remark 1 (Note ( 8)) The head constructor t is closed in our system with atomic subtyping, but the situation is in fact a bit stronger than that: the statement of vclosure of α t can be formulated in term of decomposability Γ α t : v (=). It is very close from our decomposability hypothesis Γ σ t : v (=), but uses variables α instead of full type expressions σ. We conjecture that the decomposability hypothesis (with = on the right) implies v-closure in a much larger set of subtyping systems that just atomic subtyping: it suffices that the subtyping relation is defined only in term of head constructors.

Back to the correctness criterion

Remember the correctness criterion req-SP of Simonet and Pottier:

∀σ, σ ′ , ρ, (σ t ≤ σ ′ t ∧ D[σ, ρ] =⇒ ∃ρ ′ , D[σ ′ , ρ ′ ] ∧ τ [ρ] ≤ τ [ρ ′ ]) (1)
We now show how the closure judgment Γ ⊢ τ : v ⇒ v ′ can be used to verify that this criterion holds: we will express this criterion in an equivalent form that uses the interpretation of our judgments. The first step is to rewrite the property σ t ≤ σ ′ t using the variance annotation vα of t. Again, we are taking the variance annotation for the datatype t as granted (this is why we can use it in this reasoning step), and checking that the definitions of the constructors of t are sound with respect to this annotation.

∀σ, σ ′ , ρ, ((∀i, σ i ≺ vi σ ′ i ) ∧ D[σ, ρ] =⇒ ∃ρ ′ , D[σ ′ , ρ ′ ] ∧ τ [ρ] ≤ τ [ρ ′ ]) (2)
Since, the constraint D[α, β] is a set of equalities of the form α i = T i [β] (where T i is a type), ( 2) is actually:

∀σ, σ ′ , ρ, (∀i, σ i ≺ vi σ ′ i ) ∧ (∀i, σ i = T i [ρ]) =⇒ ∃ρ ′ , (∀i, T i [ρ ′ ] = σ ′ i ) ∧ τ [ρ] ≤ τ [ρ ′
] Substituting the equalities and, in particular, removing the quantification on the σ, which are fully determined by the equality constraints σ = T [ρ], we get:

∀σ ′ , ρ, (∀i, T i [ρ] ≺ vi σ ′ i ) =⇒ ∃ρ ′ , (∀i, T i [ρ ′ ] = σ ′ i ) ∧ τ [ρ] ≤ τ [ρ ′ ] (3)
By inversion (Theorem 1), we may replace the goal τ [ρ] ≤ τ [ρ ′ ] by the formula ∃Γ, (Γ ⊢ τ : +) ∧ (ρ ≺ Γ ρ ′ ). Moreover, since Γ ⊢ τ : + always for for some Γ, we may move this quantification in front. Hence, (3) is equivalent to:

∃Γ, Γ ⊢ τ : + ∀σ ′ , ρ, (∀i, T i [ρ] ≺ vi σ ′ i ) =⇒ ∃ρ ′ , (∀i, T i [ρ ′ ] = σ ′ i ) ∧ ρ ≺ Γ ρ ′ (4)
We may recognize in second clause the simultaneous decomposability judgment (Definition 3) Γ ⊢ (T i : v i =) i∈I . Hence, ( 4) is in fact:

∃Γ, Γ ⊢ τ : + ∧ Γ ⊢ (T i : v i =) i∈I (5)
In OCaml, there is no ⊥ or ⊤ type12 . However, object types and polymorphic variant have subtyping, so they are, in general, neither upward nor downward-closed. Finally, subtyping is also used in private type definitions, that were demonstrated in the example.

Our closure-checking relation therefore degenerates into the following, quite unsatisfying, picture:

• no type is downward-closed because of the existence of private types;

• no object type but the empty object type is upward-closed;

• no arrow type is upward-closed because its left-hand-side would need to be downward-closed;

• datatypes are upward-closed if their components types are.

From a pragmatic point of view, the situation is not so bad; as our main practical motivation for finer variance checks is the relaxed value restriction, we care about upward-closure (covariance) more than downward-closure (contravariance). This criterion tells us that covariant parameters can be instantiated with covariant datatypes defined from sum and product types (but no arrow), which would satisfy a reasonably large set of use cases.

A better control on upward and downward-closure

As explained in the introduction, the problem with the upward and downward closure properties is that they are not monotonic: enriching the subtyping lattice of our type system does not preserve them. While the core language has a nice variance check for GADT, adding private types in particular destroys the downward-closure property of the whole type system. Our proposed solution to this tension is to give the user the choice to locally strengthen negative knowledge about the subtyping relation by abandoning some flexibility. Just as object-oriented languages have a concept of final classes that cannot be extended, we would like to allow to define downward-closed datatypes, whose private counterparts cannot be declared, and upward-closed datatypes that cannot be made invisible: defining type t = private τ would be rejected by the type-checker if τ was itself declared downward-closed.

Such "closure specifications" are part of the semantic properties of a type and would, as such, sometimes need to be exposed through module boundaries. It is important that the specification language for abstract types allow to say that a type is upward-closed (respectively downward-closed). These new ways to classify types raise some software engineering questions. When is it desirable to define types as upward-closed? The user must balance its ability to define semi-abstract version of the type against its use in a GADT-and potentially other type-system features that would make use of negative reasoning on the subtyping relation. We do not yet know how to answer this question and believe that more practice is necessary to get a clearer picture of the trade-off involved.

Subtyping constraints and variance assignment

We will now revisit our previous example, using the guarded existential notation:

type α expr = | Val of ∃β[α = β]. β | Int of [α = int]. int | Thunk of ∃βγ[α = γ]. β expr * (β → γ) | Prod of ∃βγ[α = β * γ]. β expr * γ expr
A simple way to get such a type to be covariant would be, instead of proving delicate, non-monotonic upward-closure properties on the tuple type involved in the equation α = β * γ, to change this definition so that the resulting type is obviously covariant:

type +α expr = | Val of ∃β[α ≥ β]. β | Int of [α ≥ int]. int | Thunk of ∃βγ[α ≥ γ]. β expr * (β → γ) | Prod of ∃βγ[α ≥ β * γ]. β expr * γ expr We have turned each equality constraint α = T [β] into a subtyping constraint α ≥ T [β]. For a type α ′ such that α ≤ α ′ , we get by transitivity that α ′ ≥ T [β].
This means that α expr trivially satisfies the correctness criterion from Simonet and Pottier. Formally, instead of checking Γ ⊢ T i : v i ⇒ (=), we are now checking Γ ⊢ T i : v i ⇒ (+), which is significantly easier to satisfy13 : when v i is itself + we can directly apply the sc-Triv rule.

While we now have a different datatype, which gives us a weaker subtyping assumption when pattern-matching, we are still able to write the classic function eval : α expr → α, because the constraints α ≥ τ are in the right direction to get an α as a result. We conjecture that moving from an equality constraint on the GADT type parameters to a subtyping constraint (bigger than, or smaller than, according to the desired variance for the parameter) is often unproblematic in practice. In the examples we have studied, such a change did not stop functions from type-checking-we only needed to add some explicit coercions.

However, allowing subtyping constraints in GADT has some disadvantages. If the language requires subtyping casts to be explicit, this would make pattern matching of GADT syntactically heavier than with current GADT where equalities constraints are used implicitly. This is related to practical implementation questions, as languages based on inference by unification tend to favor equality over subtyping, bidirectional coercions over unidirectional ones. Subtyping constraints need also be explicit in the type declaration, forcing the user out of the convenient "generalized codomain type" syntax.

From a theoretical standpoint, we think there is value in exploring both directions: experimenting with GADT using subtyping constraints, and with fine-grained closure properties for equality constraints. Both designs allow to reason in an open world setting, by being resilient to extensions of the subtyping relation. Whether it is possible to expose those features to the expert language user (e.g. library designers) without forcing all users to pay the complexity burden remains to be seen.

Future Work

Extension of the formal exposition to non-atomic subtyping As remarked in §2.1 during the definition of our formal subtyping relation, the soundness proof of Simonet and Pottier is restricted to atomic subtyping. We conjecture that their work can be extended to non-atomic subtyping, and furthermore that our results would extend seamlessly in this setting, thanks to our explicit use of the v-closure hypothesis.

On the relaxed value restriction Regarding the relaxed value restriction, which is our initial practical motivation to investigate variance in presence of GADT, there is also future work to be done to verify that it is indeed compatible with this refined notion of variance. While the syntactic proof of soundness of the relaxation doesn't involve subtyping directly, the "informal justification" for value restriction uses the admissibility of a global bottom type ⊥ to generalize a covariant unification variable; in presence of downward-closed type, there is no such general ⊥ type (only one for non-downward-closed types). We conjecture that the relaxed value restriction is still sound in this case, because the covariance criterion is really used to rule out mutable state rather than subtype from a ⊥ type; but it will be necessary to study the relaxation justification in more details to formally establish this result.

Experiments with v-closure of type constructors as a new semantic property In a language with non-atomic subtyping such as OCaml, we need to distinguish v-closed and non-v-closed type constructors. This is a new semantic property that, in particular, must be reflected through abstraction boundaries: we should be able to say about an abstract type that it is v-closed, or not say anything.

How inconvenient in practice is the need to expose those properties to have good variance for GADT? Will the users be able to determine whether they want to enforce v-closure for a particular type they are defining?

Experiments with subtyping constraints in GADT In §4.3, we have presented a different way to define GADT with weaker constraints (simple subtyping instead of equality) and stronger variance properties. It is interesting to note that, for the few GADT examples we have considered, using subtyping constraints rather than equality constraints was sufficient for the desired applications of the GADT.

However, there are cases were the strong equality relying on fine-grained closure properties is required. We need to consider more examples of both cases to evaluate the expressiveness trade-off in, for example, deciding to add only one of these solutions to an existing type system.

On the implementation side, we suspect that adding subtyping constraints to a type system that already supports GADT and private types should not require large engineering efforts (in particular, it does not implies supporting the most general forms of bounded polymorphism). Matching on a GADT α t already introduces local type equalities of the form α = T [β] in pattern matching clauses. Jacques Garrigue suggested that adding an equality of the form α = private T [β] should correspond to GADT equations of the form α ≤ T [β], and lower bounds could be represented using the dual notion of invisible types. Regardless of implementation difficulties, in a system with only explicit subtyping coercion, such subtyping constraints would still require more user annotations.

Mathematical structures for variance studies

There has been work on more structured presentation of GADT as part of a categorical framework ([GJ08] and [START_REF] Hamana | A foundation for gadts and inductive families: dependent polynomial functor approach[END_REF]). This is orthogonal to the question of variance and subtyping, but it may be interesting to re-frame the current result in this framework.

Parametrized types with variance can also be seen as a sub-field of order theory with very partial orders and functions with strong monotonicity properties. Finally, we have been surprised to find that geometric intuitions were often useful to direct our formal developments. It is possible that existing work in these fields would allow us to streamline the proofs, which currently are rather low-level and tedious.

Completeness of variance annotations with domain information For simple algebraic datatypes, variance annotations are "enough" to say anything we want to say about the variance of datatypes. Essentially, all admissible variance relations between datatypes can be described by considering the pairwise variance of their parameters, separately.

This does not work anymore with GADT. For example, the equality type (α, β) eq cannot be accurately described by considering variation of each of its parameters independently. We would like to say that (α, β) eq ≤ (α ′ , β ′ ) eq holds as soon as α = β and α ′ = β ′ . With the simple notion of variance we currently have, all we can soundly say about eq is that it must be invariant in both its parameters-which is considerably weaker. In particular, the well-known trick of "factoring out" GADT by using the eq type in place of equality constraint does not preserve variances: equality constraints allow fine-grained variance considerations based on upward or downward-closure, while the equality type instantly makes its parameters invariant.

We think it would possible to regain some "completeness", and in particular re-enable factoring by eq, by considering domain information, that is information on constraints that must hold for the type to be inhabited. If we restricted the subtyping rule with conclusion σ t ≤ σ ′ t to only cases where σ t and σ ′ t are inhabited-with a separate rule to conclude subtyping in the non-inhabited casewe could have a finer variance check, as we would only need to show that the criterion of Simonet and Pottier holds between two instances of the inhabited domain, and not any instance. If we stated that the domain of the type (α, β) eq is restricted by the constraint α = β, we could soundly declare the variance (⋊ ⋉α, ⋊ ⋉β) eq on this domain-which no longer prevents from factoring out GADT by equality types.

Conclusion

Checking the variance of GADT is surprisingly more difficult (and interesting) than we initially thought. We have studied a novel criterion of upward and downward closure of type expressions and proposed a corresponding syntactic judgment that is easily implementable. We presented a core formal framework to prove both its correctness and its completeness with respect to the more general criterion of Simonet and Pottier.

This closure criterion exposes important tensions in the design of a subtyping relation, for which we previously knew of no convincing example in the context of ML-derived programming languages. We have suggested new language features to help alleviate these tensions, whose convenience and practicality is yet to be assessed by real-world usage.

Considering extension of GADT in a rich type system is useful in practice; it is also an interesting and demanding test of one's type system design.

type

  +α expr = | Val : α → α expr | Int : int → int expr | Thunk : ∀β. β expr * (β → α) → α expr | Prod : ∀βγ. β expr * γ expr → (β * γ) expr

  let coerce : α expr → α ′ expr = function | Val (v : α) -> Val (v :> α ′ ) | Int n -> Int n | Thunk β (b : β expr) (f : β → α) -> Thunk β b (fun x -> (f x :> α ′ )) | Prod β γ ((b, c) : β expr * γ expr) -> (* if β * γ ≤ α ′ , then α ′ is of the form β ′ * γ ′ with β ≤ β ′ and γ ≤ γ ′ *)Prod β ′ γ ′ ((b :> β ′ expr), (c :> γ ′ expr))

  module M = struct type file_descr = int let stdin = 0 let open = ... end : sig type file_descr = private int val stdin : file_descr val open : string -> (file_descr, error) sum end type +α t = | K : priv -> M.file_descr t let get_eq : α t -> (α, M.file_descr) eq = function | K _ -> Refl let forge : int -> M.file_descr = fun (x : int) -> cast (get_eq p) M.stdin

  module type S = sig type (+α) collection val empty : unit -> α collection val app : α collection -> α collection -> α collection end and then implements it with linked lists module C : S = struct type +α collection = | Nil of unit | Cons of α * α collection let empty () = Nil () end The type-checker will accept this implementation, as it has the specified variance. On the contrary, type +α collection = (α list) ref let empty () = ref [] would be rejected, as ref is invariant. In the following definition: let nil = C.empty ()

Figure 1 :

 1 Figure 1: Subtyping relation

  If we have both b 1 b 2 and b 1 b 2 in our relation on base types, for two distinct base types b 1 and b 2 , we have b 1 = b 2 as types, even though they are syntactically distinct. This choice is inspired by the previous work of Simonet and Pottier.

Figure 2 :

 2 Figure 2: Variance assignment

|

  Prod : ∀α. ∀βγ[α = β * γ]. β expr * γ expr → α expr This restricted form justifies the name of guarded algebraic datatype. The ∀βγ[D].τ notation, coming from Simonet and Pottier, is a constrained type scheme: β, γ may only be instantiated with type parameters respecting the constraint D. Note that, as β and γ do not appear in the codomain anymore, we may equivalently change the outer universal into an existential on the left-hand side of the arrow: | Prod : ∀α. (∃βγ[α = β * γ]. β expr * γ expr) → α expr

  ref * β ref is upward-closed (assuming the type constructor ref is invariant and upward-closed): if (σ ref * σ ref) ≤ σ ′ , then by upward closure of the product, σ ′ is of the form σ ′ 1 * σ ′ 2 , and by its covariance σ ref ≤ σ ′ 1 and σ ref ≤ σ ′ 2 . Now by invariance of ref we have σ ′ 1 = σ ref = σ ′ 2 , and therefore σ ′ is equal to σ ref * σ ref, which is an instance 10 of β ref * β ref.

  let rec eval : α expr → α = function | Val β (v : β) -> (v :> α) | Int (n : int) -> (n :> α) | Thunk βγ ((v : β expr), (f : β → γ)) -> (f (eval v) :> α) | Prod β γ ((b : β expr), (c : γ expr)) -> ((eval b, eval c) :> α)

The variables β ′ and γ ′ of the Prod case are never really defined, only justified at the meta-level, making this code only an informal sketch.

We write T [β] for a type expression T that may contain free occurrences of variables β and T [σ] for the simultaneous substitution of σ for β in T .

This counterexample is due to Jeremy Yallop.

This counterexample is due to Jacques Garrigue.

There is a relation between this way of writing a strongly typed eval function and the "finally tagless" approach[Kis] that is known to require only simple ML types.

The reason for this order reversal is that the relations occur as hypotheses, in negative position, in definition of subtyping: if we have v ≤ w and type vα t, it is safe to assume type wα t: σ ≺w σ ′ implies σ ≺v σ ′ , which implies σ t ≤ σ ′ t. One may also see it, as Abel notes, as an "information order": knowing that σ ≺ + τ "gives you more information" than knowing that σ ≺⋊ ⋉ τ , therefore ⋊ ⋉ ≤ +.

It turns out that this condition is not necessary and can be slightly weakened: we will discuss that later (3).

This is an extended version of the soundness requirement for algebraic datatypes: it is now formulated in terms guarded existential types ∃β[D]τ rather than simple argument types τ .

We use the term instance to denote the replacement of all the free variables of a type expression under context by closed types-not the specialization of an ML type scheme.

W.l.o.g., we assume that I is reduced to {1, 2} and that there is only one free variable β in T 1 , T 2 . Since we focus on a single variable of the context we name w 1 and w 2 the variances of β in ∆ 1 and ∆ 2 , respectively. We now reason by case analysis on the variances w 1 and w 2 .If both of them are ⋊ ⋉, we have ∆ 1 ∆ 2 = (⋊ ⋉β), so we do not necessarily have Γ ≤ ∆ 1 ∆ 2 . Instead, we make a different choice for G 2 . Namely, we pick Γ for Γ 2 and keep ∆ 1 for Γ 1 . As ∆ 2 is ⋊ ⋉ we have ∆ 2 ≤ Γ 2 , so by monotonicity of

A bottom type would be admissible, but a top type would be unsound in OCaml, as different types may have different runtime representations. Existential types, that may mix values of different types, are constructed explicitly through a boxing step.

Note that the formal proofs of the precedent section were, in some cases, specialized to the equality constraint. More precisely, our decomposability criterion is still sound when extended to arbitrary subtyping constraints, but its completeness is unknown and left to future work.

RESEARCH CENTRE PARIS -ROCQUENCOURT Domaine de Voluceau, -Rocquencourt B.P. 105 -78153 Le Chesnay Cedex Publisher Inria Domaine de Voluceau -Rocquencourt BP 105 -78153 Le Chesnay Cedex inria.fr ISSN 0249-0803

Lemma 9 If the principal variance w such that (wα) ⊢ τ [α] : v holds is not the irrelevant variance ⋊ ⋉, then τ

]. This holds in particular for the principal variance w such that (wα) ⊢ τ [α] : v. Moreover, by principal inversion (Corrolary 2) applied twice, we have both ρ 1 ≺ w ρ 2 and ρ 2 ≺ w ρ 1 . If w is distinct from ⋊ ⋉ this implies ρ 1 = ρ 2 .

Lemma 10 If Γ τ : v (=) holds for some Γ, and ∆ is the most general context such that ∆ ⊢ τ : v holds, then ∆ τ : v (=) also hold.

Let ρ, σ ′ be such that have τ [ρ] ≺ v σ ′ (4). By (1), there exists ρ ′ such that τ [ρ ′ ] = σ ′ (5). To prove (3), it only remains to prove that ρ ≺ ∆ ρ ′ (6). Given (5), the inequality (4) becomes τ [ρ] ≺ v τ [ρ ′ ] (7). Then (6) follows by principal inversion (Corrolary 2) applied to (7), given (2).

Lemma 11 Let ∆ be the most general context such that ∆ ⊢ τ : v holds. If v is (=), then only variances (=) or (⋊ ⋉) may appear in ∆. If v is ⋊ ⋉, then only (⋊ ⋉) may appear in ∆.

Proof: If v is (⋊ ⋉), the context Γ with all variances set to ⋊ ⋉ satifies Γ ⊢ τ : v (as Γ ⊢ τ : v holds). By principality we have ∆ ≤ Γ, so ∆ also has only irrelevant variances as (⋊ ⋉) is the minimal variance.

If v is (=), we handle each variable of the context independently, that is we can assume, w.l.o.g., that τ has only one variable α. So ∆ is of the form (wα) and we know that for any ρ, ρ ′ such that ρ ≺ w ρ ′ we have τ

by lemma 9 applied to (1), we have ρ = ρ ′ for any ρ ≺ w ρ ′ , which means that w is (=). Summing up, we have shown that w is either (⋊ ⋉) or (=). Reasoning similarly in the general case, any variance w of ∆ is either (⋊ ⋉) or (=).

We can now prove the converse of the zip soundness (Lemma 5) that is the core of the future proof of completeness of the decomposability judgment Γ ⊢ τ : v ⇒ (=).

Theorem 2 (Zip completeness) Given any context Γ, a family of type expressions (T i [σ]) i∈I and a family of variances (v i ) i∈I , if the simultaneous decomposition Γ (T i : v i (=)) i∈I holds, then there exists a family of contexts (Γ i ) i∈I such that Γ ≤ i∈I Γ i and both Γ i ⊢ T i : v i and Γ i T i : v i (=) hold for all i. If furthermore Γ ⊢ T i : v i holds for all i, then i∈I Γ i is precisely Γ.

Proof: Let us assume the simultaneous decomposition Γ (T i : v i (=)) i∈I , which expands to:

(1) the variance checking judgment we have Γ 2 ⊢ T 2 : v 2 from (11), and we still have Γ 2 T 2 : v 2 (=) from (7). Hence (3) and ( 4) are reestablished. Finally, we have

If only one of the w i is ⋊ ⋉, we may assume, w.l.o.g., that it is w 1 . Then ∆ 1 ∆ 2 is ∆ 2 and we only need to show that Γ ≤ ∆ 2 (12). From (7), we have Γ T 2 : v 2 ⇒ (=). We then make a case analysis on v 2 : if v 2 is not (=), then by since ∆ 2 is most general and w 2 = ⋊ ⋉, we may apply Lemma 8 to get (12); Otherwise, v 2 is (=); Lemma 11 applied to (11) implies that ∆ 2 is itself (=β), and (12) trivially holds.

Finally, if none of the w i is ⋊ ⋉, we first prove that they are both (=). In fact, we only prove that w 1 is (=) (13), as the other case follows by symmetry. To prove (13), we assume that ρ ′′ be such that ρ ≺ w1 ρ ′′ and we show that ρ = ρ ′′ (14) holds. By (11), we have

. We can use those two inequalities to invoke our simultaneous decomposability hypothesis (1) with

ρ] hold. By Lemma 9 applied with (11), this implies both ρ ′ = ρ ′′ and ρ ′ = ρ, and therefore (14).

Then, comes the delicate step of this series of equivalent rewriting:

The reverse imiplication from (6) to ( 5) is is the zip soundness (Lemma 5).

The direct implication, from ( 5) to ( 6) is more involved: let Γ 0 be such that Γ 0 ⊢ τ : +. By zip completeness (Theorem 2), with the hypotheses of ( 4), there exists a family (Γ i ) i∈I satisfying the typing, zipping and decomposability of second line of (6) with Γ 0 ≤ i∈I Γ i . We take i∈I Γ i for Γ. Then, from Γ 0 ≤ Γ we get Γ ⊢ τ : + by monotonicity (Lemma 2).

As a last step, the last conjuncts of ( 6) are equivalent to ∀i, Γ i ⊢ T i : v i ⇒ (=) by interpretation of syntactic decomposability (Definition 5) and soundness and completeness of zipping (lemmas 6 and 12). Therefore, (6) is equivalent to:

which is our final criterion.

Pragmatic evaluation of this criterion This presentation of the correctness criterion only relies on syntactic judgments. It is pragmatic in the sense that it suggests a simple and direct implementation, as a generalization of the check currently implemented in type system engines -which are only concerned with the Γ ⊢ τ : + part.

To compute the contexts Γ and (Γ i ) i∈I existentially quantified in this formula, one can use a variant of our syntactic judgments where the environment Γ is not an input, but an output of the judgment; in fact, one should return for each variable α the set of possible variances for this judgment to hold. For example, the query (? ⊢ α * β ref : +) should return (α → {+, =}; β → {=}). Defining those algorithmic variants of the judgments is routine, and we have not done it here. The sets of variances corresponding to the decomposability of the (T i ) i∈I (? ⊢ T i : v i ⇒ (=)) should be zipped together and intersected with the possibles variances for τ , returned by (? ⊢ τ : +). The algorithmic criterion is satisfied if and only if the intersection is not empty; this can be decided in a simple and efficient way.

4 Closed-world vs. open-world subtyping 4.1 Upward and downward closure in a ML type system In the type system we have used so far, all types are both upward and downwardclosed. Indeed, thanks to the simplicity of our subtyping relation, we have a very strong inversion principle: two ground types in a subtyping relation necessarily have exactly the same structure. We have therefore completely determined a sound variance check for a simple type system with GADT.

This simple resolution, however, does not hold in general: richer subtyping relations will have weaker invertibility properties. As soon as a bottom type ⊥ is introduced, for example, such that that for all type σ we have ⊥ ≤ σ, downwardclosure fails for most types. For example, products are no longer downward-closed: Γ ⊢ σ * τ ≥ ⊥ does not imply that ⊥ is equal to some σ ′ * τ ′ . Conversely, if one adds a top type ⊤, bigger than all other types, then most type are not upward-closed anymore.