cs4003: formal methods · cs4003 formal methods atomic predicates ian atomic predicate is an...

155
CS4003 Formal Methods CS4003: Formal Methods Andrew Butterfield 1 1 Foundations & Methods Group, Software Systems Laboratory Andrew.Butterfi[email protected] Room G.39, O’Reilly Institute Michaelmas Term, 2013 CS4003 Formal Methods CS4003: Approach When Where What Wed 10am LB120 Lecture Thursday 5pm LB120 Lecture Friday 2pm LB107 mini-Solution; Tutorial/Examples; mini-Exercise CS4003 Formal Methods CS4003: Assessment I Exam: 80% I Coursework: 20% I Project: 10% I Class (Mini-)Exercises: 10% I Mini-exercises handed out at end of Fri 2pm class. I Mini-solutions due in at start of following Friday 2pm class. I These deadlines are hard, as solutions will be given out at the start of the 2pm Friday class. CS4003 Formal Methods CS4003: Resources I Blackboard (mymodule.tcd.ie) I Main Reference Text: Unifying Theories of Programming , C.A.R. Hoare and Jifeng He, Prentice Hall, 1998. (out of print, will be uploaded to Blackboard) I Secondary Texts: I A Logical Approach to Discrete Math, D. Gries & F. B. Schneider, Springer, 1993 (your JF math text!). I Using Z , J. Woodcock & J. Davies, Prentice Hall 1996. (out of print, will be uploaded to Blackboard)

Upload: others

Post on 19-Aug-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

CS4003: Formal Methods

Andrew Butterfield1

1Foundations & Methods Group,Software Systems [email protected] G.39, O’Reilly Institute

Michaelmas Term, 2013

CS4003 Formal Methods

CS4003: Approach

When WhereWhat

Wed 10am LB120 LectureThursday 5pm LB120 LectureFriday 2pm LB107 mini-Solution;

Tutorial/Examples;mini-Exercise

CS4003 Formal Methods

CS4003: Assessment

I Exam: 80%I Coursework: 20%

I Project: 10%I Class (Mini-)Exercises: 10%

I Mini-exercises handed out at end of Fri 2pm class.I Mini-solutions due in at start of following Friday 2pm class.I These deadlines are hard, as solutions will be given out at

the start of the 2pm Friday class.

CS4003 Formal Methods

CS4003: Resources

I Blackboard (mymodule.tcd.ie)I Main Reference Text:

Unifying Theories of Programming ,C.A.R. Hoare and Jifeng He,Prentice Hall, 1998.(out of print, will be uploaded to Blackboard)

I Secondary Texts:I A Logical Approach to Discrete Math, D. Gries &

F. B. Schneider, Springer, 1993 (your JF math text!).I Using Z , J. Woodcock & J. Davies, Prentice Hall 1996.

(out of print, will be uploaded to Blackboard)

Page 2: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

What are “Formal” Systems?

I Specified collection of Symbols (lexicon)I Specified ways of putting them together (well-formedness)I Specific ways of manipulating symbol-sequences

(inference rules)I Typically the goal is to transform a starting sequence to a

final one having desired properties.

CS4003 Formal Methods

Example: System ~z= (“H-Cross-I”)

I Symbols: ~ z =I Well-Formed Sequences, H-Things and I-Things, where:

H-Thing : A ~ followed by Crosses:Crosses : Zero or more z

I-Thing : A = followed by two H-ThingsI Manipulations (let f1 and f2 stand for arbitrary Crosses).

〈〈I-absorb〉〉 =~~f1 becomes ~f1〈〈swap-Cross-H〉〉 =~f1z~f2 becomes =~f1~zf2

I Goal: convert a starting I-Thing into a H-Thing

CS4003 Formal Methods

Example

=~zz~zzz= 〈〈swap-Cross-H〉〉

=~z~zzzz= 〈〈swap-Cross-H〉〉

=~~zzzzz= 〈〈I-absorb〉〉

~zzzzz

CS4003 Formal Methods

Interpretation

~ 0 zeroz +1 succ= + plus

=~zz~zzz + 0 + 1 + 1 0 + 1 + 1 + 1 2 + 3=~z~zzzz + 0 + 1 0 + 1 + 1 + 1 + 1 1 + 4=~~zzzzz + 0 0 + 1 + 1 + 1 + 1 + 1 0 + 5

~zzzzz 0 + 1 + 1 + 1 + 1 + 1 5

=~f1z~f2 99K =~f1~zf2 (n + 1) + m = n + (m + 1)=~~f1 99K ~f1 0 + m = m

Page 3: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

What’s the point?

I We can give very precise meanings to the symbols,I The manipulations can have a very-well defined meaning,I but, the symbols can be manipulated without our having to

understand these meanings.I which is exactly how a computer does it !

I Formal Methods allow us to limit the scope for human errorand to exploit the use of machines to help our analysis.

CS4003 Formal Methods

Formal Logic

We present a Formal System, called PredicateCalculus

SymbolsThose used for expressions and propositionallogic, as well as ∃, ∀, •.

Well-FormednessPredicates: Well structured expressions whosetype is Boolean.

Manipulation RulesClassified as Axioms and Inference Rules.

GoalTo prove a given Predicate is “True”.

CS4003 Formal Methods

Expressions

We build basic expressions out of constants (k ∈ Const ),variables (v ∈ Var ), tuples, functions and operators:

e ∈ Expr ::= k | v constants, variables| (e1, . . . ,en) | {. . .} aggregates| e1 e2 function application| e1 ⊕ e2 infix application| (e) parenthesised expr.

I Read e ∈ Expr ::= . . . as “e, an Expr , is …”I Read k as “a constant k ”I Read |as “or”I We do not give a complete definition here of expressions,

and will extend this as the course progresses.

CS4003 Formal Methods

Expressions (Aggregates)

e ∈ Expr ::= (e1, . . . ,en) | {. . .} aggregates

I Aggregates are distinguished by different brackets:

(e1, . . . ,en) tuples{e1, . . . ,en} sets〈e1, . . . ,en〉 sequences

...

Page 4: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Expressions (Function application)

I We define function application without brackets, so f xdenotes function f applied to argument x (if f is a prefixfunction — most are !)

I We can write function application with brackets if we preferso f (x ) and f x are equivalent.

I In some of the literature, function application is shownexplicitly with a dot, so f .x is the same as f x (or f (x ) ).

I In the case where f is a postfix function, then applying f tox is written as x f (e.g. raising to a power — x 2 is thesquaring function 2 post-applied to x ).

I The notation used is often a matter of style, and dependson context.

CS4003 Formal Methods

Expressions (Infix operators)

e ∈ Expr ::= e1 ⊕ e2 infix operator application

I Here ⊕ denotes any infix binary operator, such as+,−, ∗, /,=, <,>,≤,≥,∪,∩, . . .

I Parentheses and precedence behave in the same manneras found in most programming languages, so x + y ∗ z isthe same as x + (y ∗ z), but different from (x + y ) ∗ z .

CS4003 Formal Methods

Well-Typedness

I We require expressions to be well typed.e.g. we want to outlaw nonsense like 3 + (A ∪ B) or〈1,0,1,0〉 − 5 = True

I we write the assertion that expression e has type T as

e : T

I We can consider (for now) a type T as being the set ofvalues that are allowed for something of that type.

CS4003 Formal Methods

Types

We make use of a rich variety of given types and typeconstructors:

S,T ∈ Type ::= 1 unit type| B boolean values| A (ASCII) characters| N | Z | Q | R | C numbers| PT set of T| T1 × · · · × Tn cross-product| T ∗ sequence of T| S → T function from S to T

I There are rules for checking (and/or inferring) expressiontypes, which we ignore for now.

Page 5: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Expressions (Type annotations - I)

I

e ∈ Expr ::= . . .| (e : T ) type annotation

I As a standalone expression, it has type Boolean, and istrue if e has type T

I Note,if e is a variable (v ) not in scope, then v : T is alwaystrue, and so can be considered a type declaration.

I Note that an incorrect annotation is not a type error, but issimply a statement, so ((A ∪ B) : N) is a well-typedboolean-valued expression that just happens to be false(provided A ∪ B is well-typed).

CS4003 Formal Methods

Expressions (Type annotations 2)

I Sometimes we use type annotations embedded inexpressions as an abuse of notation e.g..

(x : Q)2 = 2 instead of x 2 = 2

I Strictly speaking, this is ill-typed (why?), but the intentionwas to say

(x : Q) ∧ x 2 = 2

I Usually we shall avoid this abuse of notation.

CS4003 Formal Methods CS4003 Formal Methods

Page 6: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 2

CS4003 Formal Methods

Expression Meaning

I What is our intended meaning for an expression ?(e.g. x 2 + y )

I it depends on the value of x and yI so, let x = 3 and y = 5 (say)I OK, so then x 2 + y has value 14.

I The “meaning” of an expression is the relationship itcreates between the values of its variables and its ownoverall value:

“meaning : values(x , y )→ value”

I Alternatively, we can view the meaning as a function fromvariables to the expression’s value.

CS4003 Formal Methods

Environments

I We call the association of values with variables anEnvironment (or Interpretation) and is a table associating avalue with every variable (whose value is defined).

I We assume environments are always well-formed, in thatthe associated value is always of the correct type.

I e.g.:

Variable : Type Valuelist : N∗ 〈1,1,2,3,5,8,13〉ix : N 4offset : N 2

CS4003 Formal Methods

Evaluating Expressions against Environments

Given an environment (as per previous slide), it is possible todetermine the value for an expression in a systematic way.

ix + offset 6 length list= “ lookup above table ”

4 + 2 6 length 〈1,1,2,3,5,8,13〉= “ defn. of + and length. (?) ”

6 6 7= “ defn. of 6(?) ”

True

(?) Where do we find the definitions +, length and 6 ?

Page 7: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Modelling Environments

I We usually model Environments mathematically as a finitepartial map ( 7→) from variables to values:

ρ ∈ Env = Var 7→ Value

Here the ‘type’ Value should considered as the union of allpossible types.

I A table entry mapping variable v to value k is written asv 7→ k .

I A table is a set of table entry mappings (order is irrelevant):

{list 7→ 〈1,1,2,3,5,8,13〉, ix 7→ 4,offset 7→ 2}

CS4003 Formal Methods

Expressions as Functions

I Given an expression, and then an environment, we can getthe value of that expression in that environment.

I We can therefore view the meaning of an expression as a(partial (?)) function from environments to values.

I Let [[e]] denote the “meaning of e”, and [[e]]ρ the meaninggiven environment ρ, then we can say

[[e]] : Env 7→ Value[[e]]ρ = . . .

The meaning function, given an expression, returns apartial function from environment to values.

CS4003 Formal Methods

Example

I What is the meaning of expression

ix + offset 6 length list

w.r.t. environment

ρ = {list 7→ 〈1,1,2,3,5,8,13〉, ix 7→ 4,offset 7→ 2}

?I

[[ix + offset 6 length list ]]ρ = True

I We shall see how to define [[ ]] later.

CS4003 Formal Methods

Predicates

I A Predicate is an “expression” whose type is boolean (B).

P ∈ Pred ::= . . .[[P ]] : Env → B

Remember that “type” Value contains values of all types,including B, so B ⊆ Value.

I Unlike expressions, where evaluation w.r.t. an environmentmay be undefined, we insist that predicates alwaysevaluate to either True or False.

Page 8: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Atomic PredicatesI An Atomic Predicate is an expression whose overall type is

Boolean, and whose constituent parts have non-Booleantypes

A,B,C ∈ AtmPred ::= e : B

I They can be viewed as a function from an environment tothe values true or false.

[[A]] : Env → B

I Examples:

x + 3 6 yf (x ) = g(x )− h(x )

reverse(〈x 〉a xs) = (reverse xs)a 〈x 〉CS4003 Formal Methods

True & False

I Two special predicates true and false always return Trueand False respectively, regardless of the environment.

I True and true are not the same:I True : B is a boolean valueI true : Env → B is a predicate, a function from environments

to B.I Similarly for False and false.I In practise we can often ignore the distinction, using them

interchangeably.

CS4003 Formal Methods

Identities

I (Atomic) Predicate Expressions of the form:

e1 = e2

where e1 and e2 have the same type, are known asIdentities.

I Identities play a major role in what is to come.

CS4003 Formal Methods

Predicate Logic Syntax

Given atomic predicates we can build a richer language usingPropositional Connectives (¬ ,∧,∨,⇒,≡):

P ∈ Pred::= true | false | A atomic predicates| ¬ P logical negation| P1 ∧ P2 conjunction (logic-and)| P1 ∨ P2 disjunction (logic-or)| P1 ⇒ P2 implication| P1 ≡ P2 equivalence

This gives us the same power as propositional calculus, a.k.a.“digital logic”.

Page 9: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Predicate Logic Syntax

Considerably more power is obtained by adding Quantifiers(∀,∃,∃1) to the language:

P ∈ Pred::= . . . already discussed| ∀ x : T • P universal quantification (for-all)| ∃ x : T • P existential quantification (there-exists)| ∃1 x : T • P unique existence quantification| [P ] universal closure

The type annotations (: T ) are optional and are often omittedwhen clear from context (or irrelevant!)

CS4003 Formal Methods

Predicate Meanings (Propositions)

The predicate meaning function can be described as follows:

[[true]]ρ =̂ True[[false]]ρ =̂ False

[[e]]ρ =̂ [[e]]ρ pred. meaning = expr. meaning[[¬ P ]]ρ =̂ logical inverse of [[P ]]ρ

[[P1 ∧ P2]]ρ =̂ True iff both [[P1]]ρ and [[P2]]ρare[[P1 ∨ P2]]ρ =̂ True iff either [[P1]]ρ or [[P2]]ρare

We define implication and equivalence by translation

P1 ⇒ P2 = ¬ P1 ∨ P2P1 ≡ P2 = (P1 ⇒ P2) ∧ (P2 ⇒ P1)

CS4003 Formal Methods

Manipulating Environments (Maps)

We define the domain of an environment (dom ρ) as the set ofall variables mentioned in ρ.We can use one environment (ρ′) to override part or all ofanother (ρ), indicating this by ρ⊕ ρ′.The bindings in the second map, extend and take precedenceover those in the first map — e.g.:

{a 7→ 1,b 7→ 2, c 7→ 3} ⊕ {c 7→ 33,d 7→ 44}= {a 7→ 1,b 7→ 2, c 7→ 33,d 7→ 44}

CS4003 Formal Methods

The Meaning of Quantifiers (I)

We can now give the meaning for the main two quantifiers as:

[[∀ x : T • P ]]ρ =̂ for all values k in Twe have [[P ]]ρ⊕{x 7→k} = True

“∀ x : T • P is true if P is true for all x : T ”

[[∃ x : T • P ]]ρ =̂ for at least one value k in Twe have [[P ]]ρ⊕{x 7→k} = True

“∃ x : T • P is true if P is true for at least one x : T ”

Page 10: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example

Let T = {1,3,5} and evaluate:

[[∀ x : T • x < y ]]{x 7→2,y 7→5}

For all values k in {1,3,5}k = 1 we have [[x < y ]]{x 7→1,y→5} = 1 < 5 = Truek = 3 we have [[x < y ]]{x 7→3,y→5} = 3 < 5 = Truek = 5 we have [[x < y ]]{x 7→5,y→5} = 5 < 5 = False

Overall result: False.

CS4003 Formal Methods

The Meaning of Quantifiers (II)

We can now give the meaning for the other two quantifiers as:

[[∃1 x : T • P ]]ρ =̂ for exactly one k in Twe have [[P ]]ρ⊕{x 7→k} = True

“∃1 x : T • P is true if P is true for exactly one x : T ”

[[[P ]]]ρ =̂ for any ρ′ such that dom ρ′ = dom ρwe have [[P ]]ρ′ = True

“[P ] is true if P is true for all values of all its variables”

CS4003 Formal Methods

Evaluating Quantifiers

I Consider:

∀n : N • prime(n) ∧ n > 2⇒ ¬ prime(n + 1)

True, or False?I To evaluate a quantifier, we may need to generate all

possible environments ρ′ involving the bound variable —tricky if type has an infinite number of values.

I In general, in order to reason about quantifiers we need touse Axioms and Inference Rules.

CS4003 Formal Methods

Page 11: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 3

CS4003 Formal Methods

Logic Example I

Under what circumstances is the following true?

(x < 3 ∧ x > 5)⇒ x = x + 1

CS4003 Formal Methods

Example I Commentary

(x < 3 ∧ x > 5)⇒ x = x + 1= “ definition of⇒ ”¬ (x < 3 ∧ x > 5) ∨ x = x + 1

= “ 5 < x < 3 clearly impossible ”¬ (false) ∨ x = x + 1

= “ negation ”true ∨ x = x + 1

= “ logical-OR ”true

It is always true !

CS4003 Formal Methods

Implication Truth-Table

The truth table for implication is as follows:

P Q P ⇒ QFalse False TrueFalse True TrueTrue False FalseTrue True True

Simply put, for P ⇒ Q,if P is false, then the whole thing is true,regardless of Q.

Page 12: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Logic Example II

The following statement is true:

∀n : N • n > 2⇒ prime(n)⇒ ¬ prime(n + 1)

How might we argue this?

CS4003 Formal Methods

Example II Commentary

∀n : N • n > 2⇒ (prime(n)⇒ ¬ prime(n + 1))

I Case n 6 2 : False ⇒ . . . is true.I Case n > 2 ∧ ¬ prime(n) : True ⇒ (False ⇒ . . .) is true.I Case n > 2 ∧ prime(n) : 2 is only even prime, so here n is

odd, so n + 1 is even and therefore not prime.

CS4003 Formal Methods

Quantifier Expansion

I We can view quantifiers as (approximate) shorthand forrepeated logical-and/or:

∀n : N • P(n) = P(0) ∧ P(1) ∧ P(2) ∧ P(3) ∧ . . .∃n : N • P(n) = P(0) ∨ P(1) ∨ P(2) ∨ P(3) ∨ . . .

I The equality is exact if the type quantified over is finite:

∀b : B • P(b) = P(False) ∧ P(True)∃b : B • P(b) = P(False) ∨ P(True)

CS4003 Formal Methods

Logic Example III

Assuming all variables are natural numbers, is the statement

∀ x • ∃ x • x < y

equivalent to∀ x • x < y ,

or∃ z • z < y ,

or neither?(What precisely do the three statements actually mean?)What about ∃ z • z < x?

Page 13: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example III Commentary (1)

I

[[∀ x • ∃ x • x < y ]]ρ= “ by our semantics ”

[[∃ x • x < y ]]ρ⊕{x 7→k}, for all k= “ by our semantics ”

[[x < y ]]ρ⊕{x 7→k}⊕{x 7→k ′}, for all k , for some k ′

= “ 2nd override masks 1st ”[[x < y ]]ρ⊕{x 7→k ′}, for all k , for some k ′

= “ choose k ′ = 0 ”[[0 < y ]]ρ

= “ true for natural number y if non-zero ”y 6= 0

I This is a statement about y , not about x , and the outer ∀ xis masked by inner ∃ x .

CS4003 Formal Methods

Example III Commentary (2)

[[∀ x • x < y ]]ρ= “ by our semantics ”

[[x < y ]]ρ⊕{x 7→k}, for all k= “ false if we choose k = ρ(y ) + 1 ”

False

[[∃ z • z < y ]]ρ= “ by our semantics ”

[[z < y ]]ρ⊕{z 7→k}, for some k= “ choose k = 0 ”

[[0 < y ]]ρ= “ true for natural number y if non-zero ”

y 6= 0

CS4003 Formal Methods

Example III Commentary (3)

I

[[∃ z • z < x ]]ρ= “ by our semantics ”

[[z < x ]]ρ⊕{z 7→k}, for some k= “ choose k = 0 ”

[[0 < x ]]ρ= “ true for natural number x if non-zero ”

x 6= 0

I This is a statement about x , not y , or z .

CS4003 Formal Methods

Logic Example IV

Define the following in terms of other predicates:

∃1 x • P(x )

Here P(x ) indicates explicitly that P mentions x .A reminder:

[[∃1 x : T • P ]]ρ =̂ for exactly one k in Twe have [[P ]]ρ⊕{x 7→k} = True

“∃1 x : T • P is true if P is true for exactly one x : T ”

Page 14: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example IV Commentary

∃1 x • P(x )=̂ (∃ x • P(x ))∧ (∀ x • ∀ y •

(P(x ) ∧ P(y ))⇒ x = y )

There exists only one x satisfying P , iffthere is at least one x satisfying Pand for all x and y

if both x and y satisfy P then it must the case that x = y .

CS4003 Formal Methods

Logic Example V

Simplify the following predicate:

∃ x • x = y + z ∧ x < 2 ∗ y

CS4003 Formal Methods

Example V Commentary

∃ x • x = y + z ∧ x < 2 ∗ y= “ The only way this can be true is when x = y + z ”

“ so replace x by that. ”∃ x • y + z = y + z ∧ y + z < 2 ∗ y

= “ x is not mentioned, so ∃ is now redundant ”y + z = y + z ∧ y + z < 2 ∗ y

= “ y + z = y + z is clearly true ”y + z < 2 ∗ y

= “ arithmetic ”z < y

CS4003 Formal Methods

Formal Methods: early History

I 1967, Robert W. Floyd, “Assigning Meanings to Programs”Mathematical Aspects of Computer Science, AMS, Vol.19,pp19–32

I Floyd described a technique for annotating flowcharts withpredicates describing what should be true at every point inthe execution.

I 1969, C. A. R. Hoare, “An axiomatic basis for computerprogramming” Communications of the ACM , Vol.12, No.10,pp576—580,583 October.

I Hoare introduced the notation known today as a “Hoaretriple”:

Pre{prog}Post

“if Pre holds at the start and prog terminates,then Post will be true at the end”.

Page 15: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Floyd’67: Annotated flowchart example

image © 1967 AMS

CS4003 Formal Methods

Hoare’69: Proof example

true

r :=x ;

q:=0;

while

y6r

do

r :=r−y ;

q:=1+q

¬ (y6r)

x=r+y×q

image © 1969 ACM

CS4003 Formal Methods

Floyd/Hoare as a foundation

I The framework we shall explore is known as “UnifyingTheories of Programming” (UTP)

I It is a direct descendant of the Floyd/Hoare approachI UTP aims to link theories of different kinds of programming

language:imperative, concurrent, functional, logical, dataflow,assembler, …

I C.A.R. (Tony) Hoare is one of the prime movers behindUTP

I he spent most of time in Oxford at the ProgrammingResearch Group (PRG)

I now with Microsoft Research, CambridgeI most famous outside the formal methods community for

QuickSort !

CS4003 Formal Methods

Mini-Exercise 1

Q1.1 Evaluate A ∩ elems(trace) = ∅in environment {A 7→ {2,4,6}, trace 7→ 〈1,2,1,3〉}whereI elems takes a list and returns the set of

values in that listQ1.2 Is ∃n : N • n ≥ 3 ∧ prime(n)⇒ prime(n − 1) true

or false? Justify your answerQ1.3 Write one paragraph about a software failure (not

yours) that you found most vexing.

(handwritten, due in at start of 2pm class, Fri.4th October)

Page 16: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 4

CS4003 Formal Methods

Key Concept: Free and Bound Variables

I Expressions, Formula, Propositions and Predicates usuallyinvolve a number of variables.

I Depending on context, a variable occurrence can be freeor bound .

I If a variable occurrence is bound , that is because there issomething in the context in which it occurs that is binding it.

I A binding occurence is something (a piece of syntax) thatmentions a variable in a special way, usually introducing itto stand for something specific .

I If nothing is binding an occurrence of a variable, then it isfree.

I Free occurrences of variables are usually there to denote awide range of possible values (of a given type).

CS4003 Formal Methods

Examples of Binding — Definitions

I The definition (read ‘x is defined to be 3’):

x =̂ 3 (1)

binds the variable x to 3 wherever the definition is in scope.I The following recursive definition of factorial:

fac(0) =̂ 1fac(n) =̂ n ∗ fac(n − 1)

binds two variables:I The variable fac is bound wherever this definition is in scopeI n is bound in the righthand-side of the second lineI The binding occurrence of n is in the lefthand-side.

CS4003 Formal Methods

Examples of Binding — Quantifiers

I The Logic Quantifiers ∀, ∃ are examples of bindingconstructs.

I For example: ∃ x : Q • x 2 = 2 hasI a binding occurrence of x immediately after ∃,I and it is bound in the expression to the right of •.

I Consider:

∀ x • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10

Which variable occurrences are free, bound or binding ?

Page 17: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Answer

I We shall colour-code as follows:Free Green

Binding RedBound Orange

I

∀ x • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10

I the first occurrence of y is free, whilst the second and thirdare binding and bound respectively.

I This is why we only talk about occurrences of variables asbeing free or bound.

CS4003 Formal Methods

Examples of Binding — Programs

I In a program block, local variable declarations are bindingI For example, code to swap x and y, using local variable

temp:

{ int temp ;temp = x ;x = y ;y = temp ;

}

CS4003 Formal Methods

Manipulating Free and Bound VariablesI The key operation we use to manipulate free and bound

variables is that of substitution.I This takes two forms:

I α-Substitution, or Renaming of Bound VariablesI Replacing all Free Occurrences of a Variable by an

Expression.I We change our substitution notation, instead of E [x := F ],

we writeE [F /x ]

to denote the substitution of F for every free occurrence ofx in E .

I This notation extends to cover multiple simultaneoussubstitutions:

E [F1,F2, . . . ,Fn/x1, x2, . . . , xn]

CS4003 Formal Methods

Replacing Free Variables by Expressions (I)

I We often want to replace free occurrences of variables byexpressions (of the same type).

I We denote the replacement by F of all occurrences of freevariable a in expression E , by the notation E [F /a].

I It is defined if none of the free variables in F have bindingoccurrences in E .

I Example:

(∀ x • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10) [a + 5/y ]

= ∀ x • x ≥ 3⇒ a + 5 = 0 ∧ ∃ y • y > 4 ∧ z = 10

Note that only the free occurrence of y is affected.

Page 18: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Replacing Free Variables by Expressions (II)

I Substituting x − 10 for y does not work — we get aphenomenon known as name capture:

(∀ x • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10) [x − 10/y ]

= ∀ x • x ≥ 3⇒ x − 10 = 0 ∧ ∃ y • y > 4 ∧ z = 10

I The first free occurrence of y (in y = 0) is replaced byx − 10, where the free x becomes bound!

I In E [F /x ], the free/bound status of variables in F shouldnot change.

CS4003 Formal Methods

Renaming Bound Variables (I)

I We can rename bound variables in a consistent way(binding, and all bound occurrences) without changing themeaning of the underlying expression.

I We denote the replacement of bound variable a by b in Eby E{a α

⇁ b} (read as “a α-becomes b”).I It is defined if b does not occur free in E .I It is defined in terms of free variable substitution:

〈〈∀-α-rename〉〉 (∀ x • P){x α⇁ y} = ∀ y • (P [y/x ])

〈〈∃-α-rename〉〉 (∃ x • P){x α⇁ y} = ∃ y • (P [y/x ])

CS4003 Formal Methods

Renaming Bound Variables (II)

I Example:

(∀ y • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10){y α⇁ w}

= ∀w • x ≥ 3⇒ w = 0 ∧ ∃ y • y > 4 ∧ z = 10

I Note that only the instances of y outside the inner ∃ y werereplaced.

CS4003 Formal Methods

Renaming Bound Variables (III)

I Substituting x for y is illegal:

(∀ y • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10){y α⇁ x}

= ∀ x • x ≥ 3⇒ x = 0 ∧ ∃ z • z > 4 ∧ z = 10

I We see that x becomes bound !

Page 19: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Using Both SubstitutionsI alpha-substitution is often used to get around the

restriction associated with replacing free variables.I Let’s say we really want to replace free y by x − 10 in the

following

∀ x • x ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10

I First, we use α-substitution to rename the binding andbound occurrences of x to something different (a, say) —{x α

⇁ a}

∀a • a ≥ 3⇒ y = 0 ∧ ∃ y • y > 4 ∧ z = 10

I Then we do our desired substitution [x − 10/y ]:

∀a • a ≥ 3⇒ x − 10 = 0 ∧ ∃ y • y > 4 ∧ z = 10

CS4003 Formal Methods

Function Application

I Consider a function, defined as,

f (x ) =̂ Erhs

I If applied to an argument Earg , then the result is given byreplacing all free occurrences of x in Erhs by Earg :

f (Earg) = Erhs [Earg/x ]

I Remember to use α-substitution to avoid name-capture,ifnecessary.

CS4003 Formal Methods

Use in Logic — an example

I If we know that for any s : T that P [s/x ] is true, then wecan conclude that

∀ x : T • P

I This inference rule is often written as

s : T P [s/x ]

∀ x : T • P

I Alternatively, we have the converse law:

∀ x : T • P s : TP [s/x ]

CS4003 Formal Methods

Page 20: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 5

CS4003 Formal Methods

Rule-based Manipulation

I So far, we have seen ad-hoc ways of reasoning aboutproperties.

I Calculation/EvaluationI when we had precise information about environment valuesI doing symbolic evaluation

I “Handwaving”I reasoning about a range of environmentsI reasoning over infinite cases

I We need a way to reason through symbol manipulation(the “formal approach”).

CS4003 Formal Methods

The Rules of Formal Logic

I There are many ways to formulate the laws of logic.I We shall adopt the formulation of Equational Logic .

I Logic proofs handled “equation-style”I Four inference laws (Liebniz, Transitivity, Substitution,

Equanimity)I Many axiomsI D. Gries & F. B. Schneider, A Logical Approach to Discrete

Math, Springer-Verlag, 1994.I G. Tourlakis, “On the Soundness and Completeness of

Equational Predicate Logics”, J. Log. Comput., Vol. 11, No.4, pp623–653, 2001

CS4003 Formal Methods

Inference Rules

I Inference rules describe how we may deduce the truth ofone statement (the consequent , C) from the truth of acollection of other statements (the antecedents Ai ), subjectto some side-condition S.

Rule Name:A1, . . . , An

CS

I “From the truth of A1 and … and An we can deduce C(provided S holds).”

I Side-conditions S are not predicates themselves, but areproperties of predicates.

Page 21: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Inference meta-Notation

I Sometimes both antecedents and consequents ininference rules use extra (meta-)notation not part of theformal language.

I For example, notation

P [v := Q] (Textual Substitution)

describes predicate P where all instances (if any) ofvariable v have been replaced by Q

I e.g. (x < y + z)[y := 3 ∗ n] denotes x < 3 ∗ n + z

CS4003 Formal Methods

Axioms

I Axioms are statements which are accepted as true in theirown right, and are sometimes shown as inference ruleswith no antecedents:

axiom

I For example. the law of the excluded middle:

Excluded Middle:p ∨ ¬ p

I Often axioms are simply written without any line above:

Axiom, Excluded Middle: p ∨ ¬ p

CS4003 Formal Methods

Equational Axioms of Propositional Calculus

I Axioms are laws taken as true, as a starting pointI Different sets of axioms are possibleI G&S define their own set, of which the following are just a

few:

〈〈≡-assoc〉〉 ((p ≡ q) ≡ r ) ≡ (p ≡ (q ≡ r )) (3.1)

〈〈≡-comm〉〉 p ≡ q ≡ q ≡ p (3.2)

〈〈false-def〉〉 false ≡ ¬ true (3.8)

〈〈∨-comm〉〉 p ∨ q ≡ q ∨ p (3.24)

〈〈golden-rule〉〉 p ∧ q ≡ p ≡ q ≡ p ∨ q (3.35)

〈〈⇒-join〉〉 p ⇒ q ≡ p ∨ q ≡ q (3.57)

The numbers in parentheses are those used in G&S, butthe names are different

CS4003 Formal Methods

The inference rules of Equational Logic

We have four inference rules:

Equanimity:P , P = Q

Q

Transitivity:P = Q, Q = R

P = R

Substitution:P

P [r := Q][no capture]

Leibniz:F = G

E [v := F ] = E [v := G][v a variable]

Page 22: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Inference Rule: Equanimity

P , P = QQ

I If P is true, and we know that P = Q then, we can deducethat Q must be true also.

I Simple, really !I Not actually mentioned in Gries & Schneider (1994), but

used in that text!

CS4003 Formal Methods

Inference Rule: Transitivity

P = Q, Q = RP = R

I If P equals Q and Q equals R,then P equals R.

I This key property of equality allows us to “linearise” ourproofs.

I Assume we know that A = B, B = C , C = D and D = E ,and we want to prove that A = E .

I We get branching — we can use the first two equalities togive us A = C , and the second two to get C = E , and thencombine these.

CS4003 Formal Methods

Proving with Transitivity (I)

I We can use our inference rule notation to illustrate theproof:

A = B B = CA = C

C = D D = EC = E

A = E

I Very unwieldy !

CS4003 Formal Methods

Proving with Transitivity (II)

I However, this very transitivity property allows us to re-writethe proof as

A= “ why A = B ”

B= “ why B = C ”

C= “ why C = D ”

D= “ why D = E ”

E

I Much better !

Page 23: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Predicate textual substitution

I Consider the consequent of Substitution: P [r := Q]

