Design by Contract (DbC)
- Design By Contract (DbC) is a software correctness methodology
- Term coined by Bertrand Meyer; central concept in the Eiffel programming language
- A contract can be summarised by the "three questions" that the designer must repeatedly answer in the contract:
- What does the contract expect?
- What does the contract guarantee?
- What does the contract maintain?
Design by Contract (DbC)
- Contracts allow:
- To record details of methods’ responsibilities and assumptions
- To document the intended behaviour (specification) of software components
- To avoid having to repeatedly check arguments
- To assign blame across interfaces
Design by Contract (DbC)
- Contracts are:
- More abstract than code (e.g., sqrt() might be implemented using linear search, Newton’s method, . . .)
- Not necessarily checkable (e.g., quantified over infinite types, or just textual strings)
- In cases where they are formalized,
it is usually possible to
automatically generate verification
conditions
- (Or can be) used to avoid performing time-consuming defensive checks inside production code
Design by Contract (DbC)
- Modularity of Reasoning
- As far as verification is concerned: a program is fully verified if each
annotated component is individually verified
- In order to understand what the code
does, one can read the contracts
instead of looking at all the code
- Other features
- Designs and implementations can be refined by refining contracts
- DBC can be used to understand, document, improve, and maintain an existing code base
- DBC can be used to generate tests and to
formally verify key subsystems
Design by Contract (DbC)
- Language support for contracts exists in different forms:
- Natively: Eiffel, Racket, SPARK Ada, Dafny, ...
- Third-party: JML for Java; Spec# for C#; PyContracts for Python; ...
In this course, we will use Dafny, but we will discuss
others.
Design by Contract (DbC)
Here's an example of contracts in Eiffel:
deposit (sum: INTEGER) is
-- Deposit sum into the account.
require
sum >= 0
do
add (sum)
ensure
balance = old balance + sum
end
Design by Contract (DbC)
Here's the same example in Dafny:
method deposit(sum: int)
modifies this
requires sum >= 0
ensures balance == old(balance) + sum
{
add(sum);
}
Design by Contract (DbC)
Here's an example of contracts in Java (OpenJML):
public class Subtract {
//@ requires a > 0;
//@ requires b > 0;
//@ ensures \result == a-b;
public static int subtract(int a, int b){
return a-b;
}
public static void main(String args[]){
System.out.println(subtract(2,3));
}
}
Formal Reasoning with Hoare Logic
Assertions
- We need a language that enables unambiguous
specifications: we will use FOL to express assertions
$$
\scriptsize
\begin{array}{lcl}
P, Q & ::= & & \\
& & true, false & \textrm{Boolean literals} \\
& & R(e_1, \cdots, e_n) & \textrm{Relations} \\
& & P \wedge Q,\, P \vee Q,\, P \rightarrow Q,\, \neg{P} & \textrm{Boolean operators} \\
& & \forall x . P,\, \exists x . P & \textrm{Quantifiers} \\
\end{array}
$$
First-order Logic
You have already discussed FOL in Lecture
2.
A simple programming language
$$
\scriptsize
\begin{array}{lcl}
C & ::= & & \textit{Commands}\\
& & skip & \textrm{Skip (no op)} \\
& & var := exp & \textrm{Assignment} \\
& & C ; C & \textrm{Sequential composition} \\
& & \ifthenelse{bexp}{C}{C} & \textrm{Conditional} \\
& & \whileloop{bexp}{C} & \textrm{While loops} \\
\end{array}
$$
Here, $var$ is the name of a storage cell (variable) and
$bexp$ is a quantifier-free first-order assertion.
Example
// Oldest non-trivial algorithm
// known
// Assume M > 0 and N > 0
x := M; y := N;
while x != y do
if x<y then y := y-x
else x := x-y
// On termination: x == y
## Hoare Triples
At the core of Hoare Logic is the notion of _Hoare triple_:
**$$\ht{P}{C}{Q}$$**
- **Meaning**: If command $C$ starts in a state satisfying assertion $P$, and if $C$ terminates in some final state, then this final state will satisfy the assertion $Q$.
- The assertion $P$ is called the **precondition** of $C$, while $Q$ is the **postcondition**.
## Hoare Triples
Some triples are more "informative" than others.
For example,
$$\ht{false}{x := y+1}{x\leq 5}$$
is valid, but not very informative.
## Weakest precondition
On the other hand, the triple
$$\ht{y\leq 4}{x := y+1}{x\leq 5}$$
gives us the **weakest** valid **precondition**.
- Any other possible precondition implies the _weakest precondition_ (you can
think of it as a description of all the possible states that make the triple valid).
Hoare Logic
- Hoare Logic provides axioms and
inference rules for
all the constructs of a programming language
- Inference rules are of the form
$$\ithree{\textrm{rule name}}{\textrm{Conclusion}}{\textrm{Premise 1}}{\cdots}{\textrm{Premise n}}$$
- Rules without premises are called axioms
Example
Here's a well-known inference rule:
$$
\itwo{\textit{modus ponens}}{Q}{P\rightarrow Q}{P}
$$
In words: if $P$ implies $Q$ and if we have $P$, then we can conclude
$Q$.
Axiom for skip
The command $\skipcmd$ does not change the state:
$$
\izero{Skip}{\ht{P}{\skipcmd}{P}}
$$
Assignment
Consider the following triple
$$
\ht{??}{x := x+1}{x=1}
$$
- What precondition can we use?
- How can we obtain a precondition from the
assignment and postcondition?
- The value of $x$
after executing the assignment
should equal the value of $x+1$ in the
state before executing it.
- We can replace ?? with $x=0$
Assignment
Consider the following triple, where $E$ is an arbitrary
expression and $Q$ is an assertion:
$$
\ht{??}{x := E}{Q}
$$
- How can we obtain a precondition from the
assignment and postcondition?
- The value of $x$
after executing the assignment
should equal the value of $E$ in the
state before executing it.
- For $Q$ to be true
after the assignment, the
assertion obtained by substituting $E$ for
$x$ in $Q$ must be true before
executing it.
Substitution
Substitution of a variable $x$ in $Q$ by $E$ is
denoted by $$\subst{Q}{x}{E}$$
- $\subst{Q}{x}{E}$ is the assertion obtained by
replacing all free occurrences of $x$ in $Q$ by $E$
- Examples:
- $\subst{(x=1)}{x}{x+1} = (x+1=1)$
- $\subst{(x\leq y)}{x}{x+1} = (x+1\leq y)$
Axiom for assignment
$$
\izero{Asgn}{\ht{\subst{Q}{x}{E}}{x:=E}{Q}}
$$
Example
$$
\scriptsize
\izero{Asgn}{\ht{\subst{(x=1)}{x}{1}}{x:=1}{x=1}}
$$
which is the same as
$$
\scriptsize
\izero{Asgn}{\ht{1=1}{x:=1}{x=1}}
$$
Consequence Rules
Note that
$~~~
\scriptsize
\izero{Asgn}{\ht{1=1}{x:=1}{x=1}}
$
is different from
$~~~
\scriptsize
\izero{Asgn}{\ht{true}{x:=1}{x=1}}
$
They are logically equivalent, but not syntactically
equivalent!
Consequence Rules
Strengthening the precondition of a valid triple
always produces another valid triple
$$
\itwo{\textrm{Conseq Pre}}{\ht{P}{C}{Q}}{P\rightarrow P'}{\ht{P'}{C}{Q}}
$$
Consequence Rules
Weakening the postcondition of a valid triple always produces another
valid triple
$$
\itwo{\textrm{Conseq Pos}}{\ht{P}{C}{Q}}{Q'\rightarrow Q}{\ht{P}{C}{Q'}}
$$
Example: our first proof
- Putting the rules we've seen together, we can prove
$$
\scriptsize
{\ht{x=0}{x := x+1}{x\ge 1}}
$$
- The proof is a derivation tree:
$$
\scriptsize
\itwo{\textrm{Conseq Pre}}{\ht{x=0}{x := x+1}{x\ge 1}}
{\icond{x=0 \rightarrow x+1\ge 1}}
{\izero{\textrm{Asgn}}{\ht{x+1\ge 1}{x := x+1}{x\ge 1}}}
$$
Prove that the following triples are valid
- $\ht{true}{x := 42}{x\ge 10}$
- $\ht{x=2}{x := x+1}{x=3}$
- $\ht{x \neq 0}{y := x*x}{y > 0}$
Rule for Sequential Composition
$$
\itwo{\textrm{Seq}}{\ht{P}{C1;C2}{R}}{\ht{P}{C1}{Q}}{\ht{Q}{C2}{R}}
$$
- In words: if $C1$ transforms any state that satisfies $P$ into
any state that satisfies $Q$, and if $C2$ transforms a
state that satisfies $Q$ into any state that satisfies
$R$, then $C1;C2$ transforms any state that satisfies
$P$ into a state that satisfies $R$.
Example
- Show that
$~~~
\scriptsize
\ht{x=0}{y:=2\,;\,x:=y+1}{x=3}
$
- Derivation tree:
$
\tiny
\itwo{\textrm{Seq}}
{\ht{x=0}{y:=2 ; x:=y+1}{x=3}}
{\itwo{\textrm{Asgn}}{\ht{x=0}{y:=2}{y+1=3}}
{\icond{x=0\,\rightarrow\,2+1=3}}
{\izero{\textrm{Asgn}}{\ht{2+1 = 3}{y := 2}{y+1 = 3}}}}
{\izero{\textrm{Asgn}}{\ht{y+1=3}{x:=y+1}{x=3}}}
$
Prove that the following triples are valid
- $\ht{x=0}{x := x+1; x := x+2}{x=3}$
- $\ht{x=0}{x := x+1; \skipcmd}{x=1}$
- $\ht{x=2 \wedge y=3}{x :=x+2; y := y+1}{x=y}$
Rule for Conditionals
$$
\itwo{\textrm{If}}
{\ht{P}{\ifthenelse{b}{C1}{C2}}{Q}}
{\ht{P\wedge b}{C1}{Q}}
{\ht{P\wedge\neg{b}}{C2}{Q}}
$$
- In words: if $b$ is true, the first branch is
executed and we need to establish $\ht{P}{C1}{Q}$;
otherwise, the second branch is executed and we need
to establish $\ht{P}{C2}{Q}$
Rule for While Loops
$$
\ione{\textrm{While}}
{\ht{P}{\whileloop{b}{C}}{P\wedge\neg{b}}}
{\ht{P\wedge b}{C}{P}}
$$
- When the loop terminates, we know that $b$ is false
- The assertion $P$ is called an invariant
Prove that the following triple is valid
- $\ht{x\ge 0}{\whileloop{x>0}{x:=x-1}}{x=0}$
Summary
$$
\tiny
\begin{array}{ccc}
\izero{Skip}{\ht{P}{\skipcmd}{P}} &
\izero{Asgn}{\ht{\subst{Q}{x}{E}}{x:=E}{Q}} & \\
&&\\
\itwo{\textrm{Seq}}{\ht{P}{C1;C2}{R}}{\ht{P}{C1}{Q}}{\ht{Q}{C2}{R}} &
\itwo{\textrm{If}}
{\ht{P}{\ifthenelse{b}{C1}{C2}}{Q}}
{\ht{P\wedge b}{C1}{Q}}
{\ht{P\wedge\neg{b}}{C2}{Q}} &\\
&&\\
\ione{\textrm{While}}
{\ht{P}{\whileloop{b}{C}}{P\wedge\neg{b}}}
{\ht{P\wedge b}{C}{P}} &&\\
&&\\
\itwo{\textrm{Conseq Pre}}{\ht{P}{C}{Q}}{P\rightarrow
P'}{\ht{P'}{C}{Q}} &
\itwo{\textrm{Conseq Pos}}{\ht{P}{C}{Q}}{Q'\rightarrow
Q}{\ht{P}{C}{Q'}} & \\
\end{array}
$$