You are on page 1of 117

CS709 – Formal Methods of Software Engineering

Sr No Topics Lectures Page No


01 Introduction 01 – 05 001
02 Hoare Logic 06 – 14 013
03 Applications of Formal Techniques 15 027
04 Design by Contract 16 – 18 028
05 Object Constraint Languages (OCL) 19 – 20 038
06 Algebraic Specification 21 – 27 047
07 Larch Family of Languages 28 – 30 063
08 OBJ Family of Languages 31 – 32 073
09 Model Base Specification: Vienna Development Method 33 081
10 Model Base Specification: Z Specification 34 – 41 084
11 Petri Nets 42 – 44 106
12 Course Overview 45 115

Reference Books:

• Design by contract by example by Richard Mitchell and Jim McKim


• Object-Oriented Software Construction by Bertrand Meyer
• Program Construction and Verification by Roland C. Backhouse
• Program Construction: Calculating Implementation by Roland Backhouse
• Software Engineering by Ian Sommerville
• The Object Constraint Language, precise modeling with UML by Jos Warmer and Anneke Kleppe
• The Specification of Complex Systems by B. Cohen, W. T. Harwood and M. I. Jackson
• Using Z: Specification, Refinement, and Proof by Jim Woodcock & Jim Davies

Course instructor

Dr. Fakhar Lodhi


D.Sc. Computer Science
George Washington University, USA

Published By:
www.vumultan.com
1 CS709 – Formal Methods of Software Engineering

Lecture 1

Notorious Bugs – BYTE, September 1995


http://www.byte.com/art/9509/sec7/art20.htm
• 1987 : Therac-25 – The Bug that killed
• 1990: AT&T long distance break down
• 1991: Patriot Missile – Hitting own barracks, leaving 28 dead and 98 wounded

Program to test for two equal strings


• Test cases:
• isEqual (“cat”, “dog”) - expected false
• isEqual (“Testing”, “Testing”) - expected true
• isEqual (“house”, “home”) - expected false

equal = strlen(string1) == strlen(string2);


if (equal)
for (i = 0; i < strlen(string1); i++)
equal = string1[i] == string2[i];
return equal;

Some Notations

Flow graph for bubble sort sorted = false; // 1

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


2 CS709 – Formal Methods of Software Engineering

while (!sorted) { // 2
sorted = true;
for (int i = 0; i < SIZE-1; i++) { // 3
if (a[i] > a[i+1]) { // 4
swap(a[i], a[i+1]); // 5
sorted = false;
} // 6
} // 7
} // 8

For (i=0; i<N; i++){ // 1


If(condition1)
// do something here // 2
Else
// do something here // 3
//do something here // 4
} // 5

2N Paths

Dijkstra’s Game

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


3 CS709 – Formal Methods of Software Engineering

Lecture 2
A Three Ball Game

Mathematical Model
(2 black out, 1 black in) b-2+1, w  b-1, w
f(b,w) = (2 white out, 1 black in) b+1, w-2
(1 of each out, 1 white in) b-1, w-1+1  b-1, w

• Total number of balls is reduced by exactly one in each move.


• Parity of the white ball does not change

Propositional Calculus

• A compound proposition that is always true, irrespective of the truth values of the comprising
propositions, is called a tautology. Contradiction is inverse of tautology.
pp pp
• The propositions p and q are called logically equivalent if p  q is tautology.
• It is written as ,
pq
• For example:  (p  q)   p   q

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


4 CS709 – Formal Methods of Software Engineering

Some useful equivalence


• p or true  true p or false  p
• p and true  p p and false  false
• true  p  p false  p  true
• p  true  true p  false  not p
• p or p  p p and p  p
• not not p  p
• p or not p  true p and not p  false

Distributivity of Associativity of
• and over or • , , and 
• or over and
• or over  Commutativity of
•  over and • , , and 
•  over or Demorgan’s law
•  over  • Implication
•  over  • if and only if

Logic problem for the day


• Someone asks person A, “Are you a knight?” He replies, “If I am a knight then I’ll eat my hat”.
Prove that A has to eat his hat.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


5 CS709 – Formal Methods of Software Engineering

Lecture 3
• A is a knight: A
• A eats his hat: H
• If I am a knight then I’ll eat my hat: AH
• We have seen that (X  S) therefore (A  A  H)
• Objective is to logically deduce H

Truth Table
A H AH A  (A  H)
T T T T
F T T F
T F F F
F F T F

Proof using equivalences


A  (A  H)
 A  (not A or H)
 (A and (not A or H)) or (not A and not (not A or H))
A and (not A or H)
 (A and not A) or (A and H)
 false or (A and H)
 A and H
not A and not (not A or H)
 not A and (A and not H)
 (not A and A) and not H
 false and not H
 false
Hence
A  (not A or H)
 (A and H) or false
 A and H

Rules of Inference and Logical Deduction


• Introduction
• Elimination

Introduction Introduction
p q p q
_______ _______ _______
p and q p or q p or q

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


6 CS709 – Formal Methods of Software Engineering

Elimination Elimination
p and q p and q p pq
________ _________ _________
p q q

Introduction Elimination
[p]
p not p false
q
_______ ______
_________
false p
pq

Does the Superman Exist?


If Superman were able and willing to prevent evil, he would do so. If Superman were unable to prevent
evil, he would be incapable; if he were unwilling to prevent evil, he would be malevolent. Superman does
not prevent evil. If Superman exists, he is neither incapable nor malevolent. Therefore Superman does
not exist.

Inference and deduction


• Superman exists X
• Superman is willing to prevent evil W
• Superman is able to prevent evil A
• Superman is malevolent M
• Superman is incapable I
• Superman prevents evil E

• Our objective is to prove the proposition:


((W and A)  E) // willing and able, he will prevent evil
and ((not A)  I) // not able  not capable
and ((not W)  M) // not willing  malevolent
and (not E) // does not prevent evil
and (X  not (I or M)) // if superman there, he is not capable or not malevolent
 not X
1. Assume
((W and A)  E)
and ((not A)  I)
and ((not W)  M)
and (not E)
and (X  not (I or M))
The objective is now to prove not X

2. Assume X
Use Elimination Rules to break No. 1 down into 5 premises

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


7 CS709 – Formal Methods of Software Engineering

3. (W and A)  E
4. (not A)  I
5. (not W)  M
6. not E
7. X  not (I or M)
Now application of elimination on 2 and 7 derives another simple proposition
2. Assume X
7. X  not (I or M)

8. not (I or M)
Now proving I or M will result in a contradiction
We will now analyze W

9. Assume not W
10. M (from 5 and 9)
11. I or M (from 10 - introduction)

12. Assume W
13. Assume A
14. W and A (12 and 13)
15. E (3 and 14)
16. false (6 and 15)
17. I or M (16)

18. Assume not A


19. I (4 and 18)
20. I or M (19)
21. I or M (17 and 20)
22. I or M (11 and 21)
23. false (contradiction 8 and 22)
24. not X (2 and 23)

Logic problem for the day


On the island of knights and knaves, it is rumored that there is gold buried on the island. You ask one of
the natives, A, whether there is gold on the island. He makes the following response: “There is gold on
this island if and only if I am a knight.”

The problem is as follows:


a) Can it be determined whether A is a knight or a knave?
b) Can it be determined whether there is gold on the island?

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


8 CS709 – Formal Methods of Software Engineering

Lecture 4

• There is gold on the island G


• A is a knight A
• Therefore we have

A G A↔G A  (A ↔ G)

T T T T

F T F T

T F F F

F F T F

Associativity of Equivalence
• ABC
can be evaluated as
(A  B)  C
or
A  (B  C)

Even and odd numbers


• m+n is even  m is even  n is even
• m+n is even  (m is even  n is even)

ABC
A B C AB (A  B)  C

F F F T F

F F T T T

F T F F T

F T T F F

T F F F T

T F T F F

T T F T F

T T T T T

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


9 CS709 – Formal Methods of Software Engineering

Full Adder

• a  1; A
• b  1; B
• c  1; C
• d  1; D
• D  (A  B  C)

• There is gold on the island G


• A is a knight A
A  (A  G)
(A  A)  G
true  G
G

Properties of equivalence
• constant true
true  p  p
true = (p  p)
(true  p) = p

ppqprq
pppqqr
true  p  true  r
pr

Replace the term which is repeated odd number of times by a single occurrence of the term and any
terms which is repeated an even number of times by removing all occurrences.

• A is a knight A
• A says “I am a knight.” A
AA
• Since this is always true, no meaningful conclusion can be made.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


10 CS709 – Formal Methods of Software Engineering

• A is a knight A
• B is a knight B
• A says “I am the same type as B” AB

AAB
B

Island of knights and knaves


Suppose A is the proposition “person A is a knight” and suppose A makes a statement S. Then A is true is
the same as S is true. That is:
AS

Logic problem for the day


A tourist comes to a fork in the road, where one branch leads to a restaurant and one does not. A native
of the island is standing at the fork. Formulate a single yes no question that the tourist can ask such that
the answer will be yes if the left fork leads to the restaurant, and otherwise the answer will be no.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


11 CS709 – Formal Methods of Software Engineering

Lecture 5

• Let Q be the question


• Let A be “the native is a knight”
• Let L be “the left fork leads to the restaurant”
• The response to the question Q is yes is equivalent to Q  A
• So we require that: L  Q  A or Q  (L  A )
• Is the statement that the left fork leads to the restaurant equivalent to your being a knight?

Negation
• p  p  false
• p  (p  false)
• (p  p)  false

• p  p  q  p  r  q
• p  p  p  q  q  r
• true  p  false  r
• pr

• There are two natives A and B. A says, “B is a knight is the same as I am a knave.”
• What can you determine about A and B?
• A’s statement is: BA
• So, we have: ABA
AAB
false  B
B
A?
Golden Rule
• pqpqpq

Implication
• pqppq
• pqqpq

• If I am a knight, B is a knight
• AB
• AAB
• AAAB
• AB

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


12 CS709 – Formal Methods of Software Engineering

• Three of the inhabitants – A, B, and C – were standing together in a garden. A stranger passed by
and asked A, “Are you a knight or a knave?” A answered but the stranger could not understand.
The stranger then asked B, “What did A say?”. B replied, “A said that he is a knave”. At this point,
the third C, said, “Don’t believe B; he is lying!” What are A, B, and C?

• B’s statement is: A   A


• C’s statement is:  B
• So, we have:
(B  A   A)  (C   B)
 B  (C   B)
( B  C)  ( B   B)
( B  C)   B
BC

• A says, either I am a knave or B is a knight


AAB
A  (A  false ) B
A  (A  B  false  B)
AABB
AB

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


13 CS709 – Formal Methods of Software Engineering

Lecture 6
Conditional Correctness:
• {P} S {Q}
where
P = initial state
S = set of statements
Q = final state
Express the conditional correctness of S

Weakest Precondition:
• Wp( z := x, z ≥ y) x≥y
• Wp( t := x, t  x0)  x = x0
• Wp( i := i+1, i ≤ n ) i<n
• Wp( i := 0, i = 0 )  true ~least restrictive, i.e. true for all values
• Wp( i := 0, i = 1 )  false ~impossible

The Assignment Axiom:


• Wp( x := e, Q(x))  Q(e)
✓ X will have a value which e had before executing statement
✓ Q(e) denotes the predicate obtained by substituting e for all free occurrences of x in the
predicate Q.
Examples:
• Wp( i := i-1, i = 0 ) i–1=0
• Wp( i := (l + u) div 2, l ≤ i ≤ u )  l ≤ (l + u) div 2 ≤ u
• Wp( i := 1, i = 0 )  i = 0 ~ false
• Wp( i := 1, i = 1 )  1 = 1 ~ true
• Wp( x := y, x = z ) z=y

Rule of Sequential Composition:


• wp(S1;S2,Q)  wp(S1, wp(S2,Q))
wp((x:= x+1; y := y+1), x = y)
 wp(x := x+1, wp(y := y+1, x = y))
 wp(x := x+1, x = y+1)
 x+1 = y+1
x=y
• wp(S1;S2,Q)  wp(S1, wp(S2,Q))
wp((x:= 2*x+1; y := y-1), y = 3*x)
 wp(x := 2*x+1, wp(y := y-1, y = 3*x))
 wp(x := 2*x+1, y-1 = 3*x))
 y-1 = 3*(2*x+1)
 y = 6*x + 4

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


14 CS709 – Formal Methods of Software Engineering

Lecture 7
Example:
• {x = x0 and y = y0}
t := x ; x := y ; y := t ;
{y = x0 and x = y0}
• { x = x0 and y = y0} t := x { t = x0 and y = y0}
• { t = x0 and y = y0}
x := y ; y :=t
{y = x0 and x = y0}
• { t = x0 and y = y0} x := y { t = x0 and x = y0}
• { t = x0 and x = y0} y := t { y = x0 and x = y0}

Hoare’s Consequence Rule:


• P→Q -- If P then Q

P→Q Q→R
{Q} S {R} {P} S {R}
{P} S {R} {P} S {R}

Rules for Conditions:


{P and C} S {Q} {P and C} S1 {Q}
P and (not C) → Q {P and (not C)} S2 {Q}
{P} if C then S {Q} {P} if C then S1 else S2 {Q}

Dijkstra’s Healthiness Condition:


a. wp(S, false) // false empty set
✓ False – law of excluded miracle
b. wp(S, true) // true universal set
✓ Termination condition, all states that grunted termination of S.
c. wp(while 0 ≠ n do n := n – 1, ture) ≡ 0 ≤ n

Verification:
• Invariant
✓ Something which is unchanging
✓ Key to the proofs for programs containing loops (iteration or recursion)

✓ Question seem to ask for next change


✓ Answer lies in determining what does not change

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


15 CS709 – Formal Methods of Software Engineering

Lecture 8
A Classical Problem:

Question: Can you completely cover the chessboard with these dominoes without partially using a
domino? If so how, if not, prove that you cannot.

