-
Notifications
You must be signed in to change notification settings - Fork 1
/
Hoare2.v
1843 lines (1612 loc) · 59.5 KB
/
Hoare2.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
(** * Hoare2: Hoare Logic, Part II *)
Require Export Hoare.
(* ####################################################### *)
(** * Decorated Programs *)
(** The beauty of Hoare Logic is that it is _compositional_ --
the structure of proofs exactly follows the structure of programs.
This suggests that we can record the essential ideas of a proof
informally (leaving out some low-level calculational details) by
decorating programs with appropriate assertions around each
statement. Such a _decorated program_ carries with it
an (informal) proof of its own correctness. *)
(** For example, here is a complete decorated program: *)
(**
{{ True }} ->>
{{ m = m }}
X ::= m;
{{ X = m }} ->>
{{ X = m /\ p = p }}
Z ::= p;
{{ X = m /\ Z = p }} ->>
{{ Z - X = p - m }}
WHILE X <> 0 DO
{{ Z - X = p - m /\ X <> 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z ::= Z - 1;
{{ Z - (X - 1) = p - m }}
X ::= X - 1
{{ Z - X = p - m }}
END;
{{ Z - X = p - m /\ ~ (X <> 0) }} ->>
{{ Z = p - m }}
*)
(** Concretely, a decorated program consists of the program text
interleaved with assertions. To check that a decorated program
represents a valid proof, we check that each individual command is
_locally consistent_ with its accompanying assertions in the
following sense: *)
(**
- [SKIP] is locally consistent if its precondition and
postcondition are the same:
{{ P }}
SKIP
{{ P }}
*)
(**
- The sequential composition of [c1] and [c2] is locally
consistent (with respect to assertions [P] and [R]) if [c1] is
locally consistent (with respect to [P] and [Q]) and [c2] is
locally consistent (with respect to [Q] and [R]):
{{ P }}
c1;
{{ Q }}
c2
{{ R }}
*)
(**
- An assignment is locally consistent if its precondition is
the appropriate substitution of its postcondition:
{{ P [X |-> a] }}
X ::= a
{{ P }}
*)
(**
- A conditional is locally consistent (with respect to assertions
[P] and [Q]) if the assertions at the top of its "then" and
"else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
branch is locally consistent (with respect to [P /\ b] and [Q])
and its "else" branch is locally consistent (with respect to
[P /\ ~b] and [Q]):
{{ P }}
IFB b THEN
{{ P /\ b }}
c1
{{ Q }}
ELSE
{{ P /\ ~b }}
c2
{{ Q }}
FI
{{ Q }}
*)
(**
- A while loop with precondition [P] is locally consistent if its
postcondition is [P /\ ~b] and if the pre- and postconditions of
its body are exactly [P /\ b] and [P]:
{{ P }}
WHILE b DO
{{ P /\ b }}
c1
{{ P }}
END
{{ P /\ ~b }}
*)
(**
- A pair of assertions separated by [->>] is locally consistent if
the first implies the second (in all states):
{{ P }} ->>
{{ P' }}
This corresponds to the application of [hoare_consequence] and
is the only place in a decorated program where checking if
decorations are correct is not fully mechanical and syntactic,
but involves logical and/or arithmetic reasoning.
*)
(** We have seen above how _verifying_ the correctness of a
given proof involves checking that every single command is locally
consistent with the accompanying assertions. If we are instead
interested in _finding_ a proof for a given specification we need
to discover the right assertions. This can be done in an almost
automatic way, with the exception of finding loop invariants,
which is the subject of in the next section. In the reminder of
this section we explain in detail how to construct decorations for
several simple programs that don't involve non-trivial loop
invariants. *)
(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)
(** Here is a program that swaps the values of two variables using
addition and subtraction (instead of by assigning to a temporary
variable).
X ::= X + Y;
Y ::= X - Y;
X ::= X - Y
We can prove using decorations that this program is correct --
i.e., it always swaps the values of variables [X] and [Y]. *)
(**
(1) {{ X = m /\ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
X ::= X + Y;
(3) {{ X - (X - Y) = n /\ X - Y = m }}
Y ::= X - Y;
(4) {{ X - Y = n /\ Y = m }}
X ::= X - Y
(5) {{ X = n /\ Y = m }}
The decorations were constructed as follows:
- We begin with the undecorated program (the unnumbered lines).
- We then add the specification -- i.e., the outer
precondition (1) and postcondition (5). In the precondition we
use auxiliary variables (parameters) [m] and [n] to remember
the initial values of variables [X] and respectively [Y], so
that we can refer to them in the postcondition (5).
- We work backwards mechanically starting from (5) all the way
to (2). At each step, we obtain the precondition of the
assignment from its postcondition by substituting the assigned
variable with the right-hand-side of the assignment. For
instance, we obtain (4) by substituting [X] with [X - Y]
in (5), and (3) by substituting [Y] with [X - Y] in (4).
- Finally, we verify that (1) logically implies (2) -- i.e.,
that the step from (1) to (2) is a valid use of the law of
consequence. For this we substitute [X] by [m] and [Y] by [n]
and calculate as follows:
(m + n) - ((m + n) - n) = n /\ (m + n) - n = m
(m + n) - m = n /\ m = m
n = n /\ m = m
(Note that, since we are working with natural numbers, not
fixed-size machine integers, we don't need to worry about the
possibility of arithmetic overflow anywhere in this argument.)
*)
(* ####################################################### *)
(** ** Example: Simple Conditionals *)
(** Here is a simple decorated program using conditionals:
(1) {{True}}
IFB X <= Y THEN
(2) {{True /\ X <= Y}} ->>
(3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
Z ::= Y - X
(4) {{Z + X = Y \/ Z + Y = X}}
ELSE
(5) {{True /\ ~(X <= Y) }} ->>
(6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
Z ::= X - Y
(7) {{Z + X = Y \/ Z + Y = X}}
FI
(8) {{Z + X = Y \/ Z + Y = X}}
These decorations were constructed as follows:
- We start with the outer precondition (1) and postcondition (8).
- We follow the format dictated by the [hoare_if] rule and copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
[Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both
of these implications crucially depend on the ordering of [X] and
[Y] obtained from the guard. For instance, knowing that [X <= Y]
ensures that subtracting [X] from [Y] and then adding back [X]
produces [Y], as required by the first disjunct of (3). Similarly,
knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
then adding back [Y] produces [X], as needed by the second
disjunct of (6). Note that [n - m + m = n] does _not_ hold for
arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
5]). *)
(** **** Exercise: 2 stars (if_minus_plus_reloaded) *)
(** Fill in valid decorations for the following program:
{{ True }}
IFB X <= Y THEN
{{ True /\ (X <= Y) }} ->>
{{ Y = X + (Y - X) }}
Z ::= Y - X
{{ Y = X + Z }}
ELSE
{{ True /\ ~(X <= Y) }} ->>
{{ (X + Z) = (X + Z) }}
Y ::= X + Z
{{ Y = X + Z }}
FI
{{ Y = X + Z }}
*)
(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)
(** Here is a [WHILE] loop that is so simple it needs no
invariant (i.e., the invariant [True] will do the job).
(1) {{ True }}
WHILE X <> 0 DO
(2) {{ True /\ X <> 0 }} ->>
(3) {{ True }}
X ::= X - 1
(4) {{ True }}
END
(5) {{ True /\ X = 0 }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the [hoare_while] rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2) and with
the negation of the guard to obtain (5). Note that, because the
outer postcondition (6) does not syntactically match (5), we need a
trivial use of the consequence rule from (5) to (6).
- Assertion (3) is the same as (4), because [X] does not appear in
[4], so the substitution in the assignment rule is trivial.
- Finally, the implication between (2) and (3) is also trivial.
*)
(** From this informal proof, it is easy to read off a formal proof
using the Coq versions of the Hoare rules. Note that we do _not_
unfold the definition of [hoare_triple] anywhere in this proof --
the idea is to use the Hoare rules as a "self-contained" logic for
reasoning about programs. *)
Definition reduce_to_zero' : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
X ::= AMinus (AId X) (ANum 1)
END.
Theorem reduce_to_zero_correct' :
{{fun st => True}}
reduce_to_zero'
{{fun st => st X = 0}}.
Proof.
(*
unfold reduce_to_zero'.
eapply hoare_consequence_post.
apply hoare_while.
eapply hoare_consequence_pre.
apply hoare_asgn.
constructor.
unfold assert_implies, bassn, not. intros.
my_inversion H.
simpl in H1.
destruct (st X). reflexivity. contradiction H1. simpl. reflexivity.
*)
unfold reduce_to_zero'.
(* First we need to transform the postcondition so
that hoare_while will apply. *)
eapply hoare_consequence_post.
apply hoare_while.
Case "Loop body preserves invariant".
(* Need to massage precondition before [hoare_asgn] applies *)
eapply hoare_consequence_pre. apply hoare_asgn.
(* Proving trivial implication (2) ->> (3) *)
intros st [HT Hbp]. unfold assn_sub. apply I.
Case "Invariant and negated guard imply postcondition".
intros st [Inv GuardFalse].
unfold bassn in GuardFalse. simpl in GuardFalse.
(* SearchAbout helps to find the right lemmas *)
SearchAbout [not true].
rewrite not_true_iff_false in GuardFalse.
SearchAbout [negb false].
rewrite negb_false_iff in GuardFalse.
SearchAbout [beq_nat true].
apply beq_nat_true in GuardFalse.
apply GuardFalse. Qed.
(* ####################################################### *)
(** ** Example: Division *)
(** The following Imp program calculates the integer division and
remainder of two numbers [m] and [n] that are arbitrary constants
in the program.
X ::= m;
Y ::= 0;
WHILE n <= X DO
X ::= X - n;
Y ::= Y + 1
END;
In other words, if we replace [m] and [n] by concrete numbers and
execute the program, it will terminate with the variable [X] set
to the remainder when [m] is divided by [n] and [Y] set to the
quotient. *)
(** In order to give a specification to this program we need to
remember that dividing [m] by [n] produces a reminder [X] and a
quotient [Y] so that [n * Y + X = m /\ X < n].
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the invariant is the
just first conjunct [n * Y + X = m], so we use that to decorate
the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X ::= m;
(3) {{ n * 0 + X = m }}
Y ::= 0;
(4) {{ n * Y + X = m }}
WHILE n <= X DO
(5) {{ n * Y + X = m /\ n <= X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X ::= X - n;
(7) {{ n * (Y + 1) + X = m }}
Y ::= Y + 1
(8) {{ n * Y + X = m }}
END
(9) {{ n * Y + X = m /\ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8) to
(6). Assertions (4), (3), and (2) are again backwards applications
of the assignment rule.
Now that we've decorated the program it only remains to check that
the two uses of the consequence rule are correct -- i.e., that (1)
implies (2) and that (5) implies (6). This is indeed the case, so
we have a valid decorated program.
*)
(* ####################################################### *)
(** * Finding Loop Invariants *)
(** Once the outermost precondition and postcondition are chosen, the
only creative part in verifying programs with Hoare Logic is
finding the right loop invariants. The reason this is difficult
is the same as the reason that doing inductive mathematical proofs
requires creativity: strengthening the loop invariant (or the
induction hypothesis) means that you have a stronger assumption to
work with when trying to establish the postcondition of the loop
body (complete the induction step of the proof), but it also means
that the loop body postcondition itself is harder to prove!
This section is dedicated to teaching you how to approach the
challenge of finding loop invariants using a series of examples
and exercises. *)
(** ** Example: Slow Subtraction *)
(** The following program subtracts the value of [X] from the value of
[Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
correctness with respect to the following specification:
{{ X = m /\ Y = n }}
WHILE X <> 0 DO
Y ::= Y - 1;
X ::= X - 1
END
{{ Y = n - m }}
To verify this program we need to find an invariant [I] for the
loop. As a first step we can leave [I] as an unknown and build a
_skeleton_ for the proof by applying backward the rules for local
consistency. This process leads to the following skeleton:
(1) {{ X = m /\ Y = n }} ->> (a)
(2) {{ I }}
WHILE X <> 0 DO
(3) {{ I /\ X <> 0 }} ->> (c)
(4) {{ I[X |-> X-1][Y |-> Y-1] }}
Y ::= Y - 1;
(5) {{ I[X |-> X-1] }}
X ::= X - 1
(6) {{ I }}
END
(7) {{ I /\ ~(X <> 0) }} ->> (b)
(8) {{ Y = n - m }}
By examining this skeleton, we can see that any valid [I] will
have to respect three conditions:
- (a) it must be weak enough to be implied by the loop's
precondition, i.e. (1) must imply (2);
- (b) it must be strong enough to imply the loop's postcondition,
i.e. (7) must imply (8);
- (c) it must be preserved by one iteration of the loop, i.e. (3)
must imply (4). *)
(** These conditions are actually independent of the particular
program and specification we are considering. Indeed, every loop
invariant has to satisfy them. One way to find an invariant that
simultaneously satisfies these three conditions is by using an
iterative process: start with a "candidate" invariant (e.g. a
guess or a heuristic choice) and check the three conditions above;
if any of the checks fails, try to use the information that we get
from the failure to produce another (hopefully better) candidate
invariant, and repeat the process.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing [True] as an invariant did the
job. So let's try it again here! I.e., let's instantiate [I] with
[True] in the skeleton above see what we get...
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ True }}
WHILE X <> 0 DO
(3) {{ True /\ X <> 0 }} ->> (c - OK)
(4) {{ True }}
Y ::= Y - 1;
(5) {{ True }}
X ::= X - 1
(6) {{ True }}
END
(7) {{ True /\ X = 0 }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
condition (b) is wrong, i.e. it is not the case that (7) [True /\
X = 0] implies (8) [Y = n - m]. In fact, the two assertions are
completely unrelated and it is easy to find a counterexample (say,
[Y = X = m = 0] and [n = 1]).
If we want (b) to hold, we need to strengthen the invariant so
that it implies the postcondition (8). One very simple way to do
this is to let the invariant _be_ the postcondition. So let's
return to our skeleton, instantiate [I] with [Y = n - m], and
check conditions (a) to (c) again.
(1) {{ X = m /\ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
WHILE X <> 0 DO
(3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y ::= Y - 1;
(5) {{ Y = n - m }}
X ::= X - 1
(6) {{ Y = n - m }}
END
(7) {{ Y = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) [X = m /\ Y = n]
implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to
show that [n = n - m] for arbitrary [m] and [n], which does not
hold (for instance, when [m = n = 1]). Condition (c) requires that
[n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
0]. So, although [Y = n - m] holds at the end of the loop, it does
not hold from the start, and it doesn't hold on each iteration;
it is not a correct invariant.
This failure is not very surprising: the variable [Y] changes
during the loop, while [m] and [n] are constant, so the assertion
we chose didn't have much chance of being an invariant!
To do better, we need to generalize (8) to some statement that is
equivalent to (8) when [X] is [0], since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when [X] is nonzero. Looking at how the loop
works, we can observe that [X] and [Y] are decremented together
until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially,
after one iteration of the loop we obtain [X = 1] and [Y = 4];
after two iterations [X = 0] and [Y = 3]; and then the loop stops.
Notice that the difference between [Y] and [X] stays constant
between iterations; initially, [Y = n] and [X = m], so this
difference is always [n - m]. So let's try instantiating [I] in
the skeleton above with [Y - X = n - m].
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
WHILE X <> 0 DO
(3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y ::= Y - 1;
(5) {{ Y - (X - 1) = n - m }}
X ::= X - 1
(6) {{ Y - X = n - m }}
END
(7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that [X <>
0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
natural numbers [X] and [Y].) *)
(* ####################################################### *)
(** ** Exercise: Slow Assignment *)
(** **** Exercise: 2 stars (slow_assignment) *)
(** A roundabout way of assigning a number currently stored in [X] to
the variable [Y] is to start [Y] at [0], then decrement [X] until
it hits [0], incrementing [Y] at each step. Here is a program that
implements this idea:
{{ X = m }}
Y ::= 0;
WHILE X <> 0 DO
X ::= X - 1;
Y ::= Y + 1;
END
{{ Y = m }}
Write an informal decorated program showing that this is correct. *)
(*
{{ X = m }}
Y ::= 0;
{{ X = m /\ Y = 0 }} ->>
{{ I }}
WHILE X <> 0 DO
{{ I /\ X <> 0 }} ->>
{{ I[Y |-> Y+1][X |-> X-1]}}
X ::= X - 1;
{{ I[Y |-> Y+1]}}
Y ::= Y + 1;
{{ I }}
END
{{ I /\ ~(X <> 0) }} ->>
{{ Y = m }}
I : X+Y = m.
*)
(* ####################################################### *)
(** ** Exercise: Slow Addition *)
(** **** Exercise: 3 stars, optional (add_slowly_decoration) *)
(** The following program adds the variable X into the variable Z
by repeatedly decrementing X and incrementing Z.
WHILE X <> 0 DO
Z ::= Z + 1;
X ::= X - 1
END
Following the pattern of the [subtract_slowly] example above, pick
a precondition and postcondition that give an appropriate
specification of [add_slowly]; then (informally) decorate the
program accordingly. *)
(*
{{ X = n /\ Z = m }} ->>
{{ I }}
WHILE X <> 0 DO
{{ I /\ X <> 0 }} ->>
{{ I[X |-> X-1][Z |-> Z+1] }}
Z ::= Z + 1;
{{ I[X |-> X-1] }}
X ::= X - 1
{{ I }}
END
{{ I /\ ~(X <> 0) }} ->>
{{ X = 0 /\ Z = n+m }}
I : X+Z = n+m
*)
(* ####################################################### *)
(** ** Example: Parity *)
(** Here is a cute little program for computing the parity of the
value initially stored in [X] (due to Daniel Cristofani).
{{ X = m }}
WHILE 2 <= X DO
X ::= X - 2
END
{{ X = parity m }}
The mathematical [parity] function used in the specification is
defined in Coq as follows: *)
Fixpoint parity x :=
match x with
| 0 => 0
| 1 => 1
| S (S x') => parity x'
end.
(** The postcondition does not hold at the beginning of the loop,
since [m = parity m] does not hold for an arbitrary [m], so we
cannot use that as an invariant. To find an invariant that works,
let's think a bit about what this loop does. On each iteration it
decrements [X] by [2], which preserves the parity of [X]. So the
parity of [X] does not change, i.e. it is invariant. The initial
value of [X] is [m], so the parity of [X] is always equal to the
parity of [m]. Using [parity X = parity m] as an invariant we
obtain the following decorated program:
{{ X = m }} ->> (a - OK)
{{ parity X = parity m }}
WHILE 2 <= X DO
{{ parity X = parity m /\ 2 <= X }} ->> (c - OK)
{{ parity (X-2) = parity m }}
X ::= X - 2
{{ parity X = parity m }}
END
{{ parity X = parity m /\ X < 2 }} ->> (b - OK)
{{ X = parity m }}
With this invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when [X < 2], we
have [parity X = X] (we can easily see this in the definition of
[parity]). For verifying (c), we observe that, when [2 <= X], we
have [parity X = parity (X-2)]. *)
(** **** Exercise: 3 stars, optional (parity_formal) *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
for ideas. You may find the following two lemmas useful: *)
Lemma parity_ge_2 : forall x,
2 <= x ->
parity (x - 2) = parity x.
Proof.
induction x; intro. reflexivity.
destruct x. inversion H. inversion H1.
simpl. rewrite <- minus_n_O. reflexivity.
Qed.
Lemma parity_lt_2 : forall x,
~ 2 <= x ->
parity (x) = x.
Proof.
intros. induction x. reflexivity. destruct x. reflexivity.
apply ex_falso_quodlibet. apply H. omega.
Qed.
Theorem parity_correct : forall m,
{{ fun st => st X = m }}
WHILE BLe (ANum 2) (AId X) DO
X ::= AMinus (AId X) (ANum 2)
END
{{ fun st => st X = parity m }}.
Proof.
intros.
remember (fun st => parity (st X) = parity m) as I.
apply hoare_consequence_pre with (P':=I).
eapply hoare_consequence_post.
apply hoare_while.
eapply hoare_consequence_pre.
apply hoare_asgn.
unfold assn_sub, bassn, assert_implies. intros. simpl. my_inversion H.
rewrite update_eq. rewrite <- H0. apply parity_ge_2.
simpl in H1; destruct (st X) eqn:e; inversion H1; destruct n eqn:e2; inversion H1; omega.
(*
eapply hoare_asgn.
constructor.
reflexivity.
*)
unfold assert_implies, bassn. intros. my_inversion H. rewrite <- H0.
rewrite parity_lt_2. reflexivity.
unfold not. intro. apply H1. my_inversion H. rewrite <- H3. reflexivity.
rewrite <- H2. my_inversion H3. reflexivity. reflexivity.
(*
unfold hoare_triple, bassn, assn_sub. intros. my_inversion H.
my_inversion H0. rewrite update_eq. (* unfold update; simpl. *)
rewrite <- H. apply parity_ge_2.
(*
remember (st X) as val.
induction H1.*)
simpl in H1; destruct (st X) eqn:e; inversion H1; destruct n eqn:e2; inversion H1; omega.
*)
rewrite HeqI. unfold assert_implies. intros. rewrite H. reflexivity.
Qed.
(* ####################################################### *)
(** ** Example: Finding Square Roots *)
(** The following program computes the square root of [X]
by naive iteration:
{{ X=m }}
Z ::= 0;
WHILE (Z+1)*(Z+1) <= X DO
Z ::= Z+1
END
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)
(** As above, we can try to use the postcondition as a candidate
invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 <= m /\ m<1*1 }}
Z ::= 0;
(3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
WHILE (Z+1)*(Z+1) <= X DO
(4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
Z ::= Z+1
(6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
END
(7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
(8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This didn't work very well: both conditions (a) and (c) failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions [X] while (5) mentions [m]. But note that [X] is never
assigned in this program, so we should have [X=m], but we didn't
propagate this information from (1) into the loop invariant.
Also, looking at the second conjunct of (8), it seems quite
hopeless as an invariant -- and we don't even need it, since we
can obtain it from the negation of the guard (third conjunct
in (7)), again under the assumption that [X=m].
So we now try [X=m /\ Z*Z <= m] as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m /\ 0*0 <= m }}
Z ::= 0;
{{ X=m /\ Z*Z <= m }}
WHILE (Z+1)*(Z+1) <= X DO
{{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK)
{{ X=m /\ (Z+1)*(Z+1)<=m }}
Z ::= Z+1
{{ X=m /\ Z*Z<=m }}
END
{{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
trivially satisfied.
Very often, if a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification and it is not changed by the loop) it is necessary
to add the fact that it doesn't change to the loop invariant. *)
(* ####################################################### *)
(** ** Example: Squaring *)
(** Here is a program that squares [X] by repeated addition:
{{ X = m }}
Y ::= 0;
Z ::= 0;
WHILE Y <> X DO
Z ::= Z + X;
Y ::= Y + 1
END
{{ Z = m*m }}
*)
(** The first thing to note is that the loop reads [X] but doesn't
change its value. As we saw in the previous example, in such cases
it is a good idea to add [X = m] to the invariant. The other thing
we often use in the invariant is the postcondition, so let's add
that too, leading to the invariant candidate [Z = m * m /\ X = m].
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m /\ X = m }}
Y ::= 0;
{{ 0 = m*m /\ X = m }}
Z ::= 0;
{{ Z = m*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG)
{{ Z+X = m*m /\ X = m }}
Z ::= Z + X;
{{ Z = m*m /\ X = m }}
Y ::= Y + 1
{{ Z = m*m /\ X = m }}
END
{{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the [Z = m*m] part. While
[Z] starts at [0] and works itself up to [m*m], we can't expect
[Z] to be [m*m] from the start. If we look at how [Z] progesses
in the loop, after the 1st iteration [Z = m], after the 2nd
iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable
[Y] tracks how many times we go through the loop, we derive the
new invariant candidate [Z = Y*m /\ X = m].
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m /\ X = m }}
Y ::= 0;
{{ 0 = Y*m /\ X = m }}
Z ::= 0;
{{ Z = Y*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK)
{{ Z+X = (Y+1)*m /\ X = m }}
Z ::= Z + X;
{{ Z = (Y+1)*m /\ X = m }}
Y ::= Y + 1
{{ Z = Y*m /\ X = m }}
END
{{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
This new invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition [Z = m*m] and the [Z =
Y*m] conjunct of the invariant. It is often the case that one has
to replace auxiliary variabes (parameters) with variables -- or
with expressions involving both variables and parameters (like
[m - Y]) -- when going from postconditions to invariants. *)
(* ####################################################### *)
(** ** Exercise: Factorial *)
(** **** Exercise: 3 stars (factorial) *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
1*2*...*n]). Here is an Imp program that calculates the factorial
of the number initially stored in the variable [X] and puts it in
the variable [Y]:
{{ X = m }} ;
Y ::= 1
WHILE X <> 0
DO
Y ::= Y * X
X ::= X - 1
END
{{ Y = m! }}
Fill in the blanks in following decorated program:
{{ X = m }} ->>
{{ I[Y |-> 1] /\ X = m }} (a)
Y ::= 1;
{{ I }}
WHILE X <> 0
DO {{ I /\ X <> 0 }} ->>
{{ I[X |-> X-1][Y |-> Y*X] }} (b)
Y ::= Y * X;
{{ I[X |-> X-1] }}
X ::= X - 1
{{ I }}
END
{{ I /\ ~(X <> 0) }} ->>
{{ Y = m! }} (c)
I : Y = m! / x!
(a) : OK
(b) : OK
(c) : OK
*)
(* ####################################################### *)
(** ** Exercise: Min *)
(** **** Exercise: 3 stars (Min_Hoare) *)
(** Fill in valid decorations for the following program.
For the => steps in your annotations, you may rely (silently) on the
following facts about min
Lemma lemma1 : forall x y,
(x=0 \/ y=0) -> min x y = 0.
Lemma lemma2 : forall x y,
min (x-1) (y-1) = (min x y) - 1.
plus, as usual, standard high-school algebra.
{{ True }} ->>
{{ I[Z |-> 0][Y |-> b][X |-> a] }} (#######a)
X ::= a;
{{ I[Z |-> 0][Y |-> b] }}
Y ::= b;
{{ I[Z |-> 0] }}
Z ::= 0;
{{ I }}
WHILE (X <> 0 /\ Y <> 0) DO
{{ I /\ X <> 0 /\ Y <> 0 }} ->>
{{ I[Z |-> Z+1][Y |-> Y-1][X -> X-1] }} (######b)
X := X - 1;
{{ I[Z |-> Z+1][Y |-> Y-1] }}
Y := Y - 1;
{{ I[Z |-> Z+1] }}
Z := Z + 1;
{{ I }}
END
{{ I /\ ~((X <> 0) /\ (Y <> 0)) }} ->> (#######c)
{{ Z = min a b }}
I : (min X Y) + Z = min a b
(a) : OK
(b) : min (X-1) (Y-1) + Z + 1 = min a b
<= min (X-1) (Y-1) + Z + 1 = (min X Y) + Z
lemma 2. OK
(c) (x=0 \/ y=0) -> min x y = 0.
~((X <> 0) /\ (Y <> 0)) -> (X=0 \/ Y=0) (without de_morgan.)
lemma 1.
OK
Definition peirce := forall P Q: Prop,
((P->Q)->P)->P.
Definition classic := forall P:Prop,
~~P -> P.
Definition excluded_middle := forall P:Prop,
P \/ ~P.
Definition de_morgan_not_and_not := forall P Q:Prop,
~(~P /\ ~Q) -> P\/Q.
Definition implies_to_or := forall P Q:Prop,
(P->Q) -> (~P\/Q).
*)
Lemma nat_de_morgan : forall x y,
~((x <> 0) /\ (y <> 0)) -> (x = 0 \/ y = 0).
Proof.
unfold not.
intros.
destruct x. left. reflexivity.
right.
destruct y. reflexivity.
contradiction H.
split.
intros.
inversion H0.
intros.
inversion H0.
Qed.
(** **** Exercise: 3 stars (two_loops) *)
(** Here is a very inefficient way of adding 3 numbers:
X ::= 0;
Y ::= 0;
Z ::= c;
WHILE X <> a DO
X ::= X + 1;
Z ::= Z + 1
END;
WHILE Y <> b DO
Y ::= Y + 1;
Z ::= Z + 1
END
Show that it does what it should by filling in the blanks in the
following decorated program.
{{ True }} ->>
{{ I[Z |-> c][Y |-> 0][X |-> 0] (#######Ia)
X ::= 0;
{{ I[Z |-> c][Y |-> 0]
Y ::= 0;
{{ I[Z |-> c]
Z ::= c;
{{ I
WHILE X <> a DO
{{ I /\ X <> a }} ->>
{{ I[Z |-> Z+1][X |-> X+1] (#########Ib)
X ::= X + 1;
{{ I[Z |-> Z+1]
Z ::= Z + 1
{{ I
END;
{{ I /\ ~(X <> a) }} ->>
{{ J }} (########Ic, Ja)
WHILE Y <> b DO
{{ J /\ Y <> b }} ->>
{{ J[Z |-> Z+1][Y -> Y+1] (###### Jb)
Y ::= Y + 1;
{{ J[Z |-> Z+1]
Z ::= Z + 1
{{ J
END
{{ J /\ ~(Y <> b) }} ->>
{{ Z = a + b + c }} (###### Jc)
I : Z-X = c /\ Y = 0