We now turn to the study of subtyping, a key feature needed to support the object-oriented programming style.
Suppose we are writing a program involving two record types defined as follows:
Person = {name:String, age:Nat} Student = {name:String, age:Nat, gpa:Nat}
In the simply typed lamdba-calculus with records, the term
(\r:Person. (r.age)+1) {name=Pat
,age=21,gpa=1}
is not typable, since it applies a function that wants a two-field record to an argument that actually provides three fields, while the T_App rule demands that the domain type of the function being applied must match the type of the argument precisely.
But this is silly: we're passing the function a better argument than it needs! The only thing the body of the function can possibly do with its record argument r is project the field age from it: nothing else is allowed by the type, and the presence or absence of an extra gpa field makes no difference at all. So, intuitively, it seems that this function should be applicable to any record value that has at least an age field.
More generally, a record with more fields is at least as good in
any context
as one with just a subset of these fields, in the
sense that any value belonging to the longer record type can be
used safely in any context expecting the shorter record type. If
the context expects something with the shorter type but we actually
give it something with the longer type, nothing bad will
happen (formally, the program will not get stuck).
The principle at work here is called subtyping. We say that S
is a subtype of T
, written S <: T, if a value of type S can
safely be used in any context where a value of type T is
expected. The idea of subtyping applies not only to records, but
to all of the type constructors in the language -- functions,
pairs, etc.
Safe substitution principle:
Subtyping plays a fundamental role in many programming languages -- in particular, it is closely related to the notion of subclassing in object-oriented languages.
An object in Java, C#, etc. can be thought of as a record,
some of whose fields are functions (methods
) and some of whose
fields are data values (fields
or instance variables
).
Invoking a method m of an object o on some arguments a1..an
roughly consists of projecting out the m field of o and
applying it to a1..an.
The type of an object is called a class -- or, in some languages, an interface. It describes which methods and which data fields the object offers. Classes and interfaces are related by the subclass and subinterface relations. An object belonging to a subclass (or subinterface) is required to provide all the methods and fields of one belonging to a superclass (or superinterface), plus possibly some more.
The fact that an object from a subclass can be used in place of one from a superclass provides a degree of flexibility that is extremely handy for organizing complex libraries. For example, a GUI toolkit like Java's Swing framework might define an abstract interface Component that collects together the common fields and methods of all objects having a graphical representation that can be displayed on the screen and interact with the user, such as the buttons, checkboxes, and scrollbars of a typical GUI. A method that relies only on this common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other features besides these. For example, fields can be updated. Fields and methods can be declared private. Classes can give initializers that are used when constructing objects. Code in subclasses can cooperate with code in superclasses via inheritance. Classes can have static methods and fields. Etc., etc.
To keep things simple here, we won't deal with any of these issues -- in fact, we won't even talk any more about objects or classes. (There is a lot of discussion in Pierce 2002 (in Bib.v), if you are interested.) Instead, we'll study the core concepts behind the subclass / subinterface relation in the simplified setting of the STLC.
Our goal for this chapter is to add subtyping to the simply typed lambda-calculus (with some of the basic extensions from MoreStlc). This involves two steps:
The second step is actually very simple. We add just a single rule to the typing relation: the so-called rule of subsumption:
Gamma |- t \in S S <: T
This rule says, intuitively, that it is OK to forget
some of
what we know about a term.
For example, we may know that t is a record with two fields (e.g., S = {x:A->A, y:B->B}), but choose to forget about one of the fields (T = {y:B->B}) so that we can pass t to a function that requires just a single-field record.
The first step -- the definition of the relation S <: T -- is where all the action is. Let's look at each of the clauses of its definition.
To start off, we impose two structural rules
that are
independent of any particular type constructor: a rule of
transitivity, which says intuitively that, if S is
better (richer, safer) than U and U is better than T,
then S is better than T...
S <: U U <: T
... and a rule of reflexivity, since certainly any type T is as good as itself:
Now we consider the individual type constructors, one by one, beginning with product types. We consider one pair to be a subtype of another if each of its components is.
S1 <: T1 S2 <: T2
The subtyping rule for arrows is a little less intuitive. Suppose we have functions f and g with these types:
f : C -> Student g : (C->Person) -> D
That is, f is a function that yields a record of type Student, and g is a (higher-order) function that expects its argument to be a function yielding a record of type Person. Also suppose that Student is a subtype of Person. Then the application g f is safe even though their types do not match up precisely, because the only thing g can do with f is to apply it to some argument (of type C); the result will actually be a Student, while g will be expecting a Person, but this is safe because the only thing g can then do is to project out the two fields that it knows about (name and age), and these will certainly be among the fields that are present.
This example suggests that the subtyping rule for arrow types should say that two arrow types are in the subtype relation if their results are:
S2 <: T2
We can generalize this to allow the arguments of the two arrow types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
But notice that the argument types are subtypes the other way round
:
in order to conclude that S1->S2 to be a subtype of T1->T2, it
must be the case that T1 is a subtype of S1. The arrow
constructor is said to be contravariant in its first argument
and covariant in its second.
Here is an example that illustrates this:
f : Person -> C g : (Student -> C) -> D
The application g f is safe, because the only thing the body of g can do with f is to apply it to some argument of type Student. Since f requires records having (at least) the fields of a Person, this will always work. So Person -> C is a subtype of Student -> C since Student is a subtype of Person.
The intuition is that, if we have a function f of type S1->S2, then we know that f accepts elements of type S1; clearly, f will also accept elements of any subtype T1 of S1. The type of f also tells us that it returns elements of type S2; we can also view these results belonging to any supertype T2 of S2. That is, any function f of type S1->S2 can also be viewed as having type T1->T2.
What about subtyping for record types?
The basic intuition is that it is always safe to use a bigger
record in place of a smaller
one. That is, given a record type,
adding extra fields will always result in a subtype. If some code
is expecting a record with fields x and y, it is perfectly safe
for it to receive a record with fields x, y, and z; the z
field will simply be ignored. For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat} {name:String, age:Nat} <: {name:String} {name:String} <: {}
This is known as width subtyping
for records.
We can also create a subtype of a record type by replacing the type of one of its fields with a subtype. If some code is expecting a record with a field x of type T, it will be happy with a record having a field x of type S as long as S is a subtype of T. For example,
{x:Student} <: {x:Person}
This is known as depth subtyping
.
Finally, although the fields of a record type are written in a particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as permutation subtyping
.
We could formalize these requirements in a single subtyping rule for records as follows:
forall jk in j1..jn, exists ip in i1..im, such that jk=ip and Sp <: Tk
That is, the record on the left should have all the field labels of the one on the right (and possibly more), while the types of the common fields should be in the subtype relation.
However, this rule is rather heavy and hard to read, so it is often decomposed into three simpler rules, which can be combined using S_Trans to achieve all the same effects.
First, adding fields to the end of a record type gives a subtype:
n > m
We can use S_RcdWidth to drop later fields of a multi-field record while keeping earlier fields, showing for example that {age:Nat,name:String} <: {age:Nat}.
Second, subtyping can be applied inside the components of a compound record type:
S1 <: T1 ... Sn <: Tn
For example, we can use S_RcdDepth and S_RcdWidth together to show that {y:Student, x:Nat} <: {y:Person}.
Third, subtyping can reorder fields. For example, we want {name:String, gpa:Nat, age:Nat} <: Person. (We haven't quite achieved this yet: using just S_RcdDepth and S_RcdWidth we can only drop fields from the end of a record type.) So we add:
{i1:S1...in:Sn} is a permutation of {j1:T1...jn:Tn}
It is worth noting that full-blown language designs may choose not to adopt all of these subtyping rules. For example, in Java:
on the rightas more members are added in subclasses (i.e., no permutation for classes).
multiple inheritanceof interfaces (i.e., permutation is allowed for interfaces).
Suppose we had incorrectly defined subtyping as covariant on both the right and the left of arrow types:
S1 <: T1 S2 <: T2
Give a concrete example of functions f and g with the following types...
f : Student -> Nat g : (Person -> Nat) -> Nat
... such that the application g f will get stuck during execution. (Use informal syntax. No need to prove formally that the application gets stuck.)
Finally, it is convenient to give the subtype relation a maximum element -- a type that lies above every other type and is inhabited by all (well-typed) values. We do this by adding to the language one new type constant, called Top, together with a subtyping rule that places it above every other type in the subtype relation:
The Top type is an analog of the Object type in Java and C.
In summary, we form the STLC with subtyping by starting with the pure STLC (over some set of base types) and then...
Gamma |- t \in S S <: T
S <: U U <: T
n > m
S1 <: T1 ... Sn <: Tn
{i1:S1...in:Sn} is a permutation of {j1:T1...jn:Tn}
Suppose we have types S, T, U, and V with S <: T and U <: V. Which of the following subtyping assertions are then true? Write true or false after each one. (A, B, and C here are base types like Bool, Nat, etc.)
The following types happen to form a linear order with respect to subtyping:
Write these types in order from the most specific to the most general.
Where does the type Top->Top->Student fit into this order? That is, state how Top -> (Top -> Student) compares with each of the five types above. It may be unrelated to some of them.
Which of the following statements are true? Write true or false after each one.
forall S T, S <: T -> S->S <: T->T
forall S, S <: A->A -> exists T, S = T->T /\ T <: A
forall S T1 T2, (S <: T1 -> T2) -> exists S1 S2, S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S, S <: S->S
exists S, S->S <: S
forall S T1 T2, S <: T1*T2 -> exists S1 S2, S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
Which of the following statements are true, and which are false?
Is the following statement true or false? Briefly explain your answer. (Here Base n stands for a base type, where n is a string standing for the name of the base type. See the Syntax section below.)
forall T, ~(T = Bool \/ exists n, T = Base n) -> exists S, S <: T /\ S <> T
smallestin the subtype relation) that makes the following assertion true? (Assume we have Unit among the base types and unit as a constant of this type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) \in A->A
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) \in T
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a, \z:A.z) \in A
exists S, empty |- (\p:(A*T). (p.snd) (p.fst)) \in S
What is the smallest type T that makes the following assertion true?
exists S t, empty |- (\x:T. x x) t \in S
What is the smallest type T that makes the following assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) \in T
How many supertypes does the record type {x:A, y:C->C} have? That is, how many different types T are there such that {x:A, y:C->C} <: T? (We consider two types to be different if they are written differently, even if each is a subtype of the other. For example, {x:A,y:B} and {y:B,x:A} are different.)
The subtyping rule for product types
S1 <: T1 S2 <: T2
intuitively corresponds to the depth
subtyping rule for records.
Extending the analogy, we might consider adding a permutation
rule
for products. Is this a good idea? Briefly explain why or why not.
Most of the definitions needed to formalize what we've discussed above -- in particular, the syntax and operational semantics of the language -- are identical to what we saw in the last chapter. We just need to extend the typing relation with the subsumption rule and add a new Inductive definition for the subtyping relation. Let's first do the identical bits.
In the rest of the chapter, we formalize just base types, booleans, arrow types, Unit, and Top, omitting record types and leaving product types as an exercise. For the sake of more interesting examples, we'll add an arbitrary set of base types like String, Float, etc. (Since they are just for examples, we won't bother adding any operations over these base types, but we could easily do so.)
The definition of substitution remains exactly the same as for the pure STLC.
Likewise the definitions of the value property and the step relation.
Now we come to the interesting part. We begin by defining the subtyping relation and developing some of its important technical properties.
The definition of subtyping is just what we sketched in the motivating discussion.
Note that we don't need any special rules for base types (Bool and Base): they are automatically subtypes of themselves (by S_Refl) and Top (by S_Top), and that's all we want.
(Leave this exercise Admitted until after you have finished adding product types to the language -- see exercise products -- at least up to this point in the file).
Recall that, in chapter MoreStlc, the optional section
Encoding Records
describes how records can be encoded as pairs.
Using this encoding, define pair types representing the following
record types:
Person := { name : String } Student := { name : String ; gpa : Float } Employee := { name : String ; ssn : Integer }
Now use the definition of the subtype relation to prove the following:
The following facts are mostly easy to prove in Coq. To get full benefit from the exercises, make sure you also understand how to prove them on paper!
The only change to the typing relation is the addition of the rule of subsumption, T_Sub.
The following hints help auto and eauto construct typing derivations. They are only used in a few places, but they give a nice illustration of what auto can do with a bit more programming. See chapter UseAuto for more on hints.
Do the following exercises after you have added product types to the language. For each informal typing judgement, write it as a formal statement in Coq and prove it.
The fundamental properties of the system that we want to check are the same as always: progress and preservation. Unlike the extension of the STLC with references (chapter References), we don't need to change the statements of these properties to take subtyping into account. However, their proofs do become a little bit more involved.
Before we look at the properties of the typing relation, we need to establish a couple of critical structural properties of the subtype relation:
These are called inversion lemmas because they play a similar role in proofs as the built-in inversion tactic: given a hypothesis that there exists a derivation of some subtyping statement S <: T and some constraints on the shape of S and/or T, each inversion lemma reasons about what this derivation must look like to tell us something further about the shapes of S and T and the existence of subtype relations between their parts.
The proof of the progress theorem -- that a well-typed non-value can always take a step -- doesn't need to change too much: we just need one small refinement. When we're considering the case where the term in question is an application t1 t2 where both t1 and t2 are values, we need to know that t1 has the form of a lambda-abstraction, so that we can apply the ST_AppAbs reduction rule. In the ordinary STLC, this is obvious: we know that t1 has a function type T11->T12, and there is only one rule that can be used to give a function type to a value -- rule T_Abs -- and the form of the conclusion of this rule forces t1 to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work because there's another rule that can be used to show that a value has a function type: subsumption. Fortunately, this possibility doesn't change things much: if the last rule used to show Gamma |- t1 \in T11->T12 is subsumption, then there is some sub-derivation whose subject is also t1, and we can reason by induction until we finally bottom out at a use of T_Abs.
This bit of reasoning is packaged up in the following lemma, which
tells us the possible canonical forms
(i.e., values) of function
type.
Similarly, the canonical forms of type Bool are the constants tru and fls.
The proof of progress now proceeds just like the one for the pure STLC, except that in several places we invoke canonical forms lemmas...
Theorem (Progress): For any term t and type T, if empty |- t \in T then t is a value or t --> t' for some term t'.
Proof: Let t and T be given, with empty |- t \in T. Proceed by induction on the typing derivation.
The cases for T_Abs, T_Unit, T_True and T_False are immediate because abstractions, unit, tru, and fls are already values. The T_Var case is vacuous because variables cannot be typed in the empty context. The remaining cases are more interesting:
The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the inversion lemmas for subtyping
above, there are a
number of facts about the typing relation that are immediate from
the definition in the pure STLC (formally: that can be obtained
directly from the inversion tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same has_type statement.
The following inversion lemma tells us that, if we have a derivation of some typing statement Gamma |- \x:S1.t2 \in T whose subject is an abstraction, then there must be some subderivation giving a type to the body t2.
Lemma: If Gamma |- \x:S1.t2 \in T, then there is a type S2 such that x|->S1; Gamma |- t2 \in S2 and S1 -> S2 <: T.
(Notice that the lemma does not say, then T itself is an arrow
type
-- this is tempting, but false!)
Proof: Let Gamma, x, S1, t2 and T be given as described. Proceed by induction on the derivation of Gamma |- \x:S1.t2 \in T. Cases T_Var, T_App, are vacuous as those rules cannot be used to give a type to a syntactic abstraction.
Formally:
Similarly...
The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful combination lemma
telling
us exactly what we'll actually require below.
The context invariance lemma follows the same pattern as in the pure STLC.
The substitution lemma is proved along the same lines as for the pure STLC. The only significant change is that there are several places where, instead of the built-in inversion tactic, we need to use the inversion lemmas that we proved above to extract structural information from assumptions about the well-typedness of subterms.
The proof of preservation now proceeds pretty much as in earlier chapters, using the substitution lemma at the appropriate point and again using inversion lemmas from above to extract structural information from typing assumptions.
Theorem (Preservation): If t, t' are terms and T is a type such that empty |- t \in T and t --> t', then empty |- t' \in T.
Proof: Let t and T be given such that empty |- t \in T. We proceed by induction on the structure of this typing derivation, leaving t' general. The cases T_Abs, T_Unit, T_True, and T_False cases are vacuous because abstractions and constants don't step. Case T_Var is vacuous as well, since the context is empty.
By the definition of the step relation, there are three ways t1 t2 can step. Cases ST_App1 and ST_App2 follow immediately by the induction hypotheses for the typing subderivations and a use of T_App.
Suppose instead t1 t2 steps by ST_AppAbs. Then t1 = \x:S.t12 for some type S and term t12, and t' = [x:=t2]t12.
By lemma abs_arrow, we have T1 <: S and x:S1 |- s2 \in T2. It then follows by the substitution lemma (substitution_preserves_typing) that empty |- [x:=t2] t12 \in T2 as desired.
This formalization of the STLC with subtyping omits record types for brevity. If we want to deal with them more seriously, we have two choices.
First, we can treat them as part of the core language, writing down proper syntax, typing, and subtyping rules for them. Chapter RecordSub shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and Unit types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
Unit as the base case in the encoding of tuples and the don't
care
placeholder in the encoding of records, we use Top. So:
{a:Nat, b:Nat} ----> {Nat,Nat} i.e., (Nat,(Nat,Top)) {c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e., (Nat,(Top,(Nat,Top)))
The encoding of record values doesn't change at all. It is easy (and instructive) to check that the subtyping rules above are validated by the encoding.
Each part of this problem suggests a different way of changing the definition of the STLC with Unit and subtyping. (These changes are not cumulative: each part starts from the original language.) In each part, list which properties (Progress, Preservation, both, or neither) become false. If a property becomes false, give a counterexample.
Gamma |- t \in S1->S2 S1 <: T1 T1 <: S1 S2 <: T2
S1 <: T1 S2 <: T2
Adding pairs, projections, and product types to the system we have defined is a relatively straightforward matter. Carry out this extension by modifying the definitions and proofs above:
S1 <: T1 S2 <: T2