-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hoare.v
2380 lines (1926 loc) · 74.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, Part I *)
Set Warnings "-notation-overridden,-parsing".
From PLF Require Import Maps.
From Coq Require Import Bool.Bool.
From Coq Require Import Arith.Arith.
From Coq Require Import Arith.EqNat.
From Coq Require Import Arith.PeanoNat. Import Nat.
From Coq Require Import Lia.
From PLF Require Export Imp.
From Coq Require Import Logic.FunctionalExtensionality.
(** In the final chaper of _Logical Foundations_ (_Software
Foundations_, volume 1), we began 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 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 [Equiv]
chapter). *)
(** If we stopped here, we would already 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 (sometimes also subtly wrong!).
We'll return to the theme of metatheoretic properties of whole
languages later in this volume when we discuss _types_ and _type
soundness_. In this chapter, though, we turn to a different set
of issues.
*)
(** Our goal is to carry out some simple examples of _program
verification_ -- i.e., to use the precise definition of Imp to
prove formally that particular programs satisfy particular
specifications of their behavior. We'll develop a reasoning
system called _Floyd-Hoare Logic_ -- often shortened to just
_Hoare Logic_ -- in which each of the syntactic constructs of Imp
is equipped with a generic "proof rule" that can be used to reason
compositionally about the correctness of programs involving this
construct.
Hoare Logic originated 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 multitude of tools that are being used in
academia and industry to specify and verify real software systems.
Hoare Logic combines two beautiful ideas: a natural way of writing
down _specifications_ of programs, and a _compositional proof
technique_ for proving that programs are correct with respect to
such specifications -- where by "compositional" we mean that the
structure of proofs directly mirrors the structure of the programs
that they are about. *)
(* ################################################################# *)
(** * Assertions *)
(** An _assertion_ is a claim about the current state of memory. We will
use assertions to write program specifications. *)
Definition Assertion := state -> Prop.
(** For example,
- [fun st => st X = 3] holds if the value of [X] according to [st] is [3],
- [fun st => True] always holds, and
- [fun st => False] never holds. *)
(** **** Exercise: 1 star, standard, optional (assertions)
Paraphrase the following assertions in English (or your favorite
natural language). *)
Module ExAssertions.
Definition assn1 : Assertion := fun st => st X <= st Y.
Definition assn2 : Assertion :=
fun st => st X = 3 \/ st X <= st Y.
Definition assn3 : Assertion :=
fun st => st Z * st Z <= st X /\
~ (((S (st Z)) * (S (st Z))) <= st X).
Definition assn4 : Assertion :=
fun st => st Z = max (st X) (st Y).
(* FILL IN HERE *)
End ExAssertions.
(** [] *)
(** This way of writing assertions can be a little bit heavy,
for two reasons: (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 in assertions (we
will never need to talk about two different memory states at the
same time). For discussing examples informally, we'll adopt some
simplifying conventions: we'll drop the initial [fun st =>], and
we'll write just [X] to mean [st X]. Thus, instead of writing
fun st => st X = m
we'll write just
X = m
*)
(** This example also illustrates a convention that we'll use
throughout the Hoare Logic chapters: in informal assertions,
capital letters like [X], [Y], and [Z] are Imp variables, while
lowercase letters like [x], [y], [m], and [n] are ordinary Coq
variables (of type [nat]). This is why, when translating from
informal to formal, we replace [X] with [st X] but leave [m]
alone. *)
(** Given two assertions [P] and [Q], we say that [P] _implies_ [Q],
written [P ->> Q], if, whenever [P] holds in some state [st], [Q]
also holds. *)
Definition assert_implies (P Q : Assertion) : Prop :=
forall st, P st -> Q st.
Declare Scope hoare_spec_scope.
Notation "P ->> Q" := (assert_implies P Q)
(at level 80) : 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.) *)
(** We'll also want the "iff" variant of implication between
assertions: *)
Notation "P <<->> Q" :=
(P ->> Q /\ Q ->> P) (at level 80) : hoare_spec_scope.
(** Our convention can be implemented uses Coq coercions and anotation
scopes (much as we did with [%imp] in [Imp]) to automatically
lift [aexp]s, numbers, and [Prop]s into [Assertion]s when they appear
in the [%assertion] scope or when Coq knows the type of an
expression is [Assertion]. *)
Definition Aexp : Type := state -> nat.
Definition assert_of_Prop (P : Prop) : Assertion := fun _ => P.
Definition Aexp_of_nat (n : nat) : Aexp := fun _ => n.
Definition Aexp_of_aexp (a : aexp) : Aexp := fun st => aeval st a.
Coercion assert_of_Prop : Sortclass >-> Assertion.
Coercion Aexp_of_nat : nat >-> Aexp.
Coercion Aexp_of_aexp : aexp >-> Aexp.
Arguments assert_of_Prop /.
Arguments Aexp_of_nat /.
Arguments Aexp_of_aexp /.
Declare Scope assertion_scope.
Bind Scope assertion_scope with Assertion.
Bind Scope assertion_scope with Aexp.
Delimit Scope assertion_scope with assertion.
Notation assert P := (P%assertion : Assertion).
Notation mkAexp a := (a%assertion : Aexp).
Notation "~ P" := (fun st => ~ assert P st) : assertion_scope.
Notation "P /\ Q" := (fun st => assert P st /\ assert Q st) : assertion_scope.
Notation "P \/ Q" := (fun st => assert P st \/ assert Q st) : assertion_scope.
Notation "P -> Q" := (fun st => assert P st -> assert Q st) : assertion_scope.
Notation "P <-> Q" := (fun st => assert P st <-> assert Q st) : assertion_scope.
Notation "a = b" := (fun st => mkAexp a st = mkAexp b st) : assertion_scope.
Notation "a <> b" := (fun st => mkAexp a st <> mkAexp b st) : assertion_scope.
Notation "a <= b" := (fun st => mkAexp a st <= mkAexp b st) : assertion_scope.
Notation "a < b" := (fun st => mkAexp a st < mkAexp b st) : assertion_scope.
Notation "a >= b" := (fun st => mkAexp a st >= mkAexp b st) : assertion_scope.
Notation "a > b" := (fun st => mkAexp a st > mkAexp b st) : assertion_scope.
Notation "a + b" := (fun st => mkAexp a st + mkAexp b st) : assertion_scope.
Notation "a - b" := (fun st => mkAexp a st - mkAexp b st) : assertion_scope.
Notation "a * b" := (fun st => mkAexp a st * mkAexp b st) : assertion_scope.
(** One small limitation of this approach is that we don't have
an automatic way to coerce function applications that appear
within an assertion to make appropriate use of the state.
Instead, we use an explicit [ap] operator to lift the function. *)
Definition ap {X} (f : nat -> X) (x : Aexp) :=
fun st => f (x st).
Definition ap2 {X} (f : nat -> nat -> X) (x : Aexp) (y : Aexp) (st : state) :=
f (x st) (y st).
Module ExPrettyAssertions.
Definition ex1 : Assertion := X = 3.
Definition ex2 : Assertion := True.
Definition ex3 : Assertion := False.
Definition assn1 : Assertion := X <= Y.
Definition assn2 : Assertion := X = 3 \/ X <= Y.
Definition assn3 : Assertion :=
Z * Z <= X /\ ~ (((ap S Z) * (ap S Z)) <= X).
Definition assn4 : Assertion :=
Z = ap2 max X Y.
End ExPrettyAssertions.
(* ################################################################# *)
(** * Hoare Triples, Informally *)
(** A _Hoare triple_ is a claim about the state before and after executing
a command. A standard notation is
{P} c {Q}
meaning:
- If command [c] begins execution in a state satisfying assertion [P],
- and if [c] eventually terminates in some final state,
- then that final state will satisfy the assertion [Q].
Assertion [P] is called the _precondition_ of the triple, and [Q] is
the _postcondition_.
Because single braces are already used in other ways in Coq, we'll write
Hoare triples with double braces:
{{P}} c {{Q}}
*)
(**
For example,
- [{{X = 0}} X := X + 1 {{X = 1}}] is a valid Hoare triple,
stating that command [X := X + 1] would transform a state in which
[X = 0] to a state in which [X = 1].
- [{{X = m}} X := X + 1 {{X = m + 1}}], is also a valid Hoare triple.
It's even more descriptive of the exact behavior of that command than
the previous example. *)
(** **** Exercise: 1 star, standard, optional (triples)
Paraphrase the following Hoare triples in English.
1) {{True}} c {{X = 5}}
2) forall m, {{X = m}} c {{X = m + 5)}}
3) {{X <= Y}} c {{Y <= X}}
4) {{True}} c {{False}}
5) forall m,
{{X = m}}
c
{{Y = real_fact m}}
6) forall m,
{{X = m}}
c
{{(Z * Z) <= m /\ ~ (((S Z) * (S Z)) <= m)}}
*)
(* FILL IN HERE
[] *)
(** **** Exercise: 1 star, standard, optional (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
[] *)
(* ################################################################# *)
(** * Hoare Triples, Formally *)
(** We can formalize Hoare triples and their notation in Coq as follows: *)
Definition hoare_triple
(P : Assertion) (c : com) (Q : Assertion) : Prop :=
forall st st',
st =[ c ]=> st' ->
P st ->
Q st'.
Notation "{{ P }} c {{ Q }}" :=
(hoare_triple P c Q) (at level 90, c custom com at level 99)
: hoare_spec_scope.
Check ({{True}} X := 0 {{True}}).
(** **** Exercise: 1 star, standard (hoare_post_true) *)
(** Prove that if [Q] holds in every state, then any triple with [Q]
as its postcondition is valid. *)
Theorem hoare_post_true : forall (P Q : Assertion) c,
(forall st, Q st) ->
{{P}} c {{Q}}.
Proof.
unfold hoare_triple. intros. apply H.
Qed.
(** [] *)
(** **** Exercise: 1 star, standard (hoare_pre_false) *)
(** Prove that if [P] holds in no state, then any triple with [P] as
its precondition is valid. *)
Theorem hoare_pre_false : forall (P Q : Assertion) c,
(forall st, ~ (P st)) ->
{{P}} c {{Q}}.
Proof.
unfold hoare_triple. intros. apply H in H1. contradiction.
Qed.
(** [] *)
(* ################################################################# *)
(** * Proof Rules *)
(** The goal of Hoare logic is to provide a _compositional_
method for proving the validity of specific Hoare triples. That
is, we want the structure of a program's correctness proof to
mirror the structure of the program itself. To this end, in the
sections below, we'll introduce a 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 for gluing things together. We
will then be able to 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 incomplete Hoare triple:
{{ ??? }} X := Y {{ X = 1 }}
We want to assign [Y] to [X] and finish in a state where [X] is [1].
What could the precondition be?
One possibility is [Y = 1], because if [Y] is already [1] then
assigning it to [X] causes [X] to be [1]. That leads to a valid
Hoare triple:
{{ Y = 1 }} X := Y {{ X = 1 }}
It may seem as though coming up with that precondition must have
taken some clever thought. But there is a mechanical way we could
have done it: if we take the postcondition [X = 1] and in it
replace [X] with [Y]---that is, replace the left-hand side of the
assignment statement with the right-hand side---we get the
precondition, [Y = 1]. *)
(** That same technique works in more complicated cases. For
example,
{{ ??? }} X := X + Y {{ X = 1 }}
If we replace the [X] in [X = 1] with [X + Y], we get [X + Y = 1].
That again leads to a valid Hoare triple:
{{ X + Y = 1 }} X := X + Y {{ X = 1 }}
Why does this technique work? The postcondition identifies some
property [P] that we want to hold of the variable [X] being
assigned. In this case, [P] is "equals [1]". To complete the
triple and make it valid, we need to identify a precondition that
guarantees that property will hold of [X]. Such a precondition
must ensure that the same property holds of _whatever is being
assigned to_ [X]. So, in the example, we need "equals [1]" to
hold of [X + Y]. That's exactly what the technique guarantees.
*)
(** In general, the postcondition could be some arbitrary assertion
[Q], and the right-hand side of the assignment could be some
arithmetic expression [a]:
{{ ??? }} X := a {{ Q }}
The precondition would then be [Q], but with any occurrences of
[X] in it replaced by [a]. Let's introduce a notation for this
idea of replacing occurrences: Define [Q [X |-> a]] to mean "[Q]
where [a] is substituted in place of [X]".
That yields the Hoare logic rule for assignment:
{{ Q [X |-> a] }} X := a {{ Q }}
One way of reading that rule is: If you want statement [X := a]
to terminate in a state that satisfies assertion [Q], then it
suffices to start in a state that also satisfies [Q], except
where [a] is substituted for every occurrence of [X].
To many people, this rule seems "backwards" at first, because
it proceeds from the postcondition to the precondition. Actually
it makes good sense to go in this direction: the postcondition is
often what is more important, because it characterizes what we
can assume afer running the code.
Nonetheless, it's also possible to formulate a "forward" assignment
rule. We'll do that later in some exercises. *)
(** Here are some valid instances of the assignment rule:
{{ (X <= 5) [X |-> X + 1] }} (that is, X + 1 <= 5)
X := X + 1
{{ X <= 5 }}
{{ (X = 3) [X |-> 3] }} (that is, 3 = 3)
X := 3
{{ X = 3 }}
{{ (0 <= X /\ X <= 5) [X |-> 3] (that is, 0 <= 3 /\ 3 <= 5)
X := 3
{{ 0 <= X /\ X <= 5 }}
*)
(** To formalize the rule, we must first formalize the idea of
"substituting an expression for an Imp variable in an assertion",
which we refer to as assertion substitution, or [assn_sub]. That
is, given a proposition [P], a variable [X], and an arithmetic
expression [a], we want to derive another proposition [P'] that is
just the same as [P] except that [P'] should mention [a] wherever
[P] mentions [X]. *)
(** Since [P] is an arbitrary Coq assertion, we can't directly "edit"
its text. However, we can achieve the same effect by evaluating
[P] in an updated state: *)
Definition assn_sub X a (P:Assertion) : Assertion :=
fun (st : state) =>
P (X !-> aeval st a ; st).
Notation "P [ X |-> a ]" := (assn_sub X a P)
(at level 10, X at next level, a custom com).
(** That is, [P [X |-> a]] stands for an assertion -- let's call it [P'] --
that is just like [P] except that, wherever [P] looks up the
variable [X] in the current state, [P'] instead uses the value
of the expression [a]. *)
(** To see how this works, let's calculate what happens with a couple
of examples. First, suppose [P'] is [(X <= 5) [X |-> 3]] -- that
is, more formally, [P'] is the Coq expression
fun st =>
(fun st' => st' X <= 5)
(X !-> aeval st 3 ; st),
which simplifies to
fun st =>
(fun st' => st' X <= 5)
(X !-> 3 ; st)
and further simplifies to
fun st =>
((X !-> 3 ; st) X) <= 5
and finally to
fun st =>
3 <= 5.
That is, [P'] is the assertion that [3] is less than or equal to
[5] (as expected). *)
(** For a more interesting example, suppose [P'] is [(X <= 5) [X |->
X + 1]]. Formally, [P'] is the Coq expression
fun st =>
(fun st' => st' X <= 5)
(X !-> aeval st (X + 1) ; st),
which simplifies to
fun st =>
(X !-> aeval st (X + 1) ; st) X <= 5
and further simplifies to
fun st =>
(aeval st (X + 1)) <= 5.
That is, [P'] is the assertion that [X + 1] is at most [5].
*)
(** Now, using the concept of substitution, we can give the precise
proof rule for assignment:
------------------------------ (hoare_asgn)
{{Q [X |-> a]}} X := a {{Q}}
*)
(** We can prove formally that this rule is indeed valid. *)
Theorem hoare_asgn : forall Q X a,
{{Q [X |-> a]}} 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 :
{{(X < 5) [X |-> X + 1]}}
X := X + 1
{{X < 5}}.
Proof.
(* WORKED IN CLASS *)
apply hoare_asgn. Qed.
(** (Of course, what would be even more helpful is to prove this
simpler triple:
{{X < 4}} X := X + 1 {{X < 5}}
We will see how to do so in the next section. *)
(** **** Exercise: 2 stars, standard, optional (hoare_asgn_examples)
Complete these Hoare triples...
1) {{ ??? }}
X ::= 2 * X
{{ X <= 10 }}
2) {{ ??? }}
X := 3
{{ 0 <= X /\ X <= 5 }}
...using the names [assn_sub_ex1] and [assn_sub_ex2], and prove
both with just [apply hoare_asgn]. If you find that tactic doesn't
suffice, double check that you have completed the triple properly. *)
Example assn_sub_ex1 :
{{(X <= 10) [X |-> 2 * X] }} X := 2 * X {{ X <= 10 }}.
Proof. apply hoare_asgn. Qed.
Example assn_sub_ex2: {{ (0 <= X /\ X <= 5) [X |-> 3] }} X := 3
{{ 0 <= X /\ X <= 5 }}.
Proof. apply hoare_asgn. Qed.
(* Do not modify the following line: *)
Definition manual_grade_for_hoare_asgn_examples : option (nat*string) := None.
(** [] *)
(** **** Exercise: 2 stars, standard, especially useful (hoare_asgn_wrong)
The assignment rule looks backward to almost everyone the first
time they see it. If it still seems puzzling, 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 and
argue informally that it is really a counterexample. (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.) *)
(* FILL IN HERE *)
(* Do not modify the following line: *)
Definition manual_grade_for_hoare_asgn_wrong : option (nat*string) := None.
(** [] *)
(** **** Exercise: 3 stars, advanced (hoare_asgn_fwd)
However, by using a _parameter_ [m] (a Coq number) 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 => P st /\ st X = m}}
X := a
{{fun st => P st' /\ st X = aeval st' a }}
(where st' = (X !-> m ; st))
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. (Also note that this rule is more complicated than
[hoare_asgn].)
*)
Theorem hoare_asgn_fwd :
forall m a P,
{{fun st => P st /\ st X = m}}
X := a
{{fun st => P (X !-> m ; st)
/\ st X = aeval (X !-> m ; st) a }}.
Proof.
unfold hoare_triple. intros. inversion H. subst.
destruct H0 as [H0 H1]. subst.
assert (H2: st = (X !-> st X; X !-> aeval st a; st)).
{
assert (H3: (X !-> st X; X !-> aeval st a; st) = (X !-> st X; st))
by (apply t_update_shadow).
rewrite H3. symmetry. apply t_update_same.
}
rewrite <- H2. split. assumption. reflexivity.
Qed.
(** [] *)
(** **** Exercise: 2 stars, advanced, optional (hoare_asgn_fwd_exists)
Another way to define a forward rule for assignment is to
existentially quantify over the previous value of the assigned
variable. Prove that it is correct.
------------------------------------ (hoare_asgn_fwd_exists)
{{fun st => P st}}
X := a
{{fun st => exists m, P (X !-> m ; st) /\
st X = aeval (X !-> m ; st) a }}
*)
Theorem hoare_asgn_fwd_exists :
forall a P,
{{fun st => P st}}
X := a
{{fun st => exists m, P (X !-> m ; st) /\
st X = aeval (X !-> m ; st) a }}.
Proof.
unfold hoare_triple. intros. exists (st X). inversion H. subst.
apply (hoare_asgn_fwd (st X) a P st). apply E_Ass. reflexivity.
split. assumption. reflexivity.
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
{{(X = 3) [X |-> 3]}} X := 3 {{X = 3}},
follows directly from the assignment rule,
{{True}} X := 3 {{X = 3}}
does not. This triple is valid, but it is not an instance of
[hoare_asgn] because [True] and [(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 can capture this observation with the
following rule:
{{P'}} c {{Q}}
P <<->> P'
----------------------------- (hoare_consequence_pre_equiv)
{{P}} c {{Q}}
*)
(** Taking this line of thought a bit further, we can see that
strengthening the precondition or weakening the postcondition of a
valid triple always produces another valid triple. 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.
unfold hoare_triple, "->>".
intros P P' Q c Hhoare Himp st st' Heval Hpre.
apply Hhoare with (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.
unfold hoare_triple, "->>".
intros P Q Q' c Hhoare Himp st st' Heval Hpre.
apply Himp.
apply Hhoare with (st := st).
- assumption.
- assumption.
Qed.
(** For example, we can use the first consequence rule like this:
{{ True }} ->>
{{ (X = 1) [X |-> 1] }}
X := 1
{{ X = 1 }}
Or, formally... *)
Example hoare_asgn_example1 :
{{True}} X := 1 {{X = 1}}.
Proof.
(* WORKED IN CLASS *)
apply hoare_consequence_pre with (P' := (X = 1) [X |-> 1]).
- apply hoare_asgn.
- unfold "->>", assn_sub, t_update.
intros st _. simpl. reflexivity.
Qed.
(** We can also use it to prove the example mentioned earlier.
{{ X < 4 }} ->>
{{ (X < 5)[X |-> X + 1] }}
X := X + 1
{{ X < 5 }}
Or, formally ... *)
Example assn_sub_example2 :
{{X < 4}}
X := X + 1
{{X < 5}}.
Proof.
(* WORKED IN CLASS *)
apply hoare_consequence_pre with (P' := (X < 5) [X |-> X + 1]).
- apply hoare_asgn.
- unfold "->>", assn_sub, t_update.
intros st H. simpl in *. lia.
Qed.
(** Finally, here is 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 Htriple Hpre Hpost.
apply hoare_consequence_pre with (P' := P').
- apply hoare_consequence_post with (Q' := Q').
+ assumption.
+ assumption.
- assumption.
Qed.
(* ================================================================= *)
(** ** Automation *)
(** Many of the proofs we have done so far with Hoare triples can be
streamlined using the automation techniques that we introduced in
the [Auto] chapter of _Logical Foundations_.
Recall that the [auto] tactic can be told to [unfold] definitions
as part of its proof search. Let's give that hint for the
definitions and coercions we're using: *)
Hint Unfold assert_implies hoare_triple assn_sub t_update : core.
Hint Unfold assert_of_Prop Aexp_of_nat Aexp_of_aexp : core.
(** Also recall that [auto] will search for a proof involving [intros]
and [apply]. By default, the theorems that it will apply include
any of the local hypotheses, as well as theorems in a core
database. *)
(** The proof of [hoare_consequence_pre], repeated below, looks
like an opportune place for such automation, because all it does
is [unfold], [intros], and [apply]. It uses [assumption], too,
but that's just application of a hypothesis. *)
Theorem hoare_consequence_pre' : forall (P P' Q : Assertion) c,
{{P'}} c {{Q}} ->
P ->> P' ->
{{P}} c {{Q}}.
Proof.
unfold hoare_triple, "->>".
intros P P' Q c Hhoare Himp st st' Heval Hpre.
apply Hhoare with (st := st).
- assumption.
- apply Himp. assumption.
Qed.
(** Merely using [auto], though, doesn't complete the proof. *)
Theorem hoare_consequence_pre'' : forall (P P' Q : Assertion) c,
{{P'}} c {{Q}} ->
P ->> P' ->
{{P}} c {{Q}}.
Proof.
auto. (* no progress *)
Abort.
(** The problem is the [apply Hhoare with...] part of the proof. Coq
isn't able to figure out how to instantiate [st] without some help
from us. Recall, though, that there are versions of many tactics
that will use _existential variables_ to make progress even when
the regular versions of those tactics would get stuck.
Here, the [eapply] tactic will introduce an existential variable
[?st] as a placeholder for [st], and [eassumption] will
instantiate [?st] with [st] when it discovers [st] in assumption
[Heval]. By using [eapply] we are essentially telling Coq, "Be
patient: The missing part is going to be filled in later in the
proof." *)
Theorem hoare_consequence_pre''' : forall (P P' Q : Assertion) c,
{{P'}} c {{Q}} ->
P ->> P' ->
{{P}} c {{Q}}.
Proof.
unfold hoare_triple, "->>".
intros P P' Q c Hhoare Himp st st' Heval Hpre.
eapply Hhoare.
- eassumption.
- apply Himp. assumption.
Qed.
(** Tactic [eauto] will use [eapply] as part of its proof search.
So, the entire proof can be done in just one line. *)
Theorem hoare_consequence_pre'''' : forall (P P' Q : Assertion) c,
{{P'}} c {{Q}} ->
P ->> P' ->
{{P}} c {{Q}}.
Proof.
eauto.
Qed.
(** Of course, it's hard to predict that [eauto] suffices here
without having gone through the original proof of
[hoare_consequence_pre] to see the tactics it used. But now that
we know [eauto] works, it's a good bet that it will also work for
[hoare_consequence_post]. *)
Theorem hoare_consequence_post' : forall (P Q Q' : Assertion) c,
{{P}} c {{Q'}} ->
Q' ->> Q ->
{{P}} c {{Q}}.
Proof.
eauto.
Qed.
(** We can also use [eapply] to streamline a proof,
[hoare_asgn_example1], that we did earlier as an example of using
the consequence rule: *)
Example hoare_asgn_example1' :
{{True}} X := 1 {{X = 1}}.
Proof.
eapply hoare_consequence_pre. (* no need to state an assertion *)
- apply hoare_asgn.
- unfold "->>", assn_sub, t_update.
intros st _. simpl. reflexivity.
Qed.
(** The final bullet of that proof also looks like a candidate for
automation. *)
Example hoare_asgn_example1'' :
{{True}} X := 1 {{X = 1}}.
Proof.
eapply hoare_consequence_pre.
- apply hoare_asgn.
- auto.
Qed.
(** Now we have quite a nice proof script: it simply identifies the
Hoare rules that need to be used and leaves the remaining
low-level details up to Coq to figure out. *)
(** By now it might be apparent that the _entire_ proof could be
automated if we added [hoare_consequence_pre] and [hoare_asgn] to
the hint database. We won't do that in this chapter, so that we
can get a better understanding of when and how the Hoare rules are
used. In the next chapter, [Hoare2], we'll dive deeper into
automating entire proofs of Hoare triples. *)
(** The other example of using consequence that we did earlier,
[hoare_asgn_example2], requires a little more work to automate.
We can streamline the first line with [eapply], but we can't just use
[auto] for the final bullet, since it needs [omega]. *)
Example assn_sub_example2' :
{{X < 4}}
X := X + 1
{{X < 5}}.
Proof.
eapply hoare_consequence_pre.
- apply hoare_asgn.
- auto. (* no progress *)
unfold "->>", assn_sub, t_update.
intros st H. simpl in *. lia.
Qed.
(** Let's introduce our own tactic to handle both that bullet and the
bullet from example 1: *)
Ltac assn_auto :=
try auto; (* as in example 1, above *)
try (unfold "->>", assn_sub, t_update;
intros; simpl in *; lia). (* as in example 2 *)
Example assn_sub_example2'' :
{{X < 4}}
X := X + 1
{{X < 5}}.
Proof.
eapply hoare_consequence_pre.
- apply hoare_asgn.
- assn_auto.
Qed.
Example hoare_asgn_example1''':
{{True}} X := 1 {{X = 1}}.
Proof.
eapply hoare_consequence_pre.
- apply hoare_asgn.
- assn_auto.
Qed.