CS代考 Hoare Logic: Partial Correctness

Hoare Logic: Partial Correctness
COMP1600 / COMP6260
Australian National University
Semester 2, 2020

Programming Paradigms
Functional. (Haskell, SML, OCaml, . . . )
main paradigm: functions that don’t rely on state main ingredient: recursion
Imperative. (C, Java, Algol, (Visual) Basic, . . . )
main paradigm: operations that do manipulate state. main ingredient: loops
1/51

Example: From Recursion to Loops
In Haskell.
fact_tr :: Int -> Int -> Int
fact_tr 0 acc = acc
fact_tr n acc = fact_tr (n-1) (acc * n)
fact n = fact_tr n 1
In Java.
public static int fact (int n) {
int acc = 1;
while (n > 0) { acc = acc * n; n = n-1; }
return acc;
}
Main Difference.
programs are not simple equations any more
need to keep track of changing values of variables
2/51

Verification for Imperative Languages
Main Ingredients.
properties of program states commands that modify state.
Description of both.
properties of states: formulae, e.g. x < 0 ∧ y > x commands are taken from the programming language formal rules that tell us how to manipulate both.
Hoare Logic ties in program states and formulae:
“Running program in a state that satisfies P gives a state that satisfies Q”
{P } program {Q }
3/51

C. A. R. (Tony) Hoare
The inventor of this week’s logic is also famous for inventing the Quicksort algorithm in 1960 – when he was just 26! A quote:
Computer programming is an exact science in that all the prop- erties of a program and all the consequences of executing it in any given environment can, in principle, be found out from the text of the program itself by means of purely deductive reasoning.
4/51

Logic = Syntax + Semantics + Calculus
Example. Propositional Logic
syntax: atomic propositions p, q, r, . . . + ∧, ∨, → and ¬ semantics: truth tables
calculus: natural deduction.
Hoare Logic.
syntax: triples {P} program {Q}
semantics: P in pre-state implies Q in post-state calculus: Hoare Logic
Q. What are pre/post conditions precisely? what are the programs? What about termination?
5/51

Hoare Logic: A Simple Imperative Programming Language
Q. In a Hoare triple {P} program {S}, what are the programs? A. We roll our own: a very simple Java-like language
Assignment – x := e
where x is a variable, and e is an expression built from variables and arithmetic that returns a number, e.g. 2 + 3, x∗y+1…
Sequencing – S1; S2
Conditional – if b then S1 else S2
where b is an expression built from variables, arithmetic and logic that returns a boolean (true or false), e.g. y < 0, x ̸= y ∧ z = 0... While – while b do S 6/51 A Note on (the lack of) Aliasing Assignments x := y copy values x y 12 x y 27 27 27 No Aliasing, i.e. x and y point to the same region in memory x y 12 x y 27 27 7/51 Syntax of Hoare Logic: Assertions Q. How do we describe properties of states? states are determined by the values of program variables here: states will store numbers only. Properties of States. propositional formulae built from variables, numbers and basic arithmetic: x = 3; x = y; x ̸= y; x > 0;
x ≤ (y 2 + 1 34 ); etc…
8/51

Syntax of Preconditions and Postconditions ctd.
Propositional Logic to combine simple assertions, e.g. x = 4 ∧ y = 2;
x < 0 ∨ y < 0; x>y → x=2∗y; True ;
False.
The last two logical constructions – True and False – will prove particularly useful, as we’ll later see.
Alternative. Could use first order logic – more expressive power.
9/51

Anatomy of a Hoare Triple
{P } program {Q }
program is a simple program written using assignments, conditionals,
while and sequencing
pre/post conditions are propositional formulae built from arithmetical relations
Semantics. A Hoare triple {P} program {Q} is valid if whenever we run program in a state that satisfies P
and the program terminates, then the post-state satisfies Q
10/51