• if i <= j then
m := i;
else
m := j;
• (m ≤ i and m ≤ j) and (m = i or m = j)

ELSE PART
• (i > j)
m = j;
• (m = i or m = j) and (m ≤ j and m ≤ j)
• (i>j) and (j = i or j = j) and (j ≤ i and j ≤ j)
• (i>j) and (true) and (j ≤ i and true)
• (i>j) and (j ≤ i)
• (i>j)

IF PART
• (i <= j)
m = i;
• (m = i or m = j) and (m ≤ i and m ≤ i)
• (i ≤ j) and (i = i or i = j) and (i ≤ i and i ≤ j)
• (i ≤ j) and (true) and (true and i ≤ j)
• (i ≤ j) and (i ≤ j)
• (i ≤ j)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


16 CS709 – Formal Methods of Software Engineering

Lecture 9
Loop Invariants:
• s = 0;
for i := 1 to n do
s = s + a[i];

• What is the ‘loop invariant’?


• s is the sum of elements from a[1] to a[i] immediately before i is incremented!

Weakest Precondition for While Statement {P} while B do S {Q}


• Let W be while B do S
• Condition for termination of the loop
• P0  (not B)
• P1  B and wp(S,P0)  wp(S, not B)
• Pk  B and wp(S, Pk-1)
• wp(W, true)  wp(W, not B)  (k: k  0: Pk)

• The invariant condition


{I} while B do S {I and not B}

• a = 0;
• i = 0;
• while (i < N)
a = a + i++;
N −1
• Loop Invariant: a = i
i =0

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


17 CS709 – Formal Methods of Software Engineering

Lecture 10
Verification of Functions
• Specification of a system as a set of functions where the internal state is hidden.
• Each function is specified as a set of pre and post conditions.
• Pre-condition must hold if the post-condition is to be true.

Example – minimum
• function min (X: in INTEGER_ARRAY) return INTEGER
Pre: True
Post:  j in X’First .. X’Last : min(X) = X( j ) and
 i in X’First .. X’Last : min(X)  X(i) and X = X’’

Specification of functions using pre- and post-conditions


• Procedure Search (X: in INTEGER_ARRAY;
key: in INTEGER;
found: in out Boolean;
index: in out INTEGER);
Pre: True
Post: ((found and X(index) = key) or
(NOT found and
( j in X’First … X’Last : x( j )  key)) and (X = X’’))

• Procedure binarySearch (X: in INTEGER_ARRAY;


key: in INTEGER;
found: in out Boolean;
index: in out INTEGER);
Pre:  j in X’First … X’Last-1 : x( j ) <= x( j+1 )
Post: ((found and X(index) = key) or
(NOT found and
( j in X’First … X’Last : x( j )  key)) and (X = X’’))

• Procedure binary_Search (X: in INTEGER_ARRAY;


key: in INTEGER;
found: in out Boolean;
L: in out INTEGER)
begin
bot: INTEGER := X'First;
top: INTEGER := X'Last;
mid: INTEGER;
L := (bot + top) / 2;
found := X(L) = key ;

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


18 CS709 – Formal Methods of Software Engineering

while (bot <= top AND NOT found) loop


begin
mid := (bot + top)/2;
if X(mid) = key then
found := TRUE;
L := mid;
elsif X(mid) < key then
bot := mid + 1;
else
top := mid - 1;
end if;
end loop;
end binary_Search;

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


19 CS709 – Formal Methods of Software Engineering

Lecture 11

Specification of functions using pre- and post-conditions


• Procedure binary_Search (X: in INTEGER_ARRAY;
key: in INTEGER;
found: in out Boolean;
L: in out INTEGER);
• Pre: X'Last >= X'First and Ordered(X)
• Post: ((found and X(L) = key) or
(NOT found and
( j in X’First … X’Last : x( j )  key)) and
(X = X’’))

Loop Invariant:
(found AND X(L) = key) OR
(NOT found AND
 j in X'First..bot-1, top+1..X'Last: X(j)  key))

Pre-Condition:
X'Last >= X'First and Ordered(X)
begin
bot: INTEGER := X'First;
top: INTEGER := X'Last;
mid: INTEGER;
L := (bot + top) / 2;
found := X(L) = key ;

while (bot <= top AND NOT found) loop


begin
mid := (bot + top)/2;
if X(mid) = key then
found := TRUE;
L := mid; found AND X(L) = key
elsif X(mid) < key then
bot := mid + 1;  j in X'First..bot-1: X(j)  key
else
top := mid - 1;  j in top+1..X'Last: X(j)  key
end if;
end loop;

(found AND X(L) = key) OR (NOT found AND  j in X'First..X'Last: X(j)  key))

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


20 CS709 – Formal Methods of Software Engineering

Dijkstra’s Guarded if Statement


if c1 → S1
[] c2 → S2
[] c3 → S3
fi

if b then S else T
if b → S
[] not b → T
fi

Conditional Rule
{P}
if b1 → S1
[] b2 → S2
fi
{Q}

is equivalent to conjunction of the three propositions:


P  b1  b2
{P  b1} S1 {Q}
{P  b2} S2 {Q}

Constructing Conditional Statements


• {P} S {Q} -- P and Q are given, we want to calculate S
• Three step process:
1. Split the precondition into two (or possibly more cases) b1 and b2. That is identify b1 and b2
such that P  b1  b2
2. Construct a program statement S1 that guarantees termination in a state satisfying Q given
the precondition P  b1
3. Construct a program statement S2 that guarantees termination in a state satisfying Q given
the precondition P  b2

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


21 CS709 – Formal Methods of Software Engineering

Lecture 12
Output Variables
• {true} S {i = j}
i := j; or j := i;
• Which one is the input variable and which one is the output variable?

Ghost Variables
• Suppose we want to specify that the sum of two variables i and j should remain constant
• We specify this by introducing a ghost variable C
• This variable should not be used anywhere else in the program.
• Then S specified by { i + j = C} S { i + j = C}

Simultaneous Assignment
• The left side is a list of variables and the right side is a list of expressions of the same length as the
list of variables.
x, y, z := 2*y, x+y, 3*z
• The assignment x, y := y, x
has the effect of swapping the values of x and y

Calculating Assignments
• Suppose that the requirement is to maintain the value of j+k constant while incrementing k by 1.
• Our task is to calculate and expression X such that
{j + k = C} j , k := X, k + 1 { j + k = C}
• Applying the assignment axiom, we get
{X + k + 1 = C} j , k := X, k + 1 { j + k = C}
j+k = C  X + k + 1 = C
• Now
j+k
= j+k+1–1
= (j - 1) + k + 1
• Thus a suitable value of X is j – 1
• So,
{ j + k = C} j , k := j – 1, k + 1 { j + k = C}

Example:
• Suppose variables s and n satisfy the property
s = n2
• We want to increment n by 1 whilst maintaining this relationship between s and n
• Our goal is to calculate an expression X involving only addition such that
{ s = n2 } s, n := s + X, n+1 { s = n2 }
• Applying the assignment axiom we get

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


22 CS709 – Formal Methods of Software Engineering

{ s + X = (n + 1)2 } s, n := s + X, n + 1 { s = n2 }
• So, we need
s = n2  s + X = (n + 1)2
• Now
(n + 1)2
= n2 + 2*n + 1
• That is
s = n2  s + 2*n + 1 = (n + 1)2
• So,
{ s = n2 } s, n := s + 2*n + 1, n+1 { s = n2 }

Max of two numbers


• Two number x and y
max(x,y) = x  y  x
max(x,y) = y  x  y
• pre-condition: {true}
• post-condition: {z = max(x,y)}
• two cases:
(x  y) and (y  x)
{true}  (x  y)  (y  x)

{true}
if x  y → z := e1 {z = max(x,y)}
[] y  x → z := e2 {z = max(x,y)}
fi
{z = max(x,y)}

• using the assignment axiom we calculate that


{e = max(x,y)} z := e {z = max(x,y)}
• in particular
{x = max(x,y)} z := x {z = max(x,y)}
• that is
{y  x} z := x {z = max(x,y)}
• and
{x  y} z := y {z = max(x,y)}
• we have thus determined e1 and e2

Iteration
• The do-od statement
• do b → S od

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


23 CS709 – Formal Methods of Software Engineering

Constructing Loops
• Invariant property and bound function
• Loops are designed so that each iteration of the loop body maintains the invariant whilst making
progress to the required post-condition by always decreasing the bound function.
• Suppose a problem is specified by precondition P and post-condition Q.
• We identify and invariant property inv and the bound function bf.
• The bound function is an integer-value function of the program variables and is a measure of the
size of the problem to be solved.
✓It is guaranteed to be greater than zero when loop is executed.
✓A guarantee that the value of such a bound function is always decreased at each iteration
is a guarantee that the loop will terminate.
• The post condition Q is split into a termination condition, say done, and the invariant property
inv, in such a way that
inv  done  Q
• The invariant property is designed, in combination with the termination condition, by generalizing
the required post-condition.
• The termination condition is typically related to the bound function.
• The invariant should also guarantee that the value of the bound function is greater than zero
unless the loop has terminated. That is:
inv  (bf > 0)  done
• The invariant property is chosen so that it is easy to design an initialization statement, S, that
establishes the invariant property
{P} S {inv}
• The design is completed by constructing a loop body T that maintains the invariant whilst making
progress towards the termination condition.
{inv  done  bf = C} T {inv  (done  bf < C)}
• If the termination condition, done, the bound function, bf, the invariant, inv, and the loop body,
T, have all been constructed as above, then we have
{inv} do done → T od {Q}
• Moreover, if S has been constructed then
{P} S; do done → T od {Q}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


24 CS709 – Formal Methods of Software Engineering

Lecture 13
Constructing Loops:
• Pre-condition: P
• Post-condition: Q
• Loop-invariant: inv
• Bound-function: bf
• Termination-condition: done
• Initialization-statement: S

Some rules:
• inv  done → Q
• inv → (done > 0)  done
• {P} S {inv}

