Recalling Our Intro to the Course

## The Program Correctness Problem

• Conventional models of using computers - not easy to determine correctness!
• Has become a very important issue, not just in safety-critical apps.

• Components with assured quality, being able to give a warranty, ...

• Being able to run untrusted code, certificate carrying code, ...

## A Simple Imperative Program

• Example:
#include <stdio.h>
main() {
int Number, Square;
Number = 0;
while(Number <= 5)
{ Square = Number * Number;
printf("%d\n",Square);
Number = Number + 1; } }


• Is it correct? With respect to what?
• A suitable formalism:
• to provide specifications (describe problems), and
• to reason about the correctness of programs (their implementation).
is needed.

## Natural Language

Compute the squares of the natural numbers which are less or equal than 5.''

Ideal at first sight, but:

• verbose
• vague
• ambiguous
• needs context (assumed information)
• ...

Philosophers and Mathematicians already pointed this out a long time ago...

## Logic

• A means of clarifying / formalizing the human thought process

• Logic for example tells us that (classical logic)
Plato is a friend of anyone who likes cookies

imply that
Plato is a friend of Aristotle
• Symbolic logic:
A shorthand for classical logic - plus many useful results:

• But, can logic be used:
• To represent the problem (specifications)?
• Even perhaps to solve the problem?

## Using Logic

• For expressing specifications and reasoning about the correctness of programs we need:
• Specification languages (assertions), modeling, ...
• Program semantics (models, axiomatic, fixpoint, ...).
• Proofs: program verification (and debugging, equivalence, ...).

## Generating Squares: A Specification (I)

Numbers --we will use Peano'' representation for simplicity:
0 0 1 s(0) 2 s(s(0)) 3 s(s(s(0))) ...

• Defining the natural numbers:

• A better solution:

• Order on the naturals:

## Generating Squares: A Specification (II)

• Multiplication of naturals:

• Squares of the naturals:

We can now write a specification of the (imperative) program, i.e., conditions that we want the program to meet:

• Precondition:
empty.
• Postcondition:

## Use of Logic

• For expressing specifications and reasoning about the correctness of programs we need:
• Specification languages (assertions), modeling, ...
• Program semantics (models, axiomatic, fixpoint, ...).
• Proofs: program verification (and debugging, equivalence, ...).

• Semantics:
• A semantics associates a meaning (a mathematical object) to a program or program sentence.

• Verification: proving that a program meets its specification.
• Static debugging: finding where a program does not meet specifications.
• Program equivalence: proving that two programs have the same semantics.
• etc.

## Styles of Semantics

• Operational:
The meaning of program sentences is defined in terms of the steps (transformations from state to state) that computations may take during execution (derivations). Proofs by induction on derivations.
• Axiomatic:
The meaning of program sentences is defined indirectly in terms of some axioms and rules of a logic of program properties.
• Denotational (fixpoint):
The meaning of program sentences is given abstractly as functions on an appropriate domain (which is often a lattice). E.g., -calculus for functional programming. C.f., lattice / fixpoint theory.
• Also, model (declarative) semantics: (For (Constraint) Logic Programs:) The meaning of programs is given as a minimal model (logical meaning'') of the logic that the program is written in.

 Operational Semantics

• Meaning of program sentences defined in terms of the steps (state transitions, transformations from state to state) that computations may take during executions (derivations).

• Proofs by induction on derivations.

• Examples of concrete operational semantics:
• Semantics modeling memory for imperative programs.
• Interpreters and meta-interpreters (self-interpreters).
• Resolution and CLP() resolution, for (constraint) logic programs.
• ...

• Examples of generic / standard methodologies:
• Structural operational semantics.
• Vienna definition language (VDL).
• SECD machine.
• ...

## A Simple Imperative Language

Program    ::= Statement
Statement  ::= Statement ; Statement
|   noop
|   Id := Expression
|   if Expression then Statement else Statement
|   while Expression do Statement
Expression ::= Numeral
|   Id
|   Expression + Expression


• Only integer data types.
• Variables do not need to be declared.

## Operational Semantics

• States: memory configurations -values of variables.
• denotes the value of the variable X in state .
• denotes that
if is executed in state the resulting state is .
• denotes that
if is executed in state it returns .

• Expressions:
• If is a number
• If is a variable
• If is of the form + we write:

## Operational Semantics

• Statements:
denotes a new state, identical to but where variable has value .

• Noop:
• Assignment:

• Conditional:

## Operational Semantics

• Statements (Contd.):
• Sequencing:

• Loops:

## Example

• Program:
x := 5;
y := -6;
if (x+y) then z := x else z := y


• Semantics:

where if (x+y) then z := x else z := y.
And:

 Axiomatic Semantics

## Axiomatic Semantics

• Characteristics:
• Based on techniques from predicate logic.
• There is no concept of state of the machine
(as in operational or denotational semantics).
• More abstract than, e.g., denotational semantics.
• Semantic meaning of a program is based on assertions about relationships that remain the same each time the program executes.
• Classical application:
• Proving programs to be correct w.r.t. specifications.

• (Typical, classical) limitations:
• Side-effects disallowed in expressions.
• goto command difficult to treat.
• Aliasing not allowed.
• Scope rules difficult to describe require all identifier names to be unique.