A Rough Guide to Hoare Logic Semantics
Example Statements in Hoare Logic
{x > 0} y := 0 − x {y < 0 ∧ x ̸= y} If (x > 0) is true before y := 0-x is executed then (y < 0 ∧ x ̸= y) is true afterwards. Here: (x > 0) is the precondition;
y := 0-x is a (very simple) code fragment; (y < 0 ∧ x ̸= y) is the postcondition. Hoare logic will provide the rules to prove this. 11/51 Hoare’s Notation – the Definition The Hoare triple: means: {P} S {Q} If P is true in the initial state and S terminates then Q will hold in the final state. Examples: 1. {x=2}x := x+1 {x=3} 2. {x=2}x := x+1 {x=5000} 3. {x>0}y := 0-x {y<0∧x̸=y} (Hoare Triples can be true or false) 12/51 Some Hoare Triples Q. Under what conditions are the following Hoare Triples valid? 1. {True} program {True} 2. {True} program {False} 3. {False} program {True} 4. {False} program {False} 13/51 Some Hoare Triples Q. Under what conditions are the following Hoare Triples valid? 1. {True} program {True} 2. {True} program {False} 3. {False} program {True} 4. {False} program {False} A. Consider (precondition) ∧ (termination) → (postcondition) 1. is always true (as RHS of → is true) 2. true if program never terminates 3. always true (as RHS of → is true) 4. always true (as LHS of → is false) 13/51 A Larger Hoare Triple {n ≥ 0} fact := 1; k := n; while (k>0)
fact := fact * k;
k := k-1
{fact = n!}
Q1. is this Hoare triple true or false?
14/51

A Larger Hoare Triple
{n ≥ 0}
fact := 1;
k := n;
while (k>0)
fact := fact * k;
k := k-1
{fact = n!}
Q1. is this Hoare triple true or false?
Q2. what if n < 0 initially? 14/51 Partial Correctness Partial Correctness. A program is partially correct if it gives the right answer whenever it terminates. Hoare Logic (in the form discussed now) (only) proves partial correctness. Total Correctness. A program is totally correct if it always terminates and gives the right answer. Example. {x =1} while x=1 do y:=2 {x =3} is true in Hoare logic semantics (just because the loop never terminates). 15/51 Partial Correctness is OK Why not insist on termination? We may not want termination. {True} websever {very good reason} Not accounting for termination makes things simpler. We can add termination assertions (next week) 16/51 Specification vs Verification Hoare triples allow us to say something about the intended effect of the code Q. How do we make sure that the code validates these assertions? A1. Testing. For example, for {P} program {Q}: assert (P); program; assert (Q); assert (n >= 0);
do something;
assert (m = n * n);
does this catch all possible errors?
How to structure test cases? Changes of variable values?
A2. Proving. Show that {P} program {Q} is true for all states Hoare Calculus.
a collection of rules and procedures for (formally) manipulating the
(language of) triples.
(Just like ND for classical propositional logic . . . )
17/51

The Assignment Axiom (Rule 1/6)
Rules for proving correctness of programs:
one rule per construct (assignment, sequencing, if, while) two rules to glue things together
Assignment Rule.
assignment x := e change state reflect this in pre/post condition
Terminology
Suppose Q(x) is a predicate involving a variable x,
Then Q(e) indicates the same formula with all occurrences of x
replaced by the expression e. The Rule.
{Q(e)} x := e {Q(x)}
18/51

The Assignment Axiom – Intuition
{Q(e)} x := e {Q(x)} want x to have property Q after assignment
then property Q must hold for the value e before assignment Q. Why is this backwards? Shouldn’t it be
{Q(x)} x := e {Q(e)}
Counterexample. precondition x = 0, assignment x := 1 {x = 0} x := 1 {1 = 0}
which says “if x = 0 initially and x := 1 terminates then 1 = 0 finally”
Before / After
19/51

Work from the Goal, ‘Backwards’
Forward Reasoning. Not usually helpful
start at the precondition, work your way down to the postcondition not the best way – cf. e.g. doing natural deduction proofs
Backwards Reasoning
start with the goal (postcondition)
work your way back up to the precondition
Example.
{Q(e)} x := e {Q(x)}
start with postcondition, copy it over to precondition replace all occurrences of x with e.
postcondition may have no, one, or many occurrences of x in it; all get replaced
20/51