I We do not expect P to appear with an explicit substitution(remember, [r := Q] is not in the language).

I Instead P [r := Q] denotes the case where:I P contains an occurrence of Q within it.I We use variable r to refer to that occurrence of Q

CS4003 Formal Methods

Inference Rule: Substitution

PP [r := Q]

[no capture]

I if predicate P is true,then so is P with all instances of any boolean variable (r )replaced by an arbitrary predicate Q, (provided r does notoccur inside any quantifier binding any free variable of Q— no capture).

I Example:

p ∨ ¬ p(p ∨ ¬ p)[p := (x 6 y + z)]

[p a boolean variable]

I or (performing the substitution)

p ∨ ¬ p(x 6 y + z) ∨ ¬ (x 6 y + z)

[p boolean]

CS4003 Formal Methods

Inference Rule: Leibniz

F = GE [v := F ] = E [v := G]

[v a variable]

I If F = G then, in any predicate/expression E mentioningF , we can replace that mention by G.

I a.k.a. “Substitution of equals for equals”.I Here, E , F and G stand for arbitrary predicates and/or

expressions.I Example

x+x=2∗x

(y−v )[v :=x+x ]=(y−v )[v :=2∗x ]or

x+x=2∗x

y−(x+x )=y−(2∗x )

CS4003 Formal Methods

Theorems and Proofs

I Theorems are predicates that are logical consequences ofthe axioms and inferences rules

I A predicate is shown to be a theorem by providing a proof .I A proof is either:

I an axiomI or a consequence of an inference rule whose premises are

axioms or pre-existing theorems.I in practice, we chain these together using the linear form of

the Transitivity inference rule.

Page 24: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example: R ≡ R ≡ S ≡ S, see G&S,p43

〈〈≡-assoc〉〉 ((p ≡ q) ≡ r ) ≡ (p ≡ (q ≡ r )) (3.1)

〈〈≡-comm〉〉 p ≡ q ≡ q ≡ p (3.2)

R ≡ R ≡ S ≡ S= “ 〈〈≡-comm〉〉 with p = R and q = S ”

R ≡ R= “ 〈〈≡-comm〉〉 with p = R and q = S ”

R ≡ S ≡ S ≡ R“ Axiom 〈〈≡-comm〉〉, so we are done ”

CS4003 Formal Methods

Example: R ≡ R ≡ S ≡ S alt. proof〈〈≡-assoc〉〉 ((p ≡ q) ≡ r ) ≡ (p ≡ (q ≡ r )) (3.1)

〈〈≡-comm〉〉 p ≡ q ≡ q ≡ p (3.2)

R ≡ R ≡ S ≡ S= “ 〈〈≡-comm〉〉 with R, S matching p, q resp. ”

R ≡ S ≡R ≡ S= “ 〈〈≡-comm〉〉 with R, S matching p, q resp. ”

R ≡ S ≡ S ≡ R“ Axiom 〈〈≡-comm〉〉, so we are done ”“ this proof implicitly used 〈〈≡-assoc〉〉 ”

I making implicit use of associativity, commutativity iscommon in hand proofs

I it is not so easy for mechanical proof systems

CS4003 Formal Methods

Theorems of Propositional Calculus

I We build a collection of proven theorems, from axioms,using inferences.

I We can also use these theorems in other proofsI G&S proves many, such as :

〈〈6≡-comm〉〉 (p 6≡ q) ≡ (q 6≡ p) (3.16)

〈〈∨-unit〉〉 p ∨ false ≡ p (3.30)

〈〈∧-assoc〉〉 (p ∧ q) ∧ r ≡ p ∧ (q ∧ r ) (3.37)

〈〈exclusive-or〉〉 p 6≡ q ≡ (¬ p ∧ q) ∨ (p ∧ ¬ q) (3.53)

〈〈⇒-meet〉〉 p ⇒ q ≡ p ∧ q ≡ p (3.60)

And many, many more.

CS4003 Formal Methods

Some Terminology

Conjecture a predicate we believe is true, but with no proof(yet).

Theorem a conjecture for which we have a proof.Law a theorem or an axiom

(i.e. a predicate either given as true, or proven tobe so).

Page 25: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Adding flexibility

I In principle, a proof of P uses the 4 inference rules andaxioms to transform P into axioms (e.g. proof ofR ≡ R ≡ S ≡ S above).

I We can also transform, using laws, to any law, to get aproof.i.e if P and Q are theorems, then so is P ≡ Q

I However, we can also derive new inference rules (a.k.a.derived rules)

I allows better structuring of proofsI in principle can be converted to proof using original four

rules.

CS4003 Formal Methods

Derived Proof Techniques (I)I Reduction: Prove P ≡ Q by converting P to Q (or v.v.)I Deduction: Prove P ⇒ Q by assuming P , and proving Q

careful: variables in P must be treated as constants !I Boolean Case Analysis:

Prove Q[b := P ] byproving Q[b := True] and Q[b := False]

Boolean Case Analysis:Q[b := True] Q[b := False]

Q[b := P ]

I Case Analysis: Prove P by finding Qi , i ∈ 1 . . . n such thatwe can prove (Q1 ∨ . . . ∨ Qn) and Qi ⇒ P for all i

Case Analysis:(Q1 ∨ . . . ∨ Qn) (Qi ⇒ P)i∈1...n

P

CS4003 Formal Methods

Derived Proof Techniques (II)I Mutual Implication:

Prove P ≡ Q by proving P ⇒ Q and Q ⇒ P

Mutual Implication:P ⇒ Q Q ⇒ P

P ≡ Q

I Contradiction: Prove P by proving ¬ P ⇒ false

Contradiction:¬ P ⇒ false

P

I Contrapositive: Prove P ⇒ Q by proving ¬ Q ⇒ ¬ P

Contrapositive:¬ Q ⇒ ¬ P

P ⇒ Q

CS4003 Formal Methods

Mutual Transitivity

I Transitivity works when we mix ≡ and⇒

〈〈⇒-trans〉〉 (p ⇒ q) ∧ (q ⇒ r )⇒ (p ⇒ r ) (3.82)

〈〈≡-⇒-trans〉〉 (p ≡ q) ∧ (q ⇒ r )⇒ (p ⇒ r ) (3.82)

〈〈⇒-≡-trans〉〉 (p ⇒ q) ∧ (q ≡ r )⇒ (p ⇒ r ) (3.82)

I We can mix these in Reduction proofs (here that P ⇒ R):

P⇒ “ why P ⇒ Q ”

Q≡ “ why Q ≡ R ”

R

I We call this⇒-ReductionI Also possible is <-Reduction, using =, < and 6.

Page 26: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example: x + y > 2⇒ (x > 1 ∨ y > 1) (G&S)

I We apply Contrapositive to get:

¬ (x > 1 ∨ y > 1)⇒ ¬ (x + y > 2)= “ 〈〈deMorgan〉〉 ”¬ (x > 1) ∧ ¬ (y > 1)⇒ ¬ (x + y > 2)

I We now use Deduction: assume x < 1 and y < 1 asaxioms, to show x + y < 2

I We now use <-Reduction:

x + y< “ assumption: x < 1, y < 1, arithmetic ”

1 + 1= “ arithmetic ”

2

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Page 27: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 6

CS4003 Formal Methods

Mini-Exercise 1

Q1.1 Evaluate A ∩ elems(trace) = ∅in environment {A 7→ {2,4,6}, trace 7→ 〈1,2,1,3〉}whereI elems takes a list and returns the set of

values in that listQ1.2 Is ∃n : N • n ≥ 3 ∧ prime(n)⇒ prime(n − 1) true

or false? Justify your answerQ1.3 Write one paragraph about a software failure (not

yours) that you found most vexing.

(handwritten, due in at start of 2pm class, Fri.4th October)

CS4003 Formal Methods

Quantifier Axioms

〈〈∀-1pt〉〉 (∀ x • x = E ⇒ P) ≡ P [E/x ], x 6ε E〈〈∃-1pt〉〉 (∃ x • x = E ∧ P) ≡ P [E/x ], x 6ε E〈〈∀-distr〉〉 (∀ x • P) ∧ (∀ x • Q) ≡ (∀ x • P ∧ Q)〈〈∃-distr〉〉 (∃ x • P) ∨ (∃ x • Q) ≡ (∃ x • P ∨ Q)〈〈∀-swap〉〉 (∀ x • ∀ y • P) ≡ (∀ y • ∀ x • P)〈〈∃-swap〉〉 (∃ x • ∃ y • P) ≡ (∃ y • ∃ x • P)〈〈∀-nest〉〉 (∀ x , y • P) ≡ (∀ x • ∀ y • P)〈〈∃-nest〉〉 (∃ x , y • P) ≡ (∃ x • ∃ y • P)〈〈∀-rename〉〉 (∀ x • P) ≡ (∀ y • P [y/x ]), y 6ε P〈〈∃-rename〉〉 (∃ x • P) ≡ (∃ y • P [y/x ]), y 6ε P

〈〈∨-∀-distr〉〉 P ∨ (∀ x • Q) ≡ (∀ x • P ∨ Q) x 6ε P〈〈gen-deMorgan〉〉 (∃ x • P) ≡ ¬ (∀ x • ¬ P)

CS4003 Formal Methods

A Theorem ! Proof ?

¬ (∀ x • R ⇒ ¬ P)= ¬ (∀ x • ¬ R ∨ ¬ P)= ¬ (∀ x • ¬ (R ∧ P))

= ∃ x • R ∧ P

Page 28: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Moving Bindings Around

I the following axioms move bindings around

〈〈∀-swap〉〉 (∀ x • ∀ y • P) ≡ (∀ y • ∀ x • P)〈〈∃-swap〉〉 (∃ x • ∃ y • P) ≡ (∃ y • ∃ x • P)〈〈∀-nest〉〉 (∀ x , y • P) ≡ (∀ x • ∀ y • P)〈〈∃-nest〉〉 (∃ x , y • P) ≡ (∃ x • ∃ y • P)

I often we implicitly use these laws, ignoring binding,nesting, or ordering

I Note these only apply when the quantifier is the same !

(∀ x • ∃ y • P) 6≡ (∃ y • ∀ x • P)

CS4003 Formal Methods

Quantifier Distributivity

I We can distribute a quantifier through the appropriatebinary propositional operator:

〈〈∀-distr〉〉 (∀ x • P) ∧ (∀ x • Q) ≡ (∀ x • P ∧ Q)〈〈∃-distr〉〉 (∃ x • P) ∨ (∃ x • Q) ≡ (∃ x • P ∨ Q)

I To understand these, consider them as repeated and/or:

(P(x1) ∧ P(x2) ∧ . . .) ∧ (Q(x1) ∧ Q(x2) ∧ . . .)≡ ((P(x1) ∧ Q(x1)) ∧ (P(x2) ∧ Q(x2)) ∧ . . .)

(P(x1) ∨ P(x2) ∨ . . .) ∨ (Q(x1) ∨ Q(x2) ∨ . . .)≡ ((P(x1) ∨ Q(x1)) ∨ (P(x2) ∨ Q(x2)) ∨ . . .)

I c.f. “Quantifier Expansion” slide, Class 2.

CS4003 Formal Methods

Mixed Quantifier Distributivity

I We can distribute a quantifier through the “other” binarypropositional operator, under certain circumstances:

〈〈∨-∀-distr〉〉 P ∨ (∀ x • Q) ≡ (∀ x • P ∨ Q) x 6ε P〈〈∧-∃-distr〉〉 P ∧ (∃ x • Q) ≡ (∃ x • P ∧ Q) x 6ε P

I Essentially we can merge P as shown above if it does notmention x .

I Law 〈〈∧-∃-distr〉〉 is a theorem, not an axiom(proof depends on 〈〈gen-deMorgan〉〉, so let’s defer this)

CS4003 Formal Methods

Renaming

I We have already covered this

〈〈∀-rename〉〉 (∀ x • P) ≡ (∀ y • P [y/x ]), y 6ε P〈〈∃-rename〉〉 (∃ x • P) ≡ (∃ y • P [y/x ]), y 6ε P

I We can uniformly replace binding and bound occurrencesof one variable by another,provided the new variable is“fresh”.

I Known for historical reasons as α-renaming.

Page 29: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Generalised de-Morgan

I de-Morgans laws apply to quantifiers:

〈〈gen-deMorgan〉〉 (∃ x • P) ≡ ¬ (∀ x • ¬ P)¬ (∃ x • ¬ P) ≡ (∀ x • P)¬ (∃ x • P) ≡ (∀ x • ¬ P)(∃ x • ¬ P) ≡ ¬ (∀ x • P)

I the first law above is an axiom, the rest are theoremsI Proving the three theorems above involves the axiom, and

the law of involution:

〈〈¬ -invol〉〉 ¬ ¬ p ≡ p

(voluntary exercises !)

CS4003 Formal Methods

Proof of theorem 〈〈∧-∃-distr〉〉

I Goal: P ∧ (∃ x • Q) ≡ (∃ x • P ∧ Q), x 6ε PI Strategy: Reduce left-hand side (lhs) to right-hand side

(rhs)I Proof:

P ∧ (∃ x • Q)

= “ 〈〈gen-deMorgan〉〉 ”P ∧ ¬ (∀ x • ¬ Q)

= “ 〈〈¬ -invol〉〉 ”¬ ¬ P ∧ ¬ (∀ x • ¬ Q)

= “ 〈〈deMorgan〉〉 ”¬ (¬ P ∨ (∀ x • ¬ Q))

= “ 〈〈∨-∀-distr〉〉, noting that if x 6ε P , then x 6ε ¬ P ”¬ (∀ x • ¬ P ∨ ¬ Q)

CS4003 Formal Methods

Proof of theorem 〈〈∧-∃-distr〉〉(cont.,)

I continued, repeat last line above:

¬ (∀ x • ¬ P ∨ ¬ Q)= “ 〈〈deMorgan〉〉 ”¬ (∀ x • ¬ (P ∧ Q))

= “ 〈〈gen-deMorgan〉〉 ”∃ x • P ∧ Q

I Proof complete — from here on we shall adopt this patternof stating:

I Goal — what is to be provedI Strategy — our top-level approachI Proof (Sections) — the gory details

CS4003 Formal Methods

The “one-point” laws

I The “one-point” laws are very important.

〈〈∀-1pt〉〉 (∀ x • x = E ⇒ P) ≡ P [E/x ], x 6ε E〈〈∃-1pt〉〉 (∃ x • x = E ∧ P) ≡ P [E/x ], x 6ε E

I These allow us to get rid of quantifiers.I The key intuition behind them is that having the condition

x = E in the quantifier allows us to focus on that specificvalue of x , rather than considering them all.

I Remember “Logic Example V” in Class 2 ?I Law 〈〈∃-1pt〉〉 will play a key role in the UTP theories we will

explore later on.

Page 30: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

One-point examples

I

∀n • n = 5⇒ prime(n)= “ 〈〈∀-1pt〉〉 ”

prime(n)[5/n]= “ substitution ”

prime(5)= “ prime number theory ”

true

I

∃m • ∃n • prime(m) ∧ n = m + 2 ∧ prime(n)

= “ 〈〈∃-1pt〉〉 ”∃m • (prime(m) ∧ prime(n))[m + 2/n]

= “ substitution ”∃m • prime(m) ∧ prime(m + 2)

CS4003 Formal Methods

Simultaneous one-pointI We can do multiple “points” at once — goal:

(∃ x , y • x = E ∧ y = F ∧ P) ≡ P [E ,F /x , y ], x , y 6εE ,F

I Proof (strategy, reduce lhs to rhs):

∃ x , y • x = E ∧ y = F ∧ P= “ 〈〈∃-1pt〉〉with x , given that x 6ε E ”∃ y • (y = F ∧ P)[E/x ]

= “ substitution, given that x 6ε F ”∃ y • y = F ∧ (P [E/x ])

= “ 〈〈∃-1pt〉〉, given that y 6ε F ”(P [E/x ])[F /y ]

= “ can substitute simultaneously, given that y 6ε E ”P [E ,F /x , y ]

CS4003 Formal Methods

Proof using 1-pt (many, many times …)

I Goal:(∃ t1, t2, x1, x2, y1, y2 •

t1 = x ∧ x1 = x ∧ y1 = y ∧t2 = t1 ∧ x2 = y1 ∧ y2 = y1 ∧x ′ = x2 ∧ y ′ = t2)

≡ x ′ = y ∧ y ′ = x

I Where did this strange example come from ?I Remember { int t; t=x; x=y; y=t } ?

I Strategy: reduce lhs to rhs

CS4003 Formal Methods

Proof using 1-pt, cont.

I Proof:

∃ t1, t2, x1, x2, y1, y2 •t1 = x ∧ x1 = x ∧ y1 = y ∧t2 = t1 ∧ x2 = y1 ∧ y2 = y1 ∧x ′ = x2 ∧ y ′ = t2

= “ 〈〈∃-1pt〉〉, t1, x1, y1 6ε x , y , t2, x2, y2, substitute ”∃ t2, x2, y2 •

t2 = x ∧ x2 = y ∧ y2 = y ∧x ′ = x2 ∧ y ′ = t2

= “ 〈〈∃-1pt〉〉, t2, x2, y2 6ε x , y , substitute ”x ′ = y ∧ y ′ = x

Page 31: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Mini-Exercise 2

Q2.1 For the following predicate, state for every variableoccurrence if it is free, binding or bound:(∀a • (∀b • (∃ c • a ∧ c ∨ b) ∧ (c ∨ ¬ a)) ∨ b)

Q2.2 Perform the following (simultaneous, double)substitution:(∃ t , t ′ • t ′ − t = tr ′ − tr )[t a tr , t ′ a tr ′ / tr , tr ′]Here tr and tr ′ are different variables.

Q2.3 The proof on the slide with title “A Theorem ! Proof?” has no justifications—fill them in.

Use the Proof-Section format described in class. (due in nextFri, 2pm, in class)

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Page 32: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 7

CS4003 Formal Methods

A Simple Imperative Language

I We now turn our attention to a simple (terse) imperativelanguage, with assignment, sequencing, conditionals and awhile-loop:

p,q ∈ Prog ::= skip do nothing| v := e assignment| p; q do p, then do q| p � c � q do p if c, else do q| c ~ p while c do p

I skip does nothing, but is useful to have around.I Assignment uses := (“becomes”) rather than =.I ; is an operator that joins programs together.I For now, we ignore variable declarations.

CS4003 Formal Methods

Program Examples

I Swapping the values of x and y , using t as temporary:

t := x ; x := y ; y := t

I Setting a and b to the maximum and minimum of a and brespectively:

skip � a > b � ( t := a ; a := b ; b := t )

I Setting f to factorial of n, using x as temporary

f := 1 ; x := n ; (x > 1)~ ( f := f ∗ x ; x := x − 1 )

CS4003 Formal Methods

The Meaning of an Imperative Program

I The meaning of an expression (or predicate), is a functionfrom an environment to a value of the appropriate type:

[[E ]] : Env 7→ Value[[P ]] : Env → B

I For a program, the environment maps program variables tovalues, and is often called the program state.

I The meaning of an (deterministic (?), imperative) program,is a function from an initial environment/state to a finalenvironment/state

[[p]] : Env 7→ Env

I Often we refer to a program as a state-transformer .

Page 33: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Denotational Semantics

Defining the meaning of a program as a function from programtext to some mathematical structure, in a compositional way, isknown as a denotational semantics, i.e., a function that returnswhat a program denotes.

[[−]] : Prog → Env 7→ Env[[skip]]ρ =̂ ρ

[[v := e]]ρ =̂ ρ⊕ {v 7→ [[e]]ρ}[[p; q]]ρ =̂ [[q]][[p]]ρ

[[p � c � q]]ρ =̂

