-
Notifications
You must be signed in to change notification settings - Fork 0
/
Imp.v
1691 lines (1424 loc) · 56.9 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 *)
(* $Date: 2011-06-15 14:52:03 $ *)
(** In this chapter, we begin a new direction that we'll continue for
the rest of the course: whereas up to now we've been mostly
studying Coq itself, from now on we'll mostly be using Coq to
formalize other things.
Our first case study is a _simple imperative programming language_
called Imp. This chapter looks at how to define the _syntax_ and
_semantics_ of Imp; the chapters that follow will develop a theory
of _program equivalence_ and introduce _Hoare Logic_, the best
known logic for reasoning about imperative programs. *)
(* ####################################################### *)
(** *** Sflib *)
(** A minor technical point: Instead of asking Coq to import our
earlier definitions from Logic.v, we import a small library called
Sflib.v, containing just a few definitions and theorems from
earlier chapters that we'll actually use in the rest of the
course. You won't notice much difference, since most of what's
missing from Sflib has identical definitions in the Coq standard
library. The main reason for doing this is to tidy the global Coq
environment so that, for example, it is easier to search for
relevant theorems. *)
From SF Require Export SfLib.
Require Export Lia.
Require Import String.
Open Scope string_scope.
(* ####################################################### *)
(** * 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. *)
Module AExp.
(* ####################################################### *)
(** ** Syntax *)
(** 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 file ImpParser.v develops a simple implementation of a lexical
analyzer and parser that can perform this translation. You do
_not_ need to understand that file to understand this one, but if
you haven't taken a course where these techniques are
covered (e.g., a compilers course) you may enjoy skimming it. *)
(* ####################################################### *)
(** ** Evaluation *)
(** _Evaluating_ an arithmetic expression reduces it to a single number. *)
Fixpoint aeval (e : aexp) : nat :=
match e 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 (e : bexp) : bool :=
match e with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval a1) (aeval a2)
| BLe a1 a2 => ble_nat (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 (e:aexp) : aexp :=
match e 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 e,
aeval (optimize_0plus e) = aeval e.
Proof.
intros e. induction e.
Case "ANum". reflexivity.
Case "APlus". destruct e1.
SCase "e1 = ANum n". destruct n.
SSCase "n = 0". simpl. apply IHe2.
SSCase "n <> 0". simpl. rewrite IHe2. reflexivity.
SCase "e1 = APlus e1_1 e1_2".
simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.
SCase "e1 = AMinus e1_1 e1_2".
simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.
SCase "e1 = AMult e1_1 e1_2".
simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.
Case "AMinus".
simpl. rewrite IHe1. rewrite IHe2. reflexivity.
Case "AMult".
simpl. rewrite IHe1. rewrite IHe2. reflexivity. Qed.
(* ####################################################### *)
(** * Coq Automation *)
(** The repetition in this last proof is starting to be a little
annoying. It's still just about bearable, but 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 very powerful
facilities for constructing 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, or low-level details. *)
(* ####################################################### *)
(** ** Tacticals *)
(** _Tactical_ is Coq's term for tactics that take other tactics as
arguments -- "higher-order tactics," if you will. *)
(* ####################################################### *)
(** *** The [try] Tactical *)
(** One very simple tactical is [try]: If [T] is a tactic, then [try
T] is a tactic that is just like [T] except that, if [T] fails,
[try T] does nothing at all (instead of failing). *)
(* ####################################################### *)
(** *** The [;] Tactical *)
(** Another very basic tactical is written [;]. 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.
In the special case where all of the [Ti]'s are the same tactic
[T'], we can just write [T;T'] instead of:
[[
T; [T' | T' | ... | T']
]]
That is, if [T] and [T'] are tactics, then [T;T'] is a tactic that
first performs [T] and then performs [T'] on _each subgoal_
generated by [T]. This is the form of [;] that is used most often
in practice. *)
(** For example, consider the following trivial lemma: *)
Lemma foo : forall n, ble_nat 0 n = true.
Proof.
intros.
destruct n.
(* Leaves two subgoals... *)
Case "n=0". simpl. reflexivity.
Case "n=Sn'". simpl. reflexivity.
(* ... which are discharged similarly *)
Qed.
(** We can simplify the proof above using the [;] tactical. *)
Lemma foo' : forall n, ble_nat 0 n = true.
Proof.
intros.
(* Apply [destruct] to the current goal *)
destruct n;
(* then apply [simpl] to each resulting subgoal *)
simpl;
(* then apply [reflexivity] to 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 e,
aeval (optimize_0plus e) = aeval e.
Proof.
intros e.
induction e;
(* Most cases follow directly by the IH *)
try (simpl; rewrite IHe1; rewrite IHe2; reflexivity).
Case "ANum". reflexivity.
Case "APlus".
destruct e1;
(* Most cases follow directly by the IH *)
try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).
(* The interesting case, on which the above fails, is when e1 =
ANum n. In this case, we have to destruct n (to see whether the
optimization applies) and rewrite with the inductive
hypothesis. *)
SCase "e1 = ANum n". destruct n;
simpl; rewrite IHe2; reflexivity. Qed.
(** In practice, Coq experts often use [try] with a tactic like
[induction] to take care of many similar "straightforward" 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 [e],
[[
aeval (optimize_0plus e) = aeval e.
]]
_Proof_: By induction on [e]. The [AMinus] and [AMult] cases
follow directly from the IH. The remaining cases are as follows:
- Suppose [e = 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 [e = APlus e1 e2] for some [e1] and [e2]. We
must show
[[
aeval (optimize_0plus (APlus e1 e2))
= aeval (APlus e1 e2).
]]
Consider the possible forms of [e1]. For most of them,
[optimize_0plus] simply calls itself recursively for the
subexpressions and rebuilds a new expression of the same form
as [e1]; in these cases, the result follows directly from the
IH.
The interesting case is when [e1 = ANum n] for some [n].
If [n = ANum 0], then
[[
optimize_0plus (APlus e1 e2) = optimize_0plus e2
]]
and the IH for [e2] 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 [e = 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 e,
aeval (optimize_0plus e) = aeval e.
Proof.
intros e.
induction e;
(* Most cases follow directly by the IH *)
try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);
(* ... or are immediate by definition *)
try reflexivity.
(* The interesting case is when e = APlus e1 e2. *)
Case "APlus".
destruct e1;
try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).
SCase "e1 = ANum n". destruct n;
simpl; rewrite IHe2; reflexivity. Qed.
(* ####################################################### *)
(** ** Defining New Tactic Notations *)
(** Coq also provides several ways of "programming" tactic scripts.
- The [Tactic Notation] command gives a handy way to define
"shorthand tactics" that, when invoked, apply several tactics
at the same time.
- 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
there are many examples of [Ltac] definitions in the Coq
standard library that you can use as examples.
- There is also an OCaml API that can be used to build new
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] which
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 next subsection gives a more sophisticated use of this
feature... *)
(* ####################################################### *)
(** *** Bulletproofing Case Analyses *)
(** Being able to deal with most of the cases of an [induction] or
[destruct] all at the same time is very convenient, but it can
also be a little confusing. One problem that often comes up is
that _maintaining_ proofs written in this style can be difficult.
For example, suppose that, later, we extended the definition of
[aexp] with another constructor that also required a special
argument. The above proof might break because Coq generated the
subgoals for this constructor before the one for [APlus], so that,
at the point when we start working on the [APlus] case, Coq is
actually expecting the argument for a completely different
constructor. What we'd like is to get a sensible error message
saying "I was expecting the [AFoo] case at this point, but the
proof script is talking about [APlus]." Here's a nice little
trick that smoothly achieves this. *)
Tactic Notation "aexp_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ANum" | Case_aux c "APlus"
| Case_aux c "AMinus" | Case_aux c "AMult" ].
(** For example, if [e] is a variable of type [aexp], then doing
[[
aexp_cases (induction e) Case
]]
will perform an induction on [e] (the same as if we had just typed
[induction e]) and _also_ add a [Case] tag to each subgoal
generated by the [induction], labeling which constructor it comes
from. For example, here is yet another proof of
optimize_0plus_sound, using [aexp_cases]: *)
Theorem optimize_0plus_sound''': forall e,
aeval (optimize_0plus e) = aeval e.
Proof.
intros e.
aexp_cases (induction e) Case;
try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);
try reflexivity.
(* At this point, there is already an ["APlus"] case name in the
context. The [Case "APlus"] here in the proof text has the
effect of a sanity check: if the "Case" string in the context is
anything _other_ than ["APlus"] (for example, because we added a
clause to the definition of [aexp] and forgot to change the
proof) we'll get a helpful error at this point telling us that
this is now the wrong case. *)
Case "APlus".
aexp_cases (destruct e1) SCase;
try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).
SCase "ANum". destruct n;
simpl; rewrite IHe2; reflexivity. Qed.
(** **** 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. *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 4 stars, optional (optimizer) *)
(** DESIGN EXERCISE: The optimization implemented by our
[optimize_0plus] function is only one of many imaginable
optimizations on arithmetic and boolean expressions. Write a more
sophisticated optimizer and prove it correct.
(* FILL IN HERE *)
*)
(** [] *)
(* ####################################################### *)
(** ** Relational Presentation of Evaluation *)
(** We have presented [aeval] and [beval] as functions defined by
[Fixpoints]. An alternative way to think about evaluation is as a
_relation_ between expressions and their values.
This leads naturally to Coq [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]. *)
Notation "e '==>' n" := (aevalR e n) (at level 40).
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 40).
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).
Tactic Notation "aevalR_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "E_ANum" | Case_aux c "E_APlus"
| Case_aux c "E_AMinus" | Case_aux c "E_AMult" ].
(** It is straightforward to prove that the relational and functional definitions of
evaluation agree on all possible arithmetic expressions... *)
Theorem aeval_iff_aevalR : forall a n,
(a ==> n) <-> aeval a = n.
Proof.
split.
Case "->".
intros H.
aevalR_cases (induction H) SCase; simpl.
SCase "E_ANum".
reflexivity.
SCase "E_APlus".
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
SCase "E_AMinus".
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
SCase "E_AMult".
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
Case "<-".
generalize dependent n.
aevalR_cases (induction a) SCase;
simpl; intros; subst.
SCase "E_ANum".
apply E_ANum.
SCase "E_APlus".
apply E_APlus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
SCase "E_AMinus".
apply E_AMinus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
SCase "E_AMult".
apply E_AMult.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
Qed.
(** A shorter proof making more aggressive use of tacticals: *)
Theorem aeval_iff_aevalR' : forall a n,
(a ==> n) <-> aeval a = n.
(* WORKED IN CLASS *)
split.
Case "->".
intros H; induction H; subst; reflexivity.
Case "<-".
generalize dependent n.
induction a; simpl; intros; subst; constructor;
try apply IHa1; try apply IHa2; reflexivity.
Qed.
(** **** Exercise: 2 stars, optional (bevalR) *)
(** Write a relation [bevalR] in the same style as
[aevalR], and prove that it is equivalent to [beval].*)
(*
Inductive bevalR:
(* FILL IN HERE *)
(** [] *)
*)
(** In this case, 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; in
particular, we can more readily do induction over them. On the
other hand, in some sense function definitions carry more
information, because functions are necessarily deterministic and
defined on all arguments; for a relation we have to show these
properties explicitly if we need them.
However, there are circumstances where relational definitions of
evaluation are greatly preferable to functional ones, as we'll see
shortly. *)
(* ####################################################### *)
(** ** Inference Rule Notation *)
(** We will sometimes (especially in informal discussions) write the
rules for [aevalR] and similar relations in a more "graphical" form called
_inference rules_, where the premises above the line allow you to
derive the conclusion below the line. For example, the
constructor [E_APlus] 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 or complex about inference rules:
they are just implications. You can read the rule name on the
right as the name of the constructor and read both the spaces
between premises above the line and the line itself as [->]. All
the variables mentioned in the rule ([e1], [n1], etc.) are
implicitly bound by a universal quantifier at the beginning. The
whole collection of rules is implicitly wrapped in an [Inductive]
declaration; this is sometimes indicated informally by something
like "Let [aevalR] be the smallest relation closed under the
following rules...".
Here is a complete set of inference rules for [aevalR]:
[[[
---------------- (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)
]]]
*)
End AExp.
(* ####################################################### *)
(** ** 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 1992 by William Pugh.
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.
*)
Example silly_presburger_formula : forall m n o p,
m + n <= n + o /\ o + 3 = p + 3 ->
m <= p.
Proof.
intros. lia.
Qed.
(** Andrew Appel calls this the "Santa Claus tactic." *)
(* ####################################################### *)
(** ** 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].
- [assumption]: Try to find a hypothesis [H] in the context that
exactly matches the goal; if one is found, behave just like
[apply H].
- [constructor]: Try to find and [apply] a constructor. For
example, we have been using [split] is a special case of
[constructor] to [apply] the [conj] constructor.
We'll see many examples of these in the proofs below. *)
(* ####################################################### *)
(** * Expressions With Variables *)
(** Now 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 for the moment, we'll
assume that all variables are global and that they only hold
numbers. *)
(* ##################################################### *)
(** ** Identifiers *)
(** To begin, we'll need to formalize "identifiers," such as program
variables. We could use strings for this, or (as in a real
compiler) some kind of fancier structures like symbols from a
symbol table. But for simplicity let's just use natural numbers
as identifiers.
We define a new inductive datatype [Id] so that we won't confuse
identifiers and numbers. Note that we hide this section in a
module because these definitions are actually in SfLib, but we
want to repeat them here so that we can explain them. *)
Module Id.
Inductive id : Type :=
Id : nat -> id.
Definition beq_id id1 id2 :=
match (id1, id2) with
(Id n1, Id n2) => beq_nat n1 n2
end.
(** Now, having "wrapped" numbers as identifiers in this way, it is
convenient to recapitulate a few properties of numbers as
analogous properties of identifiers, so that we can work with
identifiers in definitions and proofs abstractly, without
unwrapping them to expose the underlying numbers. Since all we
need to know about identifiers is whether they are the same or
different, just a few basic facts are all we need. *)
Theorem beq_id_refl : forall i,
true = beq_id i i.
Proof.
intros. destruct i.
apply beq_nat_refl. Qed.
(** **** Exercise: 1 star, optional *)
(** For this and the following exercises, do not prove by induction,
but rather by applying similar results already proved for natural
numbers. Some of the tactics mentioned above may prove useful. *)
Theorem beq_id_eq : forall i1 i2,
true = beq_id i1 i2 -> i1 = i2.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional *)
Theorem beq_id_false_not_eq : forall i1 i2,
beq_id i1 i2 = false -> i1 <> i2.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional *)
Theorem not_eq_beq_id_false : forall i1 i2,
i1 <> i2 -> beq_id i1 i2 = false.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional *)
Theorem beq_id_sym: forall i1 i2,
beq_id i1 i2 = beq_id i2 i1.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
End Id.
(* ####################################################### *)
(** ** States *)
(** A _state_ represents the current set of values for all the
variables at some point in the execution of a program. *)
Definition state := id -> nat.
Definition empty_state : state := fun _ => 0.
Definition update (st : state) (V:id) (n : nat) : state :=
fun V' => if beq_id V V' then n else st V'.
(** We'll need a few simple properties of [update]. *)
(** **** Exercise: 2 stars, optional *)
Theorem update_eq : forall n V st,
(update st V n) V = n.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Theorem update_neq : forall V2 V1 n st,
beq_id V2 V1 = false ->
(update st V2 n) V1 = (st V1).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
(** Before starting to play with tactics, make sure you understand
exactly what the theorem is saying! *)
Theorem update_example : forall (n:nat),
(update empty_state (Id 2) n) (Id 3) = 0.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Theorem update_shadow : forall x1 x2 k1 k2 (f : state),
(update (update f k2 x1) k2 x2) k1 = (update f k2 x2) k1.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Theorem update_same : forall x1 k1 k2 (f : state),
f k1 = x1 ->
(update f k1 x1) k2 = f k2.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Theorem update_permute : forall x1 x2 k1 k2 k3 f,
beq_id k2 k1 = false ->
(update (update f k2 x1) k1 x2) k3 = (update (update f k1 x2) k2 x1) k3.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################################### *)
(** ** 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.
Tactic Notation "aexp_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ANum" | Case_aux c "AId" | Case_aux c "APlus"
| Case_aux c "AMinus" | Case_aux c "AMult" ].
(** Shorthands for variables: *)
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 will hopefully not cause
confusion.) *)
(** Same [bexp]s as before (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.
Tactic Notation "bexp_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "BTrue" | Case_aux c "BFalse" | Case_aux c "BEq"
| Case_aux c "BLe" | Case_aux c "BNot" | Case_aux c "BAnd" ].
(* ################################################### *)
(** ** Evaluation *)
(** We extend the arith and boolean evaluators to handle variables. *)
Fixpoint aeval (st : state) (e : aexp) : nat :=
match e with
| ANum n => n
| AId i => st i (* <----- 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) (e : bexp) : bool :=
match e with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)
| BLe a1 a2 => ble_nat (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 (update empty_state X 5)
(APlus (ANum 3) (AMult (AId X) (ANum 2)))
= 13.
Proof. reflexivity. Qed.
Example bexp1 :
beval (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_ (or _statements_). *)
(* ################################################### *)
(** ** Syntax *)
(** Commands: *)
Inductive com : Type :=
| CSkip : com
| CAss : id -> aexp -> com
| CSeq : com -> com -> com
| CIf : bexp -> com -> com -> com
| CWhile : bexp -> com -> com.
Tactic Notation "com_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "SKIP" | Case_aux c "::=" | Case_aux c ";"
| Case_aux c "IFB" | Case_aux c "WHILE" ].
(** More readable concrete syntax, for examples: *)
Notation "'SKIP'" :=
CSkip.
Notation "l '::=' a" :=
(CAss l a) (at level 60).
Notation "c1 ; c2" :=
(CSeq c1 c2) (at level 80, right associativity).
Notation "'WHILE' b 'DO' c 'END'" :=
(CWhile b c) (at level 80, right associativity).
Notation "'IFB' e1 'THEN' e2 'ELSE' e3 'FI'" :=
(CIf e1 e2 e3) (at level 80, right associativity).
(* ####################################################### *)
(** ** Examples *)
(** Assignment: *)
Definition plus2 : com :=
X ::= (APlus (AId X) (ANum 2)).
Definition XtimesYinZ : com :=
Z ::= (AMult (AId X) (AId Y)).
(** Loops: *)
Definition subtract_slowly_body : com :=
Z ::= AMinus (AId Z) (ANum 1) ;
X ::= AMinus (AId X) (ANum 1).
Definition subtract_slowly : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
subtract_slowly_body
END.
Definition subtract_3_from_5_slowly : com :=
X ::= ANum 3 ;
Z ::= ANum 5 ;
subtract_slowly.
(** An infinite loop: *)
Definition loop : com :=
WHILE BTrue DO
SKIP
END.
(** Factorial: *)
Definition fact_body : com :=
Y ::= AMult (AId Y) (AId Z) ;
Z ::= AMinus (AId Z) (ANum 1).
Definition fact_loop : com :=
WHILE BNot (BEq (AId Z) (ANum 0)) DO
fact_body
END.
Definition fact_com : com :=
Z ::= AId X ;
Y ::= ANum 1 ;
fact_loop.
(* ################################################################ *)
(** * Evaluation *)
(** Next we need to define what it means to evaluate an Imp command.
[WHILE] loops actually make this a bit tricky... *)
(* #################################### *)
(** ** Evaluation Function *)
(** Here's a first try at an evaluation function for commands,
omitting [WHILE]. *)
Fixpoint ceval_step1 (st : state) (c : com) : state :=
match c with
| SKIP =>
st