Example 1 of {Q(e)} x := e {Q(x)}
Code Fragment. x := 2, postcondition y = x. copy y = x over to the precondition
replace all occurrences of x with 2
Formally.
{y = 2} x:=2 {y = x} is an instance of the assignment axiom.
21/51

Example 2 of {Q(e)} x := e {Q(x)}
Code Fragment. x := x + 1, postcondition y = x. As before.
{y = x + 1} x:=x+1 {y = x} is an instance of the assignment axiom.
22/51

Example 3 of {Q(e)} x := e {Q(x)} Q. How do we prove
{y > 0} x:=y+3 {x > 3} ?
23/51

Example 3 of {Q(e)} x := e {Q(x)} Q. How do we prove
{y > 0} x:=y+3 {x > 3} ?
A.
1. Start with the postcondition x > 3 and apply the axiom: {y + 3 > 3} x:=y+3 {x > 3}
2. usethefactthaty+3>3isequivalenttoy>0togetourresult. Equivalent Predicates.
Can always replace predicates by equivalent predicates, label with precondition equivalence, or postcondition equivalence.
23/51

Proving the Assignment Axiom sound w.r.t. semantics
Assignment Axiom.
Justification.
{Q(e)} x := e {Q(x)}
Let v be the value of expression e in the initial state. If Q(e) is true initially, then so is Q(v).
Since the variable x has value v after the assignment (and nothing else is changed in the state), Q(x) must be true after that assignment.
24/51

The Assignment Axiom is Optimal
Proof Strength. The assignment axiom is as strong as possible. {Q(e)} x := e {Q(x)}
Meaning?
If Q(x) holds after the assignment then Q(e) MUST have held before.
Suppose Q(x) is true after the assignment.
If v is the value assigned, Q(v) is true after the assignment.
Since it is only the value of x that is changed, and the predicate Q(v) does not involve x, Q(v) must also be true before the assignment.
Since v was the value of e before the assignment, Q(e) is true initially.
25/51

A non-example
What if we wanted to prove
{y = 2} x:=y {x > 0} ?
26/51

A non-example
What if we wanted to prove
{y = 2} x:=y {x > 0} ?
This is clearly true. But our assignment axiom doesn’t get us there: {y > 0} x:=y {x > 0}
Problem.
cannot just replace y > 0 with y = 2 either – they are not equivalent. Solution.
Need a new Hoare logic rule that allows for manipulation of pre (and post) conditions.
26/51

Weak and Strong Predicates
Stronger.
A predicate P is stronger than Q if P implies Q. Weaker.
Q is weaker than P if P is stronger that Q.
Intuition. If P is stronger than Q, then
P is more restrictive, i.e. holds in fewer situations
Q holds in more cases than P, including all cases where P holds. stronger predicates convey more information than weaker predicates.
Q. Can you give me an example of a really strong predicate?
Example.
I will keep unemployment below 3% is stronger than
I will keep unemployment below 15%.
The strongest possible statement is False (unemployment below 0%) The weakest possible statement is True (unemployment at or below 100%)
27/51

Weak and Strong in Pictures
weak, e.g. animal
strong, e.g. marsupial
28/51

Strong Postconditions
Example.
(x = 6) =⇒ (x > 0), so (x = 6) is stronger than (x > 0) The Hoare triple:
{x = 5} x := x + 1 {x = 6} says more about the code than does:
{x = 5} x := x + 1 {x > 0} Strong Postconditions in general
if postcondition Q1 is stronger than Q2, then {P} S {Q1} is a stronger statement than {P} S {Q2}.
if postcondition x = 6 is stronger than postcondition x > 0, then {P} S {x = 6} is a stronger statement than {P} S {x > 0}
29/51

