bertrand meyer eth zurich, eiffel software & itmo with cristiano calcagno, carlo furia,...
TRANSCRIPT
Bertrand MeyerETH Zurich, Eiffel Software & ITMO
With Cristiano Calcagno, Carlo Furia, Alexander Kogtenkov*, Martin
Nordio, Manuel Oriol+, Yu Pei, Nadia Polikarpova, Emmanuel
Stapf*, Julian Tschannen, Stephan van Staden, Yi Wei, Andreas
Zeller= & others
*Eiffel Software+ETH, then U. of York, now ABB
=U. Saarbrücken
Microsoft Summer School, Moscow, July 2011
VerificationAs a Matter Of Course
SEL at ITMO
Software Engineering Laboratory |Лаборатория Программной Инженерии
Создано в июне 2011
Ещё остаются открытые позиции!
Аспиранты и Кандидаты (на полной ставке)
Временные гранты (“sabbaticals”) для исследователей, 2 до 6 месяцев
2
Initiatives
SEC-R conference in October 2011
ESEC 2013 will take place in Saint Petersburg
New LinkedIn group:Программная Инженерия / Software Engineering Russia
Software Engineering Seminar in Saint PetersburgITMO and Polytechnical University (V. Itsykson)Every Thursday 18-21, visitors welcome
http://meyerseminar.org
3
Contents
1.The goal: trusted components
2.The EVE environment
3.Technical developments: 3.1 Towards full contracts 3.2 Negative variables & the essence of
object-oriented programming 3.3 Language convention for frames 3.4 The alias calculus 3.5 A Calculus of Object Programs
4.Conclusion and assessmentNot included:
concurrency 4
- 1 -
Scope & Goals
5
Three forms of software development
1. Casual
2. Professional
3. Critical
Simple Web sites, spreadsheets, …
Enterprise computing, simulation, “soft” real-time, …
Transportation, critical infrastructure, “hard” real-time, …
Enterprise computing, simulation, “soft” real-time, …
6
Language techniques for professional development
Dynamic allocation Classes,
objects
Exception handling Closures
(agents)Exceptions
Genericity
Inheritance
Polymorphism,dynamic binding
...
7
Research context (1): method and language
Our work is based on Eiffel: Method and language for quality-focused
development For professional systems, including very large ones Continuous, seamless development ISO standard, significant user base and code base Libraries Excellent development environment: EiffelStudio
Some advantages: Built-in, deeply ingrained use of contracts:
preconditions, postconditions, class invariants Open-source, no patent or other proprietary issues We can shape the future method, language and IDE
Java is not a Law of Nature 8
- 2 -
The EVE environment
9
Research context (2): EVE
Eiffel Verification Environment
Open source
Developed at ETH, others’ contributions welcome
Continuous integration (weekly) with EiffelStudio
The platform for trying new ideas
All ETH and ITMO contributions included
10
Verification As a Matter Of Course
Arbiter
AutoProof
Aliasanalysis
AutoFix
Test case generation
EVE Test executio
n
Test results
Inter.prover
Sep. logic
prover
AutoTest
Invariantinferenc
e
Invariantinferenc
e
Suggestions
Suggestions
11
Scores
Failed test: score = -1
Successful test run: 0 < score <= 0.9
Correctness proof: score = 1May be scaled down if some aspects not takeninto account, e.g. arithmetic overflow
In practice (AutoProof): Successful proof: score = 1 Out-of-memory, timeout: score = 0 Failed proof with abstract trace: score = -1
Carlo Furia, Julian Tschannen, Martin
Nordio
12
Demo
13
Combining static and dynamic techniques
Static verification: + More modular + Scales up better - Not always feasible - Often tests idealized version of the software - Captures only specified properties
Testing: + Generally possible + Can be automated + Tests software as it is + Can integrate non-software parts - Partial (very!) - Captures only specified properties - Not always feasible
14
Testing
To test a software system is to try to make it fail
Fiodor Chaliapineas Mephistopheles
“Ich bin der Geist, der stets verneint”
Goethe, Faust, Act I
15
AutoTest
(e.g. IEEE Computer, Sep. 2009)Integral part of EiffelStudio
Has already uncovered hundreds of bugs in libraries and other software
Three components:
Test generation Test extraction (from failures) Manual tests
Ilinca CiupaAndreas Leitner
Yi WeiEmmanuel Stapf
Arno FivaManuel Oriol…
16
AutoTest: Test generation
Input: set of classes Generates instances, calls routines with
automaticallyselected arguments
Oracles are contracts: Direct precondition violation: skip
(precondition satisfaction techniques minimize this)
Postcondition/invariant violation: bug found Any test (manual or automated) that fails becomes
part of the test suite
17
18
Maurice Maeterlinck, La Vie des Abeilles, 1901
19
AutoTest: Test generation
*SET
**
+SET1
+SET2
+ +
Test:s1, s2 : SETs2 s1
*: Deferred +: Effective
Bernd Schoeller
20
AutoTest: Test extraction
Turn a failed execution into a test case
21
Who finds what faults?
On a small EiffelBase subset,we compared:
AutoTest Manual testing (students) (3 classes, 2 with bugs
seeded) User reports from the field
Largely separate kinds of faults
AutoTest: 62% specification, 38% implementationUser reports: 36% specification, 64% implementation
I.Ciupa, A. Leitner,M.Oriol, A. Pretschner
ICST 2008 (best paper)
22
CITADEL: Daikon for Eiffel
How do programmer-written and inferred contracts compare?
Can contract inference be used to improve the quality of programmer-written contracts?
Nadia Polikarpova
Ilinca Ciupa
ISSTA 2009
23
CITADEL results
A high proportion of inferred contract clauses are correct (90%) and relevant (64%)
Contract inference does not find all programmer-written contracts (only 59%)
Programmers do not write all inferred contracts (25%)
Contract inference can strengthen programmer-written postconditions and invariants and find missing precondition clauses
24
AutoFix: programs that fix themselves
16 faults fixed out of 42
Some of the fixes are exactly the same as those proposed
by professional programmers
Passing & failing test cases
Difference
Fix to minimize the difference
Yi Wei, Yu Pei, Andreas Zeller, ISSTA 2010
Yi Wei, Yu Pei, Carlo Furia, ASE 2011 (etc.)
25
- 3.1 -
Towardscompletecontracts
26
Typical contract: list insertion
put_right (v: G) -- Insert v to the right of cursor require index <= count ensure i_th (index + 1) = v count = old count + 1 index = old index
end
count1
v
-- Previous elements unchanged!
index
27
Complete contracts
Contracts are typically incomplete(unlike those of fully formal approaches such as Z)
Our solution: Use models
A model is a mathematical interpretation of the structures
Model library: MML (Mathematical Model Library)Fully applicative (no side effects, attributes, assignment etc.)But: expressed in Eiffel (preserving executability)
Bernd Schoeller, Tobias Widmer
(2008)
Nadia Polikarpova (VSTTE 2010)
28
Typical contract: list insertion
put_right (v: G) -- Insert v to the right of cursor require index <= count ensure i_th (index + 1) = v count = old count + 1 index = old index
end
count1
v
-- Previous elements unchanged!
index
29
List insertion with model-based contract
note model: sequence, indexclass LIST [G] ...
sequence: MML_SEQUENCE [G]
put_right (v: G) -- Insert v to the right of cursor. require index <= sequence.count ensure sequence =
old (sequence.front (index).extended (x) + sequence.tail (index + 1))
index = old index end
...30
Model-based contracts: applications
On 7 of the most popular EiffelBase classesTesting found 4 “functional” faults by violation of
model-based contracts
EiffelBase2: a data structures library with full contracts Aim is to prove the code against these contracts
Now in progress: specifying application libraries (graphics, networking...)
31
- 3.2 -
Negative Variables& the Essence
of Object-Oriented
Programming32
O-O analysis, design & programming
“Principle of general relativity”: every operation in a class is expressed relative to a “current object” (self, this, Current), known only at execution time
class C featurer
dox := 1
x . f (...)end
...end
Need to model this property in the logic33
Simplified denotational rule for routines (unqualified call)
(call r (c)) (s) = r ( [s r : c])
Notations: r: body of r r : list of formal arguments of r F [v :e] : Substitution of v for e in F
(for variable v and expression e; generalized to
vectors of variables and expressions) Distributed dot (used next), for a list v = <u, v, w,
…>: x v = <x u, x v, x v, …> 34
Classic axiomatic rule for routines
(Ignoring recursion)
{P} r {Q}
{P [r : c]} call r (c) {Q [r
: c]}
35
Tentative rule for qualified (O-O) calls
(Inadequate!)
{P and INV} r {Q and INV}
{x P [r : c]} call x r (c) {x Q [r
: c]}
Standard solution (e.g. Peter Müller’s thesis): in r, replace all occurrences of an attribute a by
Current.a
36
Object-oriented calls
call x r (c)
xx’
Current
Target object
Negative variables:
y
Known by the target as x’ y
Known by the target as x’ y
x Current = x
Current x = x
x’ x = Current
x x’ = Current
Current’ = Current 37
Denotational rule for calls
Unqualified calls:(call r (c)) (s) = r (s [r : c])
Qualified calls:
(call x r (c)) (s) = x call r (x’ c) (s)
Then for any property P (such that “” distributes over P):
P (call x r (c)) = x P (call r (x’ c))
= x r (s [r : x’
c])
= x (P ( r) [r : x’ c])
38
Adequate Hoare rule for qualified calls
Reminder: inadequate rule
{P and INV} r {Q and INV}
{x P [r : x’ c]} call x r (c) {x Q [r
: x’ c]}
{P and INV} r {Q and INV}
{x P [r : c]} call x r (c) {x Q [r
: c]}
Proper rule
39
- 3.3 -
Framing:a language convention
40
The frame issue:
In a class ACCOUNT:deposit (sum: INTEGER)
require ...do...ensure
balance = old balance + sumend
What about other queries other than balance, e.g.
owner, account_number, overdraft_limit...?
What about descendant classes, e.g. MAFIA_ACCOUNT?
Specifying what does not change
41
“Modifies” clauses
ESC-Java, JML, Spec#: specify what a command can changeTheoretical problems:
This can be an infinite set Requires careful design for inheritance
Practical problem: tedious to express
Pragmatic observation from survey of JML code: Every item listed in a modifies clause also
appears in the postcondition!
42
The proposed language convention
A routine may only modify queries listed (outside of an old expression) in its postcondition
deposit (sum: INTEGER )require ...do...ensure
balance = old balance + sum
end
This also avoids introducing a special language notation to express that a routine is pure
has_penalty = (cur /= currency)
; cur: CURRENCY
oldinvolved
(is_overdraft)
43
- 3.4 -
The Alias Calculus
44
The question asked by the Alias Calculus
Given expressions e and f, and a program location p :
Can e and f ever be attached to the same object at p ?
Broy volume (IJSI, 2011)
45
An example
y
x
46
Why is this important?
Alias analysis can be a key tool for proving O-O programs (as an alternative to separation logic)
47
Applications of alias analysis
1. Without it, cannot apply standard proof techniques to programs involving pointers
2. Concurrent program analysis, in particular deadlock3. Program optimization
-- y.a = b
x.set_a (c)
?a
x
y
set_a (c)
b
c-- x.a = c-- x.a = c
-- c = c, i.e. True
Understand as x.a := c
-- y.a = b
48
Alias relations
Relation of interest:“In the computation, x might become aliased to
y”Definition:
Not necessarily transitive:if c then
x := yelse
y := zend
A binary relation is an alias relationif it is symmetric and irreflexive
Can alias x to yand y to zbut not x to z
49
Describing an alias relation
If r is a relation in E E, the following is an alias relation:
r r r-1 ― Id [E]
Example: {[x, x], [x, y], [y, z]} =
Generalized to sets:
{x, y, z} =
=D
Set difference
Identity on E
Set of binary relations on E; formally: P (E x E)
{[x, y], [y, x], [y, z], [z, y]}
{[x, y], [y, x], [x, z], [z, x], [y, z], [z, y]}
50
Canonical form and alias diagrams
Canonical form of an alias relation: e.g.
, meaning
None of the sets of variablesis a subset of another
x, y, y, z, x, u, v
x
u, v
y
x
y, z
Make it canonical:x, x
, yy
{x, y} { y, z} {x, u, v}
(not canonical)
Alias diagram:
yy
51
Alias diagrams (non-O-O)
x
u, v
y, z
x,
, y
Source node Value nodesValue nodesValue nodes
In canonical form: no label is subset of another; each label has at least two variables
52
Operations on alias relations
If a is an alias relation in in and A a set, the following are alias relations:
r \– A = r — E x A
a / x = {y: E | (y = x) [x, y] a}
53
“Quotient”, similar to equivalence class in equivalence relation
“Minus”
Set of all variables
What the calculus is about
The purpose of the calculus is to define, for any
instruction p and any alias relation a, the value of
a » p
which denotes:The aliasing relation resulting from executing
p from an initial state in which the aliasing
relation is a
For an entire program: compute » p
54
Limits of the calculus
The calculus is exact
But language simplifications cause over-approximation:
Conditional instruction:
then p else q end
Loop: loop p end
To correct over-approximation: cut instruction 55
Basic instructions
x, y, … are variables
Instructions (p, q, …):
skip
create x
x := y
forget x
(p ; q)
then p else q end
-- Eiffel: x := Void-- Java etc.: x = null;
56
Basic properties
a » skip = a
a » (then p else q end ) = (a » p) (a » q)
a » (p ; q) = (a » p) » q
a » (forget x) = a \- {x}
a » create x = a \- {x}
57
The forget rule
a » (forget x) = a \- {x}
y
x,
y, z
x,
u, v
x,
x,
y
58
Assignment
a » (x := y) = givenb = a \- {x}
then
b ({x} x (b / y)) end
All pairs of the form [x, y] or [x, u] where u was aliased to y
Symmetrize and de-reflect
a deprived of all pairs involving x
59
Operations on alias relations (reminder)
r \– A = r — E x A
a / x = {y: E | (y = x) [x, y] a}
“Quotient
“Minus”
60
Assignment example 1
x
u, vx,
, y
Afterz := x
, z
, z
61
Assignment example 2
x
u, vx,
, y
Afterx := u
x, y
62
Assignment example 3
x
u, vx,
, y
Afterx := z
x, y
x, z
x,
63
Correcting over-approximations manually
cut x, y
Semantics: remove any aliasing between x and y
64
Cut example 1
65
x
u, vx,
, yx, y
After cut x, y
Cut example 2
x, y
After cut x, u
u, vx,x, x, v
66
Cut rule
a » cut x, y = a ― x, y
67
The role of cut
cut x, y informs the alias calculus with non-alias properties that come from other sourcesExample:
if m < n then t := u else t := y endm := m + 1if m < n then x := t end
In fact x cannot be aliased to y (only to u), but the alias theory does not know this propertyTo express it, add the instruction
cut x, y; This expression represents
check x /= y end (Eiffel)assert x != y ; (JML, Spec#)
68
Alias relation:
t, u, x, t, y, x
t, u, t, y
Iterations and loops
pn (for integer n): n executions of p
(auxiliary notion)
loop p end : any sequence (incl. empty) of executions of p
69
Iterations and loops
a » p0 = a
a » pn+1 = (a » pn) » p -- For n 0
a » (loop p end) = (a » pn)n N
70
Loop aliasing theorem
a » (loop p end) is also the fixpoint of the sequence
t0 = a
tn+1 = tn (tn » p)
Gives a practical way to compute a » (loop p end)
71
Routines
Routine definitions (one of them designated as main):
r (args) do p end
Routine call: call r (c)
r
r
Notations:
Body of r:
Formal arguments of r: (args above)
Substitution in an expression F: F [u: v]
72
Alias calculus rule for routine call
a » call r (c) = a » [r : c]
--
Because of recursion, no longer just definition but equation
For entire set of routines R, making up a program, this gives a vector equation
a » R = F (a » R)
Interpret as fixpoint) equation and solve iteratively
r
73
Introducing object-oriented constructs
1. Qualified expressions: e f g …
Can be used as source (not target!) of assignments
x := e f
2. Remote calls: x r
3. Current
74
Assignment (original rule)
a » (x := y) = given
b = a \- {x}
then
b ({x} x (b / y) )
end
a deprived of all pairs involving x
This includes [x, y] ! All pairs [x, u] where u is either aliased to y in b or y itself
All u aliased to y in b, plus y itself
75
Assigning a qualified expression
x yx
x
z
x does not get aliased to x y!
(only to any z that was aliased to x
y)
x := x y
76
Assignment rule revisited
a » (x := y) = given
b = a \- {x} then
b ({x} x (b / y))
end
a deprived of all pairs involving xor an expression starting with x
77
Non-O-O diagrams
x
u, v
y, z
x,
, y
Source node Value nodesValue nodesValue nodesSingle source node(represents stack)Each value node represents a set of possible run-time valuesLinks: only from source tovalue nodes (will becomemore interesting with E4!)Edge label: set ofvariables; indicates theycan all be aliased to each otherIn canonical form: no label is subset of another; each label has at least two variables 78
O-O diagrams
:= x y
x yx
x
z
Links may now exist between value nodes(now called object nodes)Cycles possible (see next)
Source node
Value nodesValue nodesObject nodes
79
Representing a qualified call with arguments
call x r (a, b)
With, in a class C:
r (t: T ; u: U)
The formals mean
t: x’ a
u: x’ b
Negated variables
x x’
Negated variables
a
80
The qualified call rule
a » call x r (c) = x ((x’ a) » call r (x’ c))
Example: c := d call x r (c)with r (u: T)
do
v := u end
xx
’
c, dUnderstand as: c := d callwith r
do
v := u end
u := x’
c
u, v, x’ c,x’ d
x u, x v ,
x r
81
Processing a qualified call
a » call x r (c) = x ((x’ a) » call r (c)
Alias relation:
c, d
x’ c, x’ d
Prefix with x’
:
u, x’ c, x’
d
c := d callwith r
do
v := u end
u := x’
c
x f
v, u, x’ c, x’
d Prefix with x :
x v, x u, c, d
xx
’
c
u,
,
x’ c, x’ d
v,x
x
x
x
c,d
Current
c
x’
c,x c, x’ c, x’ d x d
u,v,
x
x
, d, d
82
How to prove a program with references
Compute alias relation up to and including the largest expression involved in the program
Add alias properties to contracts of program
Prove program through usual axiomatic techniques
Prove correctness of cut instructions
83
- 3.5 -
A Calculus ofObject Programs
84
The general goal
A theory to verify object-oriented programs
Handles references, aliasingSoundMechanizableClear In line with Eiffel’s Design by Contract
In particular, contracts can still be evaluated dynamically (for testing, debugging)
85
Reversing a list
reverse local previous, next: LINKABLE [G] do from next := first ; previous := Void invariant
end
first
right
right
right
right
next
?
?first right = - old first rightfirst right = - old first right
next right + previous right
= - old first right
next right + previous right
= - old first right until next = Void loop
temp := previousprevious := nextnext := next right
previous put_right (temp) end first := previous ensure
previous
86
Components of the solution
1. Compositional logic for programming languages
2. Calculus of object structures
3. Inverse variables
4. Alias calculus
5. The proof
87
Compositional logic
Compositional logic deals with properties of the formi ; e
where i is an instruction and e an expression
Meaning: the value of e after executing i
Expressed in terms of values of expressions before this execution
Examples:(x := 1) ; x = 1(x := x + 1) ; x = x + 1
88
Comparison with other approaches
Denotational:State s: State where State = Variable ValueExpression e : State Value e.g. e (s) = 3Command c : State StateAdvantage: defines program as mathematical
objectDisadvantage: not verification oriented
Axiomatic (Hoare):Pre-post: {P} A {Q}
Advantage: intended for verification; invariantsDisadvantage: not a calculus
Axiomatic (Weakest precondition):Operator: A wp Q
Advantage: Calculus version of Hoare logicDisadvantage: Boolean expressions only 89
A special case
If Q is boolean, then
i ; Q
is the weakest precondition of i for Q
90
Hoare-style properties
To prove{P } i {Q }
prove that
P ( i ; Q )
91
Properties of “;”
i ; (j ; e ) = ( i ; j ) ; e Associativity
i ; ( x y ) = ( i ; x ) ( i ; y ) Distributivity
-- For most operators
-- Only if e does not involve the old operator (see next)
CACA
CDCD
92
Reminder: function composition
Given
f : A Bg : B C
their compositionf g : A C
is the function a | g (f (a))
93
f
g
A B C
a
Composition is associative:
[f g] h = f [g h]
f g
“;” in non-OO programming
Instructionsi, j : State State
Expressionse : State Value
Then “;” is the usual composition “”, as in e.g.
i ; j (State State) (State State),i.e. (State State)
i ; e (State State) (State Value),i.e. (State Value)
i ; j ; e -- Using associativity (CA1)
94
“;” in object-oriented programming
It is again a form of composition, but applied to functions working on the “current object”
Instructionsi, j : Object State State
Expressionse : Object State Value
Then
i ; j = o | s | (i (o ) j (o)) (s )
i ; e = o | s | (i (o ) e (o)) (s )
95
The Current rule
For any instruction i :
i ; Current = Current CURCUR
96
The memory operator
For any instruction i and any expression e :
i ; old e = e
No associativity here; for example
((x := 0 ; x := 1)) ; old x = x
but
(x := 0) ; ((x := 1) ; old x) = (x := 0) ; x
= 0
OLDOLD
97
The assignment rule
(x e) ; x = e
(x e) ; y = y
:=:=
This rule applies to values of any type, including references, but will be extended for object expressions
General convention: x, y, z indicate different variables (values may be the same)
General convention: x, y, z indicate different variables (values may be the same)
A2A2
A1A1
98
An example proof in compositional logic
(item := item + 1) ; (item = old item + 1)
By distributivity of ; for =, this is: ((item := item + 1) ; item) = (item := item + 1) ; old item + 1
By the rule of old, this is: ((item := item + 1) ; item) = item + 1
By the assignment rule, this is: item + 1 = item + 1
To be proved:
CDCD
OLDOLD
A1A1
99
The call rule
The unqualified call rule:
Denotational: (call r (c)) (s) = r ( [s r : c])
Compositional: (call r (c)) ; e = r [r : c] ; eUCUC
100
The unqualified setter theorem
For an attribute a of type T, consider the routine
set_a (f: T) do whatever ; a := f end
Then
(call set_a (c)) ; a = c
Proof: this is a direct application of the preceding result
(call r (c)) ; e = r [r : c] ; e
A more general version of the theorem ( ) applies to any routine with the postcondition a = f
Proof: add at the end of the routine an instruction a := f ; this does not change its semantics. Then apply .
US1US1
UCUC
US2US2
101
The alias calculus
a » skip = a
a » (then i else j end) = (a » i) (a » j)
a » (i ; )) = (a » i) » )
a » (forget x) = a \- {x}
a » (create x) = a \- {x}
a » (x := y) = a [x: y]
a » cut x, y = a – x, y
a » p0 = a
a » pn+1 = (a » pn) » i
a » (loop i end) = (a » pn)
a » call r (a) = (a [ r : a]) » r
a » call x r (a) = x (x’ (a [x r : a]) » r) \– x r
102
n N
Plus:x Current = xCurrent x = x
x’ x = Current
x x’ = Current
Current’= Current
a [x: y] = given b = a\- {x} then
b ({x} x (b/y))
end
a purged of expressions starting
with x
The calculus of object structures: paths
Syntax: a path is one of:Empty, written <>a, where a is the name of an attributea p, where p is (recursively) a path
Semantics: x y z … denotes the object obtained from the current object by following the link corresponding to x, then the link for y, then the link for z etc.
(If from any object in this sequence the next link is not defined, that object is the value of the path.)
xy
z
Currentx y z
103
Compositional semantics for O-O programs
Reminder for variables and expressions of non-ref types:(x e) ; y = y
(x e) ; x = e
:=:=
A2A2
A1A1
They still hold, but we need to includethe effect on paths:(x e) ; x p = e
p:=
A3A3
-- If x is cycle-free for e before p (see next)
(x e) ; y p = y
p:=
A4A4
-- If x is cycle-free for e before p
Special case
104
The cycle-free condition
holds under the following condition: no prefix of p is of the form q x where e q may be aliased to Current
(“x is cycle-free for e before p”)
This condition holds in particular if the structure is acyclic
y
(x e) ; x p = e p:=
x
Counter-example:(x := y ) ; x z x
zCurrent
O2
O1
p
In final state: x z x is attached to O2But in initial state: e p, i.e. y z x , is attached to O1
e
A3A3
A3A3
105
Sequence closure
b
denotes the sequence of objectsCurrent, b, b b, b b b, …
stopping at the first from which the a link either is void or leads to an object already encountered
Generalization: if p is a path, p b denotes the
sequence
p, p b, p b b, p b b b, …
right
right right
right right right
106
List reversal: expressing the invariant
- previous right + next right ~ old right
previous next
1 2 3 4 5
right
107
Reversing a list
reverse local previous, next: LINKABLE [G] do from next := first ; previous := Void invariant
end
first
right
right
right
right
next
?
?- first right = old first right- first right = old first right
- previous right + next right
= old first right
- previous right + next right
= old first right until next = Void loop
temp := previousprevious := nextnext := next right
previous put_right (temp) end first := previous ensure
previous
- previous right + next right- previous right + next right
108
Acyclic attributes
In a class C, an attributea : C
is acyclic if no element of a may be aliased to Current
109
The closure theorem
x = <Current> + x x
Proof: from definition of No particular condition on x(e.g. x does not have to be acyclic)
More generally: p x = p + p x x
x x x x
Current
Sequence concatenation
Sequence concatenation
One-element sequence
One-element sequence
SC1SC1
SC2SC2
110
Assignment and sequence closure (1)
Theorem:
(x := e) ; x p a = e p a
(also applicable if a is x, and if the path p is empty)Proof: since the two sides are sequences, it suffices to prove that elements of the sequences are pairwise equal. The individual equalities to prove are
(x := e) ; x p a n = e p a
n
where a n is a a … a (n times), for a finite number of
values of n starting at 0. They follow from
which is applicable since by the definition of every a
n path is acyclic. (q in this equality is p a n.)
AS1AS1
(x e) ; x q = e
q:=
A3A3
111
Assignment and sequence closure (2)
Theorem:(x := e) ; x = <Current> + e x
Proof: apply successivelyThe closure theorem: x = <Current> + x x Distributivity The Current theorem :
(x := e) ; <Current> = <Current>The preceding theorem:
(x := e) ; x x = e x
AS2AS2
CURCUR
CDCD
SC1SC1
AS1AS1
112
The qualified setter theorem
Consider set_a (f: T) with the postcondition a = f
Unqualified setter theorem (reminder):
(call set_a (c)) ; a = c
QSQS
US2US2
Qualified setter theorem:
(call x set_a (c)) ; x a = c
113
Remote assignment and sequence closure
Reminder:(x := e) ; x = <Current> + e x AS2AS2
Qualified closure assignment theorem:
(call x set_a (c )) ; x a = <x > + c a QCQC
Proof:(call x set_a (c )) ; x a = <(call x set_a (c )) ; x >
+ (call x set_a (c )) ; x a
a
(call x set_a (c )) ; x = x(call x set_a (c )) ; x a a = c a
SC2SC2
AS1AS1
114
Reminders
p x = p + p x x
(x := e) ; x p a = e p a
SC2SC2
AS1AS1
115
The Proof
116
Reversing a list
reverse local previous, next: LINKABLE [G] do from next := first ; previous := Void invariant
end
first
right
right
right
right
next
?- first right = old first right- first right = old first right
until next = Void loop temp := previousprevious := nextnext := next right
previous put_right (temp) end first := previous ensure
previous
- previous right + next right- previous right + next right
117
The invariant
- previous right + next right- previous right + next right
temp := previous
previous := next
next := next right
previous put_right (temp)
- previous right + next right- previous right + next right118
Proof illustration
119
Handling previous right
temp := previous
previous := next
next := next right
previous put_right (temp)
previous rightprevious right
- previous right + next right- previous right + next right120
Handling previous right
temp := previous
previous := next
next := next right
previous put_right (temp)
<previous> + temp right<previous> + temp right
previous rightprevious right
- previous right + next right- previous right + next right121
Handling previous right
temp := previous
previous := next
next := next right
previous put_right (temp)
<previous> + temp right<previous> + temp right
<previous> + temp right<previous> + temp right
previous rightprevious right
- previous right + next right- previous right + next right122
Handling previous right
temp := previous
previous := next
next := next right
previous put_right (temp)
<previous> + temp right<previous> + temp right
<previous> + temp right<previous> + temp right
<next> + temp right<next> + temp right
previous rightprevious right
- previous right + next right- previous right + next right123
Handling previous right
temp := previous
previous := next
next := next right
previous put_right (temp)
<previous> + temp right<previous> + temp right
<previous> + temp right<previous> + temp right
<next> + temp right<next> + temp right
<next> + previous right<next> + previous right
previous rightprevious right
- previous right + next right- previous right + next right124
Handling next right
temp := previous
previous := next
next := next right
previous put_right (temp)
next rightnext right
- previous right + next right- previous right + next right125
Handling next right
temp := previous
previous := next
next := next right
previous put_right (temp)
next rightnext right
next rightnext right
- previous right + next right- previous right + next right126
Handling next right
temp := previous
previous := next
next := next right
previous put_right (temp)
next rightnext right
next right rightnext right right
next rightnext right
- previous right + next right- previous right + next right127
Handling next right
temp := previous
previous := next
next := next right
previous put_right (temp)
next rightnext right
next right rightnext right right
next rightnext right
next right rightnext right right
- previous right + next right- previous right + next right128
Handling next right
temp := previous
previous := next
next := next right
previous put_right (temp)
next rightnext right
next right rightnext right right
next rightnext right
next right rightnext right right
next right rightnext right right
- previous right + next right- previous right + next right129
Putting the two pieces together
temp := previous
previous := next
next := next right
previous put_right (temp)
next right rightnext right right<next> + previous right<next> + previous right +–
- previous right + next right- previous right + next right130
Putting the two pieces together
temp := previous
previous := next
next := next right
previous put_right (temp)
next right rightnext right right– previous right + <next >– previous right + <next > +=
next right rightnext right right<next> + previous right<next> + previous right +–
next rightnext right– previous right – previous right +=
- previous right + next right- previous right + next right131
Assessment
Limitations:Not implementedNeeds more examplesDoes not yet handle inheritanceNo proof of soundness
Pros:Minimum annotation effortHigh-level (uses contracts of routines)Adapted to modern programming styleHandles aliasing automaticallyReflects how O-O programmers think about
programs132
- 5 -
Conclusion
133
Verification As a Matter Of Course
134