-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sub.v
1582 lines (1295 loc) · 55.9 KB
/
Sub.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** 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: it involves an application of a function that wants
a one-field record to an argument that actually provides two
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.
Looking at the same thing from another point of view, 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 general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally 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. *)
(** ** Subtyping and Object-Oriented Languages *)
(** 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]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of 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 (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is 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 that can interact with the user.
Examples of such object would include 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 also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, 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 _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** 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:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
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 : S S <: T
------------------------- (T_Sub)
Gamma |- t : 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 Subtype Relation *)
(** 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. *)
(** *** Structural Rules *)
(** 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 than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two 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 (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, 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
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> 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
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
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].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types 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:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
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. If we like, we can decompose it
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
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
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} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{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 need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> 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.
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
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:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** 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.)
- [T->S <: T->S]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** 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
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
]]
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in 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) : A->A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
]]
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
]]
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** 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.)
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- 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. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** 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. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" |
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most 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. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** 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! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit"
| Case_aux c "T_Sub" ].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** 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. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
(* FILL IN HERE *)
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** 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, 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. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later 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 one 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. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
(* FILL IN HERE *) Admitted.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
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 : 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