Weak Preconditions
Formula Example.
condition (x > 0) says less about a state than x = 5.
so x > 0 is a weaker condition than x = 5 since x = 5 implies x > 0.
Hoare Triple Example
the Hoare triple {x > 0} x := x + 1 {x > 1} says more about the code than {x = 5} x := x + 1 {x > 1}
this is because it says something about more situations Weak Preconditions
If precondition P1 is weaker than P2, then {P1} S {Q} is stronger than {P2} S {Q}.
if precondition x > 0 is weaker than precondition x = 5, then {x > 0} S {Q} is stronger than {x = 5} S {Q}.
30/51

Weak/Strong Pre/Postconditions
Precondition Strengthening. If P2 is stronger than P1, then {P2} S {Q} is true whenever {P1} S {Q} is true.
Proof. Assume that {P1} S {Q} is true.
Assume that we run S in a state that satisfies P2
but since P2 is stronger than P1, we have P2 → P1 hence S also satisfies P1 so that Q is true afterwards.
Postcondition Weakening. If Q1 is a stronger postcondition than Q2, then {P} S {Q2} is true whenever {P} S {Q1} is true.
Proof. Assume that {P} S {Q1} is true.
assumes that we run S in a state that satisfies P and that S terminates
this will lead to a post-state that satisfies Q1
but because Q1 is stronger than Q2, we have Q1 → Q2 hence the post-state will also satisfy Q2.
31/51

Proof rule for Strengthening Preconditions (Rule 2/6)
Q. How do we reflect this in the Hoare calculus?
A. We codify this in terms of proof rules that we can apply.
Precondition Strengthening.
Interpretation. If the premises are provable then so is the conclusion
Ps →Pw {Pw}S{Q} {Ps} S {Q}
32/51

Proof rule for Strengthening Preconditions (Rule 2/6)
Q. How do we reflect this in the Hoare calculus?
A. We codify this in terms of proof rules that we can apply.
Precondition Strengthening.
Interpretation. If the premises are provable then so is the conclusion Ps →Pw {Pw}S{Q}
{Ps} S {Q} Example by pattern matching
y = 2 → y > 0 {y > 0} x := y {x > 0} {y = 2} x := y {x > 0}
Precondition Equivalence. If P1 ↔ P2 then both P1 → P2 and P2 → P1.
32/51

Proof rule for Weakening Postconditions (Rule 3/6)
Postcondition Weakening.
Interpretation. If the premises are provable then so is the conclusion {P}S{Qs} Qs →Qw
{P} S {Qw} Example by pattern matching
{x > 2} x := x + 1 {x > 3} x > 3 → x > 0 {x > 2} x := x + 1 {x > 0}
Postcondition Equivalence. If Q1 ↔ Q2 then Q1 → Q2 and Q2 → Q1. i.e. Qs →Qw ∧Qw →Qs
33/51

Sequencing (Rule 4/6)
Sequencing.
execute commands one after another, each one manipulates the state
need to think about the overall effect of state change Sequencing as a proof rule
Interpretation. If the premises are provable then so is the conclusion {P} S1 {Q} {Q} S2 {R}
{P}S1;S2 {R}
Example.
{x > 2} x := x + 1 {x > 3} {x > 3} x := x + 2 {x > 5} {x > 2} x := x + 1; x := x + 2 {x > 5}
34/51

Interlude: Laying out a proof
Layout Problem. Assertions may depend on more than one premise.
Linear Layout.
1. {x+2>5} x:=x+2 {x>5} 2. {x > 3} x := x + 2 {x > 5}
3. {x+1>3} x:=x+1 {x>3} 4. {x > 2} x := x + 1 {x > 3}
(Assignment) (Precondition Equivalence, 1) (Assignment) (Precondition Equivalence, 1) 5. {x>2} x:=x+1;x:=x+2 {x>5} (Sequence,4,2)
Note the numbered proof steps and justifications.
35/51

Finding a Proof
Q. Where do we get the “condition in the middle” from? {P} S1 {Q} {Q} S2 {R}
{P}S1;S2 {R}
overall precondition P and overall postcondition R are given
sequencing requires us to find a gluing condition Q A. Start with the goal R and work backwards (as usual)
{x >2} x:=x+1 {Q} {Q} x:=x+2 {x >5} {x >2} x:=x+1;x:=x+2 {x >5}
36/51

