-
Notifications
You must be signed in to change notification settings - Fork 7
/
Hoare.v
2660 lines (2265 loc) · 92.2 KB
/
Hoare.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
(** * Hoare: Hoare Logic *)
(* $Date: 2012-05-12 10:20:28 -0400 (Sat, 12 May 2012) $ *)
Require Export Imp.
(** In the past couple of chapters, we've begun applying the
mathematical tools developed in the first part of the course to
studying the theory of a small programming language, Imp.
- We defined a type of _abstract syntax trees_ for Imp, together
with an _evaluation relation_ (a partial function on states)
that specifies the _operational semantics_ of programs.
The language we defined, though small, captures some of the key
features of full-blown languages like C, C++, and Java,
including the fundamental notion of mutable state and some
common control structures.
- We proved a number of _metatheoretic properties_ -- "meta" in
the sense that they are properties of the language as a whole,
rather than properties of particular programs in the language.
These included:
- determinism of evaluation
- equivalence of some different ways of writing down the
definitions (e.g. functional and relational definitions of
arithmetic expression evaluation)
- guaranteed termination of certain classes of programs
- correctness (in the sense of preserving meaning) of a number
of useful program transformations
- behavioral equivalence of programs (in the optional chapter
[Equiv]).
If we stopped here, we would still have something useful: a set
of tools for defining and discussing programming languages and
language features that are mathematically precise, flexible, and
easy to work with, applied to a set of key properties. All of
these properties are things that language designers, compiler
writers, and users might care about knowing. Indeed, many of
them are so fundamental to our understanding of the programming
languages we deal with that we might not consciously recognize
them as "theorems." But properties that seem intuitively
obvious can sometimes be quite subtle -- or, in some cases,
actually even wrong!
We'll return to this theme later in the course when we discuss
_types_ and _type soundness_.
- We saw a couple of examples of _program verification_ -- using
the precise definition of Imp to prove formally that certain
particular programs (e.g., factorial and slow subtraction)
satisfied particular specifications of their behavior. *)
(** In this chapter, we'll take this last idea further. We'll
develop a reasoning system called _Floyd-Hoare Logic_ -- commonly
shortened to just _Hoare Logic_ -- in which each of the syntactic
constructs of Imp is equipped with a single, generic "proof rule"
that can be used to reason about programs involving this
construct.
Hoare Logic originates in the 1960s, and it continues to be the
subject of intensive research right up to the present day. It
lies at the core of a huge variety of tools that are now being
used to specify and verify real software systems. *)
(* ####################################################### *)
(** * Hoare Logic *)
(** Hoare Logic combines two beautiful ideas: a natural way of
writing down _specifications_ of programs, and a _compositional
proof technique_ for proving that these specifications are met --
where by "compositional" we mean that the structure of proofs
directly mirrors the structure of the programs that they are
about. *)
(* ####################################################### *)
(** ** Assertions *)
(** If we're going to talk about specifications of programs, the
first thing we'll want is a way of making _assertions_ about
properties that hold at particular points during a program's
execution -- i.e., properties that may or may not be true of a
given state of the memory. *)
Definition Assertion := state -> Prop.
(** **** Exercise: 1 star (assertions) *)
(** Paraphrase the following assertions in English.
1) fun st => st X = 3
2) fun st => st X = x
3) fun st => st X <= st Y
4) fun st => st X = 3 \/ st X <= st Y
5) fun st => st Z * st Z <= x /\ ~ (((S (st Z)) * (S (st Z))) <= x)
6) fun st => True
7) fun st => False
*)
(* FILL IN HERE *)
(** [] *)
(** This way of writing assertions is formally correct -- it
precisely captures what we mean, and it is exactly what we will
use in Coq proofs. We'll also want a lighter, less formal
notation for discussing examples, since this one is a bit
heavy: (1) every single assertion that we ever write is going to
begin with [fun st => ]; and (2) this state [st] is the only one that
we ever use to look up variables (we will never need to talk about
two different memory states at the same time). So, when writing down
assertions informally, we'll make some simplifications:
drop the initial [fun st =>], and write just [X] instead of [st X]. *)
(** Informally, instead of writing
fun st => (st Z) * (st Z) <= x /\ ~ ((S (st Z)) * (S (st Z)) <= x)
we'll write just
Z * Z <= x /\ ~((S Z) * (S Z) <= x).
*)
(* ####################################################### *)
(** ** Hoare Triples *)
(** Next, we need a way of specifying -- making claims about -- the
behavior of commands. *)
(** Since we've defined assertions as a way of making claims about the
properties of states, and since the behavior of a command is to
transform one state to another, it is natural to express claims
about commands in the following way:
- "If command [c] is started in a state satisfying assertion
[P], and if [c] eventually terminates, then the final state is
guaranteed to satisfy the assertion [Q]."
Such a claim is called a _Hoare Triple_. The property [P] is
called the _precondition_ of [c], while [Q] is the _postcondition_
of [c]. *)
Definition hoare_triple (P:Assertion) (c:com) (Q:Assertion) : Prop :=
forall st st',
c / st || st' ->
P st ->
Q st'.
(** Since we'll be working a lot with Hoare triples, it's useful to
have a compact notation:
{{P}} c {{Q}}.
*)
(** (Traditionally, Hoare triples are written [{P} c {Q}], but single
braces are already used for other things in Coq.) *)
Notation "{{ P }} c {{ Q }}" := (hoare_triple P c Q)
(at level 90, c at next level)
: hoare_spec_scope.
Open Scope hoare_spec_scope.
(** (The [hoare_spec_scope] annotation here tells Coq that this
notation is not global but is intended to be used in particular
contexts. The [Open Scope] tells Coq that this file is one such
context. The first notation -- with missing postcondition -- will
not actually be used for a while; it's just a placeholder for a
notation that we'll want to define later, when we discuss
decorated programs.) *)
(** **** Exercise: 1 star (triples) *)
(** Paraphrase the following Hoare triples in English.
1) {{True}} c {{X = 5}}
2) {{X = x}} c {{X = x + 5)}}
3) {{X <= Y}} c {{Y <= X}}
4) {{True}} c {{False}}
5) {{X = x}}
c
{{Y = real_fact x}}.
6) {{True}}
c
{{(Z * Z) <= x /\ ~ (((S Z) * (S Z)) <= x)}}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 1 star (valid_triples) *)
(** Which of the following Hoare triples are _valid_ -- i.e., the
claimed relation between [P], [c], and [Q] is true?
1) {{True}} X ::= 5 {{X = 5}}
2) {{X = 2}} X ::= X + 1 {{X = 3}}
3) {{True}} X ::= 5; Y ::= 0 {{X = 5}}
4) {{X = 2 /\ X = 3}} X ::= 5 {{X = 0}}
5) {{True}} SKIP {{False}}
6) {{False}} SKIP {{True}}
7) {{True}} WHILE True DO SKIP END {{False}}
8) {{X = 0}}
WHILE X == 0 DO X ::= X + 1 END
{{X = 1}}
9) {{X = 1}}
WHILE X <> 0 DO X ::= X + 1 END
{{X = 100}}
*)
(* FILL IN HERE *)
(** [] *)
(** (Note that we're using informal mathematical notations for
expressions inside of commands, for readability. We'll continue
doing so throughout the chapter.) *)
(** To get us warmed up, here are two simple facts about Hoare
triples. *)
Theorem hoare_post_true : forall (P Q : Assertion) c,
(forall st, Q st) ->
{{P}} c {{Q}}.
Proof.
intros P Q c H. unfold hoare_triple.
intros st st' Heval HP.
apply H. Qed.
Theorem hoare_pre_false : forall (P Q : Assertion) c,
(forall st, ~(P st)) ->
{{P}} c {{Q}}.
Proof.
intros P Q c H. unfold hoare_triple.
intros st st' Heval HP.
unfold not in H. apply H in HP.
inversion HP. Qed.
(* ####################################################### *)
(** ** Weakest Preconditions *)
(** Some Hoare triples are more interesting than others.
For example,
{{ False }} X ::= Y + 1 {{ X <= 5 }}
is _not_ very interesting: it is perfectly valid, but it tells us
nothing useful. Since the precondition isn't satisfied by any
state, it doesn't describe any situations where we can use the
command [X ::= Y + 1] to achieve the postcondition [X <= 5].
By contrast,
{{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }}
is useful: it tells us that, if we can somehow create a situation
in which we know that [Y <= 4 /\ Z = 0], then running this command
will produce a state satisfying the postcondition. However, this
triple is still not as useful as it could be, because the [Z = 0]
clause in the precondition actually has nothing to do with the
postcondition [X <= 5]. The _most_ useful triple (for a given
command and postcondition) is this one:
{{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }}
In other words, [Y <= 4] is the _weakest_ valid precondition of
the command [X ::= Y + 1] for the postcondition [X <= 5]. *)
(** In general, we say that "[P] is the weakest precondition of
command [c] for postcondition [Q]" if
- [{{P}} c {{Q}}], and
- whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we
have [P' st] implies [P st] for all states [st]. *)
(** That is, [P] is the weakest precondition of [c] for [Q]
if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
_weakest_ (easiest to satisfy) assertion that guarantees [Q] after
executing [c]. *)
(** The second of the conditions above is essentially a form of
logical implication at the level of assertions. Because of the
frequency of its occurrence, it is useful to define a little
notation: *)
Definition assert_implies (P Q : Assertion) : Prop :=
forall st, P st -> Q st.
(** We will write [P ~~> Q] (in ASCII, [P ~][~> Q]) for [assert_implies
P Q]. *)
Notation "P ~~> Q" := (assert_implies P Q) (at level 80).
Notation "P <~~> Q" := (P ~~> Q /\ Q ~~> P) (at level 80).
(** **** Exercise: 1 star (wp) *)
(** What are the weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} SKIP {{ X = 5 }}
2) {{ ? }} X ::= Y + Z {{ X = 5 }}
3) {{ ? }} X ::= Y {{ X = Y }}
4) {{ ? }}
IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
{{ Y = 5 }}
5) {{ ? }}
X ::= 5
{{ X = 0 }}
6) {{ ? }}
WHILE True DO X ::= 0 END
{{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, optional (is_wp_formal) *)
(** Weakest preconditions can be defined formally as follows: *)
Definition is_wp P c Q :=
{{P}} c {{Q}} /\
forall P', {{P'}} c {{Q}} -> (forall st, P' st -> P st).
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
is indeed the weakest precondition of [X ::= Y + 1] with respect to
postcondition [X <= 5]. *)
Theorem is_wp_example :
is_wp (fun st => st Y <= 4)
(X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof. unfold is_wp. split; unfold hoare_triple; intros.
inversion H.
compute. rewrite <- H5.
simpl. rewrite plus_comm. simpl.
apply le_n_S. apply H0.
intros. unfold hoare_triple in H.
remember (update st X (st Y + 1)) as st'.
assert((X ::= APlus (AId Y) (ANum 1)) / st || st' -> P' st -> st' X <= 5).
apply H. rewrite Heqst' in H1. rewrite plus_comm in H1.
unfold update in H1. simpl in H1. apply le_S_n.
apply H1. apply E_Ass. simpl. rewrite plus_comm. reflexivity.
apply H0.
Qed.
(** [] *)
(* ####################################################### *)
(** ** Proof Rules *)
(** The goal of Hoare logic is to provide a _compositional_
method for proving the validity of Hoare triples. That is, the
structure of a program's correctness proof should mirror the
structure of the program itself. To this end, in the sections
below, we'll introduce one rule for reasoning about each of the
different syntactic forms of commands in Imp -- one for
assignment, one for sequencing, one for conditionals, etc. -- plus
a couple of "structural" rules that are useful for gluing things
together. We will prove programs correct using these proof rules,
without ever unfolding the definition of [hoare_triple]. *)
(* ####################################################### *)
(** *** Assignment *)
(** The rule for assignment is the most fundamental of the Hoare logic
proof rules. Here's how it works.
Consider this (valid) Hoare triple:
{{ Y = 1 }} X ::= Y {{ X = 1 }}
In English: if we start out in a state where the value of [Y]
is [1] and we assign [Y] to [X], then we'll finish in a
state where [X] is [1]. That is, the property of being equal
to [1] gets transferred from [Y] to [X].
Similarly, in
{{ Y + Z = 1 }} X ::= Y + Z {{ X = 1 }}
the same property (being equal to one) gets transferred to
[X] from the expression [Y + Z] on the right-hand side of
the assignment.
More generally, if [a] is _any_ arithmetic expression, then
{{ a = 1 }} X ::= a {{ X = 1 }}
is a valid Hoare triple.
Even more generally, [a] is _any_ arithmetic expression and [Q] is
_any_ property of numbers, then
{{ Q(a) }} X ::= a {{ Q(X) }}
is a valid Hoare triple.
Rephrasing this a bit gives us the general Hoare rule for
assignment:
{{ Q where a is substituted for X }} X ::= a {{ Q }}
For example, these are valid applications of the assignment
rule:
{{ (X <= 5) where X + 1 is substituted for X
i.e., X + 1 <= 5 }}
X ::= X + 1
{{ X <= 5 }}
{{ (X = 3) where 3 is substituted for X
i.e., 3 = 3}}
X ::= 3
{{ X = 3 }}
{{ (0 <= X /\ X <= 5) where 3 is substituted for X
i.e., (0 <= 3 /\ 3 <= 5)}}
X ::= 3
{{ 0 <= X /\ X <= 5 }}
*)
(** To formalize the rule, we begin with the notion of "substitution
in an assertion": *)
Definition assn_sub X a Q : Assertion :=
fun (st : state) =>
Q (update st X (aeval st a)).
(** We ask that [Q] holds for the state obtained by assigning [a] to
[X], i.e. the updated state in which [X] is bound to the result of
evaluating [a]. Since we've chosen to represent assertions using
Coq propositions, this is the only way we can "substitute" a
variable inside an assertion. *)
(** Now the precise proof rule for assignment:
------------------------------ (hoare_asgn)
{{assn_sub X a Q}} X::=a {{Q}}
*)
Theorem hoare_asgn : forall Q X a,
{{assn_sub X a Q}} (X ::= a) {{Q}}.
Proof.
unfold hoare_triple.
intros Q X a st st' HE HQ.
inversion HE. subst.
unfold assn_sub in HQ. assumption. Qed.
(** Here's a first formal proof using this rule. *)
Example assn_sub_example :
{{assn_sub X (ANum 3) (fun st => st X = 3)}}
(X ::= (ANum 3))
{{fun st => st X = 3}}.
Proof.
apply hoare_asgn. Qed.
(** **** Exercise: 2 stars (hoare_asgn_examples) *)
(** Translate these informal Hoare triples...
{{ assn_sub X (X + 1) (X <= 5) }} X ::= X + 1 {{ X <= 5 }}
{{ assn_sub X 3 (0 <= X /\ X <= 5) }} X ::= 3 {{ 0 <= X /\ X <= 5 }}
...into formal statements and use [hoare_asgn] to prove them. *)
Theorem hoare_asgn_examples :
{{ assn_sub X (APlus (AId X) (ANum 1)) (fun st => st X <= 5) }} X ::= APlus (AId X) (ANum 1) {{ fun st => st X <= 5 }}.
Proof. apply hoare_asgn. Qed.
Theorem hoare_asgn_examples_2 :
{{ assn_sub X (ANum 3) (fun st => 0 <= st X /\ st X <= 5) }} X ::= ANum 3 {{ fun st => 0 <= st X /\ st X <= 5 }}.
Proof. apply hoare_asgn. Qed.
(** [] *)
(** **** Exercise: 2 stars (hoare_asgn_wrong) *)
(** The assignment rule looks backward to almost everyone the first
time they see it. If it still seems backward to you, it may help
to think a little about alternative "forward" rules. Here is a
seemingly natural one:
------------------------------ (hoare_asgn_wrong)
{{ True }} X ::= a {{ X = a }}
Give a counterexample showing that this rule is incorrect
(informally). Hint: The rule universally quantifies over the
arithmetic expression [a], and your counterexample needs to
exhibit an [a] for which the rule doesn't work. *)
(*
X = X + 1
*)
(** [] *)
(** **** Exercise: 3 stars, optional (hoare_asgn_fwd) *)
(** However, using an auxiliary variable [x] to remember the original
value of [X] we can define a Hoare rule for assignment that does,
intuitively, "work forwards" rather than backwards.
------------------------------------------ (hoare_asgn_fwd)
{{fun st => Q st /\ st X = x}}
X ::= a
{{fun st => Q st' /\ st X = aeval st' a }}
(where st' = update st X x)
Note that we use the original value of [X] to reconstruct the
state [st'] before the assignment took place. Prove that this rule
is correct (the first hypothesis is the functional extensionality
axiom, which you will need at some point). Also note that this
rule is more complicated than [hoare_asgn].
*)
Theorem update_shadow':
(forall {X Y: Type} {f g : X -> Y}, (forall (x: X), f x = g x) -> f = g) ->
forall (x1 x2 : nat) (k2 : id) (f : state),
update (update f k2 x1) k2 x2 = update f k2 x2.
Proof. intros. apply H. intros. apply update_shadow.
Qed.
Theorem update_same':
(forall {X Y: Type} {f g : X -> Y}, (forall (x: X), f x = g x) -> f = g) ->
forall (x1 : nat) (k1 : id) (f : state),
f k1 = x1 -> update f k1 x1 = f.
Proof. intros. apply H. intros. apply update_same. apply H0.
Qed.
Theorem hoare_asgn_fwd :
(forall {X Y: Type} {f g : X -> Y}, (forall (x: X), f x = g x) -> f = g) ->
forall x a Q,
{{fun st => Q st /\ st X = x}}
X ::= a
{{fun st => Q (update st X x) /\ st X = aeval (update st X x) a }}.
Proof.
intros functional_extensionality v a Q.
unfold hoare_triple. intros. split.
inversion H. rewrite update_shadow'. rewrite update_same'.
inversion H0. apply H6. apply functional_extensionality.
inversion H0. apply H7. apply functional_extensionality.
inversion H. rewrite <- H1. rewrite update_shadow'.
rewrite update_same' with (x1:= v).
rewrite H5. apply update_eq. apply functional_extensionality.
inversion H0. rewrite H1. apply H7.
apply functional_extensionality.
Qed.
(** [] *)
(** **** Exercise: 2 stars (hoare_asgn_weakest) *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
weakest precondition. *)
Theorem hoare_asgn_weakest : forall P X a Q,
{{P}} (X ::= a) {{Q}} ->
P ~~> assn_sub X a Q.
Proof. unfold assert_implies. intros.
unfold assn_sub. unfold hoare_triple in H.
apply H with (st:= st). apply E_Ass. reflexivity. apply H0.
Qed.
(** [] *)
(* ####################################################### *)
(** *** Consequence *)
(** Sometimes the preconditions and postconditions we get from the
Hoare rules won't quite be the ones we want in the particular
situation at hand -- they may be logically equivalent but have a
different syntactic form that fails to unify with the goal we are
trying to prove, or they actually may be logically weaker (for
preconditions) or stronger (for postconditions) than what we need.
For instance, while
{{assn_sub X 3 (X = 3)}} X ::= 3 {{X = 3}},
follows directly from the assignment rule,
{{True}} X ::= 3 {{X = 3}}.
does not. This triple is also valid, but it is not an instance of
[hoare_asgn] because [True] and [assn_sub X 3 (X = 3)] are not
syntactically equal assertions. However, they are logically
equivalent, so if one triple is valid, then the other must
certainly be as well. We could capture this observation with the
following rule:
{{P'}} c {{Q}}
P <~~> P'
----------------------------- (hoare_consequence_pre_equiv)
{{P}} c {{Q}}
Generalizing this line of thought a bit further, if we can derive
[{{P}} c {{Q}}], it is valid to change [P] to [P'] as long as [P']
is strong enough to imply [P], and change [Q] to [Q'] as long as
[Q] implies [Q']. This observation is captured by two _Rules of
Consequence_.
{{P'}} c {{Q}}
P ~~> P'
----------------------------- (hoare_consequence_pre)
{{P}} c {{Q}}
{{P}} c {{Q'}}
Q' ~~> Q
----------------------------- (hoare_consequence_post)
{{P}} c {{Q}}
*)
(** Here are the formal versions: *)
Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c,
{{P'}} c {{Q}} ->
P ~~> P' ->
{{P}} c {{Q}}.
Proof.
intros P P' Q c Hhoare Himp.
intros st st' Hc HP. apply (Hhoare st st').
assumption. apply Himp. assumption. Qed.
Theorem hoare_consequence_post : forall (P Q Q' : Assertion) c,
{{P}} c {{Q'}} ->
Q' ~~> Q ->
{{P}} c {{Q}}.
Proof.
intros P Q Q' c Hhoare Himp.
intros st st' Hc HP.
apply Himp.
apply (Hhoare st st').
assumption. assumption. Qed.
(** For example, we might use the first consequence rule like this:
{{ True }} =>
{{ 1 = 1 }}
X ::= 1
{{ X = 1 }}
Or, formally...
*)
Example hoare_asgn_example1 :
{{fun st => True}} (X ::= (ANum 1)) {{fun st => st X = 1}}.
Proof.
apply hoare_consequence_pre
with (P' := assn_sub X (ANum 1) (fun st => st X = 1)).
apply hoare_asgn.
intros st H. reflexivity. Qed.
(** Finally, for convenience in some proofs, we can state a "combined"
rule of consequence that allows us to vary both the precondition
and the postcondition.
{{P'}} c {{Q'}}
P ~~> P'
Q' ~~> Q
----------------------------- (hoare_consequence)
{{P}} c {{Q}}
*)
Theorem hoare_consequence : forall (P P' Q Q' : Assertion) c,
{{P'}} c {{Q'}} ->
P ~~> P' ->
Q' ~~> Q ->
{{P}} c {{Q}}.
Proof.
intros P P' Q Q' c Hht HPP' HQ'Q.
intros st st' Hc HP.
apply HQ'Q. apply (Hht st st'). assumption.
apply HPP'. assumption. Qed.
(* ####################################################### *)
(** *** Digression: The [eapply] Tactic *)
(** This is a good moment to introduce another convenient feature of
Coq. We had to write "[with (P' := ...)]" explicitly in the proof
of [hoare_asgn_example1] above, to make sure that all of the
metavariables in the premises to the [hoare_consequence_pre] rule
would be set to specific values; since [P'] doesn't appear in the
conclusion of [hoare_consequence_pre], the process of unifying the
conclusion with the current goal doesn't constrain [P'] to a
specific assertion.
This is a little annoying, both because the assertion is a bit
long and also because the very next thing we are going to do --
applying the [hoare_asgn] rule -- will tell us exactly what it
should be! We can use [eapply] instead of [apply] to tell Coq,
essentially, "Be patient: The missing part is going to be filled
in soon." *)
Example hoare_asgn_example1' :
{{fun st => True}}
(X ::= (ANum 1))
{{fun st => st X = 1}}.
Proof.
eapply hoare_consequence_pre.
apply hoare_asgn.
intros st H. reflexivity. Qed.
(** In general, [eapply H] tactic works just like [apply H]
except that, instead of failing if unifying the goal with the
conclusion of [H] does not determine how to instantiate all
of the variables appearing in the premises of [H], [eapply H]
will replace these variables with _existential variables_
(written [?nnn]) as placeholders for expressions that will be
determined (by further unification) later in the proof.
In order for [Qed] to succeed, all existential variables need to
be determined by the end of the proof. Otherwise Coq will
(rightfully) refuse to accept the proof. Remember that the Coq
tactics build proof objects, and proof objects containing
existential variables are not complete. *)
Lemma silly1 : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
(forall x y : nat, P x y) ->
(forall x y : nat, P x y -> Q x) ->
Q 42.
Proof.
intros P Q HP HQ. eapply HQ. apply HP. Admitted.
(** Coq gives a warning after [apply HP]:
No more subgoals but non-instantiated existential variables:
Existential 1 =
?171 : [P : nat -> nat -> Prop
Q : nat -> Prop
HP : forall x y : nat, P x y
HQ : forall x y : nat, P x y -> Q x |- nat]
Trying to finish the proof with [Qed] instead of [Admitted] gives
an error:
<<
Error: Attempt to save a proof with existential variables still
non-instantiated
>>
*)
(** An additional constraint is that existential variables cannot be
instantiated with terms containing (normal) variables that did not
exist at the time the existential variable was created. *)
Lemma silly2 : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
(exists y, P 42 y) ->
(forall x y : nat, P x y -> Q x) ->
Q 42.
Proof.
intros P Q HP HQ. eapply HQ. destruct HP as [y HP']. Admitted.
(** Doing [apply HP'] above fails with the following error:
Error: Impossible to unify "?175" with "y".
In this case there is an easy fix:
doing [destruct HP] _before_ doing [eapply HQ].
*)
Lemma silly2_fixed : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
(exists y, P 42 y) ->
(forall x y : nat, P x y -> Q x) ->
Q 42.
Proof.
intros P Q HP HQ. destruct HP as [y HP']. eapply HQ. apply HP'.
Qed.
(** In the last step we did [apply HP'] which unifies the existential
variable in the goal with the variable [y]. The [assumption]
tactic doesn't work in this case, since it cannot handle
existential variables. However, Coq also provides an [eassumption]
tactic that solves the goal if one of the premises matches the
goal up to instantiations of existential variables. We can use
it instead of [apply HP']. *)
Lemma silly2_eassumption : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
(exists y, P 42 y) ->
(forall x y : nat, P x y -> Q x) ->
Q 42.
Proof.
intros P Q HP HQ. destruct HP as [y HP']. eapply HQ. eassumption.
Qed.
(** **** Exercise: 2 stars (hoare_asgn_examples_2) *)
(** Translate these informal Hoare triples...
{{ X + 1 <= 5 }} X ::= X + 1 {{ X <= 5 }}
{{ 0 <= 3 /\ 3 <= 5 }} X ::= 3 {{ 0 <= X /\ X <= 5 }}
...into formal statements and use [hoare_asgn] and
[hoare_consequence_pre] to prove them. *)
Lemma hoare_assgn_examples_3 : {{ fun st => st X + 1 <= 5 }} X ::= APlus (AId X) (ANum 1) {{ fun st => st X <= 5 }}.
Proof. eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. rewrite update_eq. apply H.
Qed.
Lemma hoare_assgn_examples_4 : {{ fun st => 0 <= 3 /\ 3 <= 5 }} X ::= (ANum 3) {{ fun st => 0 <= st X /\ st X <= 5 }}.
eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. rewrite update_eq. apply H.
Qed.
(** [] *)
(* ####################################################### *)
(** *** Skip *)
(** Since [SKIP] doesn't change the state, it preserves any
property P:
-------------------- (hoare_skip)
{{ P }} SKIP {{ P }}
*)
Theorem hoare_skip : forall P,
{{P}} SKIP {{P}}.
Proof.
intros P st st' H HP. inversion H. subst.
assumption. Qed.
(* ####################################################### *)
(** *** Sequencing *)
(** More interestingly, if the command [c1] takes any state where
[P] holds to a state where [Q] holds, and if [c2] takes any
state where [Q] holds to one where [R] holds, then doing [c1]
followed by [c2] will take any state where [P] holds to one
where [R] holds:
{{ P }} c1 {{ Q }}
{{ Q }} c2 {{ R }}
--------------------- (hoare_seq)
{{ P }} c1;c2 {{ R }}
*)
Theorem hoare_seq : forall P Q R c1 c2,
{{Q}} c2 {{R}} ->
{{P}} c1 {{Q}} ->
{{P}} c1;c2 {{R}}.
Proof.
intros P Q R c1 c2 H1 H2 st st' H12 Pre.
inversion H12; subst.
apply (H1 st'0 st'); try assumption.
apply (H2 st st'0); assumption. Qed.
(** Note that, in the formal rule [hoare_seq], the premises are
given in "backwards" order ([c2] before [c1]). This matches the
natural flow of information in many of the situations where we'll
use the rule: the natural way to construct a Hoare-logic proof is
to begin at the end of the program (with the final postcondition)
and push postconditions backwards through commands until we reach
the beginning. *)
(** Informally, a nice way of recording a proof using the sequencing
rule is as a "decorated program" where the intermediate assertion
[Q] is written between [c1] and [c2]:
{{ a = n }}
X ::= a;
{{ X = n }} <---- decoration for Q
SKIP
{{ X = n }}
*)
Example hoare_asgn_example3 : forall a n,
{{fun st => aeval st a = n}}
(X ::= a; SKIP)
{{fun st => st X = n}}.
Proof.
intros a n. eapply hoare_seq.
Case "right part of seq".
apply hoare_skip.
Case "left part of seq".
eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. subst. reflexivity. Qed.
(** You will most often use [hoare_seq] and
[hoare_consequence_pre] in conjunction with the [eapply] tactic,
as done above. *)
(** **** Exercise: 2 stars (hoare_asgn_example4) *)
(** Translate this decorated program into a formal proof:
{{ True }} =>
{{ 1 = 1 }}
X ::= 1;
{{ X = 1 }} =>
{{ X = 1 /\ 2 = 2 }}
Y ::= 2
{{ X = 1 /\ Y = 2 }}
*)
Example hoare_asgn_example4 :
{{fun st => True}} (X ::= (ANum 1); Y ::= (ANum 2))
{{fun st => st X = 1 /\ st Y = 2}}.
Proof. eapply hoare_seq.
Case "Y ::= 2". eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. split. compute. apply H.
apply update_eq.
Case "X ::= 1". eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. apply update_eq.
Qed.
(** [] *)
(** **** Exercise: 3 stars (swap_exercise) *)
(** Write an Imp program [c] that swaps the values of [X] and [Y]
and show (in Coq) that it satisfies the following
specification:
{{X <= Y}} c {{Y <= X}}
*)
Example swap_exercise :
{{ fun st => st X <= st Y }} Z ::= AId X; X ::= AId Y; Y ::= AId Z {{ fun st => st Y <= st X }}.
Proof. eapply hoare_seq. eapply hoare_seq.
Case "Y = Z". eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. rewrite update_eq.
apply H.
Case "X = Y". eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. apply H.
Case "Z = X". eapply hoare_consequence_pre. apply hoare_asgn.
intros st H. unfold assn_sub. simpl. compute.
apply H.
Qed.
(** [] *)
(** **** Exercise: 3 stars, optional (hoarestate1) *)
(** Explain why the following proposition can't be proven:
forall (a : aexp) (n : nat),
{{fun st => aeval st a = n}} (X ::= (ANum 3); Y ::= a)
{{fun st => st Y = n}}.
*)
(* the expression a could contain X, and X could have a different value before and after the computation *)
(** [] *)
(* ####################################################### *)
(** *** Conditionals *)
(** What sort of rule do we want for reasoning about conditional
commands? Certainly, if the same assertion [Q] holds after
executing either branch, then it holds after the whole
conditional. So we might be tempted to write:
{{P}} c1 {{Q}}
{{P}} c2 {{Q}}
--------------------------------
{{P}} IFB b THEN c1 ELSE c2 {{Q}}
However, this is rather weak. For example, using this rule,
we cannot show that:
{{True}}
IFB X == 0
THEN Y ::= 2
ELSE Y ::= X + 1
FI
{{ X <= Y }}
since the rule tells us nothing about the state in which the
assignments take place in the "then" and "else" branches.
But, actually, we can say something more precise. In the "then"
branch, we know that the boolean expression [b] evaluates to
[true], and in the "else" branch, we know it evaluates to [false].
Making this information available in the premises of the rule
gives us more information to work with when reasoning about the
behavior of [c1] and [c2] (i.e., the reasons why they establish the
postcondition [Q]).
{{P /\ b}} c1 {{Q}}
{{P /\ ~b}} c2 {{Q}}
------------------------------------ (hoare_if)
{{P}} IFB b THEN c1 ELSE c2 FI {{Q}}
*)
(** To interpret this rule formally, we need to do a little work.
Strictly speaking, the assertion we've written, [P /\ b], is the
conjunction of an assertion and a boolean expression, which
doesn't typecheck. To fix this, we need a way of formally
"lifting" any bexp [b] to an assertion. We'll write [bassn b] for
the assertion "the boolean expression [b] evaluates to [true] (in
the given state)." *)
Definition bassn b : Assertion :=
fun st => (beval st b = true).
(** A couple of useful facts about [bassn]: *)
Lemma bexp_eval_true : forall b st,
beval st b = true -> (bassn b) st.
Proof.
intros b st Hbe.
unfold bassn. assumption. Qed.
Lemma bexp_eval_false : forall b st,
beval st b = false -> ~ ((bassn b) st).
Proof.
intros b st Hbe contra.
unfold bassn in contra.
rewrite -> contra in Hbe. inversion Hbe. Qed.
(** Now we can formalize the Hoare proof rule for conditionals
and prove it correct. *)
Theorem hoare_if : forall P Q b c1 c2,
{{fun st => P st /\ bassn b st}} c1 {{Q}} ->
{{fun st => P st /\ ~(bassn b st)}} c2 {{Q}} ->
{{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.
Proof.
intros P Q b c1 c2 HTrue HFalse st st' HE HP.
inversion HE; subst.
Case "b is true".
apply (HTrue st st').
assumption.
split. assumption.
apply bexp_eval_true. assumption.
Case "b is false".
apply (HFalse st st').
assumption.
split. assumption.
apply bexp_eval_false. assumption. Qed.
(** Here is a formal proof that the program we used to motivate the
rule satisfies the specification we gave. *)
Example if_example :
{{fun st => True}}
IFB (BEq (AId X) (ANum 0))
THEN (Y ::= (ANum 2))
ELSE (Y ::= APlus (AId X) (ANum 1))
FI
{{fun st => st X <= st Y}}.
Proof.
(* WORKED IN CLASS *)
apply hoare_if.
Case "Then".
eapply hoare_consequence_pre. apply hoare_asgn.
unfold bassn, assn_sub, update, assert_implies. simpl. intros st [_ H].
symmetry in H; apply beq_nat_eq in H.
rewrite H. omega.
Case "Else".
eapply hoare_consequence_pre. apply hoare_asgn.
unfold assn_sub, update, assert_implies; simpl; intros st _. omega.
Qed.
(* ####################################################### *)
(** *** Exercise: One-sided conditionals *)
(** **** Exercise: 4 stars, recommended (if1_hoare) *)
(** In this exercise we consider extending Imp with "one-sided
conditionals" of the form [IF1 b THEN c FI]. Here [b] is a