-
Notifications
You must be signed in to change notification settings - Fork 0
/
Imp.v
1714 lines (1387 loc) · 59.7 KB
/
Imp.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
(** * Imp: Simple Imperative Programs *)
(** In this chapter, we begin a new direction that will continue for
the rest of the course. Up to now most of our attention has been
focused on various aspects of Coq itself, while from now on we'll
mostly be using Coq to formalize other things. (We'll continue to
pause from time to time to introduce a few additional aspects of
Coq.)
Our first case study is a _simple imperative programming language_
called Imp, embodying a tiny core fragment of conventional
mainstream languages such as C and Java. Here is a familiar
mathematical function written in Imp.
Z ::= X;;
Y ::= 1;;
WHILE not (Z = 0) DO
Y ::= Y * Z;;
Z ::= Z - 1
END
*)
(** This chapter looks at how to define the _syntax_ and _semantics_
of Imp; the chapters that follow develop a theory of _program
equivalence_ and introduce _Hoare Logic_, a widely used logic for
reasoning about imperative programs. *)
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.EqNat.
Require Import Coq.omega.Omega.
Require Import Coq.Lists.List.
Import ListNotations.
Require Import Maps.
Require Import SfLib. (* for [admit] *)
(* ################################################################# *)
(** * Arithmetic and Boolean Expressions *)
(** We'll present Imp in three parts: first a core language of
_arithmetic and boolean expressions_, then an extension of these
expressions with _variables_, and finally a language of _commands_
including assignment, conditions, sequencing, and loops. *)
(* ================================================================= *)
(** ** Syntax *)
Module AExp.
(** These two definitions specify the _abstract syntax_ of
arithmetic and boolean expressions. *)
Inductive aexp : Type :=
| ANum : nat -> aexp
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp.
Inductive bexp : Type :=
| BTrue : bexp
| BFalse : bexp
| BEq : aexp -> aexp -> bexp
| BLe : aexp -> aexp -> bexp
| BNot : bexp -> bexp
| BAnd : bexp -> bexp -> bexp.
(** In this chapter, we'll elide the translation from the
concrete syntax that a programmer would actually write to these
abstract syntax trees -- the process that, for example, would
translate the string ["1+2*3"] to the AST [APlus (ANum
1) (AMult (ANum 2) (ANum 3))]. The optional chapter [ImpParser]
develops a simple implementation of a lexical analyzer and parser
that can perform this translation. You do _not_ need to
understand that chapter to understand this one, but if you haven't
taken a course where these techniques are covered (e.g., a
compilers course) you may want to skim it. *)
(** For comparison, here's a conventional BNF (Backus-Naur Form)
grammar defining the same abstract syntax:
a ::= nat
| a + a
| a - a
| a * a
b ::= true
| false
| a = a
| a <= a
| not b
| b and b
*)
(** Compared to the Coq version above...
- The BNF is more informal -- for example, it gives some
suggestions about the surface syntax of expressions (like the
fact that the addition operation is written [+] and is an
infix symbol) while leaving other aspects of lexical analysis
and parsing (like the relative precedence of [+], [-], and
[*], the use of parens to explicitly group subexpressions,
etc.) unspecified. Some additional information (and human
intelligence) would be required to turn this description into
a formal definition, for example when implementing a
compiler.
The Coq version consistently omits all this information and
concentrates on the abstract syntax only.
- On the other hand, the BNF version is lighter and easier to
read. Its informality makes it flexible, which is a huge
advantage in situations like discussions at the blackboard,
where conveying general ideas is more important than getting
every detail nailed down precisely.
Indeed, there are dozens of BNF-like notations and people
switch freely among them, usually without bothering to say
which form of BNF they're using because there is no need to:
a rough-and-ready informal understanding is all that's
important.
It's good to be comfortable with both sorts of notations:
informal ones for communicating between humans and formal ones for
carrying out implementations and proofs. *)
(* ================================================================= *)
(** ** Evaluation *)
(** _Evaluating_ an arithmetic expression produces a number. *)
Fixpoint aeval (a : aexp) : nat :=
match a with
| ANum n => n
| APlus a1 a2 => (aeval a1) + (aeval a2)
| AMinus a1 a2 => (aeval a1) - (aeval a2)
| AMult a1 a2 => (aeval a1) * (aeval a2)
end.
Example test_aeval1:
aeval (APlus (ANum 2) (ANum 2)) = 4.
Proof. reflexivity. Qed.
(** Similarly, evaluating a boolean expression yields a boolean. *)
Fixpoint beval (b : bexp) : bool :=
match b with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval a1) (aeval a2)
| BLe a1 a2 => leb (aeval a1) (aeval a2)
| BNot b1 => negb (beval b1)
| BAnd b1 b2 => andb (beval b1) (beval b2)
end.
(* ================================================================= *)
(** ** Optimization *)
(** We haven't defined very much yet, but we can already get
some mileage out of the definitions. Suppose we define a function
that takes an arithmetic expression and slightly simplifies it,
changing every occurrence of [0+e] (i.e., [(APlus (ANum 0) e])
into just [e]. *)
Fixpoint optimize_0plus (a:aexp) : aexp :=
match a with
| ANum n =>
ANum n
| APlus (ANum 0) e2 =>
optimize_0plus e2
| APlus e1 e2 =>
APlus (optimize_0plus e1) (optimize_0plus e2)
| AMinus e1 e2 =>
AMinus (optimize_0plus e1) (optimize_0plus e2)
| AMult e1 e2 =>
AMult (optimize_0plus e1) (optimize_0plus e2)
end.
(** To make sure our optimization is doing the right thing we
can test it on some examples and see if the output looks OK. *)
Example test_optimize_0plus:
optimize_0plus (APlus (ANum 2)
(APlus (ANum 0)
(APlus (ANum 0) (ANum 1))))
= APlus (ANum 2) (ANum 1).
Proof. reflexivity. Qed.
(** But if we want to be sure the optimization is correct --
i.e., that evaluating an optimized expression gives the same
result as the original -- we should prove it. *)
Theorem optimize_0plus_sound: forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a. induction a.
- (* ANum *) reflexivity.
- (* APlus *) destruct a1.
+ (* a1 = ANum n *) destruct n.
* (* n = 0 *) simpl. apply IHa2.
* (* n <> 0 *) simpl. rewrite IHa2. reflexivity.
+ (* a1 = APlus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a1 = AMinus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a1 = AMult a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
- (* AMinus *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
- (* AMult *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.
(* ################################################################# *)
(** * Coq Automation *)
(** The repetition in this last proof is starting to be a little
annoying. If either the language of arithmetic expressions or the
optimization being proved sound were significantly more complex,
it would begin to be a real problem.
So far, we've been doing all our proofs using just a small handful
of Coq's tactics and completely ignoring its powerful facilities
for constructing parts of proofs automatically. This section
introduces some of these facilities, and we will see more over the
next several chapters. Getting used to them will take some
energy -- Coq's automation is a power tool -- but it will allow us
to scale up our efforts to more complex definitions and more
interesting properties without becoming overwhelmed by boring,
repetitive, low-level details. *)
(* ================================================================= *)
(** ** Tacticals *)
(** _Tacticals_ is Coq's term for tactics that take other tactics as
arguments -- "higher-order tactics," if you will. *)
(* ----------------------------------------------------------------- *)
(** *** The [try] Tactical *)
(** If [T] is a tactic, then [try T] is a tactic that is just like [T]
except that, if [T] fails, [try T] _successfully_ does nothing at
all (instead of failing). *)
Theorem silly1 : forall ae, aeval ae = aeval ae.
Proof. try reflexivity. (* this just does [reflexivity] *) Qed.
Theorem silly2 : forall (P : Prop), P -> P.
Proof.
intros P HP.
try reflexivity. (* just [reflexivity] would have failed *)
apply HP. (* we can still finish the proof in some other way *)
Qed.
(** There is no real reason to use [try] in completely manual
proofs like these, but we'll see below that it is very useful for
doing automated proofs in conjunction with the [;] tactical. *)
(* ----------------------------------------------------------------- *)
(** *** The [;] Tactical (Simple Form) *)
(** In its most common form, the [;] tactical takes two tactics as
arguments. The compound tactic [T;T'] first performs [T] and then
performs [T'] on _each subgoal_ generated by [T]. *)
(** For example, consider the following trivial lemma: *)
Lemma foo : forall n, leb 0 n = true.
Proof.
intros.
destruct n.
(* Leaves two subgoals, which are discharged
identically... *)
- (* n=0 *) simpl. reflexivity.
- (* n=Sn' *) simpl. reflexivity.
Qed.
(** We can simplify this proof using the [;] tactical: *)
Lemma foo' : forall n, leb 0 n = true.
Proof.
intros.
(* [destruct] the current goal *)
destruct n;
(* then [simpl] each resulting subgoal *)
simpl;
(* and do [reflexivity] on each resulting subgoal *)
reflexivity.
Qed.
(** Using [try] and [;] together, we can get rid of the repetition in
the proof that was bothering us a little while ago. *)
Theorem optimize_0plus_sound': forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
(* Most cases follow directly by the IH... *)
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).
(* ... but the remaining cases -- ANum and APlus --
are different: *)
- (* ANum *) reflexivity.
- (* APlus *)
destruct a1;
(* Again, most cases follow directly by the IH: *)
try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
(* The interesting case, on which the [try...]
does nothing, is when [e1 = ANum n]. In this
case, we have to destruct [n] (to see whether
the optimization applies) and rewrite with the
induction hypothesis. *)
+ (* a1 = ANum n *) destruct n;
simpl; rewrite IHa2; reflexivity. Qed.
(** Coq experts often use this "[...; try... ]" idiom after a tactic
like [induction] to take care of many similar cases all at once.
Naturally, this practice has an analog in informal proofs.
Here is an informal proof of this theorem that matches the
structure of the formal one:
_Theorem_: For all arithmetic expressions [a],
aeval (optimize_0plus a) = aeval a.
_Proof_: By induction on [a]. Most cases follow directly from the IH.
The remaining cases are as follows:
- Suppose [a = ANum n] for some [n]. We must show
aeval (optimize_0plus (ANum n)) = aeval (ANum n).
This is immediate from the definition of [optimize_0plus].
- Suppose [a = APlus a1 a2] for some [a1] and [a2]. We
must show
aeval (optimize_0plus (APlus a1 a2))
= aeval (APlus a1 a2).
Consider the possible forms of [a1]. For most of them,
[optimize_0plus] simply calls itself recursively for the
subexpressions and rebuilds a new expression of the same form
as [a1]; in these cases, the result follows directly from the
IH.
The interesting case is when [a1 = ANum n] for some [n].
If [n = ANum 0], then
optimize_0plus (APlus a1 a2) = optimize_0plus a2
and the IH for [a2] is exactly what we need. On the other
hand, if [n = S n'] for some [n'], then again [optimize_0plus]
simply calls itself recursively, and the result follows from
the IH. [] *)
(** This proof can still be improved: the first case (for [a = ANum
n]) is very trivial -- even more trivial than the cases that we
said simply followed from the IH -- yet we have chosen to write it
out in full. It would be better and clearer to drop it and just
say, at the top, "Most cases are either immediate or direct from
the IH. The only interesting case is the one for [APlus]..." We
can make the same improvement in our formal proof too. Here's how
it looks: *)
Theorem optimize_0plus_sound'': forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
(* Most cases follow directly by the IH *)
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
(* ... or are immediate by definition *)
try reflexivity.
(* The interesting case is when a = APlus a1 a2. *)
- (* APlus *)
destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
+ (* a1 = ANum n *) destruct n;
simpl; rewrite IHa2; reflexivity. Qed.
(* ----------------------------------------------------------------- *)
(** *** The [;] Tactical (General Form) *)
(** The [;] tactical also has a more general form than the simple
[T;T'] we've seen above. If [T], [T1], ..., [Tn] are tactics,
then
T; [T1 | T2 | ... | Tn]
is a tactic that first performs [T] and then performs [T1] on the
first subgoal generated by [T], performs [T2] on the second
subgoal, etc.
So [T;T'] is just special notation for the case when all of the
[Ti]'s are the same tactic -- i.e., [T;T'] is shorthand for:
T; [T' | T' | ... | T']
*)
(* ----------------------------------------------------------------- *)
(** *** The [repeat] Tactical *)
(** The [repeat] tactical takes another tactic and keeps applying this
tactic until it fails. Here is an example showing that [10] is in
a long list using repeat. *)
Theorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
repeat (try (left; reflexivity); right).
Qed.
(* Print In10. *)
(** The [repeat T] tactic never fails: if the tactic [T] doesn't apply
to the original goal, then repeat still succeeds without changing
the original goal (i.e., it repeats zero times). *)
Theorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
repeat (left; reflexivity).
repeat (right; try (left; reflexivity)).
Qed.
(** The [repeat T] tactic also does not have any upper bound on the
number of times it applies [T]. If [T] is a tactic that always
succeeds, then repeat [T] will loop forever (e.g., [repeat simpl]
loops forever, since [simpl] always succeeds). While Coq's term
language is guaranteed to terminate, Coq's tactic language is
not! *)
(** **** Exercise: 3 stars (optimize_0plus_b) *)
(** Since the [optimize_0plus] tranformation doesn't change the value
of [aexp]s, we should be able to apply it to all the [aexp]s that
appear in a [bexp] without changing the [bexp]'s value. Write a
function which performs that transformation on [bexp]s, and prove
it is sound. Use the tacticals we've just seen to make the proof
as elegant as possible. *)
Fixpoint optimize_0plus_b (b : bexp) : bexp :=
(* FILL IN HERE *) admit.
Theorem optimize_0plus_b_sound : forall b,
beval (optimize_0plus_b b) = beval b.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, optional (optimizer) *)
(** _Design exercise_: The optimization implemented by our
[optimize_0plus] function is only one of many possible
optimizations on arithmetic and boolean expressions. Write a more
sophisticated optimizer and prove it correct.
(* FILL IN HERE *)
*)
(** [] *)
(* ================================================================= *)
(** ** Defining New Tactic Notations *)
(** Coq also provides several ways of "programming" tactic scripts.
- The [Tactic Notation] idiom illustrated below gives a handy way to
define "shorthand tactics" that bundle several tactics into a
single command.
- For more sophisticated programming, Coq offers a small built-in
programming language called [Ltac] with primitives that can
examine and modify the proof state. The details are a bit too
complicated to get into here (and it is generally agreed that
[Ltac] is not the most beautiful part of Coq's design!), but they
can be found in the reference manual and other books on Coq, and
there are many examples of [Ltac] definitions in the Coq standard
library that you can use as examples.
- There is also an OCaml API, which can be used to build tactics
that access Coq's internal structures at a lower level, but this
is seldom worth the trouble for ordinary Coq users.
The [Tactic Notation] mechanism is the easiest to come to grips with,
and it offers plenty of power for many purposes. Here's an example. *)
Tactic Notation "simpl_and_try" tactic(c) :=
simpl;
try c.
(** This defines a new tactical called [simpl_and_try] that takes one
tactic [c] as an argument and is defined to be equivalent to the
tactic [simpl; try c]. For example, writing "[simpl_and_try
reflexivity.]" in a proof would be the same as writing "[simpl;
try reflexivity.]" *)
(* ================================================================= *)
(** ** The [omega] Tactic *)
(** The [omega] tactic implements a decision procedure for a subset of
first-order logic called _Presburger arithmetic_. It is based on
the Omega algorithm invented in 1991 by William Pugh [Pugh 1991].
If the goal is a universally quantified formula made out of
- numeric constants, addition ([+] and [S]), subtraction ([-]
and [pred]), and multiplication by constants (this is what
makes it Presburger arithmetic),
- equality ([=] and [<>]) and inequality ([<=]), and
- the logical connectives [/\], [\/], [~], and [->],
then invoking [omega] will either solve the goal or tell you that
it is actually false. *)
Require Import Coq.omega.Omega.
Example silly_presburger_example : forall m n o p,
m + n <= n + o /\ o + 3 = p + 3 ->
m <= p.
Proof.
intros. omega.
Qed.
(** Leibniz wrote, "It is unworthy of excellent men to lose
hours like slaves in the labor of calculation which could be
relegated to anyone else if machines were used." We recommend
that excellent people of all genders use the omega tactic whenever
possible. *)
(* ================================================================= *)
(** ** A Few More Handy Tactics *)
(** Finally, here are some miscellaneous tactics that you may find
convenient.
- [clear H]: Delete hypothesis [H] from the context.
- [subst x]: Find an assumption [x = e] or [e = x] in the
context, replace [x] with [e] throughout the context and
current goal, and clear the assumption.
- [subst]: Substitute away _all_ assumptions of the form [x = e]
or [e = x].
- [rename... into...]: Change the name of a hypothesis in the
proof context. For example, if the context includes a variable
named [x], then [rename x into y] will change all occurrences
of [x] to [y].
- [assumption]: Try to find a hypothesis [H] in the context that
exactly matches the goal; if one is found, behave just like
[apply H].
- [contradiction]: Try to find a hypothesis [H] in the current
context that is logically equivalent to [False]. If one is
found, solve the goal.
- [constructor]: Try to find a constructor [c] (from some
[Inductive] definition in the current environment) that can be
applied to solve the current goal. If one is found, behave
like [apply c].
We'll see many examples of these in the proofs below. *)
(* ################################################################# *)
(** * Evaluation as a Relation *)
(** We have presented [aeval] and [beval] as functions defined by
[Fixpoint]s. Another way to think about evaluation -- one that we
will see is often more flexible -- is as a _relation_ between
expressions and their values. This leads naturally to [Inductive]
definitions like the following one for arithmetic expressions... *)
Module aevalR_first_try.
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum : forall (n: nat),
aevalR (ANum n) n
| E_APlus : forall (e1 e2: aexp) (n1 n2: nat),
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (APlus e1 e2) (n1 + n2)
| E_AMinus: forall (e1 e2: aexp) (n1 n2: nat),
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (AMinus e1 e2) (n1 - n2)
| E_AMult : forall (e1 e2: aexp) (n1 n2: nat),
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (AMult e1 e2) (n1 * n2).
(** As is often the case with relations, we'll find it
convenient to define infix notation for [aevalR]. We'll write [e
\\ n] to mean that arithmetic expression [e] evaluates to value
[n]. (This notation is one place where the limitation to ASCII
symbols becomes a little bothersome. The standard notation for
the evaluation relation is a double down-arrow. We'll typeset it
like this in the HTML version of the notes and use a double slash
as the closest approximation in [.v] files.) *)
Notation "e '\\' n"
:= (aevalR e n)
(at level 50, left associativity)
: type_scope.
End aevalR_first_try.
(** In fact, Coq provides a way to use this notation in the definition
of [aevalR] itself. This avoids situations where we're working on
a proof involving statements in the form [e \\ n] but we have to
refer back to a definition written using the form [aevalR e n].
We do this by first "reserving" the notation, then giving the
definition together with a declaration of what the notation
means. *)
Reserved Notation "e '\\' n" (at level 50, left associativity).
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum : forall (n:nat),
(ANum n) \\ n
| E_APlus : forall (e1 e2: aexp) (n1 n2 : nat),
(e1 \\ n1) -> (e2 \\ n2) -> (APlus e1 e2) \\ (n1 + n2)
| E_AMinus : forall (e1 e2: aexp) (n1 n2 : nat),
(e1 \\ n1) -> (e2 \\ n2) -> (AMinus e1 e2) \\ (n1 - n2)
| E_AMult : forall (e1 e2: aexp) (n1 n2 : nat),
(e1 \\ n1) -> (e2 \\ n2) -> (AMult e1 e2) \\ (n1 * n2)
where "e '\\' n" := (aevalR e n) : type_scope.
(* ================================================================= *)
(** ** Inference Rule Notation *)
(** In informal discussions, it is convenient to write the rules for
[aevalR] and similar relations in the more readable graphical form
of _inference rules_, where the premises above the line justify
the conclusion below the line (we have already seen them in the
Prop chapter). *)
(** For example, the constructor [E_APlus]...
| E_APlus : forall (e1 e2: aexp) (n1 n2: nat),
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (APlus e1 e2) (n1 + n2)
...would be written like this as an inference rule:
e1 \\ n1
e2 \\ n2
-------------------- (E_APlus)
APlus e1 e2 \\ n1+n2
*)
(** Formally, there is nothing deep about inference rules: they
are just implications. You can read the rule name on the right as
the name of the constructor and read each of the linebreaks
between the premises above the line and the line itself as [->].
All the variables mentioned in the rule ([e1], [n1], etc.) are
implicitly bound by universal quantifiers at the beginning. (Such
variables are often called _metavariables_ to distinguish them
from the variables of the language we are defining. At the
moment, our arithmetic expressions don't include variables, but
we'll soon be adding them.) The whole collection of rules is
understood as being wrapped in an [Inductive] declaration. In
informal prose, this is either elided or else indicated by saying
something like "Let [aevalR] be the smallest relation closed under
the following rules...". *)
(** For example, [\\] is the smallest relation closed under these
rules:
----------- (E_ANum)
ANum n \\ n
e1 \\ n1
e2 \\ n2
-------------------- (E_APlus)
APlus e1 e2 \\ n1+n2
e1 \\ n1
e2 \\ n2
--------------------- (E_AMinus)
AMinus e1 e2 \\ n1-n2
e1 \\ n1
e2 \\ n2
-------------------- (E_AMult)
AMult e1 e2 \\ n1*n2
*)
(* ================================================================= *)
(** ** Equivalence of the Definitions *)
(** It is straightforward to prove that the relational and functional
definitions of evaluation agree, for all arithmetic expressions... *)
Theorem aeval_iff_aevalR : forall a n,
(a \\ n) <-> aeval a = n.
Proof.
split.
- (* -> *)
intros H.
induction H; simpl.
+ (* E_ANum *)
reflexivity.
+ (* E_APlus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMinus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMult *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
- (* <- *)
generalize dependent n.
induction a;
simpl; intros; subst.
+ (* ANum *)
apply E_ANum.
+ (* APlus *)
apply E_APlus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMinus *)
apply E_AMinus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMult *)
apply E_AMult.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
Qed.
(** We can make the proof quite a bit shorter by making more
use of tacticals... *)
Theorem aeval_iff_aevalR' : forall a n,
(a \\ n) <-> aeval a = n.
Proof.
(* WORKED IN CLASS *)
split.
- (* -> *)
intros H; induction H; subst; reflexivity.
- (* <- *)
generalize dependent n.
induction a; simpl; intros; subst; constructor;
try apply IHa1; try apply IHa2; reflexivity.
Qed.
(** **** Exercise: 3 stars (bevalR) *)
(** Write a relation [bevalR] in the same style as
[aevalR], and prove that it is equivalent to [beval].*)
(*
Inductive bevalR:
(* FILL IN HERE *)
*)
(** [] *)
End AExp.
(* ================================================================= *)
(** ** Computational vs. Relational Definitions *)
(** For the definitions of evaluation for arithmetic and boolean
expressions, the choice of whether to use functional or relational
definitions is mainly a matter of taste. In general, Coq has
somewhat better support for working with relations. On the other
hand, in some sense function definitions carry more information,
because functions are by definition deterministic and defined on
all arguments; for a relation we have to show these properties
explicitly if we need them. Functions also take advantage of
Coq's computation mechanism.
However, there are circumstances where relational definitions of
evaluation are preferable to functional ones. *)
Module aevalR_division.
(** For example, suppose that we wanted to extend the arithmetic
operations by considering also a division operation:*)
Inductive aexp : Type :=
| ANum : nat -> aexp
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp
| ADiv : aexp -> aexp -> aexp. (* <--- new *)
(** Extending the definition of [aeval] to handle this new operation
would not be straightforward (what should we return as the result
of [ADiv (ANum 5) (ANum 0)]?). But extending [aevalR] is
straightforward. *)
Reserved Notation "e '\\' n"
(at level 50, left associativity).
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum : forall (n:nat),
(ANum n) \\ n
| E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (APlus a1 a2) \\ (n1 + n2)
| E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (AMinus a1 a2) \\ (n1 - n2)
| E_AMult : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (AMult a1 a2) \\ (n1 * n2)
| E_ADiv : forall (a1 a2: aexp) (n1 n2 n3: nat),
(a1 \\ n1) -> (a2 \\ n2) -> (n2 > 0) ->
(mult n2 n3 = n1) -> (ADiv a1 a2) \\ n3
where "a '\\' n" := (aevalR a n) : type_scope.
End aevalR_division.
Module aevalR_extended.
(* ----------------------------------------------------------------- *)
(** *** Adding Nondeterminism *)
(** Suppose, instead, that we want to extend the arithmetic operations
by a nondeterministic number generator [any] that, when evaluated,
may yield any number. (Note that this is not the same as making a
_probabilistic_ choice among all possible numbers -- we're not
specifying any particular distribution of results, but just saying
what results are _possible_.) *)
Reserved Notation "e '\\' n" (at level 50, left associativity).
Inductive aexp : Type :=
| AAny : aexp (* <--- NEW *)
| ANum : nat -> aexp
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp.
(** Again, extending [aeval] would be tricky, since now evaluation is
_not_ a deterministic function from expressions to numbers, but
extending [aevalR] is no problem: *)
Inductive aevalR : aexp -> nat -> Prop :=
| E_Any : forall (n:nat),
AAny \\ n (* <--- new *)
| E_ANum : forall (n:nat),
(ANum n) \\ n
| E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (APlus a1 a2) \\ (n1 + n2)
| E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (AMinus a1 a2) \\ (n1 - n2)
| E_AMult : forall (a1 a2: aexp) (n1 n2 : nat),
(a1 \\ n1) -> (a2 \\ n2) -> (AMult a1 a2) \\ (n1 * n2)
where "a '\\' n" := (aevalR a n) : type_scope.
End aevalR_extended.
(* ################################################################# *)
(** * Expressions With Variables *)
(** Let's turn our attention back to defining Imp. The next thing we
need to do is to enrich our arithmetic and boolean expressions
with variables. To keep things simple, we'll assume that all
variables are global and that they only hold numbers. *)
(* ================================================================= *)
(** ** States *)
(** Since we'll want to look variables up to find out their current
values, we'll reuse the type [id] from the [Maps] chapter for the
type of variables in Imp.
A _machine state_ (or just _state_) represents the current values
of _all_ variables at some point in the execution of a program. *)
(** For simplicity, we assume that the state is defined for
_all_ variables, even though any given program is only going to
mention a finite number of them. The state captures all of the
information stored in memory. For Imp programs, because each
variable stores a natural number, we can represent the state as a
mapping from identifiers to [nat]. For more complex programming
languages, the state might have more structure. *)
Definition state := total_map nat.
Definition empty_state : state :=
t_empty 0.
(* ================================================================= *)
(** ** Syntax *)
(** We can add variables to the arithmetic expressions we had before by
simply adding one more constructor: *)
Inductive aexp : Type :=
| ANum : nat -> aexp
| AId : id -> aexp (* <----- NEW *)
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp.
(** Defining a few variable names as notational shorthands will make
examples easier to read: *)
Definition X : id := Id 0.
Definition Y : id := Id 1.
Definition Z : id := Id 2.
(** (This convention for naming program variables ([X], [Y],
[Z]) clashes a bit with our earlier use of uppercase letters for
types. Since we're not using polymorphism heavily in this part of
the course, this overloading should not cause confusion.) *)
(** The definition of [bexp]s is unchanged (except for using the new
[aexp]s): *)
Inductive bexp : Type :=
| BTrue : bexp
| BFalse : bexp
| BEq : aexp -> aexp -> bexp
| BLe : aexp -> aexp -> bexp
| BNot : bexp -> bexp
| BAnd : bexp -> bexp -> bexp.
(* ================================================================= *)
(** ** Evaluation *)
(** The arith and boolean evaluators are extended to handle
variables in the obvious way, taking a state as an extra
argument: *)
Fixpoint aeval (st : state) (a : aexp) : nat :=
match a with
| ANum n => n
| AId x => st x (* <----- NEW *)
| APlus a1 a2 => (aeval st a1) + (aeval st a2)
| AMinus a1 a2 => (aeval st a1) - (aeval st a2)
| AMult a1 a2 => (aeval st a1) * (aeval st a2)
end.
Fixpoint beval (st : state) (b : bexp) : bool :=
match b with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)
| BLe a1 a2 => leb (aeval st a1) (aeval st a2)
| BNot b1 => negb (beval st b1)
| BAnd b1 b2 => andb (beval st b1) (beval st b2)
end.
Example aexp1 :
aeval (t_update empty_state X 5)
(APlus (ANum 3) (AMult (AId X) (ANum 2)))
= 13.
Proof. reflexivity. Qed.
Example bexp1 :
beval (t_update empty_state X 5)
(BAnd BTrue (BNot (BLe (AId X) (ANum 4))))
= true.
Proof. reflexivity. Qed.
(* ################################################################# *)
(** * Commands *)
(** Now we are ready define the syntax and behavior of Imp
_commands_ (sometimes called _statements_). *)
(* ================================================================= *)
(** ** Syntax *)
(** Informally, commands [c] are described by the following BNF
grammar. (We choose this slightly awkward concrete syntax for the
sake of being able to define Imp syntax using Coq's Notation
mechanism. In particular, we use [IFB] to avoid conflicting with
the [if] notation from the standard library.)
c ::= SKIP | x ::= a | c ;; c | IFB b THEN c ELSE c FI
| WHILE b DO c END
*)
(**
For example, here's factorial in Imp:
Z ::= X;;
Y ::= 1;;
WHILE not (Z = 0) DO
Y ::= Y * Z;;
Z ::= Z - 1
END
When this command terminates, the variable [Y] will contain the
factorial of the initial value of [X]. *)
(** Here is the formal definition of the abstract syntax of
commands: *)
Inductive com : Type :=
| CSkip : com
| CAss : id -> aexp -> com
| CSeq : com -> com -> com
| CIf : bexp -> com -> com -> com
| CWhile : bexp -> com -> com.