An example with precondition strengthening
Goal. Prove that the following is true:
{x =3} x:=x+1;x:=x+2 {x >5}
First Steps in linear layout
5. {x>2} x:=x+1;x:=x+2 {x>5}
Add the following
6. x=3 → x>2
7. {x=3} x:=x+1;x:=x+2 {x>5}
(Seeearlierslide)
(Basicarithmetic) (Prec. Strength. 5,6)
37/51

Soundness of Rule for Sequences
Lemma. If the premises of Sequencing rule are true then so is the conclusion
Proof. Suppose the premises {P}S1{Q} and {Q}S2{R} are true and let σ0 be an arbitrary state that satisfies P.
if we run S1 in state σ0 we get a state σ1 that satisfies Q
if we run S2 in state σ1 we get a state σ2 that satisfies R but executing S1;S2 just means execute S1 first and then S2 hence we end up in a state that satisfies R
Q. What about termination?
38/51

Proof Rule for Conditionals (Rule 5/6)
Conditionals.
if b then S1 else S2
b is a boolean condition that evaluates to true or false
the value of b may depend on the program state
Informal Reasoning. Case split
if b evaluates to true, then run S1
if b evaluates to false, then run S2.
Additional Precondition.
in the if-branch, additionally know that b is true
in the then-branch, additionally know that b is false
Q. What is / are the “right” premise(s) for the if-rule ?
{P}ifbthenS1 elseS2{Q}
39/51

Proof Rule for Conditionals
Proof Rule
{P ∧b} S1 {Q} {P ∧¬b} S2 {Q} {P}ifbthenS1 elseS2{Q}
Justification.
When a conditional is executed, either S1 or S2 is executed. Therefore, if the conditional is to establish Q, both S1 and S2 must
establish Q.
Similarly, if the precondition for the conditional is P, then it must also
be a precondition for the two branches S1 and S2.
The choice between S1 and S2 depends on evaluating b in the initial state, so we can also assume b to be a precondition for S1 and ¬b to be a precondition for S2.
40/51

Example of Conditional Rule
{P ∧b} S1 {Q} {P ∧¬b} S2 {Q} {P}ifbthenS1 elseS2{Q}
Example. We want to show that the following is true {x>2}if x>2 then y:=1 else y:=-1{y>0}
Using the conditional rule (pattern matching)
{x>2 ∧ x>2}y:=1{y>0} {x>2 ∧ ¬(x>2)}y:=-1{y>0}
{x>2}if x>2 then y:=1 else y:=-1{y>0}
Precondition Equivalence means that we need to show: (1) {x>2}y:=1{y>0}
(2) {False} y:=-1 {y > 0}
41/51

Example In Full
Show. {x > 2} if x>2 then y:=1 else y:=-1 {y > 0} Proof in linear layout:
1. {1 > 0} y:=1 {y > 0}
2. (1 > 0) ↔ True
3. {True} y:=1 {y > 0}
4. (x > 2) → True
(Assignment) (Prop. Logic) (Prec. Equivalence, 2, 1) (Prop. Logic) (Prec. Stre., 3, 4)
5. {x > 2} y:=1 {y > 0} (premise (1))
6. {−1 > 0} y:=-1 {y > 0}
7. False ↔ (−1 > 0)
8. {False} y:=-1 {y > 0} (premise(2))
(Assignment) (Prop. Logic) (Prec. Eq)
9. {x>2}if x>2 then y:=1 else y:=-1{y>0} (Conditional, 5, 8)
42/51

Interlude: Conditionals Without ‘Else’
Conditionals are complete in the sense that they include an else-branch: ifb thenS1 elseS2
Q. Our language could have statements of the form if b then S
What would be the rule?
43/51

Interlude: Conditionals Without ‘Else’
Conditionals are complete in the sense that they include an else-branch: ifb thenS1 elseS2
Q. Our language could have statements of the form if b then S
What would be the rule?
A. Conditionals without else are equivalent to
if b then S else (do nothing)
Conditional Rule.
{P ∧b} S {Q} {P ∧¬b} donothing {Q} {P} if b then S {Q}
43/51