## History and References

• Main original papers:
• 1967: Floyd. Assigning Meanings to Programs.
• 1969: Hoare. An Axiomatic Basis of Computer Programming.
• 1976: Dijkstra. A Discipline of Programming.
• 1981: Gries. The Science of Programming.
• Many textbooks available.

## Assertions and Correctness

• Assertion: a logical formula, say

that is true when a point in the program is reached.

• Precondition: Assertion before a command ( includes a whole program).

• Postcondition: Assertion after a command.

C a Hoare triple''

• Partial Correctness:
If the initial assertion (the precondition) is true and if the program terminates, then the final assertion (the postcondition) must be true.

Precondition + Termination Postcondition

• Total Correctness:
Given that the precondition for the program is true, the program must terminate and the postcondition must be true.

Total Correctness = Partial Correctness + Termination

## Hoare Calculus: The Assignment Axiom

• Examples:
• m := 13
• n := c*n
• k := k + 1

• Notation:
• command
• denotes substitution: putting in place of in

• Axiom for assignment command:

Work backwards:

• Postcondition:
• Command: n := c*n
• Precondition:

## Hoare Calculus: Read and Write Commands

• Notation:
• Use '' and '' to represent input and output files.
• denotes list whose head is and tail is .
• K, M, N, ... represent arbitrary numerals.
• Axiom for write command:
• write
• Note: is the list whose last element is ( represents concatenation).

## Hoare Calculus: Rules of Inference

• Format (c.f. structural operational semantics):

• Axiom for Command Sequencing:

 ,

• Axioms for If Commands:

 ,

 ,

## Hoare Calculus: Rules of Inference (Contd.)

• Weaken Postcondition:

 {P}{Q} { P }{ R }

• Strengthen Precondition:

 {Q}{R} { P }{ R }

• And and Or Rules:

• Observation:

## Example (I)

read m; read n; if m n then a := 2*m else a := 2*n

minipage0.3 Recall:
tex2html_wrap_inline${ IN = [K|L] P[V K] }$
read tex2html_wrap_inline$V$
tex2html_wrap_inline${ IN = L P }$

## Example (II)

We have

{P b} C_1 {Q}tex2html_wrap_inline$,${P b} C_2 {Q} { P } if b then C_1 else C_2 endif { Q }

So, and ; thus and .

So, for we have:

a := 2*n tex2html_wrap_inline${ P [V E] }$ tex2html_wrap_inline$V :=> E$ tex2html_wrap_inline${ P }$

and for we can have anything since the premise is false:

a := 2*m

## Example (III)

if m n then a := 2*m else a := 2*n

and

write a

which implies

## While Command

• Loop Invariant: P
• Preserved during execution of the loop.

• Loop steps:
• Initialization: show that the loop invariant is initially true.
• Preservation:
show the loop invariant remains true when the loop executes ( ).
• Completion: show that the loop invariant and the exit condition produce the final assertion ( ).

• Main Problem:
• Constructing the loop invariant.

## Loop Invariant

• A relationship among the variables that does not change as the loop is executed.
• Inspiration'' tips:
• Look for some expression that can be combined with to produce part of the postcondition.
• Construct a table of values to see what stays constant.
• Combine what has already been computed at some stage in the loop with what has yet to be computed to yield a constant of some sort.

Study carefully many examples!

## Example (exponent)

while endwhile k := N; s := 1; k0 do s := A*s; k := k-1

We follow the tips:''

• Trace algorithm with small numbers , .
• Build a table of values to find loop invariant.
• Notice that k is decreasing and that represents the computation that still needs to be done.
• Add a column to the table for the value of .
• The value remains constant throughout the execution of the loop.

## Example (Exponent)

minipage0.45 tex2html_wrap_inline${ N 0 A 0 }$
tabularll k := N; & s := 1;
while & ktex2html_wrap_inline$>$0 do
& s := A*s;
& k := k-1
endwhile

tex2html_wrap_inline${ s = A^N }$
 tabular[h]rrrr k & s & 2 & s*2 5 & 1 & 32 & 32 4 & 2 & 16 & 32 3 & 4 & 8 & 32 2 & 8 & 4 & 32 1 & 16 & 2 & 32 0 & 32 & 1 & 32

• Observe that and change when changes.
• Their product is constant, namely .
• This suggests that is part of the invariant.
• The relation seems to be invariant, and when combined with "", which is , establishes at the end of the loop.
• When is joined with , we get the postcondition .
Loop Invariant: .

Initialization:

k := N; s := 1;

Preservation:

s := A*s;

k := k-1

Completion:

## Further Topics

• Dealing with other language features:
• Nested loops.
• Procedure calls.
• Recursive procedures.
• ...
• Proving termination / total correctness.
• Well founded orderings.

## Acknowledgments

• Some slides and examples taken from:
• Enrico Pontelli
• Jim Lipton
• Ken Slonneger and Barry L. Kurtz.
Formal Syntax and Semantics of Programming Languages: A Laboratory-Based Approach. Addison-Wesley, Reading, Massachusetts.

Last modification: Tue Nov 28 21:52:52 CET 2006 <webmaster@clip.dia.fi.upm.es>