Loop body:
• {inv  done  bf = C}
T // loop statements
{inv  (done  bf < C}

Example: Sum of the values of Array


• X X / FIRST X / LAST
• PRE: ture
X / LAST
• Post: Sum =  X i 
i = X / FIRST

i
• inv: Sum =  X i 
j = X / FIRST

• done: X/ LAST - i  0 | X/ LAST  i


• bf: X/ LAST - i

Empty Set: X / FIRST  X / LAST // If this condition is not true, then


PRE: X / LAST
X / FIRST

Dutch National Flag Problem:


• How to arrange these balls are in the order that we have these colors in the Dutch national flag?

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


25 CS709 – Formal Methods of Software Engineering

Lecture 14
Dutch National Flag Problem:
• This the final arrangement that we want

• Three Boolean valued functions red, blue, and white


• red(i) evaluate to true if the ball at index i is red. Similarly blue(i) and white(i)
• swap(i,j) swaps the balls in bucket i and j

• r and w are two indices such that


0rw N
 (i: 0  i < r: red(i))
 (i: r  i < w: white(i))
 (i: w  i < N: blue(i))

Invariant
• Partition the array into four segments, three of the segments corresponding to the three colors
and containing values of that color only, and the fourth containing a mixture of colors.
• Final state: the mixed partition is empty.

Invariant, initial, and termination condition


• (0  r  w  b  N)  (i: 0  i < r: red(i)) 
(i: r  i < w: white(i))  (i: b  i < N: blue(i))

• All the colored segments are initially empty


• Initial condition: r = 0; w = 0; b = N;
• Bound function: b - w
• Termination condition: b = w

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


26 CS709 – Formal Methods of Software Engineering

Algorithm
• Progress requires reducing the size of the mixed segment by at least one in each iteration
• Examine the color of the ball at index w and put it in its right partition

• Three cases:
✓ white(w) → w := w + 1;
✓ red(w) → swap(r, w); r := r + 1; w := w + 1;
✓ blue(w) → swap(b - 1,w); b := b – 1;

• {0  N}
r:= 0; w := 0; b := N;
{Invariant:
0rwbN
 (i: 0  i < r: red(i))
 (i: r  i < w: white(i))
 (i: b  i < N: blue(i))
Bound Function: b – w}
do w < b →
if white(w) → w := w + 1;
[] blue(w) → swap(b - 1,w); b := b – 1;
[] red(w) → swap(r, w); r := r + 1; w := w + 1;
fi
od
{ 0rwN
 (i: 0  i < r: red(i))
 (i: r  i < w: white(i))
 (i: w  i < N: blue(i))
}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


27 CS709 – Formal Methods of Software Engineering

Lecture 15
Applications of Formal Techniques
Good Programs
• Reusability
• Reliability
• Defensive Programing
✓ Self-defeating
✓ Obtaining and guaranteeing reliability requires a more systematic approach
✓ Design by construct

Design by Construct

Contract violations lead to run-time error

Stack Pop Function


itemType stack :: pop()
{
If ( isEmpty() )
// error – cannot pop
else
// pop the element and return the client
}
//Defensive Programing Style

Contract base Programing


require
Stack_not_empty
conunt > 0 // pre-condition
ensure
count_decreased
count = old count – 1 // post-condition
// Function body
// Pop the element and return to the
client

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


28 CS709 – Formal Methods of Software Engineering

Lecture 16
Design by Construct
• Client – Server
• Obligation and Benefits
• Per-Condition
• Post-Condition
• Class Invariant

Class Invariants
• Pre-conditions and post-conditions describe the properties of individual methods.
• A class invariant is a global property of the instances of a class, which must be preserved by all
methods.
• A class invariant is an assertion in the class definition.
✓ E.g. a stack class might have the following class invariant:
count >= 0 and
count <= capacity and
stack_is_empty = (count = 0)
• An invariant for a class C must be satisfied by every instance of C at all “stable” times.
• “Stable” times are those in which the instance is in an observable state

Example
• A (mutable) class representing a range of real numbers:
public class RealRange {
private RealNumber min, max;
public RealRange(RealNumber min, RealNumber max) {
this.min = min;
this.max = max;
}
public void setRange(RealNumber newMin, RealNumber newMax) {
this.min = newMin;
this.max = newMax;
}
}
• invariant: min <= max

The Invariant Rule


• An assertion I is a correct invariant for a class C if and only if:
✓ Every constructor of C, when applied to arguments satisfying its precondition in a state
where the attributes have their default values, yields a state satisfying I.
✓ Every method of the class, when applied to arguments and a state satisfying both I and the
method’s precondition, yields a state satisfying I.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


29 CS709 – Formal Methods of Software Engineering

DbC and Inheritance


• What happens to assertions when classes are inherited?
• How can assertions be “preserved” in the face of redeclaration (overriding) and dynamic binding?
• Actually assertions help maintain the semantics of classes and methods when they are inherited.

Invariants
• The invariants of all the parents of a class apply to the class itself.
• The parents’ invariants are added (logically “and”ed) to the class’s own invariants.

• The parents’ invariants need not be repeated in the class.

Pre and Post conditions

Pre-condition Post-condition
Replace the original pre-condition Replace the original post-condition
by one equal or weaker by one equal or stronger

The new version must accept all The new version must guarantee at
calls that were acceptable to the least as much as the original.
original.

It may, but does not have to, accept It may, but does not have to,
more cases. guarantee more.

e.g. replace pre: x<10 by pre: e.g. replace post: x<=10 by post:
x<=10 x=10

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


30 CS709 – Formal Methods of Software Engineering

Summary
• Software reliability requires precise specifications which are honored by both the supplier and the
client.
• DbC uses assertions (pre and post conditions, invariants) as a contract between supplier and
client.
• DbC works equally well under inheritance.

Languages with third-party support:


• C and C++: DBC for C preprocessor, GNU Nana
• C#: eXtensible C# (XC#).
• Java: iContract2, Contract4J, jContractor, Jcontract, C4J, CodePro Analytix, STclass, Jass
preprocessor, OVal with AspectJ, Java Modeling Language (JML), SpringContracts for the Spring
framework, or Modern Jass, Custos using AspectJ.
• JavaScript: Cerny.js or ecmaDebug.
• Common Lisp: the macro facility or the CLOS metaobject protocol.
• Scheme: the PLT Scheme extension
• Perl: the CPAN modules Class::Contract , Carp::Datum
• Python, PyDBC , Contracts for Python.
• Ruby: Ruby DBC, ruby-contract.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


31 CS709 – Formal Methods of Software Engineering

Lecture 17
jContractor
Preconditions
• Naming convention
✓ methodName_Precondition
✓ e.g. for method X the precondition will be X_Precondition
✓ Returns a boolean
✓ It has to be protected
• A precondition method takes the same arguments as the method it is associated with and returns
a boolean.
class Stack implements Cloneable {
private Stack OLD;
private Vector implementation;
public Stack () { … }
public Stack (Object [ ] initialContents) { … }
public void push (Object o) { … }
public Object pop () { … }
public Object peek () { … }
public void clear () { … }
public int size () { … }
public Object clone () { … }
private int serachStack (Object o) { … }
}
Pre-condition Example
• Preconditions for the Stack push method can be introduced by adding the following method to
the Stack or Stack_CONTRACT class:
protected boolean push_Precondition (Object o) {
return o != null;
}
• Pre-condition for Constructor
Stack_Precondition (Object[] initialContents) {
Return(initialContents != null) && (IinitialContents.length > 0);
}
Some additional rules about preconditions
• Contract methods may not have preconditions.
• Native methods may not have preconditions.
• The main(String [] args) method may not have a precondition.
• The precondition for a static method must be static.
• The precondition for a non-static method must not be static.
• The precondition for a non-private method must be protected.
• The precondition for a private method must be private.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


32 CS709 – Formal Methods of Software Engineering

Post-condition Example
• An example postcondition method for the Stack push is shown below:
protected boolean
push_Postcondition (Object o, Void RESULT) {
return implementation.contains(o) &&
(size() == OLD.size() + 1);
}

Some additional rules about post conditions


• Contract methods may not have post conditions.
• Native methods may not have post conditions.
• The post condition for a static method must be static.
• The post condition for a non-static method must not be static.
• The post condition for a non-private method must be protected.
• The post condition for a private method must be private.
• Post conditions for constructors cannot refer to OLD.

Example of Invariant
• An example invariant for the Stack class:
protected boolean _Invariant () {
return size() >= 0;
}

Invariants
• An invariant method is similar to a post condition but does not take any arguments and is implicitly
associated with all public methods.
• It is evaluated at the beginning and end of every public method.
• It is the responsibility of the implementation class that the invariant checks succeed.

Rules for invariants


• Invariants are not checked for contract methods.
• Invariants are not checked for static methods.
• Invariants are not checked for native methods.
• Invariants are checked only at the exit of a constructor.
• The _Invariant() method must be declared protected and non-static.

Contracts and inheritance


• jContractor’s implementation of Design by Contract works well with both class and interface
inheritance.
• Contracts are inherited, just like methods.
• When a method is overridden in a subclass, that class may specify its own contracts to modify
those on the superclass method.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


33 CS709 – Formal Methods of Software Engineering

• jContractor instruments each method to enforce contract checking based on the following
operational view.
• A subclass method’s contract must:
✓Allow all input valid for its superclass method.
✓Ensure all guarantees of the superclass methods.

Interfaces
• Interfaces may also have contracts
• Contracts from interfaces are logically or-ed with the superclass and subclass contracts in the case
of preconditions.
• For post-conditions and invariants they are logically and-ed.

Separate contract classes


• jContractor allows contracts to be written in separate contract classes.
• Contract classes follow the naming convention classname_CONTRACT
• When instrumenting a class, jContractor will find its contract class and copy all the contract code
into the non-contract class.
• If the same contract is defined in both classes (both classes define a precondition for a method,
for example), the two are logically and-ed together.

class Stack_CONTRACT extends Stack {


private Stack OLD;
private Vector implementation; // dummy variable

protected boolean
Stack_Postcondition (Object [] initialContents, Void RESULT) {
return size() == initialContents.length;
}

protected boolean
Stack_Postcondition (Object [] initialContents) {
return size() == (initialContents != null) && (initialContent.length > 0);
}

protected boolean
push_Precondition (Object o) {
return o != null;
}
protected boolean
push_postcondition(Object o, Void RESULT) {
return implementation.contains(o) && (size() == OLD.size() + 1);
}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


34 CS709 – Formal Methods of Software Engineering

private int searchStack (Object o) { //dummy method


return 0;
}

private boolean
searchStack_Precondition (Object o) {
return != null;
}

protected boolean _Invariant () {


return size() <= 0;
}
}

• The separate contract class methods can reference the variables and methods of the class with
which it is associated.
• However, to get the compiler to accept the code, it is sometimes necessary to provide fake
variables and methods, such as implementation and searchStack(Object) in the contract class.

Predicate logic support


• Contracts often involve constraints that are best expressed using predicate logic quantifiers.
• jContractor provides a support library for writing expressions using predicate logic quantifiers and
operators such as Forall, Exists, suchThat, and implies.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


35 CS709 – Formal Methods of Software Engineering

Lecture 18
BankAccount.java
Public Class BankAccount implements Cloneable {
Private int balance;
Public BankAccount() {
Supper();
balance = 0;
}
Public BankAccount (int amount) {
balance = amount;
}
Public void deposit (int amount) {
balance += amount;
}
Public void withdraw (int amount) {
balance -= amount;
}
Public int getBalance () {
return balance;
}
Protected boolean _Invariant () {
return (balance >= 0);
}
Protected boolean deposit_Precondition (int amount) {
Return (amount >=0);
}
} // end of the class

AccountUsage.java
Public Class AccountUsage {
Public static void main(String[] args) {
BankAccount myAccount = new BankAccount (1000);
System.out.println(“Starting Balance = ” + myAccount.getBalance() );
myAccount.deposit(500); // if the value is (-500), Violating the deposit_Precondtion
System.out.println(“Starting Balance = ” + myAccount.getBalance() );
myAccount.withdraw(1000);
System.out.println(“Starting Balance = ” + myAccount.getBalance() );
myAccount.withdraw(1000); // balance = -500, Violating the invariant condition
System.out.println(“Starting Balance = ” + myAccount.getBalance() );
}
} // end of the class
> java jContractor AccountUsage //cmd

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


36 CS709 – Formal Methods of Software Engineering

MyStack.java
import java.util.vector;
class MyStack implements Cloneable {
Private Object [] elems;
Private int top, max;

Pulic MyStack() {
Super();
top = 0;
max = 10;
elems = new Object [max];
}
Public MyStack (int sz) {
max = sz;
top = 0;
elems = new Object [max];
}
Public void push (Object obj) {
try {
OLD = (MyStack) Clone();
}
Catch (Exception ex) {
}
elems [Top++] = obj; // add the elements that we passed
}
Public Object pop() {
Object temp;
temp = elems [--top];
return temp;
}
Public Boolean isFull() {
return top == max;
}
Public Boolean isEmpty() {
return top == 0;
}
Public int size() {
return top;
}
}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


37 CS709 – Formal Methods of Software Engineering

StackUsage.java
Public Class StackUsage {
Public static void main(String[] args) {
MyStack S = new MyStack(2); // can push at most two elements
// S.pop();
System.out.println(“push”);
S.push (new integer (1));
System.out.println(“pop”);
S.pop();
System.out.println(“push”);
S.push(new integer (23));
//S.pop();
System.out.println(“push”);
S.push(new integer (24));
System.out.println(“push”);
S.push(new integer (0)); // going out of bound
}
}

>java jContractor StackUsage //cmd

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


38 CS709 – Formal Methods of Software Engineering

Lecture 19
Object Constraint Language (OCL)

Types of expressions in OCL


• Expressions can be used in a number of places in a UML model:
✓ To specify the initial value of an attribute or association end.
✓ To specify the derivation rule for an attribute or association end.
✓ To specify the body of an operation.
✓ To indicate an instance in a dynamic diagram.
✓ To indicate a condition in a dynamic diagram.
✓ To indicate actual parameter values in a dynamic diagram.

Types of constraints in OCL


• There are four types of constraints:
✓ An invariant
✓ A precondition
✓ A postcondition
✓ A guard is a constraint that must be true before a state transition fires.

The Context of an OCL Expression


• The context definition of an OCL expression specifies the model entity for which the OCL
expression is defined.
✓ Usually this is a class, interface, datatype, or component. In terms of the UML standard,
this is called a Classifier.
• Sometimes the model entity is an operation or attribute, and rarely it is an instance.
✓ It is always a specific element of the model, usually defined in a UML diagram. This
element is called the context of the expression.
• Next to the context, it is important to know the contextual type of an expression. The contextual
type is the type of the context, or of its container.
• It is important because OCL expressions are evaluated for a single object, which is always an
instance of the contextual type.
• To distinguish between the context and the instance for which the expression is evaluated, the
latter is called the contextual instance.
• Sometimes it is necessary to refer explicitly to the contextual instance. The keyword self is used
for this purpose.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


39 CS709 – Formal Methods of Software Engineering

• For example, the contextual type for all expressions in above Figure is the class LoyaltyAccount.
The precondition (pre: i>0) has as context the operation earn. When it is evaluated, the contextual
instance is the instance of LoyaltyAccount for which the operation has been called. The initial
value (init: 0) has as context the attribute points. The contextual instance will be the instance of
LoyaltyAccount that is newly created.

Invariants on attributes
• The simplest constraint is an invariant on an attribute.
• Suppose our model contains a class Customer with an attribute age, then the following constraint
restricts the value of the attribute:
context Customer inv:
age >= 18

Invariants on associations
• One may also put constraints on associated objects.
• Suppose in our model contains the class Customer has an association to class Salesperson, with
role name salesrep and multiplicity 1, then the following constraint restricts the value of the
attribute knowledgelevel of the associated instance of Salesperson:
context Customer inv:
Salesrep.knowledgelevel >= 5

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


40 CS709 – Formal Methods of Software Engineering

Collections of objects
• In most of the cases the multiplicity of an association is not 1, but more than 1.
• Evaluating a constraint in these cases will result in a collection of instances of the associated class.
• Constraints can be put on either the collection itself, e.g. limiting the size, or on the elements of
the collection.
• Suppose in our model the association between Salesperson and Customer has role name clients
and multiplicity 1..* on the side of the Customer class, then we might restrict this relationship by
the following constraint.
context Salesperson inv:
clients->size() <= 100 and
clients->forAll(c: Customer | c.age >= 40)

Pre and Post Conditions


• In pre- and postconditions the parameters of the operation may be used.
• Furthermore, there is a special keyword result which denotes the return value of the operation.
• It can be used in the postcondition only.
• As an example we have added an operation sell to the Salesperson class.
context Salesperson::sell( item: Thing ): Real
pre: self.sellableItems->includes( item )
post: not self.sellableItems->includes( item ) and result = item.price

Derivation Rules
• Models often define derived attributes and associations.
• A derived element does not stand alone.
• The value of a derived element must always be determined from other (base) values in the model.
• Omitting the way to derive the element value results in an incomplete model.
• Using OCL, the derivation can be expressed in a derivation rule.
• In the following example, the value of a derived element usedServices is defined to be all services
that have generated transactions on the account:
context LoyaltyAccount::usedServices : Set(Services)
derive: transactions.service->asSet()
Initial Values
• In the model information, the initial value of an attribute or association role can be specified by
an OCL expression.
• In the following examples, the initial value for the attribute points is 0, and for the association end
transactions, it is an empty set:
context LoyaltyAccount::points : Integer
init: 0
context LoyaltyAccount::transactions : Set(Transaction)
init: Set{}
• Note the difference between an initial value and a derivation rule.
✓ A derivation rule states an invariant:

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


41 CS709 – Formal Methods of Software Engineering

✓ The derived element should always have the same value that the rule expresses.
✓ An initial value, however, must hold only at the moment when the contextual instance is
created. After that moment, the attribute may have a different value at any point in time.

Body of Query Operations


• The class diagram can introduce a number of query operations.
• Query operations are operations that have no side effects, i.e., do not change the state of any
instance in the system.
• Execution of a query operation results in a value or set of values, without any alterations in the
state of the system.
• Query operations can be introduced in the class diagram, but can only be fully defined by
specifying the result of the operation.
• Using OCL, the result can be given in a single expression, called a body expression.
• In fact, OCL is a full query language, comparable to SQL. The use of body expressions is an
illustration thereof.
• The next example states that the operation getCustomerName will always result in the name of
the card owner associated with the loyalty account:

context LoyaltyAccount::getCustomerName() : String


body: Membership.card.owner.name

Broken constraints
• Evaluating a constraint does not change any values in the system.
• A constraint states "this should be so".
• If for a certain object the constraint is not true, in other words, it is broken, then the only thing
we can conclude is that the object is not correct, it does not conform to our specification.
• Whether this is a fatal error or a minor mistake, and what should be done to correct the situation
is not expressed in the OCL.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


42 CS709 – Formal Methods of Software Engineering

Lecture 20

• An association between class Flight and class Person, indicating that a certain group of persons
are the passengers on a flight, will have multiplicity many (0..*) on the side of the Person class.
• This means that the number of passengers is unlimited.
• In reality, the number of passengers will be restricted to the number of seats on the airplane that
is associated with the flight.
• It is impossible to express this restriction in the diagram.
• In this example, the correct way to specify the multiplicity is to add to the diagram the following
OCL constraint:
context Flight
inv: passengers->size() <= plane.numberOfSeats

• A person may have a mortgage on a house only if that house is owned by him- or herself;
✓One cannot obtain a mortgage on the house of one's neighbor or friend.
• The start date for any mortgage must be before the end date.
• The ID card number of all persons must be unique.
• A new mortgage will be allowed only when the person's income is sufficient.
• A new mortgage will be allowed only when the counter-value of the house is sufficient.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


43 CS709 – Formal Methods of Software Engineering

Value Added by OCL

context Mortgage
inv: security.owner = borrower

context Mortgage
inv: startDate < endDate

context Person
inv: Person::allInstances()->isUnique(socSecNr)

context Person::getMortgage(sum : Money, security : House)


pre: self.mortgages.monthlyPayment->sum() <= self.salary * 0.30

context Person::getMortgage(sum : Money, security : House)


pre: security.value >= security.mortgages.principal->sum()

• The Object Constraint Language is just a specification language.


• It obeys a syntax and has keywords.
• However, unlike other languages, it can't be used to express program logic or flow control.
• By design, OCL is a query-only language; it can't modify the model (or executing system) in any
way.
• It can be used to express preconditions, postconditions, invariants (things that must always be
True), guard conditions, and results of method calls.
• OCL can be used virtually anywhere in UML and is typically associated with a classifier using a
note.
• When an OCL expression is evaluated, it is considered to be instantaneous, meaning the
associated classifier can't change state during the evaluation of an expression.

Constraints on Classifiers
• Each OCL expression must have some sense of context that an expression relates to.
• Often the context can be determined by where the expression is written.
• For example, you can link a constraint to an element using a note.
• You can refer to an instance of the context classifier using the keyword self.
• For example, if you had a constraint on Student that their GPA must always be higher than 2.0,
you can attach an OCL expression to Student using a note and refer to the GPA as follows:
self.GPA >= 2.0

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


44 CS709 – Formal Methods of Software Engineering

Constraints
• if you had a constraint on Student that their GPA must always be higher than 2.0, you can attach
an OCL expression to Student using a note to refer to the GPA as follows:
self.GPA > 2.0
• Note:
✓If you want to allow a GPA of less than 2.0 and send out a letter to the student’s parents in
the event such a low GPA is achieved, you would model such behavior using a UML
diagram such as an activity or interaction diagram.
• The following invariant on Course ensures that the instructor is being paid:
self.instructor.salary > 0.00

Business Rule
• The following expressions verify that a student’s tuition was paid before registering for a course
and that the operation registerStudent returned true:
context Course::registerStudent(s: Student): boolean
pre: s.tuitionPaid = true
post: result = true

• We can name pre and post conditions by placing a label after the pre or post keywords:
context Course::registerStudent(s: Student): boolean
pre hasPaidTuition: s.tuitionPaid = true
post studentHasRegistered: result = true

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


45 CS709 – Formal Methods of Software Engineering

• Postconditions can use the @pre keyword to refer to the value of some element before an
operation executes.
• The following expression ensures that a student was registered and the number of students in the
course has increased by 1.
context Course::registerStudent(s: Student): boolean
pre hasPaidTuition: s.tuitionPaid = true
post studentHasRegistered: result = true AND
self.students = self.students@pre + 1

• We may specify the results of a query operation using the keyword body.
• Because OCL doesn’t have syntax for program flow, we are limited to relatively simple
expressions.
• The following expressions indicate that the honors students are students with GPAs higher than
3.5.
context Course::getHonorsStudents(s: Student): boolean
body: self.students->select(GPA > 3.5)

Conditionals
• OCL supports basic Boolean expression evaluation using the if-then-else-endif keywords.
• The conditional are used only to determine which expression is evaluated; they can’t be used to
influence the underlying system or to affect program flow.
• The following invariant enforces that a student’s year of graduation is valid only if she has paid
her tuition:
context Student inv:
if tuitionPaid = true then
yearOfGraduation = 2005
else
yearOfGraduation = 0000
endif

OCL’s Logic Rules


• The boolean evaluation rules are:
1. True OR-ed with anything is true.
2. False AND-ed with anything is false.
3. False IMPLIES anything is True.
• For example, the following expression enforces that if a student's GPA is less than 1.0, their year
of graduation is set to 0. If the GPA is higher than 1.0, Rule #3 applies, and the entire expression
is evaluated as true (meaning the invariant is valid).
context Student inv:
self.GPA < 1.0 IMPLIES self.yearOfGraduation = 0000

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


46 CS709 – Formal Methods of Software Engineering

• OCL supports several complex constructs you can use to make your constraints more expressive
and easier to write.
• You can break complex expressions into reusable pieces (within the same expression) by using
the let and in keywords to declare a variable.
• You declare a variable by giving it a name, followed by a colon (:), its type, an expression for its
value, and the in keyword.
• The following example declares an expression that ensures a teacher of a high-level course has
an appropriate salary:
context Course inv:
let salary : float = self.instructor.salary in
if self.courseLevel > 4000 then
salary > 100000.00
else
salary < 100000.00
endif

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


47 CS709 – Formal Methods of Software Engineering

Lecture 21
Algebraic Specification
The Structure of an Algebraic Specification

SPECIFICATION NAME <Generic Parameters>


sort <name>
imports <LIST OF SPECIFICATION NAMES>
Informal description of the sort and its operations
Operation signatures setting out the names and the types of the parameters to the
operations defined over the sort.
Axioms defining the operations over the sort

• Constructors
✓ Change the state of an object, i.e. CREATE, ASSIGN (in above example)
• Inspectors
✓ Do not change the state of an object, i.e. FIRST, LAST, EVAL (in above example)
• Rule of thumb for writing axioms
✓ Write axioms for inspectors in term of constructors
• If m Constructors and n inspectors then
✓ Total number of axioms = m * n

Specification of Array

Array (Elem : [Undefined → Elem])

Sort Array
Imports INTEGER

Create (integer, integer) → Array


Assign (Array, integer, Elem) → Array
First (Array) → integer
Last (Array) → integer
Eval (Array, integer) → Elem

• FIRST (CREATE (F, L)) = F


• LAST (CREATE (F, L)) = L
• EVAL (CREATE (F, L), i) = Undefined
• FIRST (ASSIGN (A, i, v)) = FIRST(A)
• LAST (ASSIGN (A, i, v)) = LAST(A)
• EVAL (ASSIGN (A, i, v), j) = if (i = j) v else EVAL(A, j)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


48 CS709 – Formal Methods of Software Engineering

Lecture 22
Specification of Stack

Stack (Elem : [Undefined → Elem])

sort Stack

Create () → Stack
Push (Stack, Elem) → Stack
POP (Stack) → Stack
Top (Stack) → Elem
IsEmpty (Stack) → Boolean

• Constructors: CREATE, PUSH, POP


• Inspectors: TOP, IsEmpty

• IsEmpty (CREATE) = True


• IsEmpty (PUCH(s, e)) = False
• IsEmpty (POP(s)) =?
✓ For POP we write axiom in term of CREATE

• Top (CREATE) = Undefined


• Top (PUCH(s, e)) = e
• Top (POP(s)) =?
✓ For POP we write axiom in term of PUSH

• IsEmpty (POP(s)) = POP(CREATE()) = CREATE()


• Top (POP(s)) = POP(PUSH(s, e)) = S

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


49 CS709 – Formal Methods of Software Engineering

Specification of List

LIST (Elem : [Undefined → Elem])

sort List
Imports INTEGER

Create → List // return List


Cons (List, Elem) → List // add Elem
Tail (List) → List // remove 1st item & return List
Head (List) → Elem // return Head of List
Length (List) → Integer // return Length of List

• Constructors: CONS, TAIL, CREATE


• Inspectors: HEAD, LENGTH

• LENGTH(CREATE()) = 0
• LENGTH(CONS(L, e)) = LENGTH(L) + 1
• LENGTH(TAIL(L)) = If L == CREATE() return 0 Else return LENGTH(L) – 1

• HEAD(CREATE() = Undefined
• HEAD(CONS(L, e) = If L==CREATE return e Else return HEAD(L)
• HEAD(TAIL(L)=?
✓ We will write axiom for TAIL in term of CREATE and CONS

• TAIL(CREATE()) = CREATE
• TAIL(CONS(L, e)) = CONS(TAIL(L), e)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


50 CS709 – Formal Methods of Software Engineering

Lecture 23
Specification of Binary Search Tree
Operation Description
Create Creates an empty tree
Add(Binary_tree, Elem) Adds a node to the binary tree using the usual ordering principles.
Left(Binary_tree) Returns the left sub-tree of the top of the tree
Data(Binary_tree) Returns the value of the data element at the top of the tree
Right(Binary_tree) Returns the right sub-tree of the top of the tree
IsEmpty(Binary_tree) Returns true of the tree does not contain any elements
Contains(Binary_tree, Elem) Returns true of the tree contains the given element

BINTREE ( Elem: [ Undefined → Elem, . == . → Bool, . < . →Bool] )


sort Binary_tree
imports BOOLEAN
Defines a binary search tree where the data is of generic type Elem.
Build is an additional primitive constructor operation which is introduced to simplify the
specification. It builds a tree given the value of a node and the left and right sub-tree.
Create → Binary_tree
Add(Binary_tree, Elem) → Binary_tree
Left(Binary_tree) → Binary_tree
Data(Binary_tree) → Elem
Right(Binary_tree) → Binary_tree
IsEmpty(Binary_tree) → Boolean
Contains(Binary_tree, Elem) → Boolean
Build(Binary_tree, Elem, Binary_tree) → Biniary_tree
• Add (Create, E) = Build(Create, E, Create)
• Add (B, E) = if E < Data (B) then Add (Left(B), E) else Add (Right (B), E)
• Left (Create) = Create
• Right (Create) = Create
• Data (Create) = Undefined
• Left (Build(L, D, R)) =L
• Right (Build(L, D, R)) =R
• Data (Build(L, D, R)) =D
• IsEmpty(Create) = true
• IsEmpty (Build (L, D, R)) = false
• Contains (Create, E) = false
• Contains (Build (L, D, R), E) = if E = D then true else if E < D then Contains (L, E)
else Contains (R, E)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


51 CS709 – Formal Methods of Software Engineering

Specification of Coord

COORD

sort Coord
imports INTEGER, BOOLEAN

This specification defines a sort called Coord representing a Cartesian coordinate. The
operations defined on Coord are X and Y which evaluate the X and Y attributes of an entity of
this sort and Eq which compares two entities of sort Coord for equality.

Create (integer, integer) → Coord


X(Coord) → integer
Y(Coord) → integer
Eq (Coord, Coord) → Boolean

X (Create(x,y)) = x
Y(Create(x,y) = y
Eq (Create(x1, y1), Create(x2, y2)) = ((x1 == x2) and (y1 == y2))

CURSOR

sort Cursor
imports INTEGER, COORD, BITMAP

A cursor is a representation of a screen position. Defined operations are Create, Position,


Translate, Change_Icon and Display.

Create (Coordinate, Bitmap) → Cursor


Translate(Cursor, Integer, Integer) → Cursor
Position(Cursor) → Coord
Change_Icon(Cursor, Bitmap) → Cursor
Display(Cursor) → Cursor

Translate(Create(C, Icon), xd, yd) = Create(COORD.Create(X(C)+xd, Y(C)+yd), Icon)


Position(Create(C, Icon)) = C
Position(Translate(C, xd, yd)) = COORD.Create(X(C)+xd, Y(C)+yd)
Change_Icon(Create(C, Icon), Icon2) = Create(C, Icon2)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


52 CS709 – Formal Methods of Software Engineering

Lecture 24
New_List Specification

Operation Description
Create Brings a list into existence
Cons(New_list, Elem) Adds an element to the end of the list
Add(New_list, Elem) Adds an element to the front of the list
Head(New_List) Returns the first element in the list
Tail(New_list) Return the list with the first element removed
Member(New_list, Elem) Returns true if element is present in the list
Length(New_list) Returns the number of elements in the list

NEW_LIST ( Elem : [Undefined → Elem])

sort New_List enrich List


imports INTEGER, BOOLEAN

Add (New_List, Elem) → New_List


Member (New_List, Elem) → Boolean

Head (Add (L, v)) = v


Length (Add (L, v)) = Length (L) + 1

Tail (Add (L, v)) = L


Member (Create, v) = FALSE
Member (Cons (L, v1), v2) = if v1 == v2 then TRUE else Member (L, v2)
Member (Add (L, v1), v2) = if v1 == v2 then TRUE else Member (L, v2)

Add (Create, v) == Cons (Create, v)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


53 CS709 – Formal Methods of Software Engineering

Queue Specification

Operation Description
Create Brings a queue into existence
Cons(Queue, Elem) Adds an element to the end of the queue
Head (Queue) Returns the element at the front of the queue
Tail (Queue) Returns the queue minus its front element
Length (Queue) Returns the number of elements in the queue
Get (Queue) Returns a tuple composed of the element at the head of the queue
and the queue with the front element removed

QUEUE ( Elem : [Undefined → Elem])

sort Queue enrich List


imports INTEGER

This specification defines a queue which is first-in, first-out data structure. It can therefore be
specified as a LIST where the insert operation adds a member to the end of the queue

Get(Queue) → (Elem, Queue)

Get (Create) = (undefined, Create)


Get (Cons (Q, v)) = (Head (Q), Tail (Cons (Q, V)))

Error Specification
• Error may be tackled in three ways
✓ Use a special distinguished constant operation (Undefined) which conforms to the type
of the returned value.
✓ Define operation evaluation to be a tuple, where an element indicates success or failure.
✓ Include a special failure section in the specification

List specification with Error

LIST ( Elem : [Undefined → Elem])

sort List
imports INTEGER

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


54 CS709 – Formal Methods of Software Engineering

Create → List
Cons (List, Elem) → List
Tail (List) → List
Head (List) → Elem
Length (List) → Integer

Head (Create) = undefined -- error to evaluate an empty list


Head (Cons (L, v)) = if L == Create then v else Head (L)
Length (Create) =0
Length (Cons (L, v)) = Length (L) + 1
Tail (Create) = Create
Tail (Cons (L, v)) = if L == Create then Create else Cons (Tail (L), v))

List specification with Exceptions

LIST ( Elem )

sort List
imports INTEGER

Create → List
Cons (List, Elem) → List
Tail (List) → List
Head (List) → Elem
Length (List) → Integer

Head (Cons (L, v)) = if L == Create then v else Head (L)


Length (Create) = 0
Length (Cons (L, v)) = Length (L) + 1
Tail (Create) = Create
Tail (Cons (L, v)) = if L == Create then Create else Cons (Tail (L), v))

exceptions
Length(L) = 0  failure (Head(L))

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


55 CS709 – Formal Methods of Software Engineering

BOOLEAN

BOOLEAN

sort Bool
constants true: Bool;
false: Bool

not (Bool) → Bool


and (Bool, Bool) → Bool
or (Bool, Bool) → Bool
impl (Bool, Bool) → Bool
equal (Bool, Bool) → Bool

not(not(a)) =a
or(a,or(b, c)) = or(or(a,b),c)
or(a, b) = or(b,a)
not(false) = true
and(a, b) = not(or(not(a), not(b))
impl(a, b) = or(not(a), b)
equal(a, b) = and(impl(a,b), impl(b,a))
or(a, true) = true
or(a, false) =a

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


56 CS709 – Formal Methods of Software Engineering

Lecture 25

Structure of the File System Specification

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


57 CS709 – Formal Methods of Software Engineering

LIST (with infix notation)

LIST (Elem with { - == -: Elem, Elem → Bool; undef :→ Elem}

sort List
uses BOOLEAN
constants
0 : → List // generates an empty list
undef : → List

first : List → Elem // head


rest : List → List // tail
isundef : List → Bool
-.- : Elem, List → List // add to front
- memberOf - : Elem, List → Bool
- == - : List, List → Bool
atEnd : List → Bool // isEmpty

first(0) = undef
rest(0) = undef
first(undef) = undef
rest(undef) = undef
first(a.b) =a
rest(a.b) =b
atEnd(0) = true
atEnd(undef) = false
atEnd(a.b) = false
a.b == c.d = (a==c) and (b==d)
0 == 0 = true
a.b == 0 = false
(a == b) = (b == a)
e memberOf undef = false
e memberOf 0 = false
e memberOf a.b = (e == a) or (e memberOf b)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


58 CS709 – Formal Methods of Software Engineering

Lecture 26
Pair Specification

PAIR (A with { - == -: A, A → Bool; undef :→ A},


B with { - == -: B, B → Bool; undef :→ B})

sort Pair
constants undef : Pair
uses BOOLEAN

first : Pair → A
second : Pair → B
pair : A, B → Pair
- == - : Pair, Pair → Bool

first(pair(x, y)) =x
second(pair(x, y)) =y
pair(undef, undef) = undef
pair(x, y) == pair(u, v) = (x == u) and (y == v)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


59 CS709 – Formal Methods of Software Engineering

Quad Specification

QUAD ( A with { - == -: A, A → Bool; undef :→ A},


B with { - == -: B, B → Bool; undef :→ B},
C with { - == -: C, C → Bool; undef :→ C},
D with { - == -: D, D → Bool; undef :→ D})

sort Quad
constants undef : Quad
uses BOOLEAN

first : Quad → A
second : Quad → B
third : Quad → C
fourth : Quad → D
Quad : A, B, C, D → Quad
- == - : Quad, Quad → Bool

Quad(undef, undef, undef, undef) = undef


Quad(a, b, c, d) == Quad(u, v, w, x) = (a == u) and (b == v) and (c == w) and (d == x)
first(Quad(a, b, c, d)) =a
second(Quad(a, b, c, d)) =b
third(Quad(a, b, c, d)) =c
fourth(Quad(a, b, c, d)) =d

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


60 CS709 – Formal Methods of Software Engineering

BIMAP
BIMAP (src with { -==- : src, src → Bool},
targ1 with {-==- : targ1, targ1 → Bool; undef :→ targ1},
targ2 with {-==- : targ2, targ2 → Bool; undef :→ targ2})
sort Bimap
uses BOOLEAN
pair1 = PAIR(src, targ1), list1 = LIST(pair1)
pair2 = PAIR(src, targ2), list2 = LIST(pair2)
constants
undef : Bimap

if-then-else- : Bool, Bimap, Bimap → Bimap


if-then-else- : Bool, targ1, targ1 → targ1
if-then-else- : Bool, targ2, targ2 → targ2
-==- : Bimap, Bimap → Bool
<-,-,->*- : scr, targ1, targ2, Bimap → Bimap
-[-  -]1 : Bimap, src, targ1 → Bimap
-[-  -]2 : Bimap, src, targ2 → Bimap
retrieve1 : Bimap, src → targ1
retrieve2 : Bimap, src → targ2
list1 : Bimap → list1
list2 : Bimap → list2
if true then a else b =a
if false then a else b =b
(undef :Bimap) == (undef : Bimap) = true
<s, t1, t2> * b == <s’, t1’, t2’> * b’ = (s == s’) and (t1 == t1’) and (b == b’) and (t2 == t2’)
<s, t1, t2> * b == undef = false
undef == <s, t1, t2> * b = false
undef [s  t]1 = undef
undef [s  t]2 = undef
(<s, t1, t2> * b)[s’  t]1 = if s == s’ then <s, t, t2> *b else <s, t1, t2> *b[s’  t]1
(<s, t1, t2> * b)[s’  t]2 = if s == s’ then <s, t1, t> *b else <s, t1, t2> *b[s’  t]2
retrieve1 (undef, x) = undef
retrieve2 (undef, x) = undef
retrieve1 (<s, t1, t2> * b, x) = if s == x then t1 else retrieve1(b, x)
retrieve2 (<s, t1, t2> * b, x) = if s == x then t2 else retrieve2(b, x)
list1(undef) =0
list2(undef) =0
list1(<s, t1, t2> *b) = pair(s, t1) . list1(b)
list2(<s, t1, t2> *b) = pair(s, t2) . list2(b)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


61 CS709 – Formal Methods of Software Engineering

Lecture 27
File System

FILESYS (Pattern, Regionheader, Docheader,Fileheader


with {match: Fileheader, Pattern → Bool},
Text with {undef: → Text})

Sorts Regionid, Fileid, Docid


Uses File = BIMAP(Docid, Docheader, Text)
Region = BIMAP(Fileid, Fileheader, File)
System = BIMAP(Regionid, Regionheader, Region)
Docinfo = LIST(PAIR(Docid, Docheader))
Fileinfo = LIST(PAIR(Fileid, Fileheader))
Regioninfo = LIST(PAIR(Regionid, Regionheader))
Paddoc = PAIR(Docheader, Text)
Searchlist = LIST(QUAD(Regionid, Fileid, Docid, Docheader))

makeregionid : System → Regionid


makefileid : Region → Fileid
makedocid : File → Docid
addregion : System, Regionheader → System
addfile : System, Regionid, Fileheader → System
adddoc : System, Regionid, Fileid, Docheader, Text → System
listregions : System → Regioninfo
listfiles : System, Regionid → Fileinfo
listdocs : System, Regionid, Fileid → Docinfo
getdocs : System, Regionid, Fileid, Docid → Paddoc
search : System, Pattern → Searchlist

listregions(s) = list1(s)
listfiles(s, rid) = list1(retrieve2(s, rid))
listdocs(s, rid, fid) = list1(retrieve2(retrieve2(s, rid), fid))
addregion(s, aheader) = <mkregionid(s), aheader, undef> * s
addfile(s, rid, aheader) = s[rid  <mkfileid(retrieve2(s, rid)), aheader, undef> * retrieve2(s, rid))]2

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


62 CS709 – Formal Methods of Software Engineering

adddoc(s, rid, fid, aheader,) = s[rid  retrieve2(s, rid)


[fid  <mkdocid(retrieve2(retrieve2(s, rid), fid)), aheader, text>
* retrieve2(retrieve2(s, rid)), fid))
]2
]2
getdoc(s, rid, fid, did) =
pair(retrieve1(retrieve2(retrieve2(s, rid,), fid), did),
retrieve2(retrieve2(retrieve2(s, rid,), fid), did))
quad(rid, fid, did, x) memberof search (s, p) =
not (undef == retrieve2(retrieve2(retrieve2(s, rid), fid), did))
and (x == retieve2(retieve2(retieve2(s, rid), fid), did))
and match(x, p)

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


63 CS709 – Formal Methods of Software Engineering

Lecture 28
Larch Family of Languages
Sub-system Interfaces

Larch Family of Languages


• Family of Specification Languages
• Specification components:
✓ Larch Shared Language – common to all languages
✓ Larch Interface Language – particular to specific PL
• LSL: an algebraic language
• LIL: tailored to a programming language

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


64 CS709 – Formal Methods of Software Engineering

Some Aspects of Larch Languages


• Composability
✓ Incremental construction of specifications from other specifications
• Emphasis on Presentation
✓ Readable. Larch composition mechanisms are operations on specification, rather than on
theories or models.
• Suitability for integrated interactive tools
✓ Good for interactive construction and incremental checking of specs.
• Semantic Checking
✓ Checking of specs when they are being constructed. (i.e. theorem prover for semantic
checking)
• Trait
✓ Trait is the basic unit of specification in LSL. It introduces operators and specifies their
properties. Sometimes collection of operators corresponds to an ADT.
• Theory
✓ Theory is a set of theorems that can be proved about the terms defined in a trait.
✓ Theory contains equations and inequation (~(true = false)) that can be proved by
substituting equal for equal. BUT, if 2 terms cannot be proven to be equal then they are
not necessarily unequal. Also, if two terms are not provably unequal, it does not mean
they are equal.
• Signature
✓ domains and ranges of the operators used for sort-check (similar to type-check in PL).
• Constraints
✓ Limit the operators by means of equations that relate the terms containing them.

Larch Interface Language (LIL)


• Localized programming language dependencies
✓ Each LIL encapsulates features needed to write specifications in a particular Programming
Language and incorporates LSL in a uniform way.

Larch Prover (LP)


• LP is an interactive theorem proving system for multi-sorted first-order logic
• Assist users in finding and correcting flaws in conjectures
• Works efficiently on large problems
• Is not designed to find difficult proofs automatically
• Checks for syntax and type errors in LSL specifications
• Two files of input suitable for use with LP:
✓ LP axiomatization for an LSL specification
✓ LP proof obligations associated with logical claims made by specifiers about the logical
properties of their specifications

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


65 CS709 – Formal Methods of Software Engineering

The Larch Shared Language (LSL)


• LSL specifications define two kinds of symbols, operators and sorts.
• operators stand for total functions from tuples of values to values.
• Sorts stand for disjoint non-empty sets of values, and are used to indicate the domains and ranges
of operators.
• The trait is the basic unit of specification in LSL.
✓A trait introduces some operators and specifies some of their properties.
✓Sometimes the trait defines an abstract type. However, it is frequently useful to define a set
of properties that does not fully characterize a type.

Example – Table
Table: trait
includes Integer
introduces
new: → Tab
add: Tab, Ind, Val → Tab
- -: Ind, Tab → Bool
lookup: Tab, Ind → Val
size: Tab → Int

asserts  i, i1: Ind, v: Val, t: Tab


(i  new);
i  add(t, i1, v) == i = i1  i  t;
lookup(add(t, i, v), i1) == if i = i1 then v else lookup(t, i1);
size(new) == 0;
size(add(t, i, v)) == if i  t then size(t) else size(t) + 1

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


66 CS709 – Formal Methods of Software Engineering

Lecture 29
uses TaskQueue;
mutable type queue;
immutable type task;
task *getTask(queue q) {
modifies q;
ensures
if isEmpty(q^)
then result = NIL  unchanged(q)
else (*resylt)’ = first(q^)  q’ = tail(q^);
}

• The specification is written in LCL


• This fragment introduces two abstract types and a procedure for selecting a task from a task
queue. Briefly, * means pointer to (as in C), result refers to the value returned by the procedure,
the symbol ˆ is used to refer to the value in a location when the procedure is called, and the
symbol’ to refer to its value when the procedure returns.
• The specification of getTask is not self-contained. For example, looking only at this specification
there is no way to know which task getTask selects. Is it the one that has been in q the longest? Is
it being the one in q with the highest priority?
• Interface specifications rely on definitions from auxiliary specifications, written in LSL, to provide
semantics for the primitive terms they use.
• Specifiers are not limited to a fixed set of notations, but can use LSL to define specialized
vocabularies suitable for particular interface specifications or classes of specifications.

TaskQueue: trait
includes Nat
task tuple of id: Nat, important: Bool
introduces
new: → queue
- ┤-: task, queue → queue
isEmpty, hasImportant: queue → Bool
first: queue → task
tail: queue → queue

asserts
queue generated by new, ┤
 t: task, q: queue
isEmpty(new);
isEmpty(t ┤ q);
hasImportant(new);

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


67 CS709 – Formal Methods of Software Engineering

hasImportant(t ┤ q) == t.important  hasImportant(q);


first(t ┤ q) == if t.important  hasImportant(q) then t else first(q);
tail(t ┤ q) == if first(t ┤ q) = t the q else t ┤ tail(q)

• Based on the information in this LSL specification, one can deduce that the task pointed to by the
result of getTask is the most recently inserted important task, if such a task exists. Otherwise it is
the most recently inserted task.

Specification checker
• While some Larch specifications can be executed, most of them cannot.
• To make it possible to validate specifications before implementing or executing them, Larch
permits specifiers to make assertions about specifications that are intended to be redundant.
• These assertions can be checked mechanically.
• Several tools that assist specifiers in checking these assertions as they debug specifications are
already in use.

Example - Table
Table: trait
includes Integer
introduces
new: → Tab
add: Tab, Ind, Val → Tab
- - : Ind, Tab → Bool
lookup: Tab, Ind → Val
size: Tab → Int

asserts  i, i1: Ind, v: Val, t: Tab


(i  new);
i  add(t, i1, v) == i = i1  i  t;
lookup(add(t, i, v), i1) == if i = i1 then v else lookup(t, i1);
size(new) == 0;
size(add(t, i, v)) == if i  t then size(t) else size(t) + 1

LCL Interface Specification for Table


mutable type table;
uses Table(Table for Tab, char for Ind, char for Val, int for Int);
constant int maxTabSize;

table table_create(void) {
ensures result’ = new  fresh(result);
}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


68 CS709 – Formal Methods of Software Engineering

bool table_add(table t, char i, char c) {


modifies t;
ensures result = (size(t^) < maxTabSize  i  t^)
 (if result then t’ = add(t^, i, c) else t’ = t);
}
char table_read(table t, char i) {
requires i  t^;
ensures result = lookup(t^, i);
}
Same specification in Mojela language
INTERFACE Table;
<* TRAITS Table (CHAR for Ind, CHAR for Val, INTEGER for Int) *>
TYPE T <: OBJECT
METHODS
Add(i: CHAR; c: CHAR) RAISES {Full};
Read(i: CHAR) : CHAR;
END;
PROCEDURE Create(): T;
CONST MaxTabSize: INTEGER = 100;
EXCEPTION Full;
<*
FIELDS OF T
val: Tab;
METHOD T.Add(i, c)
MODIFIES SELF.val
ENSURES SELF.val’ = add(SELF.val, i, c)
EXCEPT size(SELF.val) ≥ MaxTabSize  (i SELF.val)
=> RAISEVAL = Full  UNCHANGED(ALL)
METHOD T.Read(i)
REQUIRES i SELF.val
ENSURES RESULT = lookup(SELF.val, i)
PROCEDURE Create
ENSURES RESULT.val = new  FRESH(RESULT)
*>
END Table

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


69 CS709 – Formal Methods of Software Engineering

Lecture 30
Interface specifications
• At the core of each Larch interface language is a model of the state manipulated by the associated
programming language.
• Each specification must provide the information needed to use an interface and to write programs
that implement it.

States
• States are mappings from locs (abstract storage locations, also known as objects) to values.
• Each variable identifier has a type and is associated with a loc of that type.
• The major kinds of values that can be stored in locs are:
✓ Basic values: These are mathematical constants, like the integer 3 and the letter A. Such
values are independent of the state of any computation.
✓ Exposed types: These are data structures that are fully described by the type constructors
of the programming language (e.g., C’s int * or Modula-3’s ARRAY [1..10] OF INTEGER).
The representation is visible to, and may be relied on by, clients.
✓ Abstract types: data types are best thought of as collections of related operations on
collections of related values. Abstract types are used to hide representation information
from clients.
• Each loc’s type defines the kind of values it can map to in any state.
• Just as each loc has a unique type, each LSL term has a unique sort.
• To connect the two tiers in a Larch specification, there is a mapping from interface language types
(including abstract types) to LSL sorts.
• Each type of basic value, exposed type, and abstract type is based on an LSL sort.
• Interface specifications are written using types and values.
• Properties of these values are defined in LSL, using operators on the corresponding sorts.
• For each interface language, a standard LSL trait defines operators that can be applied to values
of the sorts that the programming language’s basic types and other exposed types are based on.

Procedure Specification
• A specification consists of a procedure header (declaring the types of its arguments and results)
followed by a body of the form:
requires reqP
modifies modList
ensures ensP

• A specification places constraints on both clients and implementations of the procedure.


• The requires clause is used to state restrictions on the state, including the values of any
parameters, at the time of any call.
• The modifies and ensures clauses place constraints on the procedure’s behavior when it is called
properly.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


70 CS709 – Formal Methods of Software Engineering

• They relate two states, the state when the procedure is called, the pre-state, and the state when
it terminates, the post-state.
• A requires clause refers only to values in the pre-state.
• An ensures clause may also refer to values in the post-state.
• A modifies clause says what locs a procedure is allowed to change (its target list).
✓ It says that the procedure must not change the value of any locs visible to the client except
for those in the target list.

Relating implementations to specifications


• One of the advantages of Larch’s two-tiered approach to specification is that the relationship of
implementations to specifications is relatively straightforward.
• We say that if the implementation satisfies the specification then it is a correct implementation
because the relation defined by the implementation is a subset of the relation defined by the
specification.
• Every possible behavior that can be observed by a client of the implementation is permitted by
the specification.

void choose(int x, int y) int z; {


modifies z;
ensures z’ = x  z’ = y;
}

void choose(int x, int y) int z; {


if (x > y) z = x;
else z = y;
}

LP, the Larch proof assistant


• LP is a proof assistant for a subset of multi-sorted first-order logic with equality.
• It is designed to work efficiently on large problems and to be used by specifiers with relatively
little experience with theorem proving.
• LP is intended primarily as an interactive proof assistant or proof debugger, rather than as a fully
automatic theorem prover.
• Its design is based on the assumption that initial attempts to state and prove conjectures usually
fail.
• So LP is designed to carry out routine (but possibly lengthy) proof steps automatically and to
provide useful information about why proofs fail.
• To keep users from being surprised and confused by its behavior, LP does not employ complicated
heuristics for finding proofs automatically.
• It makes it easy for users to employ standard techniques such as proof by cases, by induction, or
by contradiction, but the choice among such strategies is left to the user.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


71 CS709 – Formal Methods of Software Engineering

The life cycle of proofs


• Proving is similar to programming: proofs are designed, coded, debugged, and (sometimes)
documented.
• Before designing a proof it is necessary to formalize the things being reasoned about and the
conjecture to be proved.
• Once part of a proof has been coded, LP can be used to debug it.
• Proofs of interesting conjectures hardly ever succeed the first time. Sometimes the conjecture is
wrong. Sometimes the formalization is incorrect or incomplete. Sometimes the proof strategy is
flawed or not detailed enough.
• LP provides a variety of facilities that can be used to understand the problem when an attempted
proof fails.
• While debugging proofs, users frequently reformulate axioms and conjectures.
• After any change in the axiomatization, it is necessary to recheck not only the conjecture whose
proof attempt uncovered the problem, but also the conjectures previously proved using the old
axioms.
• LP has facilities that support such regression testing.

Nat: Trait
includes AC(+, Nat)
introduces
0: → Nat
s: Nat → Nat
- < -: Nat, Nat → Bool
asserts
Nat generated by 0, s
 i, j, k: Nat
i + 0 == i;
i + s(j) == s(i + j);
 (i < 0);
0 < s(i);
s(i) < s(j) == i < j
implies  i, j, k: Nat
i < j  i < (j + k)

• The declare commands introduce the variables and operators in the LSL specification.
• The assert commands supply the LSL axioms relating the operators; the Nat generated by
assertion provides an induction scheme for Nat.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


72 CS709 – Formal Methods of Software Engineering

Sample LP Proof Script


set name nat
declare sort Nat
declare variables i, j, k: Nat
declare operators
0: → Nat
s: Nat → Nat
+: Nat, Nat → Nat
<: Nat, Nat → Bool
..
assert Nat generated by 0, s
assert ac +
assert
i + 0 == i
i + s(j) == s(i + j)
 (i < 0)
0 < s(i)
s(i) < s(j) == i < j
..
implies  i, j, k: Nat
i < j  i < (j + k)
set name lemma
prove i < j  i < (j + k) by induction j
<> 2 subgoals for proof by induction on j
[ ] basis subgoal
resume by induction on i
<> 2 subgoals for proof by induction on i
[ ] basis subgoal
[ ] induction subgoal
[ ] induction subgoal
[ ] conjecture
qed

• The prove command initiates a proof by induction of the conjecture.


• The diamond (<>) annotations are provided by LP; they indicate the introduction of subgoals for
the inductions.
• The box ([ ]) annotations are also provided by LP; they indicate the discharge of subgoals and,
finally, of the main proof.
• The resume command starts a nested induction.
• No other user intervention is needed to complete this proof.
• The qed command on the last line asks LP to confirm that there are no outstanding conjectures.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


73 CS709 – Formal Methods of Software Engineering

Lecture 31
OBJ Family of Specification
• first-order functional language
• based on equational logic
• parameterized programming
• supports declarative style that facilitates verification and allows OBJ to be used as a theorem-
prover
• can include LISP code
• provides flexible environment – convenient for specification and rapid prototyping

Equational Calculus
• Calculus of replacing terms by equal terms.
• Equational calculus derives (proves) a term equation from a conditional-equational axiom
set.
• The deduction rules in this calculus are:
✓ Reflexivity: Any term is provably equal to itself (t = t).
✓ Transitivity: If t1 is provably equal to t2 and t2 is provably equal to t3, then t1 is
provably equal to t3.
✓ Symmetry: If t1 is provably equal to t2, then t2 is provably equal to t1.
✓ Congruence: If t1 is provably equal to t2, then any two terms are provably equal
which consist of some context built around t1 and t2.

• Three kinds of top-level entities


✓ Objects: object encapsulates executable code
✓ Theories: theory defines properties that may or may not be satisfied by another object or
theory
✓ Views: a view is binding of the entities declared in the theory
✓ Objects and theories are called modules
• modules can import other modules – reuse – hierarchy
• signature defines new sort
• Variable with declared sorts
• Terms are built up from variables and operators
• Modules can be parameterized
• Parameterized modules use theories to define both the syntax and semantics of their interfaces
• Views indicate how to instantiate a parameterized module with an actual parameter
• The most important OBJ unit is the Object, which encapsulates executable code.
• Syntactically, an object begins with the key word obj and ends with endo.
• The name of the object occurs immediately after obj keyword; following this comes is, and then
body of the object.
obj <ModID> is

endo

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


74 CS709 – Formal Methods of Software Engineering

• For parameterized objects, the name is a simple identifier, such as STACK-OF-INT, PHRASE, or
OBJ14.
• Parameterized objects have an interface specification in place of a simple name.

Sort
• declared with the syntax
sorts <SortIDList>
sorts Nat Int Rat .

sort <SortID>
sort Int .

Order Sorted Algebra (OSA)


• Designed to handle cases where things of one sort are also of another sort
✓ For example, natural numbers are also integers
• Where operators or expressions have several different sorts
• Provides subsort partial ordering among sorts
• Supports multiple inheritance

Subsort Example
obj BITS1 is
sorts BIT Bits .
subsorts Bit < Bits .
ops 0 1 : -> Bits .
ops -- : Bit Bits -> Bits .
endo

Equations and Semantics


• Denotational semantics based upon OSA
• Operational semantics based upon order sorted term rewriting
• Semantics of an object are determined by its equations
• Equations are written declaratively and interpreted operationally
• Rewrite rules substitute instances of left side by corresponding substitution instances on the right
side
eq M + s N = s(M + N) .

• M and N are variables, + and s are operator symbols


• eq introduces the equation
• = separates the left and right side of the equation

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


75 CS709 – Formal Methods of Software Engineering

Operational Semantics in Reduction


• obj LIST-OF-INT is
sort List .
protecting INT .
subsort Int < List .
op -- : Int List -> List .
op length_ : List -> Int .
var I : Int . var L : List .
eq length I = 1;
eq length(I L) = 1 + length(L)
Endo

Term Evaluation
• reduce [in <ModExp> :] <Term>
• Reduce command is executed by matching the given term with the left sides of the equations and
then replacing the matched subterm with the corresponding right side.
• This is called application of rewrite rules
• The operational semantics for a conditional rewrite rule is as follows:
✓ first find a match for the left side
✓ then evaluate the condition after substituting the binding determined by the match
✓ if it evaluates to true then do the replacement by the right side, again using the values for
the variables determined by the match.
• Evaluating the condition could require non-trivial further rewriting the cases.

reduce length(17 -4 329)

reduce in LIST-OF-INT : length (17 (-4 329))


rewrites: 5
result NzNat: 3

length(17 -4 329) =>


1 + length(-4 329) =>
1+ (1 + length 329) =>
1 + 2 =>
3

We call it a trace of the computation.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


76 CS709 – Formal Methods of Software Engineering

Lecture 32

Specification of Partial Functions: (Exceptional Case)


• obj STACK-OF-NAT is sorts Stack NeStack .
subsorts NeStack < Stack .
protecting NAT .
op empty : -> Stack .
op push : Nat Stack -> NeStack .
op top_ : NeStack -> Nat .
op top_ : NeStack -> Stack .
var X : Nat . var S : Stack .
eq top push(X, S) = X .
eq pop push(X, S) = S .
Endo

• reduce top push(1, empty)


yields the natural number 1

• reduce pop push(1, empty)


yields empty

• reduce top empty .


yields
result Nat: top
r.Stack>NeStack(empty)
with empty retracted to the sort NeStack

• reduce top pop empty .


yeilds
result Nat: top
r:Stack>NeStack(pop r:Stack>NeStack(empty))

• An alternative approach to exceptions involves introducing supersorts that contain specific error
messages for exceptional conditions.

• obj STACK-OF-NAT is
sorts Stack Stack? Nat? .
subsort Stack < Stack? .
protecting NAT .
subsort Nat < Nat? .
op empty : -> Stack .
op push : Nat Stack -> Stack .

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


77 CS709 – Formal Methods of Software Engineering

op push : Nat Stack? -> Stack? .


op top_ : Stack -> Nat? .
op pop_: Stack -> Stack? .
op topless : -> Nat? .
op underflow : -> Stack? .
var X : Nat . var S : Stack .
eq top push(X, S) = X .
eq pop push(X, S) = S .
eq top empty = topless .
eq pop empty = underflow .
endo
• reduce top push(1, empty) . ***> should be: 1
reduce pop push(1, empty) . ***> should be: empty
reduce top empty . ***> should be: topless
reduce pop empty . ***> should be: underflow
reduce top pop empty . ***> should be: top r:Stack?>Stack (underflow)

Propositional Calculus Example


• obj PROPC is
sort Prop .
extending TRUTH .
protecting QID .
subsorts Id Bool < Prop .

• *** constructors ***


op _and_ : Prop Prop -> Prop [assoc comm idem idr: true prec 2] .
op _xor_ : Prop Prop -> Prop [assoc comm idr: false prec 3] .
vars p q r : Prop .
eq p and false = false .
eq p xor p = false .
eq p and (q xor r) = (p and q) xor (p and r) .

• *** derived operations ***


op _or_ : Prop Prop -> Prop [assoc prec 7] .
op not_ : Prop -> Prop [prec 1] .
op _implies_ : Prop Prop -> Prop [prec 9] .
op _iff_ : Prop Prop -> Prop [assoc prec 11] .
eq p or q = (p and q) xor p xor q .
eq not p = p xor true .
eq p implies q = (p and q) xor p xor true .
eq p iff q = p xor q xor true .
endo

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


78 CS709 – Formal Methods of Software Engineering

Some Sample Reductions


• reduce ‘a implies ‘b iff not ‘b implies not ‘a . ***> should be: true
• reduce not(‘a or ‘b) iff not ‘a and not ‘b . ***> should be: true
• reduce ‘c or ‘c and ‘d iff ‘c . ***> should be: true
• reduce ‘a iff not ‘b . ***> should be: ‘a xor ‘b
• reduce ‘a and ‘b xor ‘c and ‘a . ***> should be: ‘c
• reduce ‘a iff ‘a iff ‘a iff ‘a . ***> should be: true
• reduce ‘a implies ‘b and ‘c iff (‘a implies ‘b) and (‘a implies ‘c) . ***> should be: true

• This example illustrates a striking advantage of using a logical language; every computation is a
proof and interesting theorem can be proved by applying the right programs to be right data.
• Even if the given equations do not define a decision procedure for a given theory, so long as they
are all correct with respect to the theory, then the result of the reduction is correct.

Difficulties in domains, requirements, designs


• High level specification of domains, requirements, designs are inherently partial and evolutional
• Usually there is no established formal (mathematical) model for the problems
• It is not easy to be convinced that some important property holds for domains, requirements,
designs
• Interactive developments with analyses/verifications are needed
• Development of domain theories can help

Proof Score Approach


• Domain/requirement/design engineers are expected to construct proof scores together with
formal specifications
• Proof scores are instructions such that when executed (or “played”) and everything evaluates as
expected, then the desired property is convinced to be hold
• proof by construction/development
• proof by reduction/computation/rewriting

Modeling/Specifying and Verifying


• By understanding a problem to be modeled/specified, determine several sorts of objects (entities,
data, agents, states) and operations (functions, actions, events) over them by describing the
problem
• Define the meanings/functions of the operations by declaring equations over expressions
composed of the operations
• Write proof scores for properties to be verified

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


79 CS709 – Formal Methods of Software Engineering

Natural Numbers -- Signature –


• 0 0+1 0+1+1 0+1+1+1 0+1+1+1 …
0 s(0) s(s(0)) s(s(s(0))) s(s(s(s(0)))) …
objects: Nat
operations: 0 : returns 0 without arguments
s : given a natural numbers n returns the next natural number (s n) of n

• -- sort [ Nat ]
-- operations
op 0 : -> Nat .
op s_ : Nat -> Nat .

Natural Numbers, Expressions/terms composed of operations


• mod! BASIC-NAT
{ [ Nat ] op 0: -> Nat op s_ : Nat -> Nat }
1. 0 is a natural number
2. if n is a natural number then (s n) is a natural number
3. An object which is to be a natural number by 1 and 2 is only a natural number
• Nat = {0, s(0), s(s(0)), s(s(s(0))), s(s(s(s(0)))), …}
• Nat = {0, s 0, s s 0, s s s 0, s s s s 0, …}

Mathematical Induction over Natural Numbers


• Goal: Prove that for any natural number
n  {0, s 0, s s 0, …}, P(n) is true
• Induction Scheme:
P(0) nN, [P(n)  P(s n)]
nN, P(n)
• Concrete Procedure: (induction w.r.t. n)
1. Prove P(0) is true
2. Assume that P(n) holds, and prove the P(s n) is true

Natural Numbers with addition operation


• -- sort [ Nat ]
-- operations
op 0 : -> Nat .
op s_ : Nat -> Nat .
op _+_ : Nat Nat -> Nat .

• Nat = {0} U {s n | n  Nat } U {n1 + n2 | n1  Nat  n2  Nat}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


80 CS709 – Formal Methods of Software Engineering

• Nat = { 0 , s 0, s s 0, s s s 0, … ,
0 + 0, 0 + (s 0) , 0 + (s s 0) , 0 + (s s s 0), … ,
(s 0) + 0, (s 0) + (s 0), (s 0) + (s s 0), … ,
(s s 0) + 0, (s s 0) + (s 0), (s s 0) + (s s 0), …,

0 + (0 + 0), 0 + (0 + (s 0)), …

}

• mod! NAT+ {
-- sort [ Nat ]
-- operations
op 0 : -> Nat .
op s_ : Nat -> Nat .
op _+_ : Nat Nat -> Nat .
-- equations
eq N: Nat + 0 = N .
eq N: Nat + (s M: Nat) = s (N + M) .
}

• Inference/Computation with the equations


(s 0) + ( s s 0) = s((s 0) + (s 0)) = s s((s 0) + 0) = s s s 0

Proof Score for the proof of associativity of addition (_+_)


-- opening module NAT+ and EQL
-- EQL is a built-in meta-module
-- for making a predicate (_=_) available

open (NAT+ + EQL)


--> declaring constants as arbitrary values ops i j k : -> Nat .
--> Prove associativity: (i + j) + k = i + (j + k)
by induction on k
--> base case proof for 0: red i + (j + 0) = (i + j) + 0 .
--> induction hypothesis is: eq (i + j) + k = i + (j + k) .
--> Proof of induction step for (s k): red (i + j) + k = (s k) = i + (j + (s k)) .

-> QED {end of proof of associativity of addition (_+_)}


close

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


81 CS709 – Formal Methods of Software Engineering

Lecture 33
Model Base Specification

VDM: Vienna Development Method


• Originating in work done at IBM's Vienna Laboratory in the 1970s
• Vienna Definition Language (VDL)
✓ Used to specify semantics of PL/I
• Vienna Development Method (VDM)
✓ Attempted to cover all of software lifecycle
• The VDM Specification Language (VDM-SL).
• Extended form, VDM++,
✓ Supports the modeling of object-oriented and concurrent systems.

Example – Incubator
• The temperature needs to be carefully controlled and monitored in order to provide the correct
conditions for a particular biological experiment to be undertaken.
• The temperature of the incubator increments or decrements in response to instructions and each
time a change of one degree has been achieved, the software is informed of the change, which it
duly records.
• Safety requirements dictate that the IncubatorMonitor
temperature of the incubator must temp: integer
never be allowed to rise above 10 C, nor
increment()
fall below -10  C.
decrement()
• UML Specifications
getTemp(): int

Specifying the State in VDM-SL


• State refers to the permanent data that must be stored by the system, and which can be accessed
by means of operations.
• The state is specified by declaring variables, in a very similar manner to the way that this is done
in a programming language
✓ Variable name and type

Intrinsic types available in VDM-SL


• Mathematical Notation
: Natural numbers (positive whole numbers)
1: Natural numbers excluding zero
Z: Integers (positive and negative whole numbers)
R: Real numbers (positive and negative numbers that can include a fractional part)
B: Boolean values (TRUE or FALSE)
Char: The set of alphanumeric characters

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


82 CS709 – Formal Methods of Software Engineering

State Definition
• state IncubatorMonitor of
temp : Z
end

• increment()
ext wr temp: Z
pre temp < 10
post temp = temp + 1

• deccrement()
ext wr temp: Z
pre temp > -10
post temp = temp − 1

• getTemp() currentTemp: Z
ext rd temp: Z
pre true
post temp = currentTemp

Declaring Constants in VDM


• values
MAX: Z =10
MIN: Z = -10
now we can write
pre temp > MIN

Specifying a State Invariant


• inv mk-IncubatorMonitor(t)  MIN  t  MAX
✓ Expression mk-IncubatorMonitor(t) is the input to the inv function.
✓ This expression is itself a function, and is known as a make function
▪ (the mk is pronounced ‘make’).
✓  is read ‘is defined as’

Specifying an Initialization Function


• init mk-IncubatorMonitor(t)  t = 5

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


83 CS709 – Formal Methods of Software Engineering

Main operations on sets

{a, b, c} Set enumeration: the set of elements a, b and c


{x | x: T & P(x)} Set comprehension: the set of x from type T such that P(x)
{i, ..., j} The set of integers in the range i to j
e in set s e is an element of set s
e not in set s e is not an element of set s
s1 union s2 Union of sets s1 and s2
s1 inter s2 Intersection of sets s1 and s2
s1 \ s2 Set difference of sets s1 and s2
dunion s Distributed union of set of sets s
s1 psubset s2 s1 is a (proper) subset of s2
s1 subset s2 s1 is a (weak) subset of s2
card s The cardinality of set s

Main Operators on Sequences (s, s1, s2 are sequences)

[a, b, c] Sequence enumeration: the sequence of elements a, b and c


[f(x) | x:T & P(x)] Sequence comprehension: sequence of expressions f(x) for
each x of (numeric) type T such that P(x) holds (x values taken
in numeric order)
hd s The head (first element) of s
tl s The tail (remaining sequence after head is removed) of s
len s The length of s
elems s The set of elements of s
s(i) The ith element of s
s1^s2 the sequence formed by concatenating sequences s1 and s2

Main Operators on Mappings

{a | -> r, b | -> s} Mapping enumeration: a maps to r, b maps to s


{x | -> f(x) | x:T & P(x)} Mapping comprehension: x maps to f(x) for all x for type T
such that P(x)
dom m The domain of m
rng m The range of m
m(x) m applied to x
m1 munion m2 Union of mappings m1 and m2 (m1, m2 must be consistent
where they overlap)
m1 ++ m2 m1 overwritten by m2

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


84 CS709 – Formal Methods of Software Engineering

Lecture 34
Z Specification
The Structure of Z Scheme

A Birthday Book

• known is a set of NAMES


• birthday is a function, which when applied to a name gives the birthday associated with it.
• known is a set of values of NAMES for which birthday is defined.
• Each person can have only one birthday.
• Set known is the same as the domain of function birthday – the set of names to which can be
validly applied.
• This relationship is an invariant of the system
• This relationship is true in every state of the system and is maintained by every operation on it.

One possible state of the system


• known = {Ahmed, Iram, Farrukh}
birthday = {Ahmed ↦ 25-Mar, Iram ↦ 20-Dec, Farrukh ↦ 25-Mar}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


85 CS709 – Formal Methods of Software Engineering

Add a new birthday to the birthday book

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


86 CS709 – Formal Methods of Software Engineering

Lecture 35

Find the person with birthday with a given date and generate card

Initialize the birthday book

Strengthening the Specification


• What happens when we try to add a birthday for someone already known?
• What happens when we try to find the birthday of someone not known?
• We can describe, separately from the first specification, the errors which might be detected and
desired response to them.
• Then use Z schema calculus to combine the two.

Success

• Now use conjunction to combine AddBirthday and Success


AddBirthday ∧ Success
• This describes an operation, which, for correct input, both acts as described by AddBirthday and
Success.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


87 CS709 – Formal Methods of Software Engineering

Incorrect Input – generate appropriate report

Robust Add Birthday


• RAddBirthday ≙ (AddBirthday  Success) ∨ AlreadyKnown
• This describes a new schema obtained by combining three already defined schema

Incorrect Input – generate appropriate report

Robust Find Birthday


• RFindBirthday ≙ (FindBirthday  Success) ∨ NotKnown

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


88 CS709 – Formal Methods of Software Engineering

Lecture 36
An Insulin Pump

• Needle Assembly: Connected to pump. Insulin reservoir

Component used to deliver insulin into the Needle


Pump Clock
assembly
diabetic body.
• Sensor: Measure the level of glucose in the
Sensor Controller Alarm
user’s blood. The input from sensor is
represented by reading? in the formal
specification. Display1 Display2

• Pump: Pumps insulin from the reservoir to


Power supply
needle assembly. The value represents the
dose in the formal specification.
• Controller: Controls the entire system. Has • Displays: There are two displays. One
on/off switch plus a button to set the (reading1!) displays the last measured blood
amount to be delivered. sugar reading and the other (reading1!)
• Alarm: Goes off if there is some problem. displays status.
The value sent to the alarm is represented by • Clock: Provides the controller with the
alarm! current time.

Insulin Pump Schema

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


89 CS709 – Formal Methods of Software Engineering

Modelling the insulin pump


• The schema models the insulin pump as a number of state variables
✓ reading? ✓ alarm!
✓ dose, cumulative_dose ✓ pump!
✓ r0, r1, r2 ✓ display1!, display2!
✓ capacity

Schema invariant
• Each Z schema has an invariant part which defines conditions that are always true
• For the insulin pump schema, it is always true that
✓ The dose must be less than or equal to the capacity of the insulin reservoir
✓ No single dose may be more than 5 units of insulin and the total dose delivered in a time
period must not exceed 50 units of insulin. This is a safety constraint.
✓ display1! shows the status of the insulin reservoir.

The dosage computation


• The insulin pump computes the amount of insulin required by comparing the current reading with
two previous readings
• If these suggest that blood glucose is rising then insulin is delivered
• Information about the total dose delivered is maintained to allow the safety check invariant to be
applied
• Note that this invariant always applies - there is no need to repeat it in the dosage computation

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


90 CS709 – Formal Methods of Software Engineering

Output schemas
• The output schemas model the system displays and the alarm that indicates some potentially
dangerous condition
• The output displays show the dose computed and a warning message
• The alarm is activated if blood sugar is very low - this indicates that the user should eat something
to increase their blood sugar level

Schema consistency
• It is important that schemas are consistent. Inconsistency suggests a problem with the system
requirements
• The INSULIN_PUMP schema and the DISPLAY are inconsistent
✓ display1! shows a warning message about the insulin reservoir (INSULIN_PUMP)
✓ display1! Shows the state of the blood sugar (DISPLAY)
• This must be resolved before implementation of the system

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


91 CS709 – Formal Methods of Software Engineering

Lecture 37
Refinement
• Refine a formal specification by adding more information
• Consistency and correctness
• The refinement leads us towards implementation

Abstract Data Types (an example)


✓ An abstract data type combines a description of state with description of operations upon
that state.
A == (AState, AInit, AOp1, AOp2, …)
✓ We may use abstract data types to specify the behavior of system components

• Removal of some degree of non-determinism


• Several refinement steps may be performed until the specification approaches executable
program code.
• Questions
✓ Why might we want different views of the same system?
✓ What makes two different views consistent?
✓ What makes two consistent views different?

• Refinement relation
✓ Data type B is called a refined of A iff every interaction with B could have been an
interaction with A, A⊑B
• Proper Refinement
✓ It is quite possible that A ⊑ B but B⋢A
✓ This will be the case when description B has resolved some of the uncertainty present in A
✓ The effect of at least one of the operations is now more precisely defined.
• Refinement Ordering
✓ If B is a refinement of A, and C is a refined of B, then C is also a refinement of A.
• Example

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


92 CS709 – Formal Methods of Software Engineering

✓ If there is more than one available resource then this specification is non-deterministic
✓ It is also partial – does not state what is to be done if there are no free resources

✓ Non-determinism is resolved as long as there is at least one resource


✓ Still partial
• Refinement to code
✓ The refinement of state components and operations can take us to executable code
✓ We replace the components of the state – sets, relations, sequences – with data
structures from our chosen implementation language
➢ We resolve any non-determinism present in the description of operations

• Data refinement and relations


✓ To derive a formal definition of refinement, and hence a set of useful proof rules, we
consider the semantics of operations.
✓ An operation may be seen as a relation between states: one state is related to another if
the system could start in the first and end up in the second.
✓ Our definition of refinement for data types will depend upon a similar definition of
refinement for relations.
• Total Relations
✓ Refinement of total relations is easily defined. If R and S are total relations, then
R⊑SS⊆R
✓ Whenever R relates the same element x to two distinct elements y1 and y2 , S may omit
either x ↦ y1 or x ↦ y2
✓ Totalization
➢ To define refinement for partial relations, we consider their totalised forms:

where X = X ⋃ {⊥} Y = Y ⋃ {⊥}

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


93 CS709 – Formal Methods of Software Engineering

Lecture 38
Totalization
• To define refinement for partial relations, we consider their totalised forms:

where X = X ⋃ { ⊥} Y = Y ⋃ { ⊥}

Example:

Refinement
• Having decided upon totalization using ⊥, we may derive the conditions for one partial relation
to be a correct refinement of another.

• If σ and ρ are two partial relations of the same type then σ refines ρ precisely when  is a subset

of  .
• This is true if and only if the domain of σ is at least as big as that of ρ and σ agrees with ρ on dom
ρ.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


94 CS709 – Formal Methods of Software Engineering

• Provided some additional information by extending the domain and removed some non-
determinism

Not a Refinement

Using Totalization


• If σ and ρ are two partial relations of the same type then σ refines ρ precisely when  is a subset

of  .

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


95 CS709 – Formal Methods of Software Engineering

Example
• We may corrupt a bit – an element of set
{0, 1} – by changing its value.

• The relation corruptsto associates two sequences of bits if the second is no longer than the first,
and no two adjacent bits have been corrupted.

• For example,
<1, 0, 0, 0, 1, 1> corruptsto <1, 0, 1, 0, 0, 1>
<1, 1, 0, 1, 1, 1, 0, 0> corruptsto <0, 1, 0, 0, 1>

• The relation changesto associates two sequences of bits if the second is no longer than the first,
and every bit with an odd index has been corrupted.

• For example,
<1, 1, 0, 1, 1, 1, 0, 0> changesto <0, 1, 1, 1, 0>
<1, 0, 0, 0, 1, 1> changesto <0, 0, 1, 0, 0, 1>

• The second relation is a refinement of the first:


✓ both are total relations on seq Bit
✓ changesto resolves all the non-determinism present in the definition of corruptsto.
• If we are content with the behavior of corruptsto, then we will be content with changesto.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


96 CS709 – Formal Methods of Software Engineering

Lecture 39
Program Refinement
• A sequence of operations on a data type.
• An abstract data type X is a tuple:
(X, xi, xf, { i: I ∙ xoi})
D = (D, di, df, {do1, do2})
di ; do1 ; do2 ; df
P(X) = xi ; xo1; xo2 ; xf Parameters
• If two abstract data types A and C use the same index set for their operations, then they will
support the same selection of programs: for every program P(A), there must be a corresponding
program P(C). What is more, any two programs P(A) and P(C) will be comparable, since they have
the same source and target sets.
• We may find that the effect of P(C) is defined whenever the effect of P(A) is defined.
• We may also find that P(C) resolves some of the non-determinism in P(A).
• If this is the case for every choice of P, then it is reasonable to say that C is worthy replacement
of A.

Totalisation

• Since xi and xf are total, the process of totalisation does nothing but augment each of them with
the set of pairs {⊥} and X ⊥

Refinement

Example
A == seq Bit X Action X seq Bit
C == seq Bit X Action X seq Bit
Action ::= yes | no

• The first component of the state tuple


represents the unconsumed part of the
input sequence, the second indicates
whether or not the next bit must be
faithfully reproduced, and the third
represents the accumulated output
• Initialisation

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


97 CS709 – Formal Methods of Software Engineering

• Initially, the whole of the input sequence waits to be consumed, the output sequence is empty,
the next bit may be corrupted.
• Finalisation

• Finally, the remaining input as well as the action component are discarded. The accumulated
output is all that remains.

• To prove we must show:

Reduces to: c0  a 0

Lifting
• Augment to allow undefined-ness
• To ensure that the definition is applicable to data types with partial operations.
• Not necessary to totalize

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


98 CS709 – Formal Methods of Software Engineering

Example

Forward Simulation

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


99 CS709 – Formal Methods of Software Engineering

Lecture 40
Specification of OS Components using Z-Specification
• Our system will deal with up to n processes, where n is a natural number.
|n:N
• Each process will be associated with a process identifier, or pid.
PId == 1 .. N
nullPId == 0 no process has this value
OptPId == PId ⋃ {nullPId}

• Classifies every pid in one of four ways:


• Current, ready, blocked, free

Operations
• Create a process, adding it to the set of ready process
• Dispatch one of the ready processes to the processor
• Timeout a process, removing it from the processor and ret
• Block a process, removing it from the processor and adding it to the set of blocked processes
• Wake up a blocked process, moving it into the set of ready processes
• Destroy a process

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


100 CS709 – Formal Methods of Software Engineering

Design
• our program will use a simple data structure: an array and a few counters
• our use of this data structure can be modeled using chains:
• finite injections from PId to PId
• unique start and a unique end

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


101 CS709 – Formal Methods of Software Engineering

• Elements of the chain are connected


• Everyone may be reached from start by applying the function links a finite number of times
• Guarantees uniqueness of start and end
• how do we know that the start and end of a given chain are uniquely defined?
• what must be true of the start and end pids if set is empty?

Operations
• push an element onto the end of a chain
• pop an element from the front of a chain
• delete an element from a chain

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


102 CS709 – Formal Methods of Software Engineering

Lecture 41
Chain
• Delete from the start
• Delete from the end
• Delete from the middle

• If this element is the first element in the chain, then the delete operation has an effect that is
similar to Pop:

• The last link in the chain simply disappears:


• The disappearance is described by range subtraction; the data type invariant is enough to
determine the new value of end.

• The previous element which is identified as links~ p? will be mapped to the next element which
is identified as links p?.
• In this schema, p? itself is removed using domain restriction

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


103 CS709 – Formal Methods of Software Engineering

Design
• A design for the scheduler based upon the chain data type.
• Our design will involve three chains: one each for the sets of ready, blocked, and free processes.

• The initial states of the ready and blocked chains are defined in terms of the initialization
schema ChainInit

• The free chain is initially full


• We will require push and pop operations on the ready and free chains, and push and delete
operations on the blocked chain.
• We may define these by renaming the components of the corresponding operations on Chain:

• We will require push and pop operations on the ready and free chains, and push and delete
operations on the blocked chain.
• We may define these by renaming the components of the corresponding operations on Chain:

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


104 CS709 – Formal Methods of Software Engineering

• The state of the concrete scheduler comprises the three chains, together with an optional
current process
• It is also useful to identify the working space used: the component chainstore is the union of the
three chain functions, plus an optional map to nullPId.
• Initially, there is no current process, and all chains are empty:

• When a process is dispatched to the processor, the ready chain is popped; the result becomes
the current process.

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


105 CS709 – Formal Methods of Software Engineering

• When a process is created, an identifier is popped o the free chain and pushed onto the ready
chain.

• Repeat for others such as CWakeup, CDestroyReady

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


106 CS709 – Formal Methods of Software Engineering

Lecture 42
Petri Nets – An Introduction
Concurrency
• Independent inputs permit “concurrent” firing of transitions

Conflict
• Overlapping inputs put transitions in conflict

Modeling FSMs

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


107 CS709 – Formal Methods of Software Engineering

Producers and Consumers

Bounded Buffers

1 2

3 4

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


108 CS709 – Formal Methods of Software Engineering

5 6

7 8

9 10

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


109 CS709 – Formal Methods of Software Engineering

Lecture 43
Behavioral Properties
• Reachability
✓ “Can we reach one particular state from another?”
• Boundedness
✓ “Will a storage place overflow?”
• Liveness
✓ “Will the system die in a particular state?”

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


110 CS709 – Formal Methods of Software Engineering

Lecture 44
Reachability Example with Petri Net

• 7 reachable states, 1 dead state

Another Example

A Deadlocked Petri Net

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


111 CS709 – Formal Methods of Software Engineering

A Petri Net that can Enter a Deadlocked State

A Deadlocked Petri Net

Modification into a Live Petri Net

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


112 CS709 – Formal Methods of Software Engineering

A Petri Net that can go into Starvation

Starving Transitions t2 and t4


Modeling synchronization control

Zero-testing Nets

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


113 CS709 – Formal Methods of Software Engineering

Modeling communication protocols

An unbounded but live Petri net

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


114 CS709 – Formal Methods of Software Engineering

Initial marking

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com


115 CS709 – Formal Methods of Software Engineering

Lecture 45
Activities of Formal Methods
• The main activities of Formal methods are
✓ Writing a formal specification
✓ Proving properties about the specification
✓ Constructing a program by mathematically manipulating the specification
✓ Verifying a program by mathematical argument

Key points
• Formal system specification complements informal specification techniques
• Formal specifications are precise and unambiguous. They remove areas of doubt in a specification
• Formal specifications force an analysis of the system requirements at an early stage. That helps
us in correcting errors at this stage is cheaper than modifying a delivered system
• Formal specification techniques are most applicable in the development of critical systems and
standards.
• Algebraic techniques are suited to interface specification where the interface is defined as a set
of object classes
• Model-based techniques model the system using sets and functions. This simplifies some types of
behavioural specification

7 Myths of Formal Methods – Anthony Hall – IEEE Software Sept. 1990


1. Formal methods can guarantee that software is perfect.
2. They work by proving that programs are correct.
3. Only highly critical systems benefit from their use.
4. They involve complex mathematics.
5. They increase the cost of development.
6. They are incomprehensible to clients.
7. Nobody uses them for real projects.

Limitations to Formal Methods


• Use formal methods as supplements to quality assurance methods not a replacement for them
• Useful for consistency checks, but formal methods cannot guarantee the completeness of a
specifications
• Formal methods must be fully integrated with domain knowledge to achieve positive results

Acceptance of formal methods


• Formal methods have not become mainstream software development techniques as was once
predicted
✓ Other software engineering techniques with better quality results.
✓ Time-to-market versus high quality
✓ Hard to scale up to large systems
✓ Not well-suited for specifying and analysing user interfaces and user interaction

Dr. Fakhar Lodhi | Virtual University of Pakistan | www.vumultan.com

You might also like