Conditionals Without ‘Else’ ctd.
Q. How do we establish the following? Conditional Rule.
{P ∧P} S {Q} {P ∧¬b} donothing {Q}
{P} if b then P {Q}
Q1. How about do nothing?
A. Easy: {P} do nothing {P} is always true. Precondition Strengthening to the rescue:
{P∧b} S {Q} (P∧¬b)→Q {P} if b then S elsex:=x {Q}
44/51

Finding a Proof
Q. How do we prove that
{x =3} x:=x+1;x:=x+2 {x >5}
A. Use sequencing rule
{P} S1 {Q} {Q} S2 {R}
{P} S1 ; S2 {R}
Concrete Instance.
{x =3} x:=x+1 {Q} {Q} x:=x+2 {x >5} Seq {x =3} x:=x+1;x:=x+2 {x >5}
45/51

Finding a Proof
Goal. Prove that the following is true.
{x =3} x:=x+1;x:=x+2 {x >5}
First Take. Apply assignment axiom {Q(e)}x := e{Q(x)} Q. What rule could (?) be?
{x+2>5} x:=x+2 {x>5} {x =3} x:=x+1 {Q} {Q} x:=x+2 {x >5} ?
{x =3} x:=x+1;x:=x+2 {x >5} Seq
46/51

Finding a Proof
Goal. Prove that the following is true:
{x =3} x:=x+1;x:=x+2 {x >5}
A. Putting Q = x > 3 would mean that (?) is precondition equivalence
{x+2>5} x:=x+2 {x>5}
PreEq Seq
{x =3} x:=x+1 {x >3} {x >3} x:=x+2 {x >5} {x =3} x:=x+1;x:=x+2 {x >5}
47/51

Finding a Proof
Goal. Prove that the following is true:
{x =3} x:=x+1;x:=x+2 {x >5}
Second Take. Can apply the assignment axiom {Q(e)}x := e{Q(x)} Q. What rule could (?) be?
{x+1>3} x:=x+1 {x>3} {x+2>5} x:=x+2 {x>5}
{x =3} x:=x+1 {x >3} ? {x >3} x:=x+2 {x >5} PreEq
{x =3} x:=x+1;x:=x+2 {x >5}
Seq
48/51

Finding a Proof
A. Let’s try precondition equivalence again: x>2↔x+1>3
{x+1>3} x:=x+1 {x>3}
{x>2} x:=x+1 {x>3} PreEq {x+2>5} x:=x+2 {x>5}
{x =3} x:=x+1 {x >3} ? {x >3} x:=x+2 {x >5} P
{x =3} x:=x+1;x:=x+2 {x >5} Q. There’s still something missing. What is (?) now?
Seq
49/51
r

Finding a Proof
A. x = 3 implies x > 2 so “?” can be precondition strengthening. Precondition Strengthening.
Ps →Pw
Complete Proof as a tree
{x+1>3} x:=x+1 {x>3}
{x>2} x:=x+1 {x>3}
{Pw}S{Q} {Ps} S {Q}
PreEq {x+2>5} x:=x+2 {x>5}
{x =3} x:=x+1 {x >3} PreStr {x >3} x:=x+2 {x >5} PreE
{x =3} x:=x+1;x:=x+2 {x >5}
Seq
50/51

The Same Proof in Linear Form
1. {x+1>3} x:=x+1 {x>3} 2. x>2↔x+1>3
3. {x>2} x:=x+1 {x>3}
4. x=3→x>2
5. {x=3} x:=x+1 {x>3}
6. {x+2>5} x:=x+2 {x>5} 7. x>3↔x+2>5
8. {x>3} x:=x+2 {x>5}
9. {x=3} x:=x+1;x:=x+2 {x>5}
(Assignment) (Basicarithmetic) (Prec. Equi. 1,2) (Basicarithmetic) (Prec. Stren. 3,4)
(Assignment) (Basicarithmetic) (Prec. Equiv. 6,7)
(Seq. 5,8)
(sections separated by horizontal lines are both premises of the sequencing rule)
51/51