{[[p]]ρ, if [[c ]]ρ[[q]]ρ, if ¬ [[c ]]ρ

[[c ~ p]] =̂ µW • λ ρ • if [[c ]]ρ then (W ◦ [[p]])ρ else ρ

The last definition is a mystery left for later.In every case the meaning of a composite is given in terms ofthe meanings of its components (compositionality).

CS4003 Formal Methods

Program Meaning Example I

I Swapping the values of x and y , using t as temporary:

t := x ; x := y ; y := t

I The after-value of x is the before-value of y , and vice-versaI Using our environment notation:

[[t := x ; x := y ; y := t ]]ρ= ρ⊕ {t 7→ ρ(x ), x 7→ ρ(y ), y 7→ ρ(x )}

CS4003 Formal Methods

Program Meaning Example II

I Setting a and b to the maximum and minimum of a and brespectively:

skip � a > b � ( t := a ; a := b ; b := t )

I The after-value of a is the maximum of the before-values ofboth a and b, whilst the after value of b is the minimum.

I Using environments

[[skip � a > b � ( t := a ; a := b ; b := t )]]ρ= ρ⊕ {t 7→ ρ(a),a 7→ ρ(b),b 7→ ρ(a)}, a < b= ρ, a > b

CS4003 Formal Methods

Program Meaning Example IIII Setting f to factorial of n, using x as temporary

f := 1 ; x := n ; (x > 1)~ ( f := f ∗ x ; x := x − 1 )

I If before-value of n is negative, then the after values of fand x are 1 and n respectively, otherwise:

I The after-value of f is the factorial of the before-value of nI The after-value of n is the same as beforeI The after-value of x is 1, except if the before-value of n was

0, in which case so is x ’s after-value.I With environments

[[f := 1 ; x := n ; (x > 1)~ ( f := f ∗ x ; x := x − 1 )]]ρ= ρ⊕ {f 7→ 1, x 7→ ρ(n)}, ρ(n) ∈ {0,1}= ρ⊕ {f 7→ ρ(n)!, x 7→ 1}, ρ(n) > 1= ρ⊕ {f 7→ 1, x 7→ ρ(n)}, ρ(n) < 0

Page 34: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Too much ρ !

I The use of explicit environments is precise, but verboseI we have to distinguish between variable x and its value ρ(x )I we have a language syntax x := e that is different to that

used to express its meaning: ρ⊕ {x 7→ [[e]]ρ}.I To reduce clutter, we adopt some key ideas

I Programs are predicatesI We denote the before-value of program variable x by

predicate variable x .I We denote the after-value of program variable x by

predicate variable x ′.I Programs are now predicates that relate before and after

values.

CS4003 Formal Methods

Programs are Predicates

I Eric Hehner pushed this idea, inspiring Tony Hoare to write“Programs are predicates”, Mathematical logic andprogramming languages, Royal Society of London,pp141–155, 1984.

I Many approaches to programming language semanticskeep the programming language and the semanticslanguage separate

Meaning [[program]] = mathematical stuff

What’s inside the brackets ([[]]) is syntax, outside issemantics

I This distinction is considered by many today as artificialand unnecessary.

CS4003 Formal Methods

Extending our Predicate Language

I We are going to extend our predicate language to includeour program language:

P ,Q ∈ Pred ::= . . .| skip| v := E| P ; Q| P � c � Q| c ~ P

I c denotes a condition (boolean expression)I In effect, we shall define our programming constructs as

shorthand for equivalent predicates

CS4003 Formal Methods

skip is a predicate

I Program skip leaves that state unchanged

skip =̂ x ′ = x ∧ y ′ = y ∧ z ′ = z

(here assuming that our only variables are x , y and z !I We have a little problem here — we need to know which

variables are in scope.

Page 35: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Alphabets

We associate the set of variables in scope with every predicateP :I this set is called the alphabet of the predicate (αP ).I if variable x is in scope, the alphabet contains x and x ′

I all variables mentioned in P must be in αP .I we denote all the un-dashed alphabet variables by inαPI we denote all the dashed alphabet variables by outαP

CS4003 Formal Methods

Alphabet example

I consider the assignment

x := e

in a program where x , y and z are in scope.I e can only mention these three variablesI We have

α(x := e) = {x , x ′, y , y ′, z , z ′}inα(x := e) = {x , y , z}

outα(x := e) = {x ′, y ′, z ′}

CS4003 Formal Methods

Alphabet labelling

We can label language constructs with their alphabet (A, say)I skipA and x :=A eI We can infer alphabets for other language constructsI We often omit alphabets where obvious from contextI We are talking about using “alphabetised predicates” to

give meanings to programs

CS4003 Formal Methods

The “rest”

I Frequently we single out a few variables (zero or more) andjust want to refer to “the rest”.

I We shall use meta-variable S to refer to the set of allprogram (script) variable before values, and S ′ forafter-values.

I S ′ = S means x ′1 = x1 ∧ . . . ∧ x ′n = xn where x1 …xn arethe variables in S.

I If we want to talk about all script variables except x and y(say) we write S\x ,y

I For now, S and S ′ correspond to inα and outα, respectively.

Page 36: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

skip as an alphabetised predicate

I Given A = {S,S ′}:

〈〈skip-def〉〉 skipA =̂ S ′ = S

I All the variables are unchangedI Example, if A is {i , j , k , i ′, j ′, k ′}, then

skipA = ( i ′ = i ∧ j ′ = j ∧ k ′ = k )

CS4003 Formal Methods

x := e as an alphabetised predicate

I Given A = {S,S ′}:

〈〈:=-def〉〉 x :=A e =̂ x ′ = e ∧ S ′\x ′ = S\x

I the after-value of x takes on the value of e, evaluated inthe before-state.

I Example, if A is {i , j , k}, then

j :=A i + k = ( i ′ = i ∧ j ′ = i + k ∧ k ′ = k )

CS4003 Formal Methods

; as a binary predicate operatorI P ; Q is the sequential composition of P with Q.

How is this expressed using our predicate notation?I We phrase its behaviour as follows:

“P ; Q maps before-state S to after-state S ′, when thereexists a mid-state Sm, such that P maps S to Sm, and Qmaps Sm to S ′.”

I We get the following definition:

〈〈; -def〉〉 P ; Q =̂ (∃Sm • P [Sm/S ′] ∧ Q[Sm/S])

I The alphabets involved must satisfy the followingconditions:

outαP = (inαQ)′, {x , . . . , z}′ = {x ′, . . . , z ′}inα(P ; Q) = inαP

outα(P ; Q) = outαQCS4003 Formal Methods

Sequential Composition Example

I Consider program t := x ; x := y , with t , x and y in scope.I We calculate:

t := x ; x := y= “ 〈〈:=-def〉〉 ”

t ′ = x ∧ x ′ = x ∧ y ′ = y ; x := y= “ 〈〈:=-def〉〉 ”

t ′ = x ∧ x ′ = x ∧ y ′ = y ; t ′ = t ∧ x ′ = y ∧ y ′ = y= “ 〈〈; -def〉〉, noting S is t , x , y ”∃ tm, xm, ym •

(t ′ = x ∧ x ′ = x ∧ y ′ = y )[tm, xm, ym/t ′, x ′, y ′]∧ (t ′ = t ∧ x ′ = y ∧ y ′ = y )[tm, xm, ym/t , x , y ]

= “ substitution, twice ”∃ tm, xm, ym • tm = x ∧ xm = x ∧ ym = y∧ t ′ = tm ∧ x ′ = ym ∧ y ′ = ym

Page 37: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Sequential Composition Example, cont.

I We continue:

∃ tm, xm, ym • tm = x ∧ xm = x ∧ ym = y∧ t ′ = tm ∧ x ′ = ym ∧ y ′ = ym

= “ 〈〈∃-1pt〉〉, tm, xm, ym 6ε x , y ”t ′ = x ∧ x ′ = y ∧ y ′ = y

I We see that the net effect is like the simultaneousassignment t , x := x , y ,t now has the value of x , and x has the value of y .

CS4003 Formal Methods

� � as a ternary predicate operator

I P � c � Q, behaves like P ,if c is true, otherwise itbehaves like Q.

I Definition:

〈〈��-def〉〉 P � c � Q =̂ c ∧ P ∨ ¬ c ∧ Q

I Alphabet constraints

inα(P � c � Q) = αc = inαP = inαQoutα(P � c � Q) = outαP = outαQ

CS4003 Formal Methods

� � Example

I Program: skip � a > b � ( t := a ; a := b ; b := t ), withalphabet A = {a,a′,b,b′, t , t ′}

I Meaning:

skipA � a > b � t :=A a ; a :=A b ; b :=A t= “ 〈〈��-def〉〉 ”

a > b ∧ skipA∨¬ (a > b) ∧ ( t :=A a ; a :=A b ; b :=A t )

= “ 〈〈skip-def〉〉, 〈〈:=-def〉〉, 〈〈; -def〉〉, and 〈〈∃-1pt〉〉 ”a > b ∧ a′ = a ∧ b′ = b ∧ t ′ = t∨a < b ∧ a′ = b ∧ b′ = a ∧ t ′ = a

CS4003 Formal Methods

~ as a binary predicate operator

I Program c ~ P checks c , and if true, executes P , andthen repeats the whole process

I We won’t define it yet, instead we give a law that describeshow a while-loop can be “unrolled” once:

〈〈~-unroll〉〉 c ~ P = (P ; c ~ P) � c � skip

If c is False, we skip, otherwise we do P followed by thewhole loop (c ~ P ) once more.

I Alphabet constraints

inα(c ~ P) = αc = inαPoutα(c ~ P) = outαP = (inαP)′

Page 38: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Loop example

f := 1 ; x := n ; (x > 1)~ (f := f ∗ x ; x := x − 1)= “ 〈〈:=-def〉〉 ”

n′ = n ∧ f ′ = 1 ∧ x ′ = x;x := n; (x > 1)~ (f := f ∗ x ; x := x − 1)

There must be a better way !!

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Page 39: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 8

CS4003 Formal Methods

all the other variables …

I Consider computing the semantics of

x := x + y ; y := x − y ; x := x − y

in a scope with variables s, t ,u, v ,w , x , y , zI The program only mentions x and y , but we have to carry

equalities around for s, t , u, w and z .I We can tidy-up using the 1-pt law, but this is tedious and

error prone.I Can we show that the above program swaps the values of

x and y , without mentioning the other variables?I What we need are laws that work at the programming

language level(a.k.a. “Laws of Programming”)

CS4003 Formal Methods

Laws of Imperative Programming

I When we give a law stating that programs p1 and p2 arethe same:

p1 = p2

we are stating that both programs have the samebehaviour, i.e. that they change the state in the same way.

I Given that our programs are predicates, we can simply usepredicate calculus to prove such laws as theorems in theusual way.

I The laws typically show how various combinations oflanguage constructs are related.

CS4003 Formal Methods

(Some) Laws of Programming

I Here P , Q and R stand for arbitrary programs, A for anarbitrary alphabet, x , y and z for arbitrary variables, andc ,e and f for arbitrary expressions

〈〈skip-alt〉〉 skipA = x :=A x , x ∈ A〈〈skip-; -unit〉〉 skip ; P = P〈〈; -skip-unit〉〉 P ; skip = P

〈〈; -assoc〉〉 P ; (Q ; R) = (P ; Q) ; R〈〈:=-seq〉〉 x := e ; x := f = x := f [e/x ]

〈〈:=-swap〉〉 x := e ; y := f = y := f [e/x ] ; x := e,y 6ε e

〈〈��-true〉〉 P � True � Q = P〈〈��-false〉〉 P � False � Q = Q〈〈��-seq〉〉 (P � c � Q) ; R = (P ; R) � c � (Q ; R)

Page 40: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈skip-alt〉〉

I Goal: skipA = x :=A xI Strategy: reduce rhs to lhsI Proof:

x :=A x= “ 〈〈:=-def〉〉, A = {S,S ′} ”

x ′ = x ∧ S ′\x ′ = S\x= “ merge ”S ′ = S

= “ 〈〈skip-def〉〉, A = {S,S ′} ”skipA

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉

I Goal: skip ; P = PI Strategy: reduce lhs to rhsI Proof:

skip ; P= “ 〈〈skip-def〉〉 ”S ′ = S ; P

= “ 〈〈; -def〉〉 ”∃Sm • Sm = S ∧ P [Sm/S]

= “ 〈〈∃-1pt〉〉 ”(P [Sm/S])[S/Sm]

= “ substitution ‘inverse’ ”P

CS4003 Formal Methods

Laws of Substitution

I We have used some “laws of substitution” in our proofs.I These too have a rigorous basis.I First, we promote substitution to be part of our predicate

language:

Pred ::= . . . | P [e1, . . . ,en/v1, . . . , vn]

We assume that substitution has highest precedence(binds tighter) than all other constructs

I Next we define its effect on predicates.

CS4003 Formal Methods

Defining Single Substitution

k [e/x ] =̂ kv [e/x ] =̂ v , v 6= xx [e/x ] =̂ e

(e1 + e2)[e/x ] =̂ e1[e/x ] + e2[e/x ](¬ P)[e/x ] =̂ ¬ P [e/x ]

(P ∧ Q)[e/x ] =̂ P [e/x ] ∧ Q[e/x ](∀ x • P)[e/x ] =̂ ∀ x • P(∀ v • P)[e/x ] =̂ ∀ v • P [e/x ], v 6= x , v 6ε e(∀ v • P)[e/x ] =̂ ∀w • (P [w/v ])[e/x ],

v 6= x , v ε e,w 6ε P ,e, x

The constructs not mentioned above follow the same pattern.We shall now look at the last four lines in more detail.

Page 41: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Substitution and Quantifiers (I)

(∀ x • P)[e/x ] =̂ ∀ x • P

The simplest case: x is simply not free in ∀ x • P ,so nothing changes.

CS4003 Formal Methods

Substitution and Quantifiers (II)

(∀ v • P)[e/x ] =̂ ∀ v • P [e/x ], v 6= x , v 6ε e

I We are not substituting for v , and v does occur in e, sothere is no possibility of name capture.

I We simply recurse to the body predicate P .

CS4003 Formal Methods

Substitution and Quantifiers (III)

(∀ v • P)[e/x ] =̂ ∀w • (P [w/v ])[e/x ],v 6= x , v ε e,w 6ε P ,e, x

I The tricky case, where v occurs in e.I To avoid name capture of v in e:

I Pick a fresh variable w — i.e. one not currently in use.I α-rename the bound and binding occurrences of v to wI Then recurse into the now α-renamed body P .

CS4003 Formal Methods

Laws of single substitution

I We can identify a number of useful laws

〈〈subst-inv〉〉 P [x/y ][y/x ] = P , x 6ε P〈〈subst-comp〉〉 P [e/x ][f /x ] = P [e[f /x ]/x ]〈〈subst-swap〉〉 P [e/x ][f /y ] = P [f /y ][e/x ],

x 6ε f , y 6ε e

I We shall not prove these laws at this pointI to do so requires induction,I over the grammar (?!) of our predicate language

Page 42: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Substitution Law examples

I 〈〈subst-inv〉〉: P [x/y ][y/x ] = P , x 6ε PI (x + y )[z/x ][x/z ] = (z + y )[x/z ] = x + yI The side-condition matters:

(x + y )[y/x ][x/y ] = (y + y )[x/y ] = x + x(x + y )[x/y ][y/x ] = (x + x )[y/x ] = y + y

I 〈〈subst-comp〉〉: P [e/x ][f /x ] = P [e[f /x ]/x ]I x [x + y/x ][z/x ] = (x + y )[z/x ] = z + yI x [(x + y )[z/x ]/x ] = x [z + y/x ] = z + y

CS4003 Formal Methods

Simultaneous Substitution

I Simultaneous substitution does several replacements atonce:

(x + y )[y 2, k + x/x , y ] = y 2 + k + x

I In general, it is not the same as doing each replacementone at a time:

(x +y )[y 2/x ][k +x/y ] = (y 2 +y )[k +x/y ] = (k +x )2 +k +x

I When the first substitution does not introduce the “target ”of the second, then we can do them one at a time.

CS4003 Formal Methods

Laws of Simultaneous Substitution

I Order of substitutions does not matter:〈〈subst-comm〉〉 P [e, f /x , y ] = P [f ,e/y , x ]

I We can merge in later substitutions if they don’t act onearlier replacements:〈〈subst-seq〉〉 P [e/x ][f /y ] = P [e, f /x , y ], y 6ε e

I The above law generalises to many substitutions:

P [e1, . . . ,en/x1, . . . , xn][f /y ] = P [e1, . . . ,en, f /x1, . . . , xn, y ]

(provided y 6ε e1, . . . ,en)

CS4003 Formal Methods

Proof of 〈〈; -assoc〉〉

I Goal: P ; (Q ; R) = (P ; Q) ; RI Strategy: reduce both lhs and rhs to same predicateI Proof: hold on tight!

Page 43: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof 〈〈; -assoc〉〉 (lhs)

P ; (Q ; R)

= “ 〈〈; -def〉〉, {S,S ′} = outαQ ∪ inαR ”P ; (∃Sm • Q[Sm/S ′] ∧ R[Sm/S])

= “ 〈〈; -def〉〉, {S,S ′} = outαP ∪ inαQ ”∃Sn • P [Sn/S ′] ∧ (∃Sm • Q[Sm/S ′] ∧ R[Sm/S])[Sn/S]

= “ defn. of substitution, S 6= Sm ”∃Sn • P [Sn/S ′] ∧ ∃Sm • Q[Sm/S ′][Sn/S] ∧ R[Sm/S][Sn/S]

= “ 〈〈∧-∃-distr〉〉, Sm 6ε P [Sn/S ′] ”∃Sn,Sm • P [Sn/S ′] ∧ Q[Sm/S ′][Sn/S] ∧ R[Sm/S][Sn/S]

= “ 〈〈subst-seq〉〉, S 6ε Sm ”∃Sn,Sm • P [Sn/S ′] ∧ Q[Sm,Sn/S ′,S] ∧ R[Sm/S][Sn/S]

= “ 〈〈subst-comp〉〉, Sm[Sn/S] = Sm ”∃Sn,Sm • P [Sn/S ′] ∧ Q[Sm,Sn/S ′,S] ∧ R[Sm/S]

CS4003 Formal Methods

Proof 〈〈; -assoc〉〉 (rhs)

(P ; Q) ; R= “ 〈〈; -def〉〉, {S,S ′} = outαP ∪ inαQ ”

(∃Sn • P [Sn/S ′] ∧ Q[Sn/S]) ; R= “ 〈〈; -def〉〉, {S,S ′} = outαQ ∪ inαR ”∃Sm • (∃Sn • P [Sn/S ′] ∧ Q[Sn/S])[Sm/S ′] ∧ R[Sm/S]

= “ defn. of substitution, S ′ 6= Sn ”∃Sm • (∃Sn • P [Sn/S ′][Sm/S ′] ∧ Q[Sn/S][Sm/S ′]) ∧ R[Sm/S]

= “ 〈〈∧-∃-distr〉〉, Sn 6ε R[Sm/S] ”∃Sm,Sn • P [Sn/S ′][Sm/S ′] ∧ Q[Sn/S][Sm/S ′] ∧ R[Sm/S]

= “ 〈〈subst-seq〉〉, S ′ 6ε Sn ”∃Sm,Sn • P [Sn/S ′][Sm/S ′] ∧ Q[Sn,Sm/S,S ′] ∧ R[Sm/S]

= “ 〈〈subst-comp〉〉, Sn[Sm/S ′] = Sn ”∃Sm,Sn • P [Sn/S ′] ∧ Q[Sn,Sm/S,S ′] ∧ R[Sm/S]

“ lhs=rhs, with minor re-orderings ” �

CS4003 Formal Methods

Proof using Laws (example)I Goal:

( f := 1 ; x := n ; f := f · x ; x := x − 1 )=

( f := n ; x := n − 1 )

I Strategy: reduce lhs to rhsI Proof:

f := 1 ; x := n ; f := f · x ; x := x − 1= “ 〈〈:=-swap〉〉, f 6ε n ”

f := 1 ; f := f · n ; x := n ; x := x − 1= “ 〈〈:=-seq〉〉 ”

f := 1 · n ; x := n − 1= “ arithmetic ”

f := n ; x := n − 1�

CS4003 Formal Methods

Subtleties with Substitution (I)

Consider the following proof of 〈〈:=-seq〉〉 reducing LHS to RHS:

x := e ; x := f= “ 〈〈:=-def〉〉, A = {S,S ′} ”

x ′ = e ∧ S ′\x ′ = S\x ; x ′ = f ∧ S ′\x ′ = S\x= “ 〈〈; -def〉〉, A = {S,S ′} ”∃Sm • (x ′ = e ∧ S ′\x ′ = S\x )[Sm/S ′]∧ (x ′ = f ∧ S ′\x ′ = S\x )[Sm/x ,S]

= “ substitution, noting that e has no dashed vars ”∃Sm • xm = e ∧ Sm\xm = S\x∧ x ′ = f [Sm/S] ∧ S ′\x ′ = Sm\xm

= “ 〈〈∃-1pt〉〉, Sm 6ε e,S ”x ′ = f [e,S \x /x ,S\x ] ∧ S ′\x ′ = S\x

= “ ignore [S \x /S\x ], 〈〈:=-def〉〉 ”x := f [e/x ]

Page 44: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Subtleties with Substitution (II)

I We might have been tempted to apply 〈〈; -def〉〉 first, “do” thesubstitution, and then use 〈〈:=-def〉〉:

x := e ; x := f= “ 〈〈; -def〉〉 ”∃Sm • (x := e)[Sm/S ′]

∧ (x := f )[Sm/S]

= “ doing substitution into assignment ”∃Sm • x := e

∧ xm := f [Sm/S]

= “ 〈〈:=-def〉〉, twice ”∃Sm • x ′ = e ∧ S ′\x ′ = S\x

∧ x ′m = f [Sm/S] ∧ S ′\x ′ = S\x

I What is x ′m ? We seem to have a problem !

CS4003 Formal Methods

The Problem

I Sequential composition is designed to work with predicatesusing x , S for before-variables, and x ′ and S ′ for aftervariables.

I In x := e, the variable x stands for the program variable,and not its initial value

I We cannot do substitutions safely until we have expandedits definition.

I In fact, we cannot determine what its free variables areuntil it has been expanded.

CS4003 Formal Methods

Non-substitutable Predicates

I Some of our new predicate (programming) constructs arenon-substitutable (n.s.).

I Substitution can only be applied to these once theirdefinitions have been expanded.

I We have assignment as one example, but there are others:

skip P ; Q c ∗ P

I Of the new constructs so far, only conditional issubstitutable:

(P � c � Q)[e/x ] = P [e/x ] � c [e/x ] � Q[e/x ]

CS4003 Formal Methods

Page 45: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 9

CS4003 Formal Methods

Swapping “trick” revisited

I Re-consider computing the semantics of

x := x + y ; y := x − y ; x := x − y

in a scope with variables s, t ,u, v ,w , x , y , zI We’d like to use the laws of programming, so we can ignore

s, t ,u, v ,w and z .I We can’t use 〈〈:=-swap〉〉, because the side-condition does

not hold.I We can’t use 〈〈:=-seq〉〉, because we don’t have two

assignments to the same variable one after the other.I In fact it’s not clear what laws would work: after the first two

assignments we havex ′ = x + y ∧ y ′ = x ∧ S ′\x ′,y ′ = S\x ,y whilst at the end weget x ′ = y ∧ y ′ = x ∧ S ′\x ′,y ′ = S\x ,y .

CS4003 Formal Methods

Simultaneous Assignment

I We introduce a further extension to predicate syntax,simultaneous assignment:

Pred ::= . . .| x1, . . . , xn := e1, . . . ,en

I We introduce shorthands: ~x and ~e for x1, . . . , xn ande1, . . . ,en resp.

I Its meaning is that the expressions e1 through en areevaluated, and then all the xi are updated simultaneously:

〈〈sim-:=-def〉〉~x :=A ~e =̂ x ′1 = e1 ∧ . . . ∧ x ′n = en ∧ S ′\x ′1...x ′n = S\x1...xn ,

A = {S,S ′}, x1, . . . , xn ∈ S

CS4003 Formal Methods

Laws of Simultaneous Assignment (I)I A single assignment to y can always be merged with a

preceding simultaneous assignment to ~x , provided y /∈ ~x :

〈〈sim-:=-merge〉〉 ~x := ~e ; y := f = ~x , y := (~e, f [~e/~x ])

I Proof, reducing lhs to rhs:

~x := ~e ; y := f= “ 〈〈sim-:=-def〉〉, 〈〈:=-def〉〉 ”

~x ′ = ~e ∧ S ′\~x ′ = S\~x ; y ′ = f ∧ S ′\y ′ = S\y= “ 〈〈; -def〉〉, and substitute ”∃Sm • ~xm = ~e ∧ Sm\ ~xm = S\~x∧ y ′ = f [Sm/S] ∧ S ′\y ′ = Sm\ym

= “ 〈〈∃-1pt〉〉, noting ym = y ”~x ′ = ~e ∧ y ′ = f [~e,S \~e /~x ,S\~x ] ∧ S ′\~x ′,y ′ = S\~x ,y

= “ 〈〈sim-:=-def〉〉, ignoring [y ,S \~x ,y /y ,S\~x ,y ] ”~x , y := ~e, f [~e/~x ]

Page 46: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Laws of Simultaneous Assignment (II)I If y ∈ ~x , the sequencing law has to be slightly different

〈〈sim-:=-seq〉〉 ~x , y := ~e, f ; y := g = ~x , y := ~e,g [~e, f /~x , y ]

I Proof, reducing lhs to rhs:

~x , y := ~e, f ; y := g= “ 〈〈sim-:=-def〉〉, 〈〈:=-def〉〉 ”

~x ′ = ~e ∧ y ′ = f ∧ S ′\~x ′,y ′ = S\~x ,y ; y ′ = g ∧ S ′\y ′ = S\y= “ 〈〈; -def〉〉, and substitute ”∃Sm • ~xm = ~e ∧ ym = f ∧ Sm\ ~xm ,ym = S\~x ,y∧∧ y ′ = g [ym,Sm \ym /y ,S\y ] ∧ S ′\y ′ = Sm\ym

= “ 〈〈∃-1pt〉〉 ”~x ′ = ~e ∧ y ′ = g [~e, f ,S \~x ,y /~x , y ,S\~x ,y ] ∧ S ′ = S

= “ 〈〈sim-:=-def〉〉, ignoring [S \~x ,y /S\~x ,y ] ”~x , y := (~e,g)[~e, f /~x , y ]

CS4003 Formal Methods

Swapping Trick Proof

I Goal:x := x + y ; y := x − y ; x := x − y = x , y := y , x

I Proof, reducing lhs to rhs:

x := x + y ; y := x − y ; x := x − y= “ 〈〈sim-:=-merge〉〉 ”

x , y := x + y , (x − y )[x + y/x ] ; x := x − y= “ do substitution ”

x , y := x + y , (x + y )− y ; x := x − y= “ 〈〈sim-:=-seq〉〉 ”

x , y := (x − y )[x + y , (x + y )− y/x , y ], (x + y )− y= “ do substitution ”

x , y := x + y − ((x + y )− y ), (x + y )− y= “ arithmetic ”

x , y := y , x

CS4003 Formal Methods

Messing with notation

I Is simultaneous assignment a programming languageconstruct ?

I Depends on the language:I in languages like C, Java, it is not allowedI in Handel-C it is allowed, as it targets hardware and so we

have real parallelismI It does not matter !

I It is a predicate with a sensible meaningI It is convenient for certain proofsI It can describe outcomes concisely that are not possible

using only single assignments, e.g. x , y := y , x .I Not all predicate language extensions have to be “code”.

CS4003 Formal Methods

Programs as Predicates

I If programs are predicates, then we can join them up usingpredicate notation.

I e.g prog1 ∧ prog2I e.g prog1 ∨ prog2I e.g prog1 ⇒ prog2

I We can also mix them with non-program predicatesI e.g prog ∧ predI e.g prog ∨ predI e.g prog ⇒ pred

I Do these make sense? If so, how?I Are any of these useful?

Page 47: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Programs and Conjunction

I Consider the following:

(x := 2) ∧ (x := 3)(x := 2) ∧ (y := 3)(x := 2) ∧ x = 2(x := 2) ∧ y = 3

I What behaviour do these describe?

CS4003 Formal Methods

Examining (x := 2) ∧ (x := 3)

I

(x := 2) ∧ (x := 3)= “ 〈〈:=-def〉〉, twice ”

x ′ = 2 ∧ S ′\x ′ = S\x ∧ x ′ = 3 ∧ S ′\x ′ = S\x= “ 2 6= 3 ”

false

I Not unexpectedly, we get falsewe cannot assign 2 and 3 to x (at the same time)

CS4003 Formal Methods

Examining (x := 2) ∧ (y := 3)

I

(x := 2) ∧ (y := 3)

= “ 〈〈:=-def〉〉, twice ”x ′ = 2 ∧ y ′ = y ∧ S ′\x ′,y ′ = S\x ,y∧ x ′ = x ∧ y ′ = 3 ∧ S ′\x ′,y ′ = S\x ,y

= “ = is transitive, re-arrange ”x ′ = x ∧ y ′ = y ∧ S ′\x ′,y ′ = S\x ,y∧ x ′ = 2 ∧ y ′ = 3 ∧ x = 2 ∧ y = 3

= “ 〈〈skip-def〉〉 ”skip ∧ x ′ = 2 ∧ y ′ = 3 ∧ x = 2 ∧ y = 3

I true only if x and y start as 2 and 3 resp., and do notchange.

CS4003 Formal Methods

Examining (x := 2) ∧ x = 2

I

(x := 2) ∧ x = 2= “ 〈〈:=-def〉〉 ”

x ′ = 2 ∧ S ′\x ′ = S\x ∧ x = 2

I We get a predicate stating that the assignment occurred, ina starting state where x had value 2.

I It is the same as Skip ∧ x = 2

Page 48: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Examining (x := 2) ∧ y = 3

I

(x := 2) ∧ y = 3= “ 〈〈:=-def〉〉 ”

x ′ = 2 ∧ S ′\x ′ = S\x ∧ y = 3

I We get a predicate stating that the assignment occurred, ina starting state where y had value 3.

CS4003 Formal Methods

Programs and Conjunction—Comment

I Conjoining two programs (prog1 ∧ prog2) easily leads tocontradiction

I Predicateprog ∧ ~x = ~e

describes a run of prog that started in a state wherevariables ~x had values ~e.

I Remember, x := e means x is changed, and that all othervariables are left unchanged .

CS4003 Formal Methods

Programs and Disjunction

I Consider the following:

(x := 2) ∨ (x := 3)(x := 2) ∨ (y := 3)(x := 2) ∨ x = 2

CS4003 Formal Methods

Examining (x := 2) ∨ (x := 3)

I

(x := 2) ∨ (x := 3)= “ 〈〈:=-def〉〉, twice ”

x ′ = 2 ∧ S ′\x ′ = S\x∨ x ′ = 3 ∧ S ′\x ′ = S\x

= “ 〈〈∧-∨-distr〉〉 ”(x ′ = 2 ∨ x ′ = 3) ∧ S ′\x ′ = S\x

I Variable x ends up having either value 2 or 3, and all othervariables are unchanged.

I The choice between 2 or 3 is arbitrary — nothing herestates how that choice is made.

Page 49: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Examining (x := 2) ∨ (y := 3)

I

(x := 2) ∨ (y := 3)

= “ 〈〈:=-def〉〉, twice ”x ′ = 2 ∧ y ′ = y ∧ S ′\x ′,y ′ = S\x ,y∨ x ′ = x ∧ y ′ = 3 ∧ S ′\x ′,y ′ = S\x ,y

= “ 〈〈∧-∨-distr〉〉 ”(x ′ = 2 ∧ y ′ = y ∨ x ′ = x ∧ y ′ = 3) ∧ S ′\x ′,y ′ = S\x ,y

I Either x ends up having value 2, or y ends up equal to 3,and all other variables are unchanged.

I The choice between changing x or y is arbitrary — nothinghere states how that choice is made.

CS4003 Formal Methods

Examining (x := 2) ∨ x = 2

I

(x := 2) ∨ x = 2)= “ 〈〈:=-def〉〉, twice ”

x ′ = 2 ∧ S ′\x ′ = S\x ∨ x = 2

I Either x becomes 2, or we started with x equal to 2 andthen anything could have happened !

I if x is not equal to 2 to start, then it equals 2 at the end andno other variable changes

I if x equals 2 at the beginning, then the final values of allvariables are arbitrary.

CS4003 Formal Methods

Programs and Disjunction—Comment

I Disjoining two programs (prog1 ∨ prog2) denotes anarbitrary choice between the two behaviours.

I Predicateprog ∨ ~x = ~e

tells us that we get:I the behaviour of prog ,

if initial values of ~x are not all equal to ~e;I arbitrary behaviour, if they are all equal.

CS4003 Formal Methods

Programs and Negation

I How do we “not” assign something?

¬ (x := e)

I Let’s calculate:

¬ (x := e)= “ 〈〈:=-def〉〉 ”¬ (x ′ = e ∧ S ′\x ′ = S\x )

= “ 〈〈deMorgan〉〉 ”x ′ 6= e ∨ S ′\x ′ 6= S\x

I So, ¬ (x := e) is any situation whereI either x does not end up with value eI or some other variable gets changed

Page 50: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Programs and Implication

I Consider the following:

(x := 2)⇒ (x := 3)(x := 2)⇒ (y := 3)(x := 2)⇒ x ′ = 2(x := 2)⇒ x ′ ∈ {1, . . . ,10}

CS4003 Formal Methods

Examining (x := 2)⇒ (x := 3)

I

(x := 2)⇒ (x := 3)= “ 〈〈:=-def〉〉, twice ”

x ′ = 2 ∧ S ′\x ′ = S\x ⇒ x ′ = 3 ∧ S ′\x ′ = S\x= “ 〈〈⇒-def〉〉 ”¬ (x ′ = 2 ∧ S ′\x ′ = S\x ) ∨ x ′ = 3 ∧ S ′\x ′ = S\x

= “ 〈〈deMorgan〉〉 ”x ′ 6= 2 ∨ S ′ 6= S ∨ x ′ = 3 ∧ S ′\x ′ = S\x

= “ 〈〈∨-∧-absorb〉〉, with p matched to S ′ 6= S ”x ′ 6= 2 ∨ S ′ 6= S ∨ x ′ = 3

= “ 〈〈⇒-join〉〉, given that x ′ = 3⇒ x ′ 6= 2 ”x ′ 6= 2 ∨ S ′ 6= S

I This can only be true if the assignment x := 2 does nothappen.

CS4003 Formal Methods

Examining (x := 2)⇒ (y := 3)

I

(x := 2)⇒ (y := 3)

= “ 〈〈:=-def〉〉, twice ”x ′ = 2 ∧ y ′ = y ∧ S ′\x ′,y ′ = S\x ,y⇒ x ′ = x ∧ y ′ = 3 ∧ S ′\x ′,y ′ = S\x ,y

= “ 〈〈⇒-def〉〉 ”¬ (x ′ = 2 ∧ y ′ = y ∧ S ′\x ′,y ′ = S\x ,y )∨ x ′ = x ∧ y ′ = 3 ∧ S ′\x ′,y ′ = S\x ,y

= “ 〈〈deMorgan〉〉 ”x ′ 6= 2 ∨ y ′ 6= y ∨ S ′ 6= S∨ x ′ = x ∧ y ′ = 3 ∧ S ′\x ′,y ′ = S\x ,y

= “ 〈〈∨-∧-absorb〉〉, with p matched to S ′\x ′,y ′ 6= S\x ,y ”x ′ 6= 2 ∨ y ′ 6= y ∨ S ′\x ′,y ′ 6= S\x ,y ∨ x ′ = x ∧ y ′ = 3

I Complicated !CS4003 Formal Methods

Examining (x := 2)⇒ x ′ = 2

I

(x := 2)⇒ x ′ = 2)= “ 〈〈:=-def〉〉 ”

x ′ = 2 ∧ S ′\x ′ = S\x ⇒ x ′ = 2= “ 〈〈⇒-def〉〉 ”¬ (x ′ = 2 ∧ S ′\x ′ = S\x ) ∨ x ′ = 2

= “ 〈〈deMorgan〉〉 ”x ′ 6= 2 ∨ S ′\x ′ 6= S\x ∨ x ′ = 2

= “ 〈〈excluded-middle〉〉 ”true ∨ S ′\x ′ 6= S\x

= “ 〈〈∨-zero〉〉 ”true

I This is always true: if we assign 2 to x , then the final valueof x is 2.

Page 51: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Examining (x := 2)⇒ x ′ ∈ {1, . . . ,10}

I

(x := 2)⇒ x ′ ∈ {1, . . . ,10})= “ 〈〈:=-def〉〉 ”

x ′ = 2 ∧ S ′\x ′ = S\x ⇒ x ′ ∈ {1, . . . ,10}= “ 〈〈⇒-def〉〉, 〈〈deMorgan〉〉 ”

x ′ 6= 2 ∨ S ′\x ′ 6= S\x ∨ x ′ ∈ {1, . . . ,10}= “ i ∈ {1, . . . , k , . . . ,n} ≡ i = k ∨ i ∈ {1, . . . , k , . . . ,n} ”

x ′ 6= 2 ∨ S ′\x ′ 6= S\x ∨ x ′ = 2 ∨ x ′ ∈ {1, . . . ,10}= “ 〈〈excluded-middle〉〉 ”

true ∨ S ′\x ′ 6= S\x ∨ x ′ ∈ {1, . . . ,10}= “ 〈〈∨-zero〉〉 ”

true

I This is always true: if we assign 2 to x , then the final valueof x is between 1 and 10.

CS4003 Formal Methods

Programs and Implication—Comment

I Predicate prog1 ⇒ prog2 is true ifI the before-after relationship described by prog1 does not

hold, or …I prog1 holds, and the behaviour described by prog2

somehow includes the behaviour of prog1

I Predicate prog ⇒ pred is true ifI the before-after relationship described by prog does not

hold, or …I prog holds, and the situation described by pred is covered

by the behaviour of prog

CS4003 Formal Methods

Mini-Exercise 3

Q3.1 Prove(∀ x • P) ≡ ¬ (∃ x • ¬ P)

using only the following axioms:

〈〈gen-deMorgan〉〉 (∃ x • P) ≡ ¬ (∀ x • ¬ P)〈〈¬ -invol〉〉 ¬ ¬ p ≡ p

Q3.2 Prove

〈〈; -skip-unit〉〉 P ; skip = P

(due in next Friday, 2pm, in class)

CS4003 Formal Methods

Page 52: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 10

CS4003 Formal Methods

Taking StockI We are playing a BIG formal gameI We have a well-defined extensible language:

Pred ::= true | . . . | ∀ x • P | . . .

I We have given it a well-defined meaning:

[[∃ x • P ]]ρ =̂ . . .

I We have provided rules to do proofs:

F = GE [v := F ] = E [v := G]

I Does it all make sense?

CS4003 Formal Methods

Truth and Provability

I StatementsWe are interested in statements of the following form:

Whenever predicates P1, . . . ,Pn are true, then so is Q.(Let us use Γ as a shorthand for P1, . . . ,Pn).

I Truth — Γ |= QThe above statement is true when, for every environment ρthat makes all the Pi true, we have [[Q]]ρ = True.

I Provability — Γ ` QThe above statement is provable when, given the Pi asassumptions, we can prove Q as a theorem.

CS4003 Formal Methods

Truth vs. ProvabilityI Truth and Provability are not the same thing!I Soundness

A proof system is sound if whenever we can provesomething, it is also true:

Γ ` Q means that Γ |= Q

I CompletenessA proof system is complete if whenever something is true,it can proved to be so:

Γ |= Q means that Γ ` Q

I The “Holy Grail”of formal systems is a sound and completeformal system

Page 53: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Soundness

I Soundess is a critical propertyI Unsound proof systems allow “proofs” of false statements

Very undesirable!I Unsoundness can arise in one of two ways:

I InconsistencyI A proof system is inconsistent if anything can be proved

using itI In particular if we can prove false, we can prove anything.

I Environment Mismatch Even if consistent, a proof systemcan be unsound if our axioms and inference rules areincorrect, and fail to capture the truth properly.

I Ensuring soundness require great care in determiningaxioms and inference rules.

CS4003 Formal Methods

Completeness

I Completeness is a “nice-to-have” propertyI In principle a complete proof-system can be made fully

automatic.I Incompleteness simply means there are some true

properties for which there are no proofs in our formalsystem.

I Gödel’s Incompleteness Theorems (1931):1. Any proof-system powerful enough for arithmetic cannot be

both consistent and complete.2. Any proof-system powerful enough to prove theorems

about itself (arithmetic !), is inconsistent iff it can prove itsown consistency

I Most formal systems we want to use embody arithmeticand so are incomplete as just described.

CS4003 Formal Methods

Meta-mathematics

I Meta-mathematics is the study of mathematics itself, as a“mathematical object”

I A major focus of meta-mathematics is the study ofproof-systems

I There is a large body of soundness and completenessresults out there for different formal systems.

I This course is based on a (mainly) sound but incompletelogic system

I Mainly ???I Yes, but …I We will be extending our language later by adding axioms

of our own …

CS4003 Formal Methods

Relating x := 2 and x ′ ∈ {1, . . . ,10}

I x ′ ∈ {1, . . . ,2} could be viewed as a specification:“pick a number between 1 and 10, call it x ”.

I x := 2 is clearly a program that satisfies that specificationI So does x := 5 (say)I More surprisingly, so does the program x := 2 ; y := 99 !

The spec. says nothing about y (or any other variable).I Interestingly, the “program” x := 2 ∨ x := 5 also satisfies

the specification.

Page 54: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Specifying “pick a number”

I the problem with x ′ ∈ {1, . . . ,10} is that it allows anythingto happen to variables other than x .

I We can strengthen it to require that only x be modified:

x ′ ∈ {1, . . . ,10} ∧ S ′\x ′ = S\x

I This idiom is so common we invent specific notation for it:

x :[x ′ ∈ {1, . . . ,10}

]The outer x : says, “modifying x only,”

I The notation x :[. . .] is called a (specification) “frame”.

CS4003 Formal Methods

Formally introducing frames

I Once again, we extend our predicate language, withspecification frames (n.s.)

Pred ::= . . .| ~x :[P ]

I It asserts P , and that any variable not in ~x is unchanged:

〈〈frame-def〉〉 ~x :[P ] =̂ P ∧ S ′\~x ′ = S\~x , A = {S,S ′}

I Not be confused with [P ], the universal closure of P ,or x : T , asserting that x has type T ,or P [e/x ] where e replaces free x in P .

CS4003 Formal Methods

Satisfying Specifications

I Given specification S =̂ x :[x ′ ∈ {1, . . . ,10}], how do wecheck if an offered program P fully satisfies it?

I P2 =̂ x := 2 clearly satisfies it,and we saw previously that P2 ⇒ S.

I Can we conclude then that we want P ⇒ S as ouracceptance criteria ?

I Problem: predicate P ⇒ S does not give us a yes/noanswer.

I Instead, we get a predicate whose truth depends on thevalues of variables.

CS4003 Formal Methods

Is Implication Satisfaction ?

I Consider x := 2⇒ x :[x ′ ∈ {1, . . . ,10}]I Formally (assuming only x and y in scope):

x := 2⇒ x : [x ′ ∈ {1, . . . ,10}]= “ 〈〈:=-def〉〉, 〈〈frame-def〉〉 ”

x ′ = 2 ∧ y ′ = y ⇒ x ′ ∈ {1, . . . ,10} ∧ y ′ = y )= “ equality substitution (? — see later) ”

x ′ = 2 ∧ y ′ = y ⇒ 2′ ∈ {1, . . . ,10} ∧ y = y= “ set theory, reflexivity of equality ”

x ′ = 2 ∧ y ′ = y ⇒ true ∧ true= “ prop. logic ”

true

I Seems OK.

Page 55: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Implication is not Satisfaction (I)

I Consider y := 99⇒ x :[x ′ ∈ {1, . . . ,10}]I Formally (assuming only x and y in scope):

y := 99⇒ x : [x ′ ∈ {1, . . . ,10}]= “ 〈〈:=-def〉〉, 〈〈frame-def〉〉 ”

x ′ = x ∧ y ′ = 99⇒ x ′ ∈ {1, . . . ,10} ∧ y ′ = y= “ equality substitution (? — see later) ”

x ′ = x ∧ y ′ = 99⇒ x ∈ {1, . . . ,10} ∧ 99 = y

The truth/falsity of this satisfaction question seems to dependon initial x already satisfying the specification, and initial ybeing 99 already!

CS4003 Formal Methods

Implication is not Satisfaction (II)

I Consider x := x + 10⇒ x :[x ′ > y ′]I Formally (assuming only x and y in scope):

x := x + 10⇒ x :[x ′ > y ′]= “ 〈〈:=-def〉〉, 〈〈frame-def〉〉 ”

x ′ = x + 10 ∧ y ′ = y ⇒ x ′ > y ′ ∧ y ′ = y= “ equality substitution (? — see later) ”

x ′ = x + 10 ∧ y ′ = y ⇒ x + 10 > y ∧ y = y= “ logic, arithmetic ”

x ′ = x + 10 ∧ y ′ = y ⇒ x > y − 10

I Program x := x + 10 only satisfies specification x :[x ′ > y ′]if x is greater than y − 10 to begin with.

CS4003 Formal Methods CS4003 Formal Methods

Page 56: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 11

CS4003 Formal Methods

Full Satisfaction (a.k.a. “Refinement”)I Given specification S and program P :

I all before/after-relationships resulting from P must satisfythose required by S

I so P must imply S for all possible variable before- andafter-values

I So we require universal implication,saying that P satisfies S iff

[P ⇒ S]

I Once more, we add special predicate notation, saying thatS is “refined by” P , written S v P

Pred ::= . . . | S v P〈〈v-def〉〉 S v P =̂ [P ⇒ S]

CS4003 Formal Methods

Universal Closure re-visited

I Reminder: notation [P ] asserts that P is true for all valuesof its variables

I [P ] ≡ ∀ x1, . . . , xn • P , FV P ⊆ {x1, . . . , xn}I It satisfies the following laws:

〈〈[]-true〉〉 [true] ≡ true〈〈[]-false〉〉 [false] ≡ false

〈〈[]-∧-distr〉〉 [P ∧ Q] ≡ [P ] ∧ [Q]〈〈[]-idem〉〉 [[P ]] ≡ [P ]

〈〈[]-∀-absorb〉〉 [∀ x1, . . . , xn • P ] ≡ [P ]〈〈[]-1pt〉〉 [x = e ⇒ P ] ≡ [P [e/x ]]〈〈[]-split〉〉 [P ] ≡ [P ] ∧ P [~e/~x ], αP = {~x}

I It does not distribute over logical-or [P ∨ Q] 6≡ [P ] ∨ [Q]

CS4003 Formal Methods

Example: Assignment as Frame refinement

Consider x :[P ] v x := e, assuming x and y in scope,

[x := e ⇒ x :[P ]]= “ 〈〈:=-def〉〉, 〈〈frame-def〉〉 ”

[x ′ = e ∧ y ′ = y ⇒ P ∧ y ′ = y ]= “ 〈〈shunting〉〉 ”

[x ′ = e ⇒ (y ′ = y ⇒ P ∧ y ′ = y )]= “ (A⇒ B ∧ A) ≡ (A⇒ B) ”

[x ′ = e ⇒ (y ′ = y ⇒ P)]= “ 〈〈[]-1pt〉〉 ”

[y ′ = y ⇒ P [e/x ′]]= “ 〈〈[]-1pt〉〉 ”

[ P [e/x ′][y/y ′] ]

Page 57: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Example: x :[x ′ ∈ {1, . . . ,10}] v x := 2

x :[x ′ ∈ {1, . . . ,10}] v x := 2= “ previous slide ”

[ (x ′ ∈ {1, . . . ,10})[2/x ′][y/y ′] ]= “ substitution ”

[2 ∈ {1, . . . ,10}]= “ set theory ”

[true]= “ 〈〈[]-true〉〉 ”

true

CS4003 Formal Methods

Example: wrong-Assignment as Frame refinement

Consider x :[P ] v y := e, assuming x and y in scope,

[y := e ⇒ x :[P ]]= “ 〈〈:=-def〉〉, 〈〈frame-def〉〉 ”

[x ′ = x ∧ y ′ = e ⇒ P ∧ y ′ = y ]= “ 〈〈shunting〉〉 ”

[x ′ = x ⇒ (y ′ = e ⇒ P ∧ y ′ = y )]= “ 〈〈[]-1pt〉〉 ”

[(y ′ = e ⇒ P ∧ y ′ = y )[x ′/x ]]= “ 〈〈[]-1pt〉〉 ”

[(P ∧ y ′ = y )[x/x ′][e/y ′]]= “ substitution ”

[ (P [x/x ′][e/y ′] ∧ e = y ) ]

CS4003 Formal Methods

Example: x :[x ′ ∈ {1, . . . ,10}] 6v y := 99

x :[x ′ ∈ {1, . . . ,10}] v y := 99= “ previous slide ”

[ (x ′ ∈ {1, . . . ,10})[x/x ′][99/y ′] ∧ 99 = y ) ]= “ substitution ”

[x ∈ {1, . . . ,10} ∧ 99 = y ]= “ 〈〈[]-split〉〉 ”

[x ∈ {1, . . . ,10} ∧ 99 = y ]∧ (x ∈ {1, . . . ,10} ∧ 99 = y )[0,0/x , y ]

= “ substitution ”[x ∈ {1, . . . ,10} ∧ 99 = y ] ∧ 0 ∈ {1, . . . ,10} ∧ 99 = 0

= “ set-theory, arithmetic, logic, hand-waving ”false

CS4003 Formal Methods

Equality Substitution

I Earlier, we used a law referred to as “equality substitution”.I If we assert a number of equalities, and something else, it

allows us to use those equalities in the “something else”I Formally:

〈〈=-∧-subst〉〉 x = e ∧ P ≡ x = e ∧ P [e/x ]

I Proof is by induction over the structure of P , so we omit it(consider it an axiom).

I The law still holds if we only substitute e for x in part of P ,rather than all of it. We also have the following theorem:

〈〈=-⇒-subst〉〉 (x = e ∧ P ⇒ Q) ≡ (x = e ∧ P ⇒ Q[e/x ])

Page 58: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Refinement Example: MinMax (I)

I Consider the following specification:

S =̂ x , y :[x , y := max (x , y ),min(x , y )]

I “changing only x and y , ensure that x ends up as themaximum of the two, whilst y is the minimum.”

I We posit the following “code” as a solution:

Q =̂ skip � x ≥ y � x , y := y , x

I Does Q refine S ?

CS4003 Formal Methods

S v Q? Solution (Ia)

x , y :[x , y := max (x , y ),min(x , y )]v skip � x ≥ y � x , y := y , x

= “ 〈〈v-def〉〉 ”[skip � x ≥ y � x , y := y , x⇒ x , y :[x , y := max (x , y ),min(x , y )]

]= “ 〈〈��-def〉〉 ”[

x ≥ y ∧ skip ∨ x < y ∧ x , y := y , x⇒ x , y :[x , y := max (x , y ),min(x , y )]

]= “ (A ∨ B ⇒ C) ≡ (A⇒ C) ∧ (B ⇒ C) ”

(x ≥ y ∧ skip⇒ x , y :[x , y := max (x , y ),min(x , y )])∧ (x < y ∧ x , y := y , x⇒ x , y :[x , y := max (x , y ),min(x , y )])

CS4003 Formal Methods

S v Q? Solution (Ib)

= “ 〈〈[]-∧-distr〉〉 ”[x ≥ y ∧ skip⇒ x , y :[x , y := max (x , y ),min(x , y )]

]∧[

x < y ∧ x , y := y , x⇒ x , y :[x , y := max (x , y ),min(x , y )]

]= “ 〈〈skip-def〉〉, 〈〈frame-def〉〉(2), 〈〈sim-:=-def〉〉 ”[

x ≥ y ∧ x ′ = x ∧ y ′ = y⇒ x ′ = max (x , y ) ∧ y ′ = min(x , y )

]∧[

x < y ∧ x ′ = y ∧ y ′ = x⇒ x ′ = max (x , y ) ∧ y ′ = min(x , y )

]

CS4003 Formal Methods

S v Q? Solution (Ic)

= “ 〈〈shunting〉〉(2) ”[x ′ = x ∧ y ′ = y ⇒ x ≥ y⇒ x ′ = max (x , y ) ∧ y ′ = min(x , y )

]∧[

x ′ = y ∧ y ′ = x ⇒ x < y⇒ x ′ = max (x , y ) ∧ y ′ = min(x , y )

]= “ 〈〈[]-1pt〉〉(2), replacing x ′ and y ′ ”[

x ′ = x ∧ y ′ = y ⇒x ≥ y ⇒ x = max (x , y ) ∧ y = min(x , y )

]∧[

x ′ = y ∧ y ′ = x ⇒x < y ⇒ y = max (x , y ) ∧ x = min(x , y )

]

Page 59: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

S v Q? Solution (Id)

= “ properties of max and min ”[x ′ = x ∧ y ′ = y ⇒ true]∧

[x ′ = y ∧ y ′ = x ⇒ true]= “ 〈〈⇒-r-zero〉〉 ”

[true] ∧ [true]= “ 〈〈[]-true〉〉 ”

true ∧ true= “ logic ”

true�

CS4003 Formal Methods

Refinement Example: MinMax (II)

I Given the following (familiar) program

P =̂ x := x + y ; y := x − y ; x := x − y

I Can we replace x , y := y , x in Q by P and still have itrefine S ?

CS4003 Formal Methods CS4003 Formal Methods

Page 60: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 12

CS4003 Formal Methods

Mini-Issues (1–3)

A number of issues have been raised by class members whileworking through the mini-exercises:I Precisely how to interpret laws, when doing matching

against them.I The strange notation P(b).

We address these briefly.

CS4003 Formal Methods

Pattern Matching Laws

Consider, for example, the following laws:

(∃ x • P) ≡ (¬ (∀ x • ¬ P))

v := e ≡ v ′ = e ∧ S ′ = S

x , v ′ are regular observation variables, P is a predicate variable,e is an expression variable, and v is a program variable.In general these match anything of the corresponding type.The exception is when such a variable has been definedelsewhere to mean something specific. In such a case avariable can only match itself.So far the only example we have seen of this is when we havedefined a specific alphabet. S,S ′ are list-variables that matchthemselves, or the alphabet, if known.

CS4003 Formal Methods

What is P(b)?

Previously, we saw a law of the form

(∀b : B • P(b)) ≡ P(False) ∧ P(True)

Here, the intended meaning of P(b) is that P is a predicate that(possibly) mentions b, as a free variable.Then P(True) is P with all such free b replaced by True.It is a convenient shorthand, more formally written as

(∀b : B • P) ≡ P [False/b] ∧ P [True/b]

Page 61: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

re-examining Refinement

I Consider the following laws:

〈〈v-refl〉〉 P v P〈〈v-trans〉〉 (S v Q) ∧ (Q v P)⇒ (S v P)〈〈v-anti〉〉 (P = Q) ≡ (P v Q) ∧ (Q v P)

What do they say about refinement ?I It is a partial order.

CS4003 Formal Methods

Partial Orders (reminder)

I A set S, with a binary relation 4 between its elements, iscalled a partial order (p.o.) iff:

I the relation is reflexive: ∀ x : S • x 4 xI the relation is transitive:∀ x , y , z : S • x 4 y ∧ y 4 z ⇒ x 4 z

I the relation is anti-symmetric:∀ x , y : S • x 4 y ∧ y 4 x ⇒ x = y

I Examples:I (N,6), natural numbers under usual numeric ordering.I (PT ,⊆), sets, under the subset relation.I (Pred ,⇒), predicates, under the implication relation.I (Pred ,v), predicates, under the refinement relation.

I Partiality: in general some of these orders are partial, inthat, given arbitrary x and y , it may not be the case thateither x 4 y or y 4 xe.g. {1,2} 6⊆ {3} and {3} 6⊆ {1,2}

CS4003 Formal Methods

Meet and Join (a.k.a. Min and Max)

I Given two elements x and y in a p.o.„ we can ask if theirminimum or maximum exists under that ordering.

I We refer to the minimum as the “meet” (u), and themaximum as the “join” (t).

I If x 4 y then the meet of x and y is x , and their join is y .

(x u y = x ) ≡ (x 4 y ) ≡ (x t y = y )

I Meets and joins exists for all our examples so far:I (N,6), meet is minimum, join is maximumI (PT ,⊆), meet is intersection, join is union.I (Pred ,⇒), meet is logical-and, join is logical-or.

CS4003 Formal Methods

Meet and Join in Refinement

I We use the general symbols u and t to stand for meet andjoin with respect to the refinement ordering

I Meet and Join for refinement have simple definitions.

〈〈u-def〉〉 P u Q =̂ P ∨ Q〈〈t-def〉〉 P t Q =̂ P ∧ Q

I From these we can deduce the following laws:

〈〈v-join〉〉 (P v Q) ≡ (P t Q ≡ Q)〈〈v-meet〉〉 (P v Q) ≡ (P u Q ≡ P)

I A p.o. in which meets and joins exists for all pairs ofelements is called a Lattice.

Page 62: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Complete Lattices

I A lattice is Complete if meets and joins (maxima/minima)can be found for arbitrary sets of elements:

I de S — the minimum of all the elements of SI⊔

S — the maximum of all the elements of SI Not all of our examples are complete lattices:

I (N,6) is not complete — what is the maximum element ofthe set of all even naturals?

I The following are complete lattices:I PT ,⊆, take

⋂and

⋃.

I (Pred ,⇒), take ∀, ∃(?).

CS4003 Formal Methods

Complete Lattices: a Key Property

I A complete lattice (S,4) has overall maximum andminimum elements

I The minimal element (⊥ or “bottom”) is simply

⊥ =̂ de S

I The maximal element (> or “top”) is simply

> =̂⊔

S

I Clearly. both top and bottom satisfy the following laws:

⊥ 4 x , for all x ∈ Sx 4 >, for all x ∈ S

CS4003 Formal Methods

Refinement is a Complete LatticeI The set of all predicates under the refinement relation

forms a complete latticeI

P u Q ≡ P ∨ QP t Q ≡ P ∧ Qde S ≡

∨S

de {P1, . . . ,Pn} ≡ P1 ∨ . . . ∨ Pn⊔S ≡

∧S⊔

{P1, . . . ,Pn} ≡ P1 ∧ . . . ∧ Pn

I The minimal events:

⊥ ≡ truetrue v P> ≡ falseP v false

CS4003 Formal Methods

What are true and false ?I So, we have

true v P v false

for any predicate P .I In terms of our interpretation of predicates as programs

and/or specifications, what do true and false denote?I true is the weakest possible specification (“whatever”) or

the most badly behaved program (“do anything”)I We shall call it “Chaos” (a.k.a “abort”)

Chaos =̂ true

I false is capable of satisfying any specification !I We shall call it “miracle” (a.k.a. “magic”).

miracle =̂ false

Page 63: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Implication Lattice

relating predicates with universal implication ([ ⇒ ]),:

false strong

x ′ = 3 x ′ = 6

x ′ = 3 ∨ x ′ = 6

x ′ ∈ {1 . . . 10}

true weak

CS4003 Formal Methods

Refinement Lattice

relating programs/specifications with refinement (v):

miracle prog.

x := 3 x := 6

x := 3 u x := 6

x : [x ′ ∈ {1 . . . 10}]

Chaos spec.

v

CS4003 Formal Methods

The Theology of Computing

miracle prog.

x := 3 x := 6

x := 3 u x := 6

x : [x ′ ∈ {1 . . . 10}]

Chaos spec.

v

CS4003 Formal Methods

Refinement

I The notion of Refinement, relating a specification to anyprogram that satisfies it, is key in formal methods.

I In our formalism, UTP, it (v) is defined as“universally-closed ( [ ] ) reverse implication (⇐):

〈〈v-def〉〉 S v P =̂ [S ⇐ P ]

I The key thing to remember is the reversal of theimplication, e.g.

S v P ≡ [P ⇒ S]

Page 64: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Laws of Implication

I There are many laws of implication:

〈〈⇒-refl〉〉 P ⇒ P ≡ true〈〈⇒-trans〉〉 (P ⇒ Q) ∧ (Q ⇒ R)⇒ (P ⇒ R)

〈〈≡-⇒-trans〉〉 (P ≡ Q) ∧ (Q ⇒ R)⇒ (P ⇒ R)〈〈⇒-≡-trans〉〉 (P ⇒ Q) ∧ (Q ≡ R)⇒ (P ⇒ R)

〈〈strengthen-ante〉〉 P ∧ Q ⇒ P〈〈weaken-cnsq〉〉 P ⇒ P ∨ Q〈〈ante-∨-distr〉〉 P ∨ Q ⇒ R ≡ (P ⇒ R) ∧ (Q ⇒ R)〈〈cnsq-∧-distr〉〉 P ⇒ Q ∧ R ≡ (P ⇒ Q) ∧ (P ⇒ R)

I As refinement is defined as “universally-closed reverseimplication”, we expect to derive many refinement lawsfrom these, and similar laws.

CS4003 Formal Methods

(some) Laws of Refinement

〈〈v-refl〉〉 P v P〈〈v-trans〉〉 (S v Q) ∧ (Q v P)⇒ (S v P)〈〈v-anti〉〉 (P = Q) ≡ (P v Q) ∧ (Q v P)

〈〈≡-v-trans〉〉 (S = Q) ∧ (Q v P)⇒ (S v P)〈〈v-≡-trans〉〉 (S v Q) ∧ (Q = P)⇒ (S v P)〈〈v-prog-alt〉〉 S v P ∨ Q ≡ (S v P) ∧ (S v Q)〈〈v-spec-split〉〉 S ∧ T v P ≡ (S v P) ∧ (T v P)〈〈≡-imp-v〉〉 (P = Q)⇒ (P v Q)

〈〈spec-weakening〉〉 S ∨ T v T〈〈prog-strengthen〉〉 P v P ∧ Q

CS4003 Formal Methods

Exploring the Refinement Laws (I)

I P v P 〈〈v-refl〉〉Anything refines itself (trivially).

I (P = Q)⇒ (P v Q) 〈〈≡-imp-v〉〉Equality is a (fairly trivial) refinement.

I (P = Q) ≡ (P v Q) ∧ (Q v P) 〈〈v-anti〉〉Two programs/specifications are equal if they refine eachother.

I (S v Q) ∧ (Q v P)⇒ (S v P) 〈〈v-trans〉〉If Q refines S, and P refines Q, then P also refines S.We can do refinement in several steps.

I (S = Q) ∧ (Q v P)⇒ (S v P) 〈〈≡-v-trans〉〉(S v Q) ∧ (Q = P)⇒ (S v P) 〈〈v-≡-trans〉〉A refinement step can also be a replacement by somethingequal.

CS4003 Formal Methods

Exploring the Refinement Laws (II)

I S v P ∨ Q ≡ (S v P) ∧ (S v Q) 〈〈v-prog-alt〉〉Refining by an arbitrary choice of alternatives is the sameas refining by both options individually

I S ∧ T v P ≡ (S v P) ∧ (T v P) 〈〈v-spec-split〉〉Satisfying a specification with two mandatory parts is thesame as satisfying both parts individually.

I S ∨ T v T 〈〈spec-weakening〉〉A specification offering alternatives can be satisfied bychoosing one of those alternatives

I P v P ∧ Q 〈〈prog-strengthen〉〉A specification can be refined by adding in extraconstraints.

Page 65: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proving some refinement laws

I Select and do in class.I Note the following meta-theorem:

I If P is a theorem, then so is [P ]I Why: because if P is a theorem, then it is true for all

instantiations of variables it contains. So, it remains true ifwe quantify over the expression variables.

CS4003 Formal Methods

Proof of 〈〈≡-v-trans〉〉

I Goal: (S = Q) ∧ (Q v P)⇒ (S v P).I Strategy: reduce to law 〈〈⇒-≡-trans〉〉.I Proof:

(S = Q) ∧ (Q v P)⇒ (S v P)= “ 〈〈v-def〉〉 ”

S = Q ∧ [P ⇒ Q]⇒ [P ⇒ S]= “ equality substitution, S = Q ”

S = Q ∧ [P ⇒ Q]⇒ [P ⇒ Q]= “ 〈〈strengthen-ante〉〉 ”

true�

CS4003 Formal Methods

Mini-Exercise 4

Q4.1 Prove law ~x :[A] v ~x :[A ∧ B]

(due in next Friday, 2pm, in class)

CS4003 Formal Methods

Page 66: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 13

CS4003 Formal Methods

Exploring the Refinement Laws (III)

I Consider the addition of a notation for arrays into ourexpression language.

I If a is an array, then ai denotes the i th element.I We assume the array elements are indexed from 1 . . .N .

CS4003 Formal Methods

Find index of a valueI Consider specification spec :

p :[ap′ = w � w ∈ a � p′ = 0

]Modifying p, set it equal to the index of an element in thearray equal to w , otherwise zero.

I Consider prog1:

p := 1; (ap 6= w ∧ p < N)~ p := p + 1; p := 0 � p = N � skip

I Consider prog2:

p := N; (ap 6= w ∧ p > 0)~ p := p − 1

CS4003 Formal Methods

Running the programs

I Consider starting state

w = 3 ∧ a =1

22

13

34

15

36

2 (N = 6)

I Running prog1 results in the final outcome:

p′ = 3

(it searches left-to-right)I Running prog2 results in the final outcome:

p′ = 5

(it searches right-to-left)

Page 67: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Relating spec and the progi

I We see that both programs refine the specification:

spec v progi , i ∈ 1,2

I Both programs, however, have different outcomes.

prog1 6= prog2

(p′ = 3 vs. p′ = 5).I An arbitrary choice between the programs also refines the

spec:spec v prog1 ∨ prog2

(p′ = 3 ∨ p′ = 5)

CS4003 Formal Methods

Refinement and non-determinism

I The programs are deterministic

prog1 search left-to-rightprog2 search right-to-left

I The choice between them has some non-determinism

prog1 ∨ prog2 search either l-to-r, or r-to-l

I The specification has lots of non-determinism

spec search any which-way

I Refinement is essentially about reducing non-determinism.

CS4003 Formal Methods

Program-Oriented Refinement Laws

I Most of the refinement laws seen to date are derived fromthe implication laws.

I We have others as well, based on language constructs:

〈〈v-:=〉〉 x ′ = e v x := e〈〈v-sim-:=〉〉 ~x ′ = ~e v ~x := ~e〈〈:=-lead〉〉 P v x := e ; P , x 6ε P〈〈:=-trail〉〉 P v P ; x := e, x ′ 6ε P

〈〈sim-:=-lead〉〉 P v ~x := ~e ; P , ~x 6ε P〈〈sim-:=-trail〉〉 P v P ; ~x := ~e, ~x ′ 6ε P

〈〈v-; 〉〉 (S1 v P1) ∧ (S2 v P2)⇒ (S1 ; S2) v (P1 ; P2)

I The conditions x /∈ P and x ′ /∈ P exclude a lot, e.g. allassignment statements (why?)

CS4003 Formal Methods

Proof of 〈〈v-:=〉〉

x ′ = e v x := e= “ 〈〈:=-def〉〉 ”

x ′ = e v x ′ = e ∧ S ′\x ′ = S\x= “ 〈〈v-def〉〉 ”

[ x ′ = e ∧ S ′\x ′ = S\x ⇒ x ′ = e ]= “ prop. law: A ∧ B ⇒ A ”

[true]= “ 〈〈[]-true〉〉 ”

true

Page 68: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈:=-trail〉〉

P v P ; x := e= “ 〈〈v-def〉〉,〈〈:=-def〉〉 ”

[ P ; x ′ = e ∧ S ′\x ′ = S\x ⇒ P ]= “ 〈〈; -def〉〉 ”

[ (∃ xm,Sm\xm • P [xm,Sm \xm /x ′,S ′\x ′ ]∧ (x ′ = e ∧ S ′\x ′ = S\x )[xm,Sm \xm /x ,S\x ])⇒ P ]

= “ substitution, noting x ′ 6ε P ”[ (∃ xm,Sm\xm • P [Sm \xm /S ′\x ′ ]∧ x ′ = e[xm,Sm \xm /x ,S\x ] ∧ S ′\x ′ = Sm\xm )⇒ P ]

(cont. overleaf)

CS4003 Formal Methods

Proof of 〈〈:=-trail〉〉 (cont.)

[ (∃ xm,Sm\xm • P [Sm \xm /S ′\x ′ ]∧ x ′ = e[xm,Sm \xm /x ,S\x ] ∧ S ′\x ′ = Sm\xm )⇒ P ]

= “ 〈〈∃-1pt〉〉 ”[ (∃ xm • P [Sm \xm /S ′\x ′ ][S ′ \x ′ /Sm\xm ]∧ x ′ = e[xm,Sm \xm /x ,S\x ][S ′ \x ′ /Sm\xm ] )⇒ P ]

= “ 〈〈subst-inv〉〉,〈〈∧-∃-distr〉〉 with xm 6ε P ”[ P ∧ (∃ xm • x ′ = e[xm,S ′ \x ′ /x ,S\x ][S ′ \x ′ /Sm\xm ] ) ⇒ P ]

= “ prop. law: A ∧ B ⇒ A ”[true]

= “ 〈〈[]-true〉〉 ”true

CS4003 Formal Methods

Real Life: BASE Trusted Gateway

Goal — Trusted Gateway for transferring messagesbetween different security levels,for British Aerospace Systems & Equipment.

Approach — Two teams, one conventional, the other usingformal methods.

Method — Formal team employed VDM-SL, using IFADToolkit.

Who — T.M.Brookes, J.S.Fitzgerald & P.G.Larsen,“Formal and Informal Specifications of a SecureSystem Component”in FME’96: Industrial Benefit and Advances inFormal Methods,LNCS 1051, pp214–227, 1996.

CS4003 Formal Methods

BASE: Key Results (1)

I Formal approach spent more time up front in SystemDesign (43% as against 34%).

I Formal approach uncovered an implicit special conditionfrom requirements.Informal code had to be re-written at late stage to cope.

I Formal code was less complex (“McCabe Complexity”)I Formal code one-fifth the size of informal code.

Page 69: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

BASE: Key Results (2)

Formal system started up slower(4 times longer)

1. Formal System Invariant better understood, so more carewas taken by resulting initialisation code.

2. Not a big issue as the system is meant to stay up andrunning.

CS4003 Formal Methods

BASE: Key Results (3)

Formal system throughput higher(almost 14 times faster)

1. The informal system had to have a last-minute fix, so thecode speed got worse.

2. If code is formally verified, then you don’t need so manyrun-time checks (array bounds, etc.)

CS4003 Formal Methods

Reasoning about Loops

I So far we have one law regarding loops, that “unrolls” once:

〈〈~-unroll〉〉 c ~ P = (P ; c ~ P) � c � skip

I This has limited utility, as we often want to reason aboutarbitrary numbers of “un-rollings”.

CS4003 Formal Methods

Loop SemanticsI What is the meaning of c ~ P ?I Let us call it W .I It must satisfy the un-rolling law:

W = (P ; W ) � c � skip

I It must also be the the least predicate that satisfies this law:

(X = (P ; X ) � c � skip)⇒W v X

I These results come from a branch of mathematics called“fixpoint theory”

I The “meaning” of recursion is (typically) the least fixed pointof an appropriate higher-order function

I We shall not concern ourselves with this at present.

Page 70: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Infinite Loops

I What is the meaning of true~ skip ?I It is an infinite loop, so call it ForeverI It must satisfy the un-rolling law:

Forever = (skip; Forever ) � true � skip= skip; Forever

I However, all of the following satisfy this instance of theun-rolling law:

I miracle = skip ; miracleI skip = skip ; skipI Chaos = skip ; ChaosI P = skip ; P for any P (It’s law 〈〈skip-; -unit〉〉) !

I Why pick the least of these as the meaning of Forever ?

CS4003 Formal Methods

Forever is bad

I Every predicate satisfies the Forever unrolling law,including miracle and Chaos, our two extremes.

I It makes no sense to pick a predicate “in the middle”, sowhich extreme point should we use ?

I If we use miracle, then Forever refines any specification,which is not desirable at all.

I It makes sense to choose Chaos, as it is least in ourordering, and the only thing refining it is itself.

I So Forever = Chaos = trueSo Chaos covers all unpredictable/undesirable behaviour,including non-termination.

CS4003 Formal Methods CS4003 Formal Methods

Page 71: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 14

CS4003 Formal Methods

Loop Reasoning

I Given a loop c ~ P , and possible candidate W :I checking the unroll-law is not too bad:

W = (P ; W ) � c � skip

I checking for the least such fixpoint is painful:

(X = (P ; X ) � c � skip)⇒W v X , for any X

I Fortunately, in many cases, the fixpoint is unique.I We won’t characterise the unique cases here (quite

technical).I Instead we shall just use the unroll check.I A challenge still remains: finding W !

CS4003 Formal Methods

A Simple example (I)I Our specification: summing (natural) numbers between 1

and n:

SSum =̂ s, i :

s′ =∑

j∈1...n

j

.

I Our program:

PSum =̂ s := 0 ; i := n ; (i > 0)~(s := s+i ; i := i−1)

I Our goal, to prove the program satisfies our specification:

SSum v PSum

I We assume all variables are natural numbers1.1a.k.a. “unsigned int” CS4003 Formal Methods

A convenient shorthand

I To simplify matters we defined the following shorthand

S(m) =̂∑

i∈1...m i

So S(m) is the sum of numbers from 1 to m.I Note that i above is local, being bound by the

∑operator.

I It obeys the following laws:

S(0) = 0S(n) = S(n − 1) + n, n > 0

I Our specification becomes:

SSum =̂ s, i :[s′ = S(n)]

Page 72: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Simple example (II)I Our strategy, to split the spec and program into two parts:

initialisation and the loop, and do these separately:

SInit v PInitSLoop v PLoop

I Here, we have

PInit =̂ s := 0 ; i := nPLoop =̂ (i > 0)~ (s := s + i ; i := i − 1)

I We then use the following law of refinement (〈〈v-; 〉〉) tocomplete:

(S1 v P1) ∧ (S2 v P2)⇒ (S1 ; S2) v (P1 ; P2)

I The question now is, what are SInit and SLoop ? CS4003 Formal Methods

A Simple example (III — SInit v PInit )

I We take a simple approach here, setting SInit = PInitI

PInit= “ defn. ”

s := 0; i := n= “ 〈〈sim-:=-merge〉〉 ”

s, i := 0,n= “ 〈〈sim-:=-def〉〉 ”

s′ = 0 ∧ i ′ = n ∧ n′ = n= “ by design ”

SInit

CS4003 Formal Methods

A Simple example (IV — SLoop v PLoop)

I Our loop specification says we sum on top of starting svalue:

SLoop =̂ s, i :[s′ = s + S(i)

]I But what is PLoop ?I We need to find W such that

W = (s := s + i ; i := i − 1 ; W ) � i > 0 � skip

I Do we guess ? informed guess ? informed by what ?

CS4003 Formal Methods

A Simple example (V — “guessing” W )

I We suggest the following definition for W :

W =̂ i ′ = 0 ∧ s′ = s + S(i) ∧ n′ = n

I It iterates until i = 0, so hence i ′ = 0.I It sums from starting i down to 1I It adds on top of the starting value of sI It does not change n.

Page 73: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Simple example (VI.a — simplifying W )

I It is useful to do some pre-computation:

i = 0 ∧W= “ defn. W ”

i = 0 ∧ i ′ = 0 ∧ s′ = s + S(i) ∧ n′ = n= “ equality substitution ”

i = 0 ∧ i ′ = 0 ∧ s′ = s + S(0) ∧ n′ = n= “ arithmetic ”

i = 0 ∧ i ′ = 0 ∧ s′ = s ∧ n′ = n= “ 〈〈skip-def〉〉 ”

i = 0 ∧ skip

CS4003 Formal Methods

A Simple example (VI.b — simplifying W )

I More pre-computation (here ignoring n and n′ for brevity):

i > 0 ∧ (s := s + i ; i := i − 1 ; W )= “ defn. W , ”

i > 0 ∧ (s′ = s + i ∧ i ′ = i − 1 ;i ′ = 0 ∧ s′ = s + S(i))

= “ 〈〈; -def〉〉, substitution ”i > 0 ∧ (∃ sm, im • sm = s + i ∧ im = i − 1 ;

i ′ = 0 ∧ s′ = sm + S(im))= “ 〈〈∃-1pt〉〉 ”

i > 0 ∧ i ′ = 0 ∧ s′ = s + i + S(i − 1)= “ arithmetic ”

i > 0 ∧ i ′ = 0 ∧ s′ = s + S(i)= “ defn. W ”

i > 0 ∧W

CS4003 Formal Methods

A Simple example (VII — checking W )

I We need to check our W is a fixed-point:

(s := s + i ; i := i − 1 ; W ) � i > 0 � skip= “ 〈〈��-def〉〉, 〈〈sim-:=-merge〉〉 ”

i > 0 ∧ (s, i := s + i , i − 1 ; W ) ∨ i = 0 ∧ skip= “ previous calculations ”

i > 0 ∧W ∨ i = 0 ∧W= “ 〈〈∧-∨-distr〉〉 ”

(i > 0 ∨ i = 0) ∧W= “ 〈〈excluded-middle〉〉, noting i : N ”

true ∧W= “ 〈〈∧-unit〉〉 ”

W

CS4003 Formal Methods

A Simple example (VIII — SLoop vW )

I We need to show that W , our semantics for PLoop does infact refine the loop specification.

SLoop vW= “ defns. ”

[ i ′ = 0 ∧ s′ = s + S(i) ∧ n′ = n⇒s, i :[s′ = s + S(i)] ]

= “ 〈〈frame-def〉〉 ”[ i ′ = 0 ∧ s′ = s + S(i) ∧ n′ = n⇒s′ = s + S(i) ∧ n′ = n ]

= “ prop. law [A ∧ B ⇒ A] ”true

Page 74: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Simple example (IX — final assembly)

I We have SInit = PInit and SLoop v PLoop, so we canconclude by 〈〈v-; 〉〉 that SInit ; SLoop v PInit ; PLoop.

I However, we need to show that SSum = SInit ; SLoop

SInit ; SLoop= “ defns. ”

s′ = 0 ∧ i ′ = n ∧ n′ = n ; s′ = s + S(i) ∧ n′ = n= “ 〈〈; -def〉〉, subst. ”∃ sm, im,nm • sm = 0 ∧ im = n ∧ nm = n

∧ s′ = sm + S(im) ∧ n′ = nm= “ 〈〈∃-1pt〉〉 ”

s′ = 0 + S(n) ∧ n′ = n= “ arithmetic, 〈〈frame-def〉〉 ”

s, i :[s′ = S(n)]

CS4003 Formal Methods

Uuuugh !

I We showed that SLoop v PLoopI It was an ad-hoc approachI Complicated, long-windedI Is there a better, more systematic way ?

CS4003 Formal Methods

A Simple example (revisited — I)

I Consider two cases:1. the loop is continuing, as i > 0, so we have

i > 0 ⇒ W = s := s + i ; i := i − 1 ; W

2. the loop has terminated, as i = 0, so we have

i = 0 ⇒ W = skip

I Whilst the loop is continuing, we see that W is in somesense doing the same thing each time round

I Somehow W must embody a property true before andafter each iteration: the loop invariant (inv ).

CS4003 Formal Methods

A Simple example (revisited — II)

I Consider partway through, where 0 < i < n.We have summed from n down to i + 1.

I So the final sum should be the current value of s, plus theremaining numbers to be added, namely from i down to 1.

I We posit:inv =̂ S(n) = s + S(i)

I At the start, i = n ∧ s = 0, so inv holdsI At the end, i = 0 ∧ inv , so s = S(n) holds

Page 75: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Simple example (revisited — III)I From where did we magic this invariant?

s + S(i) = S(n)

I Considering execution snapshots often helps

i : n n − 1 n − 2 k 0

s : 0 nn+

(n − 1)

n+

(n − 1)+...+

(k + 1)

n+

(n − 1)+...+1

S(i) : S(n) S(n − 1) S(n − 2) S(k ) S(0)

As i shrinks, s increasesCS4003 Formal Methods

Invariants

I For a while-loop c ~ P , an invariant inv is:I a condition (undashed variables only)I required to be true before we execute the loopI will be true after each iteration around the loopI will be true on exit from the loop

I Such conditions are called “invariants” because they statea property that does not change as the loop executes.

I Surprisingly, the loop invariant is key to proving that a loopdoes the right thing !

I A “variant” predicate, describing how P changes things ineach iteration does not help in this regard !!

CS4003 Formal Methods

Loops and InvariantsI if inv is an invariant for c ~ P , then the following holds:

I If c and inv are true, then execution of the loop body willleave inv ′ true.

〈〈rel-is-invariant〉〉 ~v :[c ∧ inv ⇒ inv ′] v P

I If inv is true beforehand, then on termination of the loop,inv ′ is true, as is ¬ c ′

〈〈rel-v-〉〉~v :[inv ⇒ inv ′ ∧ ¬ c ′] v c ~ (~v :[c ∧ inv ⇒ inv ′])

I Note that we have to carry the same frame ~v :[. . .] throughthe refinement.

I So, we have two refinement checks:I 〈〈rel-is-invariant〉〉 checks that inv is an invariant for c ~ PI 〈〈rel-v-〉〉 states how we can refine such a loop

CS4003 Formal Methods

Loop Refinement (I)

I We can put two refinements together into a refinementinference rule:

~v :[c ∧ inv ⇒ inv ′

]v P

~v :[inv ⇒ inv ′ ∧ ¬ c ′

]v c ~ (~v :

[c ∧ inv ⇒ inv ′

])

~v :[inv ⇒ inv ′ ∧ ¬ c ′

]v c ~ P

I In other words, in order to show that S v c ~ P , we needto:1. Look at c and P to find an appropriate invariant inv ,

satisfying 〈〈rel-is-invariant〉〉.2. Show S is refined by inv ⇒ inv ′ ∧ ¬ c ′

3. Show that 〈〈rel-v-〉〉 holds.I Proof of these rules is (slightly) beyond the scope of this

course.

Page 76: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Loop Refinement (II)

I However, using invariants requires that inv holds at loopstart.We need to ensure that initialization brings this about.

I Another refinement rule 〈〈rel-init-loop-v〉〉 allows us tocouple both initialisation and the loop:

~v :[pre ⇒ inv ′ ∧ ¬ c ′]v ~v :[pre ⇒ inv ′] ; c ~ ~v :[c ∧ inv ⇒ inv ′]

I Given refinement check S v c ~ P , we no longer look foran appropriate W .

I Instead we have to find inv , which is simpler.

CS4003 Formal Methods

The Simple example (redone — I)

I Reminder: we want to show

s, i :[s′ = S(n)]v s, i := 0,n ; (i > 0)~ (s, i := s + i , i − 1)

using inv = s + S(i) = S(n).I We need to get the specification into the correct form,

which requires the very useful, very general refinementinference rule 〈〈strengthen-post〉〉:

~v :[Post1] v ~v :[Post2]

~v :[pre ⇒ Post1] v ~v :[pre ⇒ Post2]

(The rationale for this law will follow shortly)

CS4003 Formal Methods

The Simple example (redone — II)

We can now proceed:

s, i :[s′ = S(n)]= “ 〈〈⇒-l-unit〉〉 ”

s, i :[true⇒ s′ = S(n)]v “ 〈〈strengthen-post〉〉, using ~x :[A] v ~x :[A ∧ B] ”

s, i :[true⇒ s′ = S(n) ∧ i ′ = 0]= “ 0 = S(0) = S(i ′) and frame requires n′ = n ”

s, i :[true⇒ s′ + S(i ′) = S(n′) ∧ i ′ = 0]v “ 〈〈rel-init-loop-v〉〉 ”

s, i :[true⇒ s′ + S(i ′) = S(n′)]; (i > 0)~ s, i :[i > 0 ∧ s + S(i) = S(n)⇒ s′ + S(i ′) = S(n′)]

At this point we can refine the two statements individually.

CS4003 Formal Methods

Reminder: “equality substitution”

I We have the law 〈〈=-∧-subst〉〉:x = e ∧ P ≡ x = e ∧ P [e/x ]

I From this we can derive many useful laws, e.g.

〈〈=-⇒-subst〉〉 (x = e ∧ P ⇒ Q) ≡ (x = e ∧ P ⇒ Q[e/x ])〈〈=-v-subst〉〉 (S v P ∧ x = e) ≡ (S[e/x ] v P ∧ x = e)

I Remember also, that the laws above also apply even if wedon’t replace all free x with e, but instead only changesome.

Page 77: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Intuition for “equality substitution”

I In essence the equality substitution laws just mentionedexpress when we can propagate an identity (e1 = e2)around the rest of its containing predicate.

I by “propagating e1 = e2” we mean identifying places in thecontaining predicate where we can replace e1 by e2, or v.v.

I Identities propagate through logical-and (∧).I Identities propagate leftwards through implication (⇒), i.e.

following the arrow.

CS4003 Formal Methods

The Simple example (redone — III)

The first statement

s, i :[true⇒ s′ + S(i ′) = S(n′)] v s, i := 0,n= “ 〈〈⇒-l-unit〉〉,〈〈frame-def〉〉, 〈〈sim-:=-def〉〉 ”

s′ + S(i ′) = S(n′) ∧ n′ = n v s′ = 0 ∧ i ′ = n ∧ n′ = n= “ 〈〈v-def〉〉 ”

[ s′ = 0 ∧ i ′ = n ∧ n′ = n ⇒ s′ + S(i ′) = S(n′) ∧ n′ = n ]= “ 〈〈=-⇒-subst〉〉 ”

[ s′ = 0 ∧ i ′ = n ∧ n′ = n ⇒ 0 + S(n) = S(n) ∧ n = n ]= “ arithmetic ”

[ s′ = 0 ∧ i ′ = n ∧ n′ = n ⇒ true ]= “ 〈〈⇒-r-zero〉〉 ”

true

CS4003 Formal Methods

The Simple example (redone — IV)The second statement

s, i :[i > 0 ∧ s + S(i) = S(n)⇒ s′ + S(i ′) = S(n′)]v s, i := s + i , i − 1

= “ 〈〈frame-def〉〉, 〈〈sim-:=-def〉〉 ”(i > 0 ∧ s + S(i) = S(n)⇒ s′ + S(i ′) = S(n′)) ∧ n′ = nv s′ = s + i ∧ i ′ = i − 1 ∧ n′ = n

= “ 〈〈=-v-subst〉〉 ”(i > 0 ∧ s + S(i) = S(n)⇒ s + i + S(i − 1) = S(n)) ∧ n = nv s′ = s + i ∧ i ′ = i − 1 ∧ true

= “ arithmetic, esp laws of S(x ) ”(i > 0 ∧ s + S(i) = S(n)⇒ s + S(i) = S(n))v s′ = s + i ∧ i ′ = i − 1 ∧ n′ = n

= “ prop. calc A ∧ B ⇒ A ”true v s′ = s + i ∧ i ′ = i − 1 ∧ n′ = n

= “ true (Chaos) is refined by anything ”true

CS4003 Formal Methods

Refining by Initialised While-Loops: recap

To refine ~v :[S] by init ; c ~ P we need to :1. find an appropriate invariant inv2. find an appropriate pre-condition pre (often true will do)3. show that ~v :[S] v ~v :[pre ⇒ inv ′ ∧ ¬ c ′]4. Then it remains to verify both

~v :[pre ⇒ inv ′] v init~v :[c ∧ inv ⇒ inv ′] v P

Page 78: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Invariants: the last words

I Invariants capture a property that is true before and afterevery iteration of the loop body

I However, the existence of an invariant, does not mean thatnothing changes going round the loop

I Clearly something must change or the loop would notachieve its goal (or terminate).

I The trick in verifying loops is finding the appropriateinvariant.

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Page 79: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 15

CS4003 Formal Methods

Pre and post conditions

I We have seen a few specifications now of the form

P ⇒ Q

I Typically P has been a condition (no dashed-variables)whilst Q may have had both dashed and non-dashedvariables.

I We shall use lower-case names for predicates that areconditions

I p : a pre-condition (no dashed variables)I p′ : a post -condition (only dashed variables)I P : a pre-post-relation (mixed variables)

CS4003 Formal Methods

Interpreting Implications (I)

I The specificationpre ⇒ post ′

I is interpreted as“if pre holds at the start, the we must ensure that post holdsat the end”.

I relates a “pre-snapshot” to a “post-snapshot”I The specification

pre ⇒ Rel

I is interpreted as“if pre holds at the start, then we must ensure that start andend states are related by Rel ”.

I relates a “pre-snapshot” to a relationship between beforeand after states

CS4003 Formal Methods

Interpreting Implications (II)

I Given specification pre ⇒ Rel what should our refinementdo, in situations were pre is False?

I Guiding principle: guarantees and commitmentsI The pre-condition pre is a guarantee that some other agent

will set things up appropriately.I Given that guarantee has been met, then Rel is the

commitment that any refinement must make.I But, but, if the guarantee isn’t met ?I If the pre-condition is False we can do anything .

I in general we cannot offer anything better than thatconsider: x , r : R ∧ x ≥ 0⇒ (r ′)2 = xwhat can we do if x < 0?

Page 80: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Loop Refinement Example 1 (Floyd ’67)

Given

a : array 1 . . . n of RA(0) = 0A(x ) = ax + A(x − 1), x > 0

ASpec =̂ s, i :[s′ = A(n)]

αAProg = {n, i , s,n′, i ′, s′}AProg =̂ i , s := 1,0 ; (i ≤ n) ∗ (s, i := s + ai , i + 1)

ProveASpec v AProg

CS4003 Formal Methods

Refining Floyd’67: process

We need to1. find appropriate invariant ainv2. show ASpec v s, i :[ainv ′ ∧ i ′ > n′]

(precondition is true, so we ignore it)3. show s, i :[ainv ′] v i , s := 1,04. show s, i :[i ≤ n ∧ ainv ⇒ ainv ′] v s, i := s + ai , i + 1

CS4003 Formal Methods

Refining Floyd’67: process (1)

Looking at loop execution:

i 1 2 3 k n n + 1s 0 a1 a1 + a2 a1 + · · · ak−1 a1 + · · · an−1 a1 + · · · an

A(0) A(1) A(2) A(k − 1) A(n − 1) A(n)

We can see that for i = k that s +∑n

j=k aj = A(n).

ainv =̂ s +∑n

j=i = A(n)

CS4003 Formal Methods

Refining Floyd’67: process (1x)

We introduce a shorthand, with laws:

A(`,u) =̂∑u

j=` aj

A(k , k ) = akA(`,u) = 0, ` > uA(`,u) = a` + A(`+ 1,u), ` 6 uA(1,n) = A(n), n > 0

Now the invariant is more concise

ainv =̂ s + A(i ,n) = A(n)

Page 81: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Refining Floyd’67: process (2)

We must show ASpec v s, i :[ainv ′ ∧ i ′ > n′]

s, i :[s′ = A(n)] v s, i :[s′ + A(i ′,n′) = A(n′) ∧ i ′ > n′]= “ 〈〈frame-def〉〉 ”

s′ = A(n) ∧ n′ = n v s′ + A(i ′,n′) = A(n′) ∧ i ′ > n′ ∧ n′ = n= “ A(i ′,n′) = 0 if i ′ > n′ ”

s′ = A(n) ∧ n′ = n v s′ = A(n′) ∧ i ′ > n′ ∧ n′ = n= “ 〈〈=-v-subst〉〉 ”

s′ = A(n′) ∧ n′ = n v s′ = A(n′) ∧ i ′ > n′ ∧ n′ = n= “ 〈〈prog-strengthen〉〉 ”

true

CS4003 Formal Methods

Refining Floyd’67: process (3)

We must show s, i :[ainv ′] v i , s := 1,0

s, i :[s′ + A(i ′,n′) = A(n′)] v i , s := 1,0= “ 〈〈frame-def〉〉,〈〈sim-:=-def〉〉 ”

s′ + A(i ′,n′) = A(n′) ∧ n′ = n v i ′ = 1 ∧ s′ = 0 ∧ n′ = n= “ 〈〈=-v-subst〉〉 ”

0 + A(1,n′) = A(n′) ∧ n′ = n v i ′ = 1 ∧ s′ = 0 ∧ n′ = n= “ law A(1,n) = A(n) ”

true ∧ n′ = n v i ′ = 1 ∧ s′ = 0 ∧ n′ = n= “ 〈〈∧-unit〉〉,〈〈prog-strengthen〉〉 ”

true

CS4003 Formal Methods

Refining Floyd’67: process (4)

We must show s, i :[i ≤ n ∧ ainv ⇒ ainv ′] v s, i := s + ai , i + 1

s, i :[i ≤ n ∧ s + A(i ,n) = A(n)⇒ s′ + A(i ′,n′) = A(n′)]v s, i := s + ai , i + 1

= “ 〈〈sim-:=-def〉〉 ”s, i :[i ≤ n ∧ s + A(i ,n) = A(n)⇒ s′ + A(i ′,n′) = A(n′)]v s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

= “ 〈〈=-v-subst〉〉 ”s, i :[i ≤ n ∧ s + A(i ,n) = A(n)⇒ s + ai + A(i + 1,n) = A(n)]v s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

= “ law of A( , ) ”s, i :[i ≤ n ∧ s + A(i ,n) = A(n)⇒ s + A(i ,n) = A(n)]v s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

CS4003 Formal Methods

Refining Floyd’67: process (4 cont.)

s, i :[i ≤ n ∧ s + A(i ,n) = A(n)⇒ s + A(i ,n) = A(n)]v s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

= “ A ∧ B ⇒ B ”s, i :[true]v s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

= “ 〈〈frame-def〉〉 ”true ∧ n′ = nv s′ = s + ai ∧ i ′ = i + 1 ∧ n′ = n

= “ 〈〈prog-strengthen〉〉 ”true

Page 82: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Loop Refinement Example 2 (Hoare ’69)

Given

HSpec =̂ r ,q :[y ′ > r ′ ∧ x ′ = r ′ + y ′ ∗ q ′]

HProg =̂ r ,q := x ,0 ; (y ≤ r ) ∗ (r ,q := r − y ,1 + q)

ProveHSpec v HProg

CS4003 Formal Methods

Refining Hoare’69: process

We need to1. find appropriate invariant hinv2. show HSpec v r ,q :[hinv ′ ∧ y ′ > r ′]

(precondition is true, so we ignore it)3. show r ,q :[hinv ′] v r ,q := x ,04. show r ,q :[y ≤ r ∧ hinv ⇒ hinv ′] v r ,q := r − y ,1 + q

CS4003 Formal Methods

Refining Hoare’69: process (1)

Looking at loop execution:

r x x − y x − 2y x − k · y x − n · yq 0 1 2 k n

We can see that for q = k that r = x − k · y .

hinv =̂ x = r + q · y

CS4003 Formal Methods

Refining Hoare’69: process (2)

We must show HSpec v r ,q :[hinv ′ ∧ y ′ > r ′]

r ,q :[y ′ > r ′ ∧ x ′ = r ′ + y ′ ∗ q ′]v r ,q :[x ′ = r ′ + q ′ ∗ y ′ ∧ y ′ > r ′]

= “ 〈〈v-refl〉〉 ”true

Page 83: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Refining Hoare’69: process (3)

We must show r ,q :[hinv ′] v r ,q := x ,0

r ,q :[x ′ = r ′ + q ′ ∗ y ′] v r ,q := x ,0= “ 〈〈frame-def〉〉,〈〈sim-:=-def〉〉 ”

x ′ = r ′ + q ′ ∗ y ′ ∧ x ′ = x ∧ y ′ = yv r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ 〈〈=-v-subst〉〉 ”x = x + 0 ∗ y ∧ x ′ = x ∧ y ′ = yv r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ arithmetic ”true ∧ x ′ = x ∧ y ′ = y v r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ 〈〈prog-strengthen〉〉 ”true

CS4003 Formal Methods

Refining Hoare’69: process (4)

We must show r ,q :[y ≤ r ∧ hinv ⇒ hinv ′] v r ,q := r − y ,1 + q

r ,q :[y ≤ r ∧ x = r + q ∗ y ⇒ x ′ = r ′ + q ′ ∗ y ′]v r ,q := r − y ,1 + q

= “ 〈〈frame-def〉〉,〈〈sim-:=-def〉〉 ”(y ≤ r ∧ x = r + q ∗ y ⇒ x ′ = r ′ + q ′ ∗ y ′) ∧ x ′ = x ∧ y ′ = yv r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

= “ 〈〈=-v-subst〉〉 ”(y ≤ r ∧ x = r + q ∗ y⇒ x = r − y + (q + 1) ∗ y ) ∧ x ′ = x ∧ y ′ = y

v r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

CS4003 Formal Methods

Refining Hoare’69: process (4 cont.)

(y ≤ r ∧ x = r + q ∗ y⇒ x = r − y + (q + 1) ∗ y ) ∧ x ′ = x ∧ y ′ = y

v r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y= “ arithmetic ”

(y ≤ r ∧ x = r + q ∗ y ⇒ x = r − q ∗ y ) ∧ x ′ = x ∧ y ′ = yv r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

= “ A ∧ B ⇒ B ”true ∧ x ′ = x ∧ y ′ = yv r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

= “ 〈〈prog-strengthen〉〉 ”true

CS4003 Formal Methods

One More Loop Example

I We shall finish off with one more different loop exampleI A loop whose termination is not pre-determined

I e.g., searching an arrayI p :[ap′ = w � w ∈ a � p′ = 0]

Page 84: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Searching an Array

a : array 1 . . .N of Tw : Tp : N

ASSpec =̂ p :[ap′ = w � w ∈ a � p′ = 0

]ASProg =̂ p := N ; (ap 6= w ∧ p > 0) ∗ p := p − 1

ASSpec v ASProg

CS4003 Formal Methods

The Proof obligations

1. find an appropriate invariant asinv2. Prove ASSpec v p :

[asinv ′ ∧ ¬ (ap′ 6= w ∧ p′ > 0)

]3. Prove p :[asinv ′] v p := N4. Prove p :[ap 6= w ∧ p > 0 ∧ asinv ⇒ asinv ′] v p := p − 15. For simplicity, we shall assume w ′ = w and a′ = a

throughout, so we can ignore the frames.

CS4003 Formal Methods

Array Stuff

I We need to have some laws/definitions regarding arraymembership:

w ∈ a =̂ ∃ k • 1 6 k 6 N ∧ ak = w

I We also want to talk about membership in a subset of anarray:

w ∈ a`...u =̂ ∃ k • ` 6 k 6 u ∧ ak = w , 1 6 ` 6 u 6 Nw ∈ a`...u = w = a` ∨ w ∈ a`+1...u , ` 6 uw ∈ a`...u = false, ` > u

CS4003 Formal Methods

Picking the invariant

I An overview of a run of the algorithm looks like:

0 1

a1

2

a2 · · ·k

ak

k+1

ak+1 · · ·N

aN

I When p = k , we have come down from N ,without finding w .

I We also know that p will range from N down to 0I We propose asinv = 0 6 p 6 N ∧ w /∈ ap+1...N

Page 85: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

The Proof obligations (revisited)

1. We drop frames, assume a = a′ and w = w ′ throughout2. Prove

ASSpecv 0 6 p′ 6 N ∧ w /∈ ap′+1...N ∧ ¬ (ap′ 6= w ∧ p′ > 0)

3. Prove 0 6 p′ 6 N ∧ w /∈ ap′+1...N v p := N4. Prove

ap 6= w ∧ p > 0 ∧ 0 6 p 6 N ∧ w /∈ ap+1...N⇒ 0 6 p′ 6 N ∧ w /∈ a′p′+1...N

v p := p − 1

5. Left as exercise for the very keen !

CS4003 Formal Methods

Uh-Oh ! Heuston, we have a problem …I Clearly Forever ; P = Forever = P ; Forever , right?

(Remember,Forever is true ∗ skip.)I

Forever ; P= “ semantics of Forever ”

true ; P= “ 〈〈; -def〉〉 ”∃Sm • true[Sm/S ′] ∧ P [Sm/S]

= “ substitution ”∃Sm • true ∧ P [Sm/S]

= “ 〈〈∧-unit〉〉 ”∃Sm • P [Sm/S]

= “ 〈〈∃-α-rename〉〉 ”∃S • P

I This doesn’t reduce to true as expected.I We get an execution of P in an arbitrary starting state !

CS4003 Formal Methods

Wrong Choice ?I Maybe we chose wrong earlier — should Forever be

miracle ?I

miracle ; P= “ defn. miracle ”

false ; P= “ 〈〈; -def〉〉 ”∃Sm • false[Sm/S ′] ∧ P [Sm/S]

= “ substitution ”∃Sm • false ∧ P [Sm/S]

= “ 〈〈∧-zero〉〉 ”∃Sm • false

= “ 〈〈∃-free〉〉, defn. miracle ”miracle

I This works — but we ruled it out because it refines anyspecification.

CS4003 Formal Methods

Page 86: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 16

CS4003 Formal Methods

Partial vs. Total Correctness

I We have a theory of partial correctness.I Right now, a proof of

Spec v Prog

proves that Prog satisfies Spec , if it terminates.I We want a theory of total correctness.I In other words, a proof of

Spec v Prog

should prove that Prog terminates and satisfies Spec .

CS4003 Formal Methods

What’s the problem regarding termination ?

I We can’t observe it !I All our theory allows us to do is:

I observe variable values at the start (A)I observe variable values at the end (B)I relate these observations (C)

I For (B) and (C) it is necessary that the program terminates.I In other words, a hidden (wrong!) assumption in our theory

so far is that all programs terminate!

CS4003 Formal Methods

When things go bad: Divergence

I A program execution is divergent ifI a serious error has occurredI the error is unrecoverableI future system behaviour is effectively unpredictable

I In our theory to date, the predicate true (a.k.a. Forever )captures such unpredictability

I In our theory so-far of (sequential) programming,non-termination is an instance of divergence.

I Divergence is sometimes also referred to as “Instability”.

Page 87: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Observing (non-)Divergence

I We shall extend our theory by allowingdivergence/non-divergence to be an observable notion.

I We introduce a new variable : okok = True program is non-divergent (a.k.a. “stable”)

ok = False program is diverging (a.k.a. “unstable”)I Variable ok is not a program variable

I it is an auxiliary or model variable.I We assume no program has such a variableI ok /∈ S

I As with program variable, we distinguish before- and after-execution:

I ok — stability/non-divergence at start(i.e. of “previous” program)

I ok ′ — stability/non-divergence at end

CS4003 Formal Methods

Using ok and ok ′

I Consider the specification: pre ⇒ PostI i.e. if pre holds at start, the Post relates start and end

(provided the program stops)I We shall now replace the above by:

ok ∧ pre ⇒ ok ′ ∧ PostI if started in a stable state okI and pre holds at startI then, we end in a stable state ok ′,I and the relation Post holds of starting and ending states.

I For sequential imperative programs, stability is terminationI Important: We assume that neither pre nor Post mention

ok or ok ′.I Also, variables ok and ok ′ are added to the alphabet of

every language construct.

CS4003 Formal Methods

The Meaning of ok ∧ pre ⇒ ok ′ ∧ Post

Given this specification, then for any run of a satisfyingprogram:I If ok = False, i.e. we started in a divergent state

(previous program diverged)and then any subsequent behavour was acceptable.

I If pre = False, then anything was also allowed.I If ok = pre = True, then ok ′ must have been true

(the program terminated without diverging), and relationPost was satisfied.

CS4003 Formal Methods

Program Semantics using ok and ok ′

I We can now give our program language semantics in thisstyle:

〈〈skip-def〉〉 skip =̂ ok ⇒ ok ′ ∧ S ′ = S〈〈:=-def〉〉 x := e =̂ ok ⇒ ok ′ ∧ x ′ = e ∧ S ′\x ′ = S\x〈〈; -def〉〉 P ; Q =̂ ∃Sm,okm •

P [Sm,okm/S ′,ok ′]∧ Q[Sm,okm/S,ok ]

I The rules regarding alphabets are unchanged,remembering that ok and ok ′ now belong.

I All other language constructs are defined as before, exceptfor the while-loop, which has some differences.

I Many of the laws remain unchanged.

Page 88: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

(Some) Laws of Programming

I The followings laws, seen before, all still hold.

〈〈skip-alt〉〉 skipA = x :=A x〈〈; -assoc〉〉 P ; (Q ; R) = (P ; Q) ; R〈〈:=-seq〉〉 x := e ; x := f = x := f [e/x ]

〈〈:=-swap〉〉 x := e ; y := f = y := f [e/x ] ; x := e,y 6ε e

〈〈��-true〉〉 P � True � Q = P〈〈��-false〉〉 P � False � Q = Q〈〈��-seq〉〉 (P � c � Q) ; R = (P ; R) � c � (Q ; R)

CS4003 Formal Methods

Laws requiring the new form

I If P has the (new) form

ok ∧ pre ⇒ ok ′ ∧ Post

then the following laws also hold:

〈〈skip-; -unit〉〉 skip ; P = P〈〈; -skip-unit〉〉 P ; skip = P

I However, they are no longer true for arbitrary P .I This occurs with laws involving assignment and skip whose

definitions have changed.

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (Setup)

I Goal skip ; P = P ,given new definition for skipand P of the form ok ∧ pre ⇒ ok ′ ∧ Post

I Strategy: reduce lhs to rhs

skip; ok ∧ pre ⇒ ok ′ ∧ Post= “ proof steps … ”

ok ∧ pre ⇒ ok ′ ∧ Post

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (I)

skip; ok ∧ pre ⇒ ok ′ ∧ Post= “ (new) 〈〈skip-def〉〉 ”

ok ⇒ ok ′ ∧ S ′ = S; ok ∧ pre ⇒ ok ′ ∧ Post= “ (new) 〈〈; -def〉〉 ”∃Sm,okm •

(ok ⇒ ok ′ ∧ S ′ = S)[Sm,okm/S ′,ok ′]∧ (ok ∧ pre ⇒ ok ′ ∧ Post )[Sm,okm/S,ok ]

= “ substitution, noting that ok ,ok ′ 6ε pre,Post ”∃Sm,okm •

(ok ⇒ okm ∧ Sm = S)∧ (okm ∧ pre[Sm, /S]⇒ ok ′ ∧ Post [Sm/S])

We have something of the form ∃ xs • (A⇒ B) ∧ (C ⇒ D),which we now transform.

Page 89: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (II)

∃ xs • (A⇒ B) ∧ (C ⇒ D)= “ 〈〈⇒-def〉〉 ”∃ xs • (¬ A ∨ B) ∧ (¬ C ∨ D)

= “ Distributivity laws ”∃ xs • ¬ A ∧ ¬ C ∨ ¬ A ∧ D ∨ B ∧ ¬ C ∨ B ∧ D

= “ 〈〈∃-distr〉〉, several times ”(∃ xs • ¬ A ∧ ¬ C) ∨ (∃ xs • ¬ A ∧ D) ∨(∃ xs • B ∧ ¬ C) ∨ (∃ xs • B ∧ D)

If we apply this to our proof we get

(∃Sm,okm • ¬ ok ∧ ¬ (okm ∧ pre[Sm, /S])) ∨(∃Sm,okm • ¬ ok ∧ ok ′ ∧ Post [Sm/S]) ∨(∃Sm,okm • okm ∧ Sm = S ∧ ¬ (okm ∧ pre[Sm, /S])) ∨(∃Sm,okm • okm ∧ Sm = S ∧ ok ′ ∧ Post [Sm/S])

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (III)

I We shall now simplify each of the four componentsobtained above

I For convenience we give them labels (using “S;U” as shortfor 〈〈skip-; -unit〉〉):

(S;U.1) ∃Sm,okm • ¬ ok ∧ ¬ (okm ∧ pre[Sm, /S])(S;U.2) ∃Sm,okm • ¬ ok ∧ ok ′ ∧ Post [Sm/S](S;U.3) ∃Sm,okm • okm ∧ Sm = S ∧ ¬ (okm ∧ pre[Sm, /S])(S;U.4) ∃Sm,okm • okm ∧ Sm = S ∧ ok ′ ∧ Post [Sm/S]

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (IV, simplifying S;U.1)

∃Sm,okm • ¬ ok ∧ ¬ (okm ∧ pre[Sm, /S])= “ move quantifier in ”¬ ok ∧ ∃Sm,okm • ¬ (okm ∧ pre[Sm, /S])

= “ witness: okm = False makes existential body true ”¬ ok ∧ true

= “ simplify ”¬ ok

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (V, simplifying S;U.2)

∃Sm,okm • ¬ ok ∧ ok ′ ∧ Post [Sm/S]= “ move quantifier in ”¬ ok ∧ ok ′ ∧ ∃Sm,okm • Post [Sm/S]

= “ okm 6ε Post ”¬ ok ∧ ok ′ ∧ ∃Sm • Post [Sm/S]

Page 90: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (VI, simplifying S;U.3)

∃Sm,okm • okm ∧ Sm = S ∧ ¬ (okm ∧ pre[Sm, /S])= “ de-Morgan ”∃Sm,okm • okm ∧ Sm = S ∧ (¬ okm ∨ ¬ pre[Sm, /S])

= “ distributivity ”∃Sm,okm • okm ∧ Sm = S ∧ ¬ okm∨ okm ∧ Sm = S ∧ ¬ pre[Sm, /S]

= “ contradiction ”∃Sm,okm • False ∨ okm ∧ Sm = S ∧ ¬ pre[Sm, /S]

= “ simplify, one-point ”∃okm • okm ∧ ¬ pre

= “ witness, okm = True ”¬ pre

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (VII, simplifying S;U.4)

∃Sm,okm • okm ∧ Sm = S ∧ ok ′ ∧ Post [Sm/S]= “ one-point law ”∃okm • okm ∧ ok ′ ∧ Post

= “ witness: okm = true ”ok ′ ∧ Post

CS4003 Formal Methods

Proof of 〈〈skip-; -unit〉〉 (VIII)

We now merge our four simplifications, and continue:

¬ ok ∨ ¬ ok ∧ ok ′ ∧ ∃Sm • Post [Sm/S] ∨ ¬ pre ∨ ok ′ ∧ Post= “ 〈〈∨-∧-absorb〉〉 ”¬ ok ∨ ¬ pre ∨ ok ′ ∧ Post

= “ deMorgan ”¬ (ok ∧ pre) ∨ ok ′ ∧ Post

= “ 〈〈⇒-def〉〉 ”ok ∧ pre ⇒ ok ′ ∧ Post

CS4003 Formal Methods

“Witness” ?I What is meant by the proof steps labelled “witness” ?I Remember, ∃ x • P is true if any value of x exists that

makes P true. Such a value is is a “witness” (to the truth ofthe existential).

I We have a law that states: P [e/x ]⇒ ∃ x • PI by 〈〈⇒-join〉〉this becomes P [e/x ] ∨ ∃ x • P ≡ ∃ x • PI In effect, knowing that P [e/x ] is true, we can replace∃ x • P by true:

∃ x • P= “ law above ”

P [e/x ] ∨ (∃ x • P)= “ we know (can show) that P [e/x ] = true ”

true ∨ (∃ x • P)= “ simplify ”

true

Page 91: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Frame Specifications with ok , ok ′

I What is the semantics of a frame specification ~x :[S] in ournew theory ?

I In the old theory it was

~x :[S] =̂ S ∧ S ′\~x ′ = S\~x

I How do we fit in ok , ok ′ ?

CS4003 Formal Methods

Frame Syntax change

I To fit our new theory, frames now have to explicitlydistinguish pre and post conditions:

~x :[pre , Post ]

I We also need to note that if ok = False at the outset, thenwe can modify any variables, not just those in the frame.

I The definition we get is therefore:

〈〈frame-def〉〉~x :[pre , Post ] =̂ ok ∧ pre ⇒ ok ′ ∧ Post ∧ S ′\~x ′ = S\~x

CS4003 Formal Methods

Upgrading frame specs to new theory

I An old specification of the form

w :[P ]

where P is not an implication, becomes

w :[true , P ]

I An old specification of the form

w :[pre ⇒ Post ]

becomesw :[pre , Post ]

CS4003 Formal Methods

Refinement with ok , ok ′

I How does adding in ok and ok ′ affect refinement laws ?I e.g. (old rules)

〈〈prog-strengthen〉〉 P v P ∧ Q〈〈=-v-subst〉〉 (S v P ∧ x = e)

≡ (S[e/x ] v P ∧ x = e)〈〈v-:=〉〉 x ′ = e v x := e

I Can we use these as is ?I Are there more useful variants of these ?

Page 92: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Using 〈〈prog-strengthen〉〉 with ok , ok ′

〈〈prog-strengthen〉〉 : P v P ∧ Q

I The rule is still validI However we are less likely to be able to use it, as the

P ∧ Q part will often occur on the rhs of an implication.I The following variant is useful

〈〈prog-strengthen〉〉 (P ⇒ Q) v (P ⇒ Q ∧ R)

I In particular, often, P will be ok ∧ pre,and Q will be ok ′ ∧ Post .

CS4003 Formal Methods

Using 〈〈=-v-subst〉〉 with ok , ok ′

〈〈=-v-subst〉〉 : (S v P ∧ x = e) ≡ (S[e/x ] v P ∧ x = e)

I the rule is still valid, but again we now have those extraimplications

I The following variant is useful

〈〈=-v-subst〉〉 (S v p ⇒ Q ∧ x ′ = e)≡ (S[e/x ′] v p ⇒ Q ∧ x ′ = e)

Note here that p does not mention x ′.I As before, we often find that P will be ok ∧ pre,

and Q will be ok ′ ∧ Post .

CS4003 Formal Methods

Using 〈〈v-:=〉〉 with ok , ok ′

〈〈v-:=〉〉 : x ′ = e v x := e

I The specification x ′ = e is no longer valid— it does not mention ok and ok ′ in a valid way

I We get useful variants if we change the specification to fitour new theory:

〈〈v-:=〉〉 ~w :[pre , x ′ = e] v x := e, x ∈ ~w

CS4003 Formal Methods

Revisiting Loop Refinement Example 2 (Hoare ’69)

Given

HSpec =̂ r ,q :[true , y ′ > r ′ ∧ x ′ = r ′ + y ′ ∗ q ′]

HProg =̂ r ,q := x ,0 ; (y ≤ r ) ∗ (r ,q := r − y ,1 + q)

ProveHSpec v HProg

using new version of our theory, with ok and ok ′

Page 93: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Refining Hoare’69: revisited

We need to1. find appropriate invariant hinv

I this is still x = r + q ∗ y , as before

2. show HSpec v r ,q :[true , hinv ′ ∧ y ′ > r ′]3. show r ,q :[true , hinv ′] v r ,q := x ,04. show r ,q :[y ≤ r ∧ hinv , hinv ′] v r ,q := r − y ,1 + q

CS4003 Formal Methods

Refining Hoare’69: revisited (1)

We must show HSpec v r ,q :[true , hinv ′ ∧ y ′ > r ′]

r ,q :[true , y ′ > r ′ ∧ x ′ = r ′ + y ′ ∗ q ′]v r ,q :[true , x ′ = r ′ + q ′ ∗ y ′ ∧ y ′ > r ′]

= “ 〈〈v-refl〉〉 ”true

CS4003 Formal Methods

Refining Hoare’69: revisited (2)

We must show true :[r ,q , hinv ′] v r ,q := x ,0

r ,q :[true , x ′ = r ′ + q ′ ∗ y ′] v r ,q := x ,0= “ 〈〈frame-def〉〉,〈〈sim-:=-def〉〉 ”

ok ⇒ ok ′ ∧ x ′ = r ′ + q ′ ∗ y ′ ∧ x ′ = x ∧ y ′ = yv ok ⇒ ok ′ ∧ r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ 〈〈=-v-subst〉〉(new variant) ”ok ⇒ ok ′ ∧ x = x + 0 ∗ y ∧ x ′ = x ∧ y ′ = yv ok ⇒ ok ′ ∧ r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ arithmetic ”ok ⇒ ok ′ ∧ true ∧ x ′ = x ∧ y ′ = yv ok ⇒ ok ′ ∧ r ′ = x ∧ q ′ = 0 ∧ x ′ = x ∧ y ′ = y

= “ 〈〈prog-strengthen〉〉(new variant) ”true

CS4003 Formal Methods

Refining Hoare’69: revisited (3)

We must show r ,q :[y ≤ r ∧ hinv , hinv ′] v r ,q := r − y ,1 + q

r ,q :[y ≤ r ∧ x = r + q ∗ y , x ′ = r ′ + q ′ ∗ y ′]v r ,q := r − y ,1 + q

= “ 〈〈frame-def〉〉,〈〈sim-:=-def〉〉 ”ok ∧ y ≤ r ∧ x = r + q ∗ y⇒ ok ′ ∧ x ′ = r ′ + q ′ ∗ y ′ ∧ x ′ = x ∧ y ′ = yv ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

= “ 〈〈=-v-subst〉〉(new variant) ”ok ∧ y ≤ r ∧ x = r + q ∗ y⇒ ok ′ ∧ x = r − y + (q + 1) ∗ y ∧ x = x ∧ y = y

v ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

Page 94: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Refining Hoare’69: revisited (3 cont.)

ok ∧ y ≤ r ∧ x = r + q ∗ y⇒ ok ′ ∧ x = r − y + (q + 1) ∗ y ∧ x = x ∧ y = y

v ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y= “ arithmetic, and e = e ≡ true ”

ok ∧ y ≤ r ∧ x = r + q ∗ y ⇒ ok ′ ∧ x = r + q ∗ yv ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y

= “ (A ∧ B ⇒ C ∧ B) ≡ (A ∧ B ⇒ C) ”ok ∧ y ≤ r ∧ x = r + q ∗ y ⇒ ok ′

v ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = 1 + q ∧ x ′ = x ∧ y ′ = y= “ (A ∧ B ⇒ C) v (A⇒ C ∧ D) ”

true

(Exercise (voluntary): prove the last two laws used).

CS4003 Formal Methods

What was the point ?

I We have proved that if the Hoare’69 program starts ok,then it terminates, establishing y ′ > r ′ ∧ x ′ = y ′ ∗ q ′ + r ′

I The proof of correctness was very similar to beforeI We had to handle the extra complexity of

ok ∧ . . .⇒ ok ′ ∧ . . .I What have we gained ?I in fact, things aren’t just pointless, they are worse than

that !

CS4003 Formal Methods

We have “proved” something False !!

I This is a cardinal error — it means our proof system isunsound !

I A proof system is unsound if we can use it to give a “proof”of a property, that, by some other means, we know is in factFalse .

I Unsoundness means there is a mismatch between ourproof method and our intended meaning for the predicateswe are manipulating.

I Hold on ! How do we know the property is False ?

CS4003 Formal Methods

Hoare’69 can fail to terminate

Consider the following execution of the program:start x=3, y=0

init x=3, y=0, r=3, q=0, y 6 rloop1 x=3, y=0, r=3, q=1, y 6 rloop2 x=3, y=0, r=3, q=2, y 6 rloop3 x=3, y=0, r=3, q=3, y 6 rloop4 x=3, y=0, r=3, q=4, y 6 r

and so on …So our proof technique is flawed.

Page 95: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 17

CS4003 Formal Methods

Fixing our Proof System

I So the addition of ok and ok ′ hasn’t completely solved ourneed to reason about total correctness.

I The problem is that invariants tell us about loopcorrectness, if they terminate.

I We need something extra to showthat loops do indeed terminate.

I We need to show progress towards termination,by using a “variant”.

CS4003 Formal Methods

Loop Variants

I A Variant V for a loop c ∗ P , is:I An expression over program variables.I Has a finite numeric (integer) valueI Is always greater than or equal to zeroI Always decreases by at least one on each loop iteration.

I The existence of an expression V with the aboveproperties proves that a loop terminates.

CS4003 Formal Methods

How does a variant guarantee termination ?

I as the loop starts V will have some value k0

I after the 1st iteration it will have value k1, with k1 < k0

I after at most k0 iterations it will have value 0I the loop must have terminated at this point (Why?)I it is hasn’t terminated, then either

I the next iteration does not decrease V , orI the value of V becomes negative

I in both cases, we do not have a variant property, so Vcannot have been a variant after all.

Page 96: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Revising our loop proof method

To refine ~v :[pre , Post ] by init ; c ∗ P we need to :1. Find an appropriate invariant inv and variant V2. Show that

~v :[pre , Post ] v ~v :[pre , inv ′ ∧ ¬ c ′]

3. show~v :[pre , inv ′] v init

4. show~v :[c ∧ inv , inv ′ ∧ 0 6 V ′ < V ] v P

This is the key difference: we now have to show the variantis reduced, but never below zero.

CS4003 Formal Methods

Revisiting Hoare ’69 (one more time)

I We need to determine a variant for Hoare’69V = f (x , y , r ,q)

I Should be zero when loop terminates (r < y )

r < y ⇒ f (x , y , r ,q) = 0

I Should decrease by at least once per iterationr ,q := r − y ,q + 1

f (x , y , r − y ,q + 1) < f (x , y , r ,q)

I intuitively, the variant measures the“distance to go” towards termination.

CS4003 Formal Methods

A Variant for Hoare’69

I We shall try the following variant:

V =̂ r y

where a b = a − b, if b 6 a, and equals zero otherwise.I The proof obligation involving the variant is now

r ,q : [ y 6 r ∧ x = q ∗ y + r ,x ′ = q ′ ∗ y ′ + r ′ ∧ 0 6 r ′ y ′ < r y ]

v r ,q := r − y ,q + 1

CS4003 Formal Methods

Attempting to prove that r y is a variant (I)

I Rather than prove the whole thing, we focus on the variantpart

r ,q :[y 6 r , 0 6 r ′ y ′ < r y ] v r ,q := r − y ,q + 1

I We expand the lhs using 〈〈frame-def〉〉:

ok ∧ y 6 r ⇒ ok ′ ∧ 0 6 r ′ y ′ < r y ∧ x ′ = x ∧ y ′ = y

I We expand the rhs using 〈〈sim-:=-def〉〉:

ok ⇒ ok ′ ∧ r ′ = r − y ∧ q ′ = q + 1 ∧ x ′ = x ∧ y ′ = y

Page 97: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Attempting to prove that r y is a variant (II)I We use the rhs, and 〈〈=-v-subst〉〉(new version) to transform

the lhs:

ok ∧ y 6 r ⇒ ok ′ ∧ 0 6 (r − y ) y < r y ∧ x = x ∧ y = y

I Again we ignore the variables ok , x , and their dashedvariants and focus on the key variant part:

y 6 r ⇒ 0 6 (r − y ) y < r y

I The first part 0 6 (r − y ) y is always true because never returns a negative result

I For the second part, having y 6 r ensures that r − y is notnegative, but we cannot guarantee that (r − y ) y < r y ,unless y > 0 !

CS4003 Formal Methods

Revising Hoare ’69We now know that there was a missing pre-condition: y > 0 !Given a revised specification

HSpec =̂ r ,q :[y > 0 , y ′ > r ′ ∧ x ′ = r ′ + y ′ ∗ q ′]

HProg =̂ r ,q := x ,0 ; (y ≤ r ) ∗ (r ,q := r − y ,1 + q)

We can now prove

HSpec v HProg

by choosing invariant

inv =̂ x = q ∗ y + r

and variantV =̂ r y

within the new version of our theory, with ok and ok ′.

CS4003 Formal Methods

Debugging by Proof

I The Hoare’69 example wasn’t just about a pre-conditionthat we forgot/ignored.

I It showed another strength of reasoning by proofI In attempting to prove what we believed was a correct

result, we uncovered an error in our initial assumptions.I We discovered/calculated an important pre-conditionI “95% of theorems are false”

(John Rushby, PVS Theorem Prover, 1990s)

CS4003 Formal Methods

Formal Methods: recent Research

I (2000–2007, w/Jim Woodcock, Richard Corrigan)Formal Semantics for Handel-C

I (2008–2011, w/Jim Woodcock, Art O’Catháin)Formal Models of Flash Memory

I (2003–present, w/Jim Woodcock)Using UTP to model synchronous Circus. (a.k.a.“slotted-Circus”)

I (2007–2011, w/Paweł Gancarski)Semantics of priority in slotted-Circus.

I (2008–2012, w/Riccardo Bresciani)Semantics of probabilistic programs in UTP

Page 98: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Formal Methods: current Research

I (2003–present, w/Jim Woodcock)Using UTP to model synchronous Circus. (a.k.a.“slotted-Circus”)

I (2008–2013, w/Arshad Beg)Formal translation from Circus to CSP

I (2007–∞, w/various)Developing the U ·(TP)2 proof assistant

I (2011–2014, w/Lero)Formal aspects of modelling software developmentprocesses

I (2012–2013, w/David Sanán, Lero & ESA)Investigating techniques to formally model and verify asecure partitioning microkernel.

CS4003 Formal Methods

Circus, Flash

I GC6 is a computing “grand-challenge” to develop librariesof verified software, currently with a number of “pilotprojects”:

I Mondex Smart Card (Natwest Bank)I POSIX filestore (NASA JPL)

I Circus is a formal language that combines imperativeprogramming (variables, assignment) with concurrentsystems (message-passing)(see http://www.cs.york.ac.uk/circus/).

I work between TCD and York has focussed on formalmodels of Flash Memory

CS4003 Formal Methods

Handel-C, slotted-Circus

I Handel-C is the C language extended withmessage-passing and parallelism, that compiles directly tohardware (FPGAs).(see http://www.mentor.com/products/fpga/handel-c/)

I it is based on notion of synchronously clocked time-slots.I “slotted-Circus” is a generic framework for adding discrete

time to Circus, suitable for modelling time-slot languageslike Handel-C.

I it is currently be worked on here at TCD, using UTP as thesemantic framework.

CS4003 Formal Methods

Kernel Verification

I ESA wants to put multiple applications on one computerI currently each application (propulsion, telemetry,

experiment, sensor array) has its own computing hardwareI want integrated modular avionics (IMA) to save weight

I This requires a time-space partitioning kernel (hypervisor)to ensure non-interference between applications.

I We are doing a feasibility study:I Develop a Reference Specification.I Formalise it (Using Isabelle/HOL).I Explore feasibility of verifying the correctness of actual

kernel code.

Page 99: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Formal Methods: recent Publications2009, , P. Gancarski, J. Woodcock “State Visibility andCommunication in Unifying Theories of Programming”, TASE 2009 ,IEEE CS, pp47–54.2009, , P. Gancarski, “The Denotational Semantics ofslotted-Circus”, FM 2009 , LNCS 5850, pp451–466.2010, , P. Gancarski, “Prioritized slotted-Circus”, ICTAC 2010, LNCS6255, pp91-105.2010, , “Saoithin: A Theorem Prover for UTP”, UTP 2010, LNCS6445, pp137-156.2010, , “Denotational Semantics of Handel-C”, Formal Aspects ofComputing , 23, (2), 2011, p153 - 170.2012, R. Bresciani, , “A probabilistic theory of designs based ondistributions”, UTP 2012 LNCS 7681, pp105 - 123.2012, Andrew Butterfield, “The Logic of UTP2”, UTP 2012 LNCS7681, pp124 - 143.2012, R. Bresciani, , “A UTP semantics of pGCL as a homogeneousrelation”, IFM 2012 LNCS 7321, pp191-205.2013, R. Bresciani, , “From Distributions toProbabilistic ReactivePrograms”, ICTAC 2013 , LNCS 8049, pp94 - 111.

CS4003 Formal Methods

Mini-Exercise 5

Q5 Given

n, f , x : Nfac(0) = 1fac(n) = n ∗ fac(n − 1), n > 0

FSpec =̂ f , x :[f ′ = fac(n)]FProg =̂ f , x := 1,2 ; (x 6 n)~ f , x := f ∗ x , x + 1

Using the partial correctness theory only:5.1 State clearly the proofs that need to be done.5.2 Determine a suitable invariant.5.3 Prove the statement that states that FSpec is

refined appropriately (Hint: one of the proofs in theanswer to 5.1).

(due in next Friday week, 2pm, in class)

CS4003 Formal Methods CS4003 Formal Methods

Page 100: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 18

CS4003 Formal Methods

quite a lot of Handwaving !

I In the proofs so far, we have seen proof-step justificationslike

I “ arithmetic ”I “ defn. of 6 ”I “ 5 < x < 3 clearly impossible ”

I Such justifications are “hand-waving” and not formallyrigorous.

I How do we formalise these proof steps so they are part ofour formal game ?

CS4003 Formal Methods

“Theory” as an organising Principle

I In order to formalise arithmetic, say, we have to:I extend our language syntax to cover arithmetic notationI extend our axioms to cover the new notationI build a collection of useful theorems from those axioms

I A “Theory ” is a collection of all the above pieces ofinformation, along with any necessary support material.

I We shall briefly explore two theories:I ArithmeticI Lists

CS4003 Formal Methods

A small theory of equality

It will prove useful to have a theory of equalityI Syntax: e, f ∈ Expr ::= . . . | e1 = e2 | e1 6= e2

I Axioms:

〈〈=-refl〉〉 e = e〈〈=-comm〉〉 (e = f ) ≡ (f = e)〈〈=-trans〉〉 (e = f ) ∧ (f = g)⇒ (e = g)〈〈6=-def〉〉 (e 6= f ) =̂ ¬ (e = f )

Equality is an equivalence relation (reflexive, symmetric,transitive)

I We will extend this theory as needed.

Page 101: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Theory of Arithmetic (Syntax)We use m,n for numeric expressions

m,n ∈ Expr ::= . . .| 0 | 1 | 2 | . . . numeric constants| succ n | pred n basic operations| m + n | m − n additive operators| m ∗ n | m/n | . . . multiplicative operators| mn . . . exponential operators

We use r and s for atomic predicates over numeric values

r , s ∈ Expr ::= . . .| m = n | m 6= n equalities| m < n | m > n comparisons (strict)| m 6 n | m > n comparisons (non-strict)| n : T numeric type assertions

(T ∈ N,Z,Q,R,C)

CS4003 Formal Methods

Some axioms for arithmetic

Axioms cover the basic building blocksI Zero is a natural number〈〈0-is-N〉〉 0 : N

I If n is a natural number then so is the successor of n〈〈succ-is-N〉〉 (n : N)⇒ (succ n : N)

I The successor of a natural number is never zero〈〈succ-not-0〉〉 succ n 6= 0

I Successor maps different values to different results〈〈succ-injective〉〉 (n = m) ≡ (succ n = succ m)

I If P(0) is true, and whenever P(n) is true, we can showthat P(n + 1) is true, them P(x ) is true for all x : N

〈〈N-induction〉〉 P [0/x ] ∧ (∀n • P [n/x ]⇒ P [succ n/x ])⇒ (∀ x | x : N • P)

CS4003 Formal Methods

Some definitions for arithmetic

〈〈0-+-def〉〉 0 + m = m〈〈succ-+-def〉〉 (succ n) + m = succ(n + m)

〈〈0-∗-def〉〉 0 ∗m = 0〈〈succ-∗-def〉〉 (succ n) ∗m = m + (n ∗m)

〈〈ˆ-0-def〉〉 m0 = 1〈〈ˆ-succ-def〉〉 msucc n = m ∗mn

〈〈1-def〉〉 1 = succ 0〈〈2-def〉〉 2 = succ 1〈〈3-def〉〉 3 = succ 2

...

(Strictly speaking we need to model digit strings and theirvaluations in order to do the last three definitions properly)

CS4003 Formal Methods

Some theorems for arithmetic

〈〈+-0-unit〉〉 n + 0 = n〈〈+-succ-comm〉〉 (succ n) + m = n + (succ m)

〈〈+-comm〉〉 n + m = m + n〈〈+-assoc〉〉 `+ (m + n) = (`+ m) + n〈〈∗-comm〉〉 n ∗m = m ∗ n〈〈∗-0-def〉〉 n ∗ 0 = 0〈〈∗-assoc〉〉 ` ∗ (m ∗ n) = (` ∗m) ∗ n

〈〈∗-+-distr〉〉 ` ∗ (m + n) = ` ∗m + ` ∗ n

〈〈1+1-equals-2〉〉 1 + 1 = 2〈〈2+2-equals-4〉〉 2 + 2 = 4

Page 102: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈1+1-equals-2〉〉

Goal: 1 + 1 = 2Strategy: reduce to true

1 + 1 = 2= “ 〈〈1-def〉〉, 〈〈2-def〉〉 ”

(succ 0) + (succ 0) = succ 1= “ 〈〈succ-+-def〉〉, 〈〈1-def〉〉 ”

succ(0 + succ 0) = succ(succ 0)= “ 〈〈0-+-def〉〉 ”

succ(succ 0) = succ(succ 0)= “ 〈〈=-refl〉〉 ”

true�

CS4003 Formal Methods

Proof of 〈〈+-0-unit〉〉

Goal: n + 0 = nStrategy: ???I A traditional proof of this uses induction, on n.I We show it is true for n = 0, i.e. that 0 + 0 = 0I We then assume it (i.e. n + 0 = n) and show it is true for

succ n,succ n + 0 = succ n

I We have an induction principle (law 〈〈N-induction〉〉), but howdo we use it in our proof system ?

CS4003 Formal Methods

Developing an Induction StrategyI The induction law has the general form A⇒ BI Any such law suggests that if we want to show B to be true,

then one such way is to prove A.I Given A⇒ B, the use of 〈〈⇒-join〉〉 transforms this to

B ≡ B ∨ AI Now, consider our proof of B:

B= “ by alternate form of law above ”

B ∨ A= “ given a proof of A ”

B ∨ true= “ 〈〈∨-zero〉〉 ”

true

I So from a proof of A, we may construct a proof of B.CS4003 Formal Methods

The Induction Strategy

I Assume an Induction Principle, i.e., a law of the form

Q1 ∧ Q2 ∧ . . .Qn ⇒ ∀ x • P

I In order to prove ∀ x • P , we now know it suffices to proveindividually each of the Qi

I So, given goal ∀ x | x : N • P an inductive proof allows usto prove it via the following two sub-goals:

P [0/x ]P [n/x ] ⇒ P [succ n/x ]

Page 103: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

∀ and Theoremhood

I What does it mean to say that P is a theorem(or axiom/law) ?

I It means that P evaluates to true, regardless of theenvironment.

I This is the same as stating that [P ] is a theoremRemember: [P ] is true only if P is true for all environments.

I We have quantified over nothing (P ), and everything ([P ]),but what about ∀ xs • P ?

I If P is a theorem, then so is ∀ xs • PI It turns out, regardless of what the xs are, that if any of the

following is a theorem, they all are:

P (∀ xs • P) [P ]

CS4003 Formal Methods

Proof of 〈〈+-0-unit〉〉 (again)I Goal: n + 0 = nI Strategy: Induction on n using 〈〈N-induction〉〉.I 1st sub-goal (a.k.a. “the base case”)

0 + 0 = 0

I 2nd sub-goal (a.k.a. “the inductive step”)

∀n • (n + 0 = n)⇒ (succ n) + 0 = succ n

I However showing the above a theorem is the same asshowing the following to be a theorem

I

(n + 0 = n)⇒ (succ n) + 0 = succ n

CS4003 Formal Methods

Proof of 〈〈+-0-unit〉〉 (base case)

(sub-)Goal: 0 + 0 = 0(sub-)Strategy: reduce lhs to rhs

0 + 0= “ 〈〈+-0-unit〉〉 ”

0

CS4003 Formal Methods

Proof of 〈〈+-0-unit〉〉 (inductive step)

(sub-)Goal: (n + 0 = n)⇒ (succ n) + 0 = succ n(sub-)Strategy: assume antecedent 〈〈+-0-def.hyp〉〉 n + 0 = n,Show consequent (reduce to true):

(succ n) + 0 = succ n= “ 〈〈succ-+-def〉〉 ”

succ (n + 0) = succ n= “ 〈〈+-0-def.hyp〉〉 ”

succ n = succ n= “ 〈〈=-refl〉〉 ”

true

Page 104: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Arithmetic Theory: summary

I Induction using 〈〈N-induction〉〉 is the main proof techniquefor the laws of arithmetic.

I Most if not all of the laws shown are done this wayI For example, 〈〈+-succ-comm〉〉 can be proven by induction

on n, and using 〈〈+-0-unit〉〉 to assist in the base-case.

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Class 19

Page 105: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

More Arithmetic Theory

We can also define numeric ordering, and supply sometheoremsI Definitions

〈〈0-6-def〉〉 0 6 n〈〈succ-6-def〉〉 (succ n) 6 (succ m) ≡ n 6 m〈〈0-6-bottom〉〉 ¬ (succ n 6 0)

I Theorems

〈〈1-lessthan-2〉〉 1 6 2〈〈2-not-lessthan-1〉〉 ¬ (2 6 1)

〈〈+-increases〉〉 n 6 n + m〈〈+-0-same〉〉 n + m 6 n ⇒ m = 0

CS4003 Formal Methods

Hold on ! What about − and / ?

I I hoped you wouldn’t notice !I Ok, lets have a look at some definitions/theoremsI What’s wrong with the simple life anyway ?

CS4003 Formal Methods

Definitions and Theorems for Subtraction

I Definitions:

〈〈−-0-def〉〉 n − 0 = n〈〈−-succ-def〉〉 (succ n)− (succ m) = n −m

I Theorems2:

〈〈+-−-inv〉〉 (m + n)− n = m〈〈−-+-inv〉〉 (m − n) + n = m

〈〈−-decreases〉〉 (m − n) 6 m

〈〈3-minus-2-is-1〉〉 3− 2 = 1〈〈1-minus-3-lt-1〉〉 1− 3 6 1

I Let’s prove some of these.

2probably ? CS4003 Formal Methods

Proof of 〈〈3-minus-2-is-1〉〉Goal: 3− 2 = 1Strategy: reduce lhs to rhs3.

3− 2= “ 〈〈3-def〉〉, 〈〈2-def〉〉 ”

(succ 2)− (succ 1)= “ 〈〈−-succ-def〉〉 ”

2− 1= “ 〈〈2-def〉〉, 〈〈1-def〉〉 ”

(succ 1)− (succ 0)= “ 〈〈−-succ-def〉〉 ”

1− 0= “ 〈〈−-0-def〉〉 ”

1

3works for theorems using = as well as ≡.

Page 106: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈+-−-inv〉〉

I Goal: (m + n)− n = mI Strategy: Induction on nI Base-Case: (m + 0)− 0 = mI Inductive Step:

((m + n)− n = m)⇒ ((m + (succ n))− (succ n) = m)

CS4003 Formal Methods

Proof of 〈〈+-−-inv〉〉, Base Case

Goal: (m + 0)− 0 = mStrategy: reduce lhs to rhs

(m + 0)− 0= “ 〈〈+-0-unit〉〉 ”

m − 0= “ 〈〈−-0-def〉〉 ”

m

CS4003 Formal Methods

Proof of 〈〈+-−-inv〉〉, Inductive StepGoal: ((m + n)− n = m)⇒ ((m + (succ n))− (succ n) = m)Strategy: assume antecedent〈〈+-−-ind-hyp〉〉 (m + n)− n = mand reduce consequent lhs to rhs

(m + (succ n))− (succ n)= “ 〈〈+-comm〉〉 ”

((succ n) + m)− (succ n)= “ 〈〈succ-+-def〉〉 ”

succ(n + m)− (succ n)= “ 〈〈−-succ-def〉〉 ”

(n + m)− n= “ 〈〈+-−-ind-hyp〉〉 ”

m

CS4003 Formal Methods

Proof of 〈〈1-minus-3-lt-1〉〉

Goal: 1− 3 6 1Strategy: reduce to true

1− 3 6 1= “ 〈〈1-def〉〉, 〈〈3-def〉〉 ”

(succ 0)− (succ 2) 6 (succ 0)= “ 〈〈−-succ-def〉〉 ”

0− 2 6 (succ 0)= “ ??? no law applies ??? ”

I It turns out that 〈〈1-minus-3-lt-1〉〉 is not a theorem!I Neither is its negation!I Whazzup?

Page 107: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Definitions for Subtraction (reminder)

I Definitions:

〈〈−-0-def〉〉 n − 0 = n〈〈−-succ-def〉〉 (succ n)− (succ m) = n −m

CS4003 Formal Methods

Subtraction is partial

I Natural number subtraction as just described is partial :I it is not defined for all values of its argumentsI in fact m − n is only defined if n 6 m

I This means that the value of m − n is undefined if m < nI For example, 〈〈−-+-inv〉〉 as stated (m − n) + n = m)

is not a theorem.I If we revise it to n 6 m ⇒ ((m − n) + n = m),

then it becomes a theorem.I The big question for us now is how do we handle the

issues of partiality and undefinedness?

CS4003 Formal Methods

Handling Undefinedness (I - make it go away)

I Our problems arose because subtraction is partiallydefined

I Why don’t we “totalise” it?I remember ?

I To avoid confusion, we use to denote the totalisedversion, which satisfies 〈〈−-0-def〉〉, 〈〈−-succ-def〉〉 and

〈〈−-totalise〉〉 0m = 0

I We can now easily prove that 1 3 6 1I Sorted ?

CS4003 Formal Methods

Problems with

I The “theorem” (m n) + n = m is still not true(take m = 1, n = 2, for example)

I we still need that side-condition (n 6 m)I In general we find that most laws using (−) requiring

side-conditions like n 6 m, still require theseside-conditions if we use instead.

I We get more problems with divisionI What should m/0 be?I Careful ! A wrong choice here allows us to prove that “black

is white”!

Page 108: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Problems with “Totalisation”

I If a naturally partial function is to be totalised, be careful !I Laws may become unsound unless side-conditions are

addedI The side-conditions will frequently coincide with those that

determine when that function is defined.

CS4003 Formal Methods

Handling Undefinedness (II - live with it)

I Division’s partiality is a minor nuisanceI Just remember to add y 6= 0 whenever we see x/y

I However in computer science we have a more fundamentalproblem

I Consider a possibly partial function f : N→ Nimplemented faithfully as a program progF :

I If f (x ) is defined, then progF terminates on input x with theright answer

I If f (x ) is undefined, then progF may not terminateI The question “is f defined on x ” is then equivalent to

solving the halting problem for progFI The Halting Problem is undecidable — no algorithm can

ever solve it in all cases.

CS4003 Formal Methods

Consider this

I Consider the following code, (assuming n : N):

(n > 1)~ n := n/2 � even n � n := (3 · n + 1)/2

I Prove it refines the following (total-correctness)specification: n > 0 ` n′ = 1

I Done yet ?I If so, well done, take a bow, leave the class, go to MIT,

Stanford, Microsoft Research, wherever …I It is the so-called Collatz Conjecture (1937): it is known to

terminate for all n 6 260 (May 2011), but no proof that itterminates for all n has been found.

CS4003 Formal Methods

Handling Undefinedness (III - living with it)

I In the computer science domain, undefinedness is a fact oflife

I However, there is no universal agreement on how to handleit in formal logics.

I Some approaches:I Lots of definedness side-conditionsI Giving “meanings” to undefined expressionsI Triple-valued logics

Page 109: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Handling Undefinedness (IV - how we shall live with it)

I The use of a partial function/operator implies itsdefinedness side-conditione.g. the term (x + y )− z implies a condition z 6 x + y .

I When replacing a term by one that is equal, we shallexplicitly add in definedness conditions if the term thatrequired it disappears.

I e.g consider predicate v = ((x + y )− z)− ((x + y )− z)and law e − e = 0

I The term has an implicit side-condition: z 6 x + yI if we replace the term by 0 we get v = 0

but we have lost information about the side-condition.I We shall re-introduce the side-condition explicitly, so getting

v = 0 ∧ z 6 x + y .

CS4003 Formal Methods

A Theory of Lists (Syntax)

We use σ, τ for lists (a.k.a. sequences)

σ, τ ∈ T ∗ ::= . . .| 〈〉 empty list| x o

o σ list construction| 〈x1, . . . xn〉 list enumeration| head (σ) | tail(σ) list destruction (1)| front (σ) | last (σ) list destruction (2)| σ a τ list concatenation| #σ list length| σ 6 τ list prefix relation

CS4003 Formal Methods

Some axioms for lists

Axioms cover the basic building blocks

〈〈〈〉-is-T ∗〉〉 〈〉 : T ∗〈〈oo-is-T ∗〉〉 x : T ∧ σ : T ∗ ⇒ (x o

o σ) : T ∗〈〈〈〉-not-oo〉〉 〈〉 6= x o

o σ〈〈oo-injective〉〉 (x = y ) ∧ (σ = τ) ≡ (x o

o σ) = (y oo τ)

〈〈T ∗-Induction〉〉 P [〈〉/σ] ∧ (∀ v , τ • P [τ/σ]⇒ P [(v oo τ)/σ])

⇒ (∀σ | σ : T ∗ • P)

CS4003 Formal Methods

Some definitions for lists (!) (??)

〈〈head -def〉〉 head (x oo σ) = x

〈〈tail -def〉〉 tail(x oo σ) = σ

〈〈enumeration-def〉〉 〈x1, x2, . . . , xn〉 = x1oo (x2

oo (. . . (xn

oo 〈〉)))

〈〈a-〈〉-def〉〉 〈〉a τ = τ

〈〈a-oo-def〉〉 (x oo σ)a τ = x o

o (σ a τ)〈〈#-〈〉-def〉〉 #〈〉 = 0〈〈#-oo-def〉〉 #(x o

o σ) = 1 + #σ〈〈front -single-def〉〉 front 〈x 〉 = xs

〈〈front -oo-def〉〉 front (x oo σ) = x o

o front (σ)〈〈last -single-def〉〉 last 〈x 〉 = x

〈〈last -oo-def〉〉 last (x oo σ) = last (σ)

Note that head , tail , front and last are partial , defined only fornon-empty lists.

Page 110: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Some theorems for lists

〈〈a-r-unit〉〉 σ a 〈〉 = σ

〈〈#-a-morphism〉〉 #(σ a τ) = #σ + #τ

Proofs in class

CS4003 Formal Methods

Proof of 〈〈a-r-unit〉〉 (I)

I Goal: σ a 〈〉 = σ

I Strategy: induction over σ

Property P(σ) =̂ σ a 〈〉 = σBase Case Show P(〈〉)

Inductive Step Show P(τ)⇒ P(x oo τ)

CS4003 Formal Methods

Proof of 〈〈a-r-unit〉〉 (II)

Base Case P(〈〉) ≡ (〈〉a 〈〉 = 〈〉)Strategy: reduce LHS to RHS

〈〉a 〈〉= “ 〈〈a-〈〉-def〉〉 ”〈〉

CS4003 Formal Methods

Proof of 〈〈a-r-unit〉〉 (III)

Inductive Step P(τ)⇒ P(x oo τ)

Goal: (τ a 〈〉 = τ)⇒ ((x oo τ)a 〈〉 = x o

o τ)Strategy: assume LHS to show RHS〈〈ind-hyp〉〉 τ a 〈〉 = τ

(x oo τ)a 〈〉 = x o

o τ

= “ 〈〈a-oo-def〉〉 ”x o

o (τ a 〈〉) = x oo τ

= “ 〈〈ind-hyp〉〉 ”x o

o τ = x oo τ

= “ 〈〈=-refl〉〉 ”true

Page 111: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Some definitions for lists (!) (??)

〈〈front -single-def〉〉 front 〈x 〉 = 〈〉〈〈front -oo-def〉〉 front (x o

o σ) = x oo front (σ)

〈〈last -single-def〉〉 last 〈x 〉 = x〈〈last -oo-def〉〉 last (x o

o σ) = last (σ)

front and last are problematical, but not because they arepartial.

CS4003 Formal Methods

Gotcha !

Explain in Class

CS4003 Formal Methods

Ddefinitions for lists (Corrected, Safe)

〈〈head -def〉〉 head (x oo σ) = x

〈〈tail -def〉〉 tail(x oo σ) = σ

〈〈enumeration-def〉〉 〈x1, x2, . . . , xn〉 = x1oo (x2

oo (. . . (xn

oo 〈〉)))

〈〈a-〈〉-def〉〉 〈〉a τ = τ

〈〈a-oo-def〉〉 (x oo σ)a τ = x o

o (σ a τ)〈〈#-〈〉-def〉〉 #〈〉 = 0〈〈#-oo-def〉〉 #(x o

o σ) = 1 + #σ〈〈front -single-def〉〉 front 〈x 〉 = x

〈〈front -oo-def〉〉 front (x oo y o

o σ) = x oo front (y o

o σ)〈〈last -single-def〉〉 last 〈x 〉 = x

〈〈last -oo-def〉〉 last (x oo y o

o σ) = last (y oo σ)

Note that head , tail , front and last are partial , defined only fornon-empty lists.

CS4003 Formal Methods

Lists Theory: summary

I Induction using 〈〈T ∗-Induction〉〉 is the main proof techniquefor the laws of lists.

I Most if not all of the laws shown are done this wayI Care needs to be taken when defining functions ‘by cases’

I Need to ensure that overlapping cases do not conflict.

Page 112: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

A Theory of Sets

Axioms:

〈〈¬ -in-{}〉〉 x /∈ {}〈〈in-singleton〉〉 x ∈ {y} ≡ x = y

〈〈set-extensionality〉〉 S = T ≡ ∀ x • x ∈ S ≡ x ∈ T

Not a “traditional” axiomatization of set-theory !Definitions:

〈〈in-∪〉〉 x ∈ (S ∪ T ) ≡ x ∈ S ∨ x ∈ T〈〈in-∩〉〉 x ∈ (S ∩ T ) ≡ x ∈ S ∧ x ∈ T〈〈in-\〉〉 x ∈ (S \ T ) ≡ x ∈ S ∧ x /∈ T

〈〈def-⊆〉〉 S ⊆ T ≡ ∀ x • x ∈ S ⇒ x ∈ T

CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Class 20

Page 113: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Mini-Exercise 5

Q5 Given

n, f , x : Nfac(0) = 1fac(n) = n ∗ fac(n − 1), n > 0

FSpec =̂ f , x :[f ′ = fac(n)]FProg =̂ f , x := 1,2 ; (x 6 n)~ f , x := f ∗ x , x + 1

Using the partial correctness theory only:5.1 State clearly the proofs that need to be done.5.2 Determine a suitable invariant.5.3 Prove the statement that states that FSpec is

refined appropriately (Hint: one of the proofs in theanswer to 5.1).

(due in next Friday week, 2pm, in class)CS4003 Formal Methods

Tool Support

I Formal Methods sounds like a good idea in theoryI What about in practise ?I Real-world problems result in lots of small, non-trivial proof,

each not quite the same as any other.I Real-world use of formal methods requires tool support to

be practical.

CS4003 Formal Methods

Introducing U ·(TP)2

I U ·(TP)2 is a theorem proving assistant designed for UTPI It is under development here at TCDI A recet release suitable for CS4003 is now available

I U ·(TP)2 0.97α8I Open-source, has been built on Linux/Mac OS X; Binaries

for Windows

CS4003 Formal Methods

Getting and installing U ·(TP)2

I Follow link from Blackboard (“Tool Support” area)I (Windows) Download the ZIP fileI Copy everything into a new folderI If using Unix/Mac OS X, you can build from source

http://www.scss.tcd.ie/Andrew.Butterfield/Saoithin/I requires Haskell, wxHaskell (good luck!)

Page 114: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Distribution Files

Binaries UTP2.exewxc-msw2.8.10-0.11.1.2.dllSaoithin-*.wavkeep together

Documentation *.txtread !

CS4003 Formal Methods

Running U ·(TP)2

I Here we give examples on the Windows versionUn*x or OS X version will be much the same.

I To run, simply double-click on the .exe fileI A MS-DOS console window appears, followed shortly by

the top-level window.I the screenshots shown here are from an earlier years

version, but essentials are the same.

CS4003 Formal Methods

Workspaces

All your working files live in a workspace:I A directory holding your filesI U ·(TP)2 allows you to give it a nicknameI You can generate many independent such workspaces

CS4003 Formal Methods

Warnings

I Don’t mess with the files that appear in workspace foldersI Only exit the application using the Quit menu item in the

top-level “Theories” Window.I Avoid clicking the red X button in the top right corner of a

window(exception: do this to end the “Proof Key Shortcuts”window)

Page 115: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

U ·(TP)2 Top Level Window (first use)

CS4003 Formal Methods

U ·(TP)2 Top-Level Theory Stack

I Related definitions, axioms and laws form a “Theory”I U ·(TP)2 maintains a stack of theories, most general at the

bottom, most specific at the topI Higher theories may depend on lower onesI Theory 1 depends on Theory 2 if a proof in Theory 1 uses

a law from Theory 2I Circular dependencies are not permitted.

CS4003 Formal Methods

U ·(TP)2 Top Level Window (theory loaded)

CS4003 Formal Methods

U ·(TP)2 User-Interface

I We have the usual pull-down menusI Double-clicking on some items will “open” or “activate”

themI Right-clicking on some items or windows will bring up a

context-sensitive menu

Page 116: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

U ·(TP)2 Theories

I Theories consist of a series of tables:LAWS Name → Law Laws

OBS Name → Type Observation VariablesLANGUAGE Theory-specific language constructsPRECEDENCE Name → Type Binary Operator

PrecedencesTYPEdef Name → Type Type Definitions

CONSTdef Name → Expr Constant DefinitionsEXPRdef Name → Expr Expression DefinitionsPREDdef Name → Pred Predicate Definitions

TYPES Var → Type TypesCONJ. Name → Law Conjectures

THEOREMS Name → Proof Theorems

CS4003 Formal Methods

U ·(TP)2 Top Level Window (TYPES in Theory)

CS4003 Formal Methods

U ·(TP)2 Top Level Window (Laws)

CS4003 Formal Methods

U ·(TP)2 Top Level Window (Conjectures)

Page 117: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proving Conjectures

I To prove a conjecture, double-click on itI A proof window appearsI You have to pick a strategy for the proof.I The goal predicate is shown with the current “focus”

underlinedI All prover commands work on the focusI You move the focus with the arrow keys.

CS4003 Formal Methods

Proof Strategies

Deduce Reduce Goal down to true.L2R Transform Goal LHS (of ≡) into RHSR2L Transform Goal RHS into LHS

Red. Both Transform both LHS and RHS of Goal into samething

Law Reduce Transform named Law into GoalAssume Assume Goal LHS (of⇒) and prove RHS using

one of the first 4 strategies above.

CS4003 Formal Methods

Proof Actions

I The current focus in the goal is underlined, e.g. P ≡ QI Arrow keys allow the focus to be moved,

e.g., Down, then Left changes the above focus to P ≡ Q.I Right-click brings up the laws that can be applied to the

focusI Useful Key shortcuts

(see Help menu in Proof window for more):u undoes the most recent proof stepp prints the current proof state to a text filec switches between proof cases

(only applicable in certain strategies, like Red. Both)

CS4003 Formal Methods

Theorems

I Once a proof is complete it becomes a theorem and isstored in the theorems table.

I The default is also to make the theorem a law, and to saveit to a file.

I Right-clicking on a theory in the THEOREMS tab allowsyou to save the proof in ASCII text or LaTeX form

I (LATEX needs saoithin.sty — in installation zip)

Page 118: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods CS4003 Formal Methods

CS4003 Formal Methods CS4003 Formal Methods

Class 21

Page 119: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Design Lattice

true ` false Miracle

true ` x ′ = 3 true ` x ′ = 6

true ` (x ′ = 3 ∨ x ′ = 6)

true ` x ′ ∈ {1 . . . 10}

false ` true Chaos

v

CS4003 Formal Methods

Design-Predicate Lattice

¬ ok Miracle

ok⇒ok ′∧x ′=3 ok⇒ok ′∧x ′=6

ok⇒ok ′∧(x ′=3∨x ′=6)

ok⇒ok ′∧x ′∈{1...10}

true Chaos

v

CS4003 Formal Methods

Theology of Computing

¬ ok Miracle

ok⇒ok ′∧x ′=3 ok⇒ok ′∧x ′=6

ok⇒ok ′∧(x ′=3∨x ′=6)

ok⇒ok ′∧x ′∈{1...10}

true Chaos

v

CS4003 Formal Methods

Page 120: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 22

CS4003 Formal Methods

“Design-hood”?

I Consider the following:¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\′x = S\x

I When started in a divergent state, we terminate, incrementx , and leave other variables unchanged.

I Clearly not possible for a real program¬ ok means ‘not properly/yet started’)

I Is this predicate a design?I Can we re-write it in the form ok ∧ P ⇒ ok ′ ∧ Q?

I if not, how can “prove” it is not a design?

CS4003 Formal Methods

When is a predicate a Design?

I Our theory of total correctness is based on the notion ofdesigns,i.e. predicates of the form: ok ∧ P ⇒ ok ′ ∧ Q(or P ` Q)

I However, given an arbitrary predicate, how do wedetermine if it is a design ?

I Clearly one way is to transform it into the above form.I This can be quite difficult to do in some cases.I Is there an easier way?I Also, just what is it that characterises designs in any case?

CS4003 Formal Methods

Healthiness Conditions

I We view designs as “healthy” predicates,i.e., those that describe real programs and specifications.

I We shall introduce “healthiness conditions” that test apredicate to see if it is healthy.

I These conditions capture key intuitions about how realprograms behave

I Some will be mandatory — all programs and specificationswill satisfy these.

I Some will be optional — these characterise particularywell-behaved programs

Page 121: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Healthiness Condition 1 (H1)

H1 P = (ok ⇒ P)

I P only ‘takes effect’ when ok is true — i.e. program hasstarted

I When ¬ ok , then P says nothingI H1 above is equivalent to satisfying both of the following

laws:〈〈skip-; -unit〉〉 skip ; P = P〈〈; -L-Zero〉〉 Forever ; D = Forever

I Any design P ` Q satisfies the three laws above.

CS4003 Formal Methods

H1 Example (1)

What about ¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x ?

ok ⇒ ¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x= “ 〈〈⇒-def〉〉 ”¬ ok ∨ ¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x

= “ 〈〈∨-∧-absorb〉〉 ”¬ ok

So it is not H1-healthy

CS4003 Formal Methods

H1 Example (2)

What about x := e?

ok ⇒ x := e= “ 〈〈:=-def〉〉 ”

ok ⇒ (ok ⇒ ok ′ ∧ x ′ = e ∧ S ′\x ′ = S\x )= “ 〈〈shunting〉〉 ”

ok ∧ ok ⇒ ok ′ ∧ x ′ = e ∧ S ′\x ′ = S\x= “ 〈〈∧-idem〉〉 ”

ok ⇒ ok ′ ∧ x ′ = e ∧ S ′\x ′ = S\x= “ 〈〈:=-def〉〉 ”

x := e

So x := e is H1-healthy

CS4003 Formal Methods

H1 Example (3)

What about P ` Q?

ok ⇒ (P ` Q)= “ 〈〈`-def〉〉 ”

ok ⇒ (ok ∧ P ⇒ ok ′ ∧ Q= “ 〈〈shunting〉〉 ”

ok ∧ ok ∧ P ⇒ ok ′ ∧ Q= “ 〈〈∧-idem〉〉 ”

ok ∧ P ⇒ ok ′ ∧ Q= “ 〈〈`-def〉〉 ”

P ` Q

So any design is H1-healthy

Page 122: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Healthiness Condition 2 (H2)

H2 [P [False/ok ′]⇒ P [True/ok ′]]

I No specification can require non-termination.I if P is true when ok ′ is false, then it must also be true if ok ′

is true.I We introduce the following abbreviation:

Pb =̂ P [b/ok ′]

I so H2 becomes [P f ⇒ P t ](with f and t the obvious abbreviations for False and True.

I It is equivalent to satisfying the following law:

〈〈; -H2-R-Unit〉〉 P ; J = P〈〈J -def〉〉 J =̂ (ok ⇒ ok ′) ∧ S ′ = S

CS4003 Formal Methods

H2 Example (1)

Again, lets try ¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x .

(¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x )[False/ok ′]⇒ (¬ ok ∧ ok ′ ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x )[True/ok ′]

= “ substitution ”(¬ ok ∧ False ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x )⇒ (¬ ok ∧ True ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x )

= “ simplify ”False ⇒ (¬ ok ∧ x ′ = x + 1 ∧ S ′\x ′ = S\x )

= “ 〈〈GS3.75〉〉 ”true

So it is H2-healthy !

CS4003 Formal Methods

H2 Example (2)

Now, try ok ⇒ ¬ ok ′ (i.e requiring non-termination).

(ok ⇒ ¬ ok ′)[False/ok ′]⇒ (ok ⇒ ¬ ok ′)[True/ok ′]= “ substitution ”

(ok ⇒ ¬ False)⇒ (ok ⇒ ¬ True)= “ simplify ”

(ok ⇒ True)⇒ (ok ⇒ False)= “ 〈〈⇒-r-zero〉〉, 〈〈¬ -def〉〉 ”

True ⇒ ¬ ok= “ 〈〈⇒-l-unit〉〉 ”¬ ok

So it is not H2-healthy

CS4003 Formal Methods

H2 Example (3)

Finally, what about P ` Q,or ok ∧ P ⇒ ok ′ ∧ Q ?

(ok ∧ P ⇒ ok ′ ∧ Q)f ⇒ (ok ∧ P ⇒ ok ′ ∧ Q)t

= “ substitution, noting P and Q do not mention ok ′ ”(ok ∧ P ⇒ False ∧ Q)⇒ (ok ∧ P ⇒ True ∧ Q)

= “ simplify ”(ok ∧ P ⇒ False)⇒ (ok ∧ P ⇒ Q)

= “ 〈〈¬ -def〉〉 ”¬ (ok ∧ P)⇒ (ok ∧ P ⇒ Q)

= “ 〈〈⇒-def〉〉, 〈〈¬ -invol〉〉 ”ok ∧ P ∨ ¬ (ok ∧ P) ∨ Q

= “ 〈〈excluded-middle〉〉, simplify ”true

So designs are H2-healthy

Page 123: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Designs are H1,H2 are Designs are H1,H2 are …

I Any Design satisfies both H1 and H2I Any predicate satisfying both H1 and H2 is a DesignI So H1 and H2 are our mandatory healthiness conditions.I All programs and specifications (incl. Chaos and miracle)

satisfy these.I Two more conditions (H3, H4) characterise more

“well-behaved” predicates.

CS4003 Formal Methods

Healthiness Condition 3 (H3)

H3 P = P ; skip

I Running skip afterwards makes no differenceI Not true of all Designs (which fail this?)I If fails for a design P ` Q iff P is not a condition (i.e. has

dashed variables).

CS4003 Formal Methods

H3 Example (1)

I Let’s try x ′ = 2 ` trueexpands to ok ∧ x ′ = 2⇒ ok ′

“If started, and x ends up equal to 2, then I terminate”I

ok ∧ x ′ = 2⇒ ok ′

= “ 〈〈⇒-def〉〉, 〈〈deMorgan〉〉 ”¬ ok ∨ x ′ 6= 2 ∨ ok ′

= “ 〈〈⇒-def〉〉 ”ok ⇒ x ′ 6= 2 ∨ ok ′

“If started, either x ends up different from 2, or I terminate”I It’s a design, so H1,H2-healthy

CS4003 Formal Methods

H3 Example (1, cont.)

ok ∧ x ′ = 2⇒ ok ′; skip= “ 〈〈skip-def〉〉 ”

ok ∧ x ′ = 2⇒ ok ′; ok ⇒ ok ′ ∧ S ′ = S= “ 〈〈⇒-def〉〉, 〈〈; -def〉〉, 6-way (!) simplification ”¬ ok ∨ (∃ xm,okm • ¬ (xm = 2) ∧ ¬ okm) ∨ ok ′ ∨ (. . .)

= “ witness, xm = 1,okm = False ”¬ ok ∨ true ∨ ok ′ ∨ (. . .)

= “ 〈〈∨-zero〉〉 ”true

Not equal to ok ∧ x ′ = 2⇒ ok ′, so not H3-healthy

Page 124: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

H3 Example (2)

Now, try miracle, a.k.a. ¬ ok

¬ ok ; skip= “ 〈〈skip-def〉〉, 〈〈⇒-def〉〉 ”¬ ok ; ¬ ok ∨ ok ′ ∧ S ′ = S

= “ 〈〈; -def〉〉,substitution ”∃okm,Sm • ¬ ok ∧ (¬ okm ∨ ok ′ ∧ S ′ = Sm)

= “ 〈〈∧-∨-distr〉〉, 〈〈∃-distr〉〉 ”(∃okm,Sm • ¬ ok ∧ ¬ okm) ∨(∃okm,Sm • ¬ ok ∧ ok ′ ∧ S ′ = Sm)

= “ simplify ”¬ ok ∨ ¬ ok ∧ ok ′

= “ 〈〈∨-∧-absorb〉〉 ”¬ ok

So miracle is H3-healthy

CS4003 Formal Methods

Healthiness Condition 4 (H4)

H4 P ; true = true

I A H4-healthy program cannot force termination of whatruns afterward.

I All real programs satisfy this property.I H4 states that a predicate is Feasible.

There is a program that has this behaviour.

CS4003 Formal Methods

H4 Example (1)

What about miracle?It satisfies any specification?Is it feasible?

miracle; true= “ miracle is ¬ ok ”¬ ok ; true

= “ 〈〈; -def〉〉, substitution ”∃okm,Sm • ¬ ok ∧ true

= “ drop quantifiers, simplify ”¬ ok

It is not feasible, thankfully !

CS4003 Formal Methods

Healthiness: SummaryI We have 2 mandatory healthiness conditions for designs

H1 P = ok ⇒ P(skip; P = P) ∧ (true; P = true)

H2 [P f ⇒ P t ]P = P ; J

I We have 2 additional conditions capturing better behaviour

H3 P = P ; skipH4 P ; true = true

I If P and Q are Hi-healthy (i ∈ 1 . . . 4), then so are

P ; Q P u Q P � c � Q c ~ P

Page 125: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Design Semantics of true~ skip

I As before, we try to find something that satisfies theloop-unrolling law for Forever , namely:

X = skip; X

I However, now we restrict ourselves to designs only, anduse the design definition for skip

I Under what conditions does design D(= P ` Q) satisfy theabove law ?

I All designs satisfy it !It is just law 〈〈skip-; -unit〉〉, already proven.

CS4003 Formal Methods

Choosing fixpoint for meaning of true~ skip

I Any design satisfies the loop-unrolling law for true~ skip(a.k.a. Forever ).

I We have a good reason to want the least such design,namely false ` true (which reduces to true).

〈〈Forever -def〉〉 Forever =̂ true

I Does it give us the desired laws ?

〈〈; -L-Zero〉〉 Forever ; D = Forever〈〈; -R-Zero〉〉 D; Forever = Forever

Here D are designs

CS4003 Formal Methods

Proof of 〈〈; -L-Zero〉〉

Goal: Forever ; D = ForeverStrategy: reduce rhs to lhs

Forever ; D= “ 〈〈Forever -def〉〉, D = P ` Q ”

true; P ` Q= “ 〈〈`-def〉〉 ”

true; ok ∧ P ⇒ ok ′ ∧ Q= “ 〈〈; -def〉〉, with substitution ”∃Sm,okm • true ∧ (okm ∧ P [Sm/S]⇒ ok ′ ∧ Q[Sm/S])

= “ simplify, 〈〈⇒-def〉〉 ”∃Sm,okm • ¬ (okm ∧ P [Sm/S]) ∨ ok ′ ∧ Q[Sm/S]

= “ 〈〈deMorgan〉〉 ”∃Sm,okm • ¬ okm ∨ ¬ P [Sm/S] ∨ ok ′ ∧ Q[Sm/S]

CS4003 Formal Methods

Proof of 〈〈; -L-Zero〉〉, cont.

∃Sm,okm • ¬ okm ∨ ¬ P [Sm/S] ∨ ok ′ ∧ Q[Sm/S]= “ shrink ∃ scope ”

(∃okm • ¬ okm) ∨ (∃Sm • ¬ P [Sm/S] ∨ ok ′ ∧ Q[Sm/S])= “ witness, okm = False ”

true ∨ (∃Sm • ¬ P [Sm/S] ∨ ok ′ ∧ Q[Sm/S])= “ simplify ”

true= “ 〈〈Forever -def〉〉 ”

Forever�

Page 126: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Proof of 〈〈; -R-Zero〉〉

I Goal: D; Forever = ForeverI Strategy: reduce rhs to lhsI

D; Forever= “ 〈〈Forever -def〉〉 ”

D; true

I But stating this equals Forever , i.e. true, is the same asstating that D is H4-healthy (feasible)!

I We need to revise our law:

〈〈; -R-Zero〉〉 D is H4⇒ (D; Forever = Forever )

CS4003 Formal Methods

Design Coda

I You have been introduced to Predicate Calculus as aFormal Language “game”.

I You have seen how the language can be extended so thatyou can play with the meanings of programs.

I You have seen how the key concepts of loop invariant andvariant respectively allow you to reason formally about thecorrectness and termination of while-loops.

I You have (just) encountered the notion of a Design,namely a predicate describing a specification or programas an explicit pre-/post-pair, with termination handledimplicity.

I We have seen that Designs, and interesting sub-classescan be characterised as healthiness conditions onpredicates.

CS4003 Formal Methods CS4003 Formal Methods

Page 127: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 23

CS4003 Formal Methods

Using U ·(TP)2

I This class is a live demo of the U ·(TP)2 proof assistantI Uses a theory based on the Gries & Schneider book “A

Logical Approach to Discrete Math”, Springer, 1995.I Some proofs will be done in class.I More will be left as an exercise

See Blackboard for details

CS4003 Formal Methods CS4003 Formal Methods

Page 128: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 24

CS4003 Formal Methods

Formalising Healthiness

I We want to formalise our notion of healthinessI Remember, the following are our conditions

H1 P = ok ⇒ PH2 P = P ; JH3 P = P ; skipH4 P ; true = true

I They all (except H4) have the same form: P = H(P)where H describes the appropriate “function” of P .

I We shall now formalise this notion

CS4003 Formal Methods

Formalising H1

I We shall define a function that takes a predicate asparameter, and returns True if the predicate is H1-healthy:

isH1(P) =̂ P = (ok ⇒ P)

I We refine this further by introducing another function thatgiven a predicate returns an appropriately modifiedpredicate

mkH1(P) =̂ ok ⇒ PisH1(P) =̂ P = mkH1(P)

I What we have done is to start a new formal gamealtogether !

CS4003 Formal Methods

Higher-Order Logic

I Up to now, we have been using “First-Order predicatecalculus”

I we have built predicates from basic parts using fixedoperators.

I Any functions have only existed inside the expression(sub-)language

I All quantification variables have been limited to expressionvariables only

I Now we are moving towards “Higher-Order Logic”I We are introducing predicates about predicates (e.g. isH1)I We are introducing functions

that transform predicates (e.g. mkH1)I UTP also allows quantifier variables

to range over predicates

Page 129: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

2nd-Order Predicates

I A first-order predicate P is a function over environmentvariables, returning True or False:

[[P ]] : Env → B

I A second-order predicate P is a function from predicates toTrue or False:

[[P]] : Pred → B

I We can expand this as:

[[P]] : (Env → B)→ B

I So isH1 is just such a 2nd-order predicate.CS4003 Formal Methods

Predicate Transformers

I A predicate-transformer F is a function over predicates,returning a predicate as a result:

[[F]] : Pred → Pred

I We can expand this also as

[[F]] : (Env → B)→ (Env → B)

I Function mkH1 is a predicate transformer

CS4003 Formal Methods

Changing the Game (I)

I We add a new category to our language: that of ahigher-order definition

P ,Q,R,S ∈ PVar predicate (meta-)variablesH,F ∈ HOF higher order functions

HOFDef ::= H(P) =̂ body HOF definition

I We extend our notion of predicate to allow the applicationof a HOF to a predicate argument

P ∈ Pred ::= . . . | H(P)

CS4003 Formal Methods

Changing the Game (II)

I Given H(P) =̂ body , we have a new law:

H(MyPred ) = body [MyPred/P ]

Where we now have substitution notation extended to allowpredicates to replace predicate variables.

I The addition of higher-order functions(i.e. those that take predicates as arguments) gives“monadic 2nd-order logic”

I If we also allow quantification over predicates

Pred ::= . . . | ∀P • H(P)

we get “full 2nd-order logic”

Page 130: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

2nd-order Logic

I 2nd-order logic is strictly more powerful than 1st-orderI When quantifying over a predicate, it is interpreted as a

function from the environment to booleanI so

∀P • H(P)

is interpreted as meaning :“ for all functions F : Env → B, the predicateH(F ) evaluates to true in any environment ”

I UTP is based on full 2nd-order logicI needed to treat recursion properlyI needed to reason about healthiness.

CS4003 Formal Methods

Revisiting Healthiness

I We can now formalise our healthiness conditions asfollows:

mkH1(P) =̂ ok ⇒ PmkH2(P) =̂ P ; JmkH3(P) =̂ P ; skip

isHi(P) =̂ P = mkHi(P), i ∈ 1,2,3isH4(P) =̂ P ; true = true

I Apart from H4, we have the same pattern:I a predicate transformer mkHI a predicate condition isH, defined in terms of the former

I We shall take a closer look at mkH.

CS4003 Formal Methods

The Nature of mkH

I Consider the application mkH(P)I We can interpret mkH as a “healthifying” function

(i.e. it makes predicates healthy)I What if P is already healthy?

I Then it satisifes isH, which says P = mkH(P)I So mkH should not change an already healthy predicate

I We are led to the following requirement for any “healthifier”mkH:

mkH(mkH(P)) = mkH(P)mkH ◦mkH = mkH

i.e. all such HOFs must be idempotent .I Once a predicate has been “made healthy”, then further

attempts to do so should bring about no further change.

CS4003 Formal Methods

A Notational Convention (obvious, yet confusing!)

I We have definitions provided for mkHI We define isH as P = mkH(P)

I It is standard practise in the UTP literature to use H todenote both of these functions

I Which of mkH or isH is meant can (usually) be deducedfrom context

I We shall adopt this convention from now on.

Page 131: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

H1 is idempotent

We want to show that H1 ◦ H1 = H1Reduce Lhs to Rhs

H1(H1(P))= “ defn. H1 (a.k.a mkH1) ”

ok ⇒ (ok ⇒ P)= “ 〈〈⇒-def〉〉 ”¬ ok ∨ ¬ ok ∨ P

= “ 〈〈∨-idem〉〉 ”¬ ok ∨ P

= “ 〈〈⇒-def〉〉 ”ok ⇒ P

= “ defn. H1 ”H1(P)

CS4003 Formal Methods

H2 is idempotent

We want to show that H2 ◦ H2 = H2Reduce Lhs to Rhs

H2(H2(P))= “ defn. H2 ”

(P ; J); J= “ 〈〈; -assoc〉〉 ”

P ; (J ; J)= “ Lemma: J ; J = J ”

P ; J= “ defn. H2 ”

H2(P)

CS4003 Formal Methods

Lemma Proof (I)

Goal: J ; J = JReduce lhs to rhs

J ; J= “ defn. J ”

((ok ⇒ ok ′) ∧ S ′ = S); ((ok ⇒ ok ′) ∧ S ′ = S)= “ 〈〈⇒-def〉〉, 〈〈; -def〉〉, substitution ”∃okm,Sn •

(¬ ok ∨ okm) ∧ Sm = S ∧ (¬ okm ∨ ok ′) ∧ S ′ = Sm= “ 〈〈∃-1pt〉〉, Sm = S ”∃okm • (¬ ok ∨ okm) ∧ (¬ okm ∨ ok ′) ∧ S ′ = S

= “ shrink scope, 〈〈∧-∨-distr〉〉, 〈〈∨-∧-distr〉〉 ”S ′ = S ∧ (∃okm •¬ ok ∧ ¬ okm ∨ ¬ ok ∧ ok ′

∨ okm ∧ ¬ okm ∨ okm ∧ ok ′)

CS4003 Formal Methods

Lemma Proof (II)

S ′ = S ∧ (∃okm •¬ ok ∧ ¬ okm ∨ ¬ ok ∧ ok ′

∨ okm ∧ ¬ okm ∨ okm ∧ ok ′)= “ 〈〈contradiction〉〉, shrink scope, simplify ”S ′ = S ∧ (¬ ok ∧ (∃okm • ¬ okm)

∨ ¬ ok ∧ ok ′

∨ (∃okm • ¬ okm) ∧ ok ′ )= “ witness, simplify ”S ′ = S ∧ (¬ ok ∨ ¬ ok ∧ ok ′ ∨ ok ′ )

= “ 〈〈∨-∧-absorb〉〉 ”S ′ = S ∧ (¬ ok ∨ ok ′ )

= “ 〈〈⇒-def〉〉, ”S ′ = S ∧ (ok ⇒ ok ′)

= “ defn. J ”J

Page 132: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Aside: the (un-)Healthiness of J

I We have just seen that J ; J = J , i.e. that J is H2-healthyI What about H1(J) and H3(J)?I Careful calculation shows

H1(J) = ok ⇒ J = skipH3(J) = J ; skip = skip

I So J is not H1 or H3, and attempts to “healthify” it usingeither H1 or H3 turn it into skip

CS4003 Formal Methods

H3 is idempotent

We want to show that H3 ◦ H3 = H3Reduce Lhs to Rhs

H3(H3(P))= “ defn. H3 ”

(P ; skip); skip= “ 〈〈; -assoc〉〉 ”

P ; (skip; skip)= “ 〈〈skip-; -unit〉〉, with P = skip ”

P ; skip= “ defn. H3 ”

H3(P)

CS4003 Formal Methods

Designs: a final comment

I Given D which we know is a design(because we have shown it to be H1 and H2)can we write it in the form P ` Q

I Can we determine P and Q, given D ?I Yes

I If D is H1- and H2-healthy, then

D = (¬ D f ` D t )

I The precondition is those situations that do not lead took ′ = False, i.e. ¬ D[False/ok ′]

I The post condition is those situations that end withok ′ = True, i.e. D[True/ok ′]

CS4003 Formal Methods

Other Useful Properties of Healthiness

I We require healthiness transformers to be idempotentI Another useful property is having independence of

healthiness conditions:I the order in which most healthiness transformers are

applied is immaterial.I e.g.

H1 ◦ H2 = H2 ◦ H1H1 ◦ H3 = H3 ◦ H1H3 ◦ H2 = H2 ◦ H3

We say that H1, H2 and H3 “commute”.

Page 133: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Why Commuting is good

I Commuting healthiness is very convenient.Knowing P is both H1 and H2 allows us to replace it byeither H1(P) or H2(P) in a proof.

I If Ha and Hb (say) don’t commute, then Ha(Hb(P)) andHb(Ha(P)) are different.

I If P is (Ha ◦ Hb)-healthy,then we can replace P in a proof by

Ha(P) or Ha(Hb(P))

but not byHb(P).

I Why/Why not? (do in class)

CS4003 Formal Methods

Proof that H1 and H2 commute

I Goal: H1 ◦ H2 = H2 ◦ H1I alternatively

H1(H2(P)) = H2(H1(P))

I Strategy: reduce both sides to same

CS4003 Formal Methods

Proof that H1 and H2 commute (LHS)

H1(H2(P))= “ defns., H1, H2 ”

ok ⇒ (P ; J)= “ 〈〈⇒-def〉〉 ”¬ ok ∨ (P ; J)

= “ ¬ ok (a.k.a. miracle) is a design and hence H2 ”H2(¬ ok ) ∨ (P ; J)

CS4003 Formal Methods

Proof that H1 and H2 commute (RHS)

H2(H1(P))= “ defns., H1, H2 ”

(ok ⇒ P); J= “ 〈〈∨-; -distr〉〉 (see below) ”

(¬ ok ; J) ∨ (P ; J)= “ defn. H2 ”

H2(¬ ok ) ∨ (P ; J)�

We have used 〈〈∨-; -distr〉〉: (P ∨ Q); R ≡ (P ; R) ∨ (Q; R)whose proof is left as a (voluntary) exercise.

Page 134: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 25

CS4003 Formal Methods

Monotonicity of HOFsI We have an ordering on predicates based on refinement

I If P refines S, then we view S as having less informationthan P , and we write S v P .

I We see Chaos, the “whatever” specification as least by thisordering

I We view miracle, the “satisfy-anything” (infeasible) programas top-most

I We now introduce the notion of monotonicity for HOFsI HOF F is monotonic if, forall predicates P and Q

(P v Q) ⇒ (F(P) v F(Q))

I Note how monotonicity can be defined as a 2nd-orderpredicate!

I This property states that if F is monotonic then refining itsargument refines its result.

CS4003 Formal Methods

Program Language Constructs as HOFs

I We can re-cast much of our program language constructsas HOFs.

I For example, consider the while loop: c ~ PI We can consider this a function of P (how?)I Simple, define

WLOOPc(P) =̂ c ~ P

I It turns out that WLOOPc is monotonicI So if P v Q then

WLOOPc(P) vWLOOPc(Q),i.e. c ~ P v c ~Q

CS4003 Formal Methods

2-place HOFs

I With 2-place HOFs we can define the other languageconstructs

I

SEQ(P ,Q) =̂ P ; QCONDc(P ,Q) =̂ P � c � Q

I We say a 2-place HOF F( , ) is:I Monotonic in 1st arg. if P v Q ⇒ F(P ,R) v F(Q,R)I Monotonic in 2nd arg. if P v Q ⇒ F(R,P) v F(R,Q)

I F( , ) is simply Monotonic, if it is monotonic in botharguments

I Both SEQ and CONDc are (simply) MonotonicI The notion of monotonicity extends to n-place HOFs in the

obvious way.

Page 135: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Monotonicity preserved by composition

If F and G are monotonic, then so is F ◦G

P v Q⇒ “ G is monotonic ”

G(P) v G(Q)⇒ “ F is monotonic ”

F(G(P)) v F(G(Q))

This generalises to n-place HOFs as well

CS4003 Formal Methods

Testing for Monotonicity

I There are two ways to test F to see if it is monotonic.I The hard (direct) way:

Prove the relevant (2nd-order) theorem:

∀P ,Q • (P v Q)⇒ (F(P) v F(Q))

I An easier (indirect way):Consider the definition of F, which will look something like:

F(P) =̂ a predicate mentioning P somewhere

I By analysing the “predicate mentioning P ” we candetermine (to a great extent) if F is monotonic.

CS4003 Formal Methods

Monotonicity Analysis

I F(P) is monotonic if every occurrence of P in its definitionis at a “positive” location.

I A location is positive if we pass down through an evennumber of negations to get to it.

I a negation here is either(i) going through an application of ¬ , or(ii) going down the lhs of⇒ (why?)

I A location is negative if we pass down through an oddnumber of negations to get to it.

I If P occurs in both positive and negative locations, then itsoccurrences are said to be mixed .

I passing through either argument of ≡ results in a mixedoccurrence.

I U ·(TP)2 keeps track of a location’s polarity as focus ismoved into a predicate.

CS4003 Formal Methods

Anti-Monotonicity

I HOF F is anti-monotonic if, forall predicates P and Q

(P v Q) ⇒ (F(Q) v F(P))

I F(P) is anti-monotonic if every occurrence of P is in anegative location.

Page 136: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Monotonicity Example I

Is F(P) =̂ P ∧ (∃ x • Q ⇒ P) monotonic?

P ∧ (∃ x • Q ⇒ P)“ mark occurrence polarity ”

P+ ∧ (∃ x • Q− ⇒ P+)+

“ both P are labelled with + ”F confirmed monotonic

CS4003 Formal Methods

Monotonicity Example II

Is F(Q) =̂ P ∧ (∃ x • Q ⇒ P) monotonic?

P ∧ (∃ x • Q ⇒ P)“ mark occurrence polarity ”

P+ ∧ (∃ x • Q− ⇒ P+)+

“ the sole Q is labelled with − ”F confirmed non-monotonic

CS4003 Formal Methods

Monotonicity Example III

Is F(P) =̂ P ∧ ¬ (∃ x • P ⇒ Q) monotonic?

P ∧ ¬ (∃ x • P ⇒ Q)“ mark occurrence polarity ”

P+ ∧ (¬ (∃ x • P+ ⇒ Q−)−)+

“ both P are labelled with + ”F confirmed monotonic

CS4003 Formal Methods

Monotonicity Example V

Is F(P) =̂ P ∧ (P ≡ Q) monotonic?

P ∧ (P ≡ Q)“ mark occurrence polarity ”

P+ ∧ (P± ≡ Q±)+

“ so, not monotonic then... ”= “ logic (exercise) ”

P ∧ Q“ mark occurrence polarity ”

P+ ∧ Q+

“ so is monotonic after all !!! ”

This example shows the limitations of this technique for testingfor monotonicity

Page 137: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Polarity Testing: preparationI The last example shows a limitation of polarity marking for

assessing monotonicityI The problem area was any operator that introduces mixed

polarityI One strategy is to simplify the predicate by replacing

P ≡ Q by either

(P ⇒ Q) ∧ (Q ⇒ P)

or(P ∧ Q) ∨ (¬ P ∧ ¬ Q)

I Then do further simplification, down to the “the or-ing of theand-ing of possibly negated atomic predicates”

I However this is getting almost as complicated as doing adirect proof of monotonicity.

CS4003 Formal Methods

Fixpoints

I For a function f whose input and output types are the same(endofunction), a fixed point (fixpoint) is a solution to theequation

x = f (x )

I Fixpoints crop up everywhere in CS theoryI any time iteration or recursion is involved

I There are at least two uses of fixpoints in UTP:1. defining the meaning of recursion/iteration2. healthy predicates are fixpoints of “healthifiers”

CS4003 Formal Methods

Further Significance of Monotonicity

I Knaster-Tarski Fixpoint Theorem (1955)I Let L be a complete lattice,I and F : L → L be a monotonic function,I then the fixpoints of F form a complete lattice

I A complete lattice is non-empty, so at least one fixpointmust exist

I We must have a least and greatest fixpointI Under the right conditions (F continuous, or n ranging

transfinitely), then we can compute the least fixpoint as

lub{Fn(⊥) | n ∈ 0 . . .}F0(x ) =̂ x

Fn+1(x ) =̂ F(Fn(x ))

where lub is the least upper bound

CS4003 Formal Methods

Healthy Lattices

I Healthy Predicates are fixpoints of “healthifier” functionsI If those “healthifiers” are monotonic, then the healthy

predicates themselves form a complete lattice w.r.t.refinement

I Are H1, H2 and H3 monotonic?

Page 138: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Monotonicity Check: H

H1H1(P) = ok ⇒ P+

(monotonic)

H2

H2(P) = P ; J= ∃Om • P+[Om/O′] ∧ J [Om/O]

(monotonic)

H3

H3(P) = P ; Skip= ∃Om • P+[Om/O′] ∧ Skip[Om/O]

(monotonic)

CS4003 Formal Methods

Recursion in UTP

I Healthy predicates (H1,H2,H3) form a complete latticeunder the refinement ordering

I All our programming language HOFs are monotonicI So we can define the while loop semantics as the least

fixed point of an appropriate HOF w.r.t the refinementordering:

c ~ P =̂ lfp(λW • P ; W � c � Skip)

I Our functions are usually continuous, so we can computethe fixpoint:

lfp F =∧{Fn(Chaos) | n ∈ 0 . . .}

CS4003 Formal Methods

Calculating While-Loop Semantics

So often we can calculate the while-loop semantics as

c ~ P = ⊥∧ P ; ⊥ � c � Skip∧ P ; (P ; ⊥ � c � Skip) � c � Skip∧ P ; (P ; (P ; ⊥ � c � Skip) � c � Skip) � c � Skip...

where ⊥ = Chaos = true

CS4003 Formal Methods

Refinement Revisited

I We are now in a position to look at refinement againI A key property we want of refinement is that it be

compositional:I we should be able to refine a specification into code in small

steps.I This breaks into two aspects:

I Transitivity : we want to proceed by stages

(S v D) ∧ (D v P) ⇒ S v P

We can refine S first to D, and then refine that to PI Monotonicity : we want to work on sub-parts

(D v P) ⇒ F(D) v F(P)

We can refine F(D) by refining component D into P .

Page 139: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Spec-/Program-Construct Monotonicity

I Having specification and programming constructs that aremonotonic is very important in allowing practicalrefinement.

I We have seen that the program constructs (SEQ, CONDc ,WLOOPc ) are monotonic

I What about specification frames (w :[P , Q]),or designs (P ` Q) ?

I Lets define HOFs for these:

SPECw (P ,Q) =̂ w :[P , Q]DSGN(P ,Q) =̂ P ` Q

Are they monotonic ?

CS4003 Formal Methods

Designs, Frames and (Anti-)Monotonicity

I Expand our definitions of SPECw and DSGN :

SPECw (P ,Q) = ok ∧ P ⇒ ok ′ ∧ Q ∧ S ′ = SDSGN(P ,Q) = ok ∧ P ⇒ ok ′ ∧ Q

I We find that both are monotonic in their second argument,but anti -monotonic in their first .

I This explain why in refinement laws, in order to show that

(P ` Q) v (R ` S)

it is necessary to show R v P , rather than vice-versa.I In other words, preconditions appear in a negative position.

CS4003 Formal Methods CS4003 Formal Methods

Page 140: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 26

CS4003 Formal Methods

Live Proof Demo using U ·(TP)2

That’s all, folks!

CS4003 Formal Methods CS4003 Formal Methods

Page 141: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 27

CS4003 Formal Methods

Correctness via Verification Conditions

I Introduce notion of assertion statementsI Programmer adds assertions to program at appropriate

pointsI Verification Conditions are automatically extractedI Verification conditions are proven (automatically?).I Technique tailored for sequential imperative programs

CS4003 Formal Methods

Assertions

I An assertion c⊥ is a (specification) statement that acondition holds.

I if c is true, then c⊥ behaves like SkipI if c is false, then c⊥ behaves like ChaosI

c⊥ =̂ Skip � c � Chaos

I Often written as as {c} in the literatureI In UTP we can reason about them directly (e.g.):

b⊥; c⊥ = (b ∧ c)⊥

CS4003 Formal Methods

Verification Conditions

I A verification condition (VC) is a predicate relating twoassertions

I Verification conditions depend on the program fragmentbetween the two assertions.

I Given (suitably) annotated program pre⊥; prog ; post⊥:I we can automatically derive a VC involving pre⊥ and post⊥I that depends on the structure and contents of prog .

I Hope: VCs are simple enough to be proven automatically.I Think of them as machine-readable (machine-verifiable?)

comments !

Page 142: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Appropriate Annotations

A program is appropriately annotated ifI in a sequence P1; P2; · · · ; Pn there is an assertion before

every statement that is not an assignment or Skip.I in every while-loop there is an (invariant) assertion at the

start of the loop bodyI The first assertion should be a consequence of the

pre-condition from the specificationI The last assertion should imply the specification

post-condition.I Note: this approach works for post-conditions that are

conditions (i.e. snapshots of state, and not before-afterrelations).

CS4003 Formal Methods

Annotation Example

The integer division algorithm from [Hoare69] with annotations:

true⊥;r := x ;q := 0;(y ≤ r )∗

( (x = r + y ∗ q)⊥;r := r − y ;q := q + 1

);(x = r + (y ∗ q) ∧ r < y )⊥

CS4003 Formal Methods

Generating VCs

I VCs are generated for all the program statementsI We shall define VC generation recursively over program

structuregenVC : Program → PVC

CS4003 Formal Methods

VC generation (; )

I Given that the last statement is an assignment

genVC(p⊥; P1; . . . ; Pn−1; v := e; q⊥)= genVC(p⊥; P1; . . . ; Pn−1; q[e/v ]⊥)

We drop the assignment and replace all free occurrencesof v in the last assertion by e.

I Given that the last statement is an not an assignment

genVC(p⊥; P1; . . . ; Pn−1; r⊥; Pn; q⊥)= genVC(r⊥; Pn; q⊥)∪ genVC(p⊥; P1; . . . ; Pn−1; r⊥)

We process the last statement and the recursively treat therest of the sequence.

Page 143: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

VC generation (:=)I

genVC(p⊥; x := e; q⊥) =̂ {p ⇒ q[e/x ]}The pre-condition must imply the post-condition with vreplaced by e.

I Example:

genVC(p⊥; r := r − y ; q⊥) =̂ {p ⇒ q[r − y/r ]}

I So, given (x = r + y ∗ q)⊥; r := r − y , what assertion atthe end will work?

I Not (x = r + y ∗ q)⊥, because

x = r + y ∗ q 6⇒ x = r − y + y ∗ q

I Assertion x = r + y ∗ (q + 1)⊥ does work, because

x = r + y ∗ q ⇒ x = r − y + y ∗ (q + 1)

CS4003 Formal Methods

VC generation (� �)

I

genVC(p⊥; P1 � c � P2; q⊥)= genVC((p ∧ c)⊥; P1; q⊥)∪genVC((p ∧ ¬ c)⊥; P2; q⊥)

We add the branch condition to the pre-condition of thethen-branch, and its negation to that of the else-branch.

CS4003 Formal Methods

VC generation (∗)

I

genVC(p⊥; c ∗ (i⊥; P); q⊥)= {p ⇒ i , i ∧ ¬ c ⇒ q}∪genVC((i ∧ c)⊥; P ; i⊥)

I These correspond closely to our proof technique for loops:I p ⇒ i

— pre-condition sets up invariantI i ∧ ¬ c ⇒ q

— invariant and termination satisfies postconditionI (i ∧ c)⊥; P ; i⊥

— invariant and loop-condition preserve the invariant

CS4003 Formal Methods

VCs generated by our example.

I Do in classI Solution

true ⇒ x = x ∧ 0 = 0r = x ∧ q = 0 ⇒ x = r + (y ∗ q)

x = r + y ∗ q ∧ ¬ (y ≤ r ) ⇒ x = r + (y ∗ q) ∧ r < yx = r + y ∗ q ∧ y ≤ r ⇒ x = r − y + (y ∗ (q + 1))

I These are simple enough to do by hand (or with U ·(TP)2).I Automated provers with good arithmetic facilities should

also handle these.

Page 144: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

VCs in the “real world”

VC generation and proof is used in a wide range of verificationtools:I SparkADA — dialect of ADA used by Praxis used in the

Tokeneer projectI Java/ESC — Extended Static Checker for Java (uses Java

Modelling Language for assertion annotations)I Spec# — Mircosofts Specification/Verification oriented

language

CS4003 Formal Methods

Avoiding Annotations

I Using VCs requires lots of annotations by the programmerI Can be good discipline for documention codeI Can it be avoided ?I Can it be automated ?

Given pre⊥; prog ; post⊥ can we generate the internalassertions, and then the VCs ?

CS4003 Formal Methods

Another look at refinement

I We want to determine if pre ` post ′ is refined by prog

pre ` post ′ v prog= [prog ⇒ pre ` post ′]= [prog ⇒ (ok ∧ pre ⇒ ok ′ ∧ post ′)]= [ok ∧ pre ⇒ (prog ⇒ ok ′ ∧ post ′)]= [ok ∧ pre ⇒ ∀okm,Sm • prog ⇒ ok ′ ∧ post ′]= [ok ∧ pre ⇒ ¬ ∃okm,Sm • prog ∧ (ok ′ ⇒ ¬ post ′)]= [ok ∧ pre ⇒ ¬ (prog ; ¬ post ′)]

I ¬ (prog ; ¬ post ′) is the weakest condition under whichprog is guaranteed to achieve post ′

CS4003 Formal Methods

Weakest PreconditionI We define a new language construct

prog wp post

It means the weakest pre-condition under which runningprog will guarantee outcome (condition) post .

I In UTP we can define it as

Q wp r =̂ ¬ (Q; ¬ r ′)

Look familiar ?I It can be shown to obey the following laws:

x := e wp r ≡ r [e/x ]P ; Q wp r ≡ P wp (Q wp r )

(P � c � Q) wp r ≡ (P wp r ) � c � (Q wp r )(P uQ) wp r ≡ (P wp r ) ∧ (Q wp r )

Page 145: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Using WP

I The idea is to start with the post-condition and workbackwards, generating weakest conditions.

P1; . . . ; Pn−2; Pn−1; Pn wp post≡ P1; . . . ; Pn−2; Pn−1 wp (Pn wp post )≡ P1; . . . ; Pn−2 wp (Pn−1 wp (Pn wp post ))...≡ P1 wp (. . .Pn−2 wp (Pn−1 wp (Pn wp post )) . . .)

I We then show that the precondition pre implies the overallweakest precondition

pre ⇒ P1; . . . ; Pn−2; Pn−1; Pn wp post

CS4003 Formal Methods

The problem with WP

I Where is the while-loop ?I We can show the following for WP and while-loops:

(c ∗ P) wp r =̂ w such thatw ⇒ (¬ c ⇒ r )w ⇒ c ⇒ P wp ww is the weakest such predicate

I Calculating c ∗ P wp r involves some form of a search forsuch a w .

I Automating it successfully is equivalent to solving theHalting Problem (impossible).

CS4003 Formal Methods

WP for while loops

I If the user supplies an Invariant inv and variant V , then wecan define c ∗ P wp r

I If we ignore termination, we can define the following

(c ∗ P) wp r =̂ inv∧ (c ∧ inv ⇒ P wp inv )∧ (¬ c ∧ inv ⇒ r )

(Technically this is weakest liberal precondition — WLP)I We can automatically put in placeholder names for inv

(and V ), but at some stage the user will have to decidewhat they should be.

CS4003 Formal Methods

Page 146: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 28

CS4003 Formal Methods

Laws of WP

This class was live proofs of the wp laws from the previous class

CS4003 Formal Methods CS4003 Formal Methods

Page 147: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 29

CS4003 Formal Methods

Real Life: Mondex Electronic Purse

Goal — Smart card as electronic purse (1990s),certified to ITSEC E6.Verified security protocol.http://www.mondex.com

Approach —required by E6:I formal model of security policyI formal model of security architectureI refinement proof that architecture satisfies

policy.Method — Z, based on predicate calculus and ZF set

theoryWho —

Susan Stepney (Logica)David Cooper (NatWest)Jim Woodcock (Oxford)

CS4003 Formal Methods

Mondex: Key Results

I Susan Stepney, David Cooper and Jim Woodcock,An Electronic Purse: Specification, Refinement, and Proof ,Technical Monograph PRG-126, Oxford UniversityComputing Laboratory. July 2000.http://www-users.cs.york.ac.uk/~susan/bib/ss/z/monog.htm

I Design was proved correctI Scale (380 pages):

I abstract model: 20 pagesI concrete model: 60 pagesI hand proof: 200 pagesI support stuff: 100 pages

I FM within process:I found logging protocol errorI under budget, ahead of schedule

CS4003 Formal Methods

Grand Challenge Pilot Project

I In January 2006, the Mondex verification was introducedas a pilot-project for GC6 (Grand Challenge: DependableSystems Evolution)

I Original Mondex verification used hand proofs.I Idea: ask formal tool developers to apply their tools to the

verification problemI At least 8 took up the challenge:

I Alloy, ASM, KIV, Event-B, USE, RAISE, Z/Eves, PerfectDeveloper, π-calculus

Page 148: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Mondex Pilot Project outcomes

I The formalisms and tools used varied a lot in terms ofpower and expressiveness.

I Surprisingly almost all of the groups got very similarresults, finding similar errors.

I Key conclusions:I Using tool-support to formally analyse a real-world system

like Mondex is quite feasible.I The precise choice of tool is often not that important.

I A special issue (Vol. 20, No. 1, Jan 2008) of the FormalAspects of Computing journal has papers detailing theseresults.

CS4003 Formal Methods

Real Life: Needham-Schroeder Public Key Protocol

I Want to establish mutual authentication between initiator Aand responder B.

I Using public-key protocol:I Agents have public keys known to all (Ka, Kb)I Agents have secret keys, known only to themselves (K−1

a ,K − 1b)

I Agents can generate nonces (random numbers) (Na,Nb)I The Needham-Schroeder Public Key Protocol (NS-PKP)

I published in 1978I uses a 7-message sequence to ensure A and B know they

are talking to each other.

CS4003 Formal Methods

A Formalism(?) for Describing Protocols

I If agent A includes its own name in a message, we denotethat simply as A.

I {M}k denotes message M encrypted with key k .I We denote A’s public/secret keys respectively as

PK (A),SK (A).I We build up composite messages using dots (A.b.{X }k ).I A message m.n from A to B is described as

A→ B : m.n.o

CS4003 Formal Methods

NS-PKP (3-step version)

I We shall focus on a shorter 3-step versionI The protocol:

1. A→ B : A.B.{Na.A}PK (B)

A sends B his name and nonce, encoded with B ’s publickey.

2. B → A : B.A.{Na.Nb}PK (A)B uses his private key to decode A’s message, and replieswith A’s nonce and his own, encrypted for A’s eyes only

3. A→ B : A.B.{Nb}PK (B)

A decodes the previous message and send B ’s nonce backI At the end both A and B are convinced they are talking to

each other, because there is no way anyone else could getat the nonces …

Page 149: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

17 years laterGavin Lowe, then a postdoc at Oxford, encodes NS-PKP inCSP.

a,b,a.b,a.b.c , . . . ∈ Events Events (possibly structured)g ∈ Guard guard predicates

P ,Q,R,∈ Proc ::= Processes| Stop do nothing, not even terminate| Skip do nothing and terminate| a → P do a, then act like P| g & P guarded process| P ; Q sequential composition| P uQ internal choice| P �Q external choice| P ‖A Q parallel composition| P \ A event hiding| Chaos do anything

CS4003 Formal Methods

CSP Tool Support

I A proof by hand of correctness would be hard anderror-prone

I Gavin Lowe used a tool called “FDR”I “FDR” — Failures-Diverence RefinementI Reads an ASCII syntax version of CSPI Does exhaustive search to check an assertionI See http://www.fsel.com

CS4003 Formal Methods

Failure !

I The check with FDR failedI NS-PKP was found to be vulnerable to a

“man-in-the-middle” attackI Gavin Lowe, “An Attack on the Needham-Schroeder

Public-Key Authentication Protocol” Inf. Process. Lett,1995, 56, 3, pp131–133.

I Gavin Lowe, “Breaking and Fixing theNeedham-Schroeder Public-Key Protocol Using FDR”, inTools and Algorithms for Construction and Analysis ofSystems, Second International Workshop, Springer LNCS1055, pp147–166, 1996.

I This attack had gone unnoticed for 17 years !

CS4003 Formal Methods

The Attack

I It interleaves two runs α and β, one between A and I , theother between I imitating A to B (here denoted as I(A).

I

A→ I : A.I .{Na.A}PK (I)I(A)→ B : A.B.{Na.A}PK (B)

B → I(A) : B.A.{Na,Nb}PK (A)I → A : I .A.{Na,Nb}PK (A)A→ I : A.I .{Nb}PK (I)

I(A)→ B : A.B.{Nb}PK (B)

Page 150: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Corrections

I Gavin Lowe then derived a corrected protocol:1. A→ B : A.B.{Na.A}PK (B)

A sends B his name and nonce, encoded with B ’s publickey.

2. B → A : B.A.{Na.Nb .B}PK (A)B uses his private key to decode A’s message, and replieswith A’s nonce and his own, and his own identity, encryptedfor A’s eyes only

3. A→ B : A.B.{Nb}PK (B)

A decodes the previous message and send B ’s nonce backI He checked it also with FDR — it came up clean.I This protocol know known (in educated circles) as the

Needham-Schroeder-Lowe protocol.

CS4003 Formal Methods

Real Life: SparkADA

I SparkADA: a subset of ADA with a formal semanticsI Spark Examiner: tool supporting correct refinement to

SparkADAI Developed and marketed by Praxis High Integrity SystemsI http://www.praxis-his.com/sparkada/

CS4003 Formal Methods

The big idea

I SparkADA is full ADA without any language constructs thatmake formal reasoning (too) difficult

I Tools support a very high degree of rigorous formaldevelopment

I Programmer productivity is much higher than normalI Errors found after product shipped are way lower.

CS4003 Formal Methods

Tokeneer Project

I The Tokeneer project was done by Praxis for the U.S.National Security Agency.(biometric access control)

I Key results:lines of code: 9939total effort (days): 260productivity (lines of code per day, overall) : 38productivity (lines of code per day, coding phase) : 203defects discovered by NSA after delivery: 1

I Very high quality outcome by industry standards

Page 151: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Tokeneer Project (ongoing)

I NSA did project to demonstrate that their requirement forformal methods was reasonable and cost-effective.

I NSA release it open-sourcehttp://www.adacore.com/home/gnatpro/tokeneer/(requirements; specification; code; proofs)

I 4 more bugs uncovered in codeI Work by Jim Woodcock uncovered nine

requirements-related defects

CS4003 Formal Methods

Recent FM Research at TCD: overview

I Handel-C semanticsI UTP, esp. slotted CircusI Flash Memory modellingI Global Computation (Matthew Hennessey, et al.)I OS kernel verification

CS4003 Formal Methods

Recent Research at TCD: “slotted Circus”

I We are using UTP to model hardware languages likeHandel-C

I program-like syntax (C with parallelism)I synchronous clocks — assignments synchronise with clockI true parallelism — x , y := y , x works directlyI inter-thread channel communication

I The language Circus describes concurrent/shared-variableprograms

I has a UTP semanticsI key auxiliary observation:

Traces : sequences of Events (tr , and tr ′)I Developed by Jim Woodcock and Ana Cavalcanti at York

I In TCD we have slotted-CircusI Language has a Wait (for clock tick) primitive.I Traces are chopped into discrete time-slots.

CS4003 Formal Methods

Recent Research at TCD: “slotted Circus++”

I One project looked at giving a semantics to priorityI Concept of event priority is non-trivial and involves time in

an essential wayI PhD, Paweł Gancarski (2011)

I Another project looked at giving a UTP semantics toprobability

I Done already, relating starting state to sets of finaldistributiuons

I The trick was to get a homogeneous relations (samestart/finish type)

I We relate start distributions to final ones (harder than itsounds)

I PhD, Riccardo Bresciani (2012)I Both projects looked at extensions to slotted Circus.

Page 152: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Recent Research at TCD: Flash Memory

I One of the grand challenge pilot studies was proposed byNASA JPL

I verify a POSIX filesystem built on Flash MemoryI We looked at modelling the Flash Memory devices

themselves (in Z)I We also looked at modelling the hardware/software

interface and verifying Flash Memory internal control FSMsagainst that interface

I We found errors in the Nand Flash SpecificationI Open Nand Flash interface (ONFi)

CS4003 Formal Methods

Recent Research at TCD: Kernel Verification (I)

I Current spacecraft have many special purpose computersI ESA wants to merge these into one general purpose

computing platformI to save weightI known as Integrated Modular Avionics (IMA)I Aircraft did this 20 years ago

I IMA requires an operating system that securely partitionsapplications

I each app has its own partitionI all inter-app communication and access to hardware

resources is via o/s kernel

CS4003 Formal Methods

Recent Research at TCD: Kernel Verification (II)

I Our task:I develop a (informal) Reference Specification for a

separating partitioning µkernel.I Scope out and choose a formalism and tools to formally

verify a kernel implementation, to CC EAL5+ (probablyEAL7+)We chose Isabelle/HOL

I Formalise the specification using the chosen formalismI Do a dry run at the verification to get an idea of feasibility

and cost.

CS4003 Formal Methods

FM & FP — a teaching history

I The availability of courses on both formal methods (FM)and functional programming has changed in recent yearson the CS B.A. (Mod.), now the ICS.

I Academic year 2010/11 and before:I CS3001, Formal Methods, JS Elective, 5 ECTSI CS4011, Functional Programming, SS Elective, 10 ECTS

I Academic year 2011/12 and after:I CS4003, Formal Methods, SS Elective, 5 ECTSI CS3016, Functional Programming, JS Mandatory, 5 ECTSI CS4012, Topics in Functional Programming , SS Elective, 5

ECTS

Page 153: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

2011/12 — a transition year

I At the start of 2011/12:I JS students had no FM, and no choice to do it, and had to

do FP.I SS students had no FP, but some had chosen it. Also,

some had done FM, and wanted moreI Academic year 2011/12

I CS4003 was a follow-on to CS3001 from 2010/11I CS3016/CS4012 Functional Programming was a joint

JS/SS class.I Academic year 2012/13/14 …

I CS4003 is basically CS3001 from 2010/11 and before,called CS3BA31 back in 2008/09

I CS3016 is a reduced version of CS3016/CS4012 from2011/12, with some content overlapping with CS4011 in2010/11.

CS4003 Formal Methods

What’s wait all about?

I For reactive systems (I/O performing) weneed todistinguish non-termination from unrecoverable errors

I Add extra boolean auxiliary variable: waitI wait = True — process is waiting for events (not terminated)I wait = False — process has terminated, no longer waiting

I We have three valid combinations of ok and wait :I ¬ ok — divergence has occurredI ok ∧ wait — process is stable and still runningI ok ∧ ¬ wait — process has terminated successfully.

CS4003 Formal Methods CS4003 Formal Methods

Page 154: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 30

CS4003 Formal Methods

FM & FP — a teaching history

I The availability of courses on both formal methods (FM)and functional programming has changed in recent yearson the CS B.A. (Mod.), now the ICS.

I Academic year 2010/11 and before:I CS3001, Formal Methods, JS Elective, 5 ECTSI CS4011, Functional Programming, SS Elective, 10 ECTS

I Academic year 2011/12 and after:I CS4003, Formal Methods, SS Elective, 5 ECTSI CS3016, Functional Programming, JS Mandatory, 5 ECTSI CS4012, Topics in Functional Programming , SS Elective, 5

ECTS

CS4003 Formal Methods

2011/12 — a transition year

I At the start of 2011/12:I JS students had no FM, and no choice to do it, and had to

do FP.I SS students had no FP, but some had chosen it. Also,

some had done FM, and wanted moreI Academic year 2011/12

I CS4003 was a follow-on to CS3001 from 2010/11I CS3016/CS4012 Functional Programming was a joint

JS/SS class.I Academic year 2012/13/14 …

I CS4003 is basically CS3001 from 2010/11 and before,called CS3BA31 back in 2008/09

I CS3016 is a reduced version of CS3016/CS4012 from2011/12, with some content overlapping with CS4011 in2010/11.

CS4003 Formal Methods

CS4003: relevant exam papers

3BA31 2008/09 (Q4 a bit off-topic)CS3001 2009/10

3BA31 2010/11

But not CS4003 2011/12 !

Page 155: CS4003: Formal Methods · CS4003 Formal Methods Atomic Predicates IAn Atomic Predicate is an expression whose overall type is Boolean, and whose constituent parts have non-Boolean

CS4003 Formal Methods

Class 31

CS4003 Formal Methods

Good Luck

I CS3001 has been an introduction to Formal MethodsI You have been exposed to key ideas about very rigourous

reasoning about program correctnessI Even if you never apply these techniques, hopefully they

have given you key intellectual tools for program problemsolving:

I pre/post-conditionsI loop invariants and variantsI specification-to-program refinement

I Thank you all for your attention and involvement.

CS4003 Formal Methods CS4003 Formal Methods