<<

App eared as technical rep ort UIB Universitat Ulm Fakultat fur Informatik Dec

Mechanized of Simple Imp erative

Programming Constructs

H Pfeifer A Dold F W von Henke H Rue

Abt Kunstliche Intelligenz

Fakultat fur Informatik

Universitat Ulm

D Ulm

verifixkiinformatikuniulmde

Abstract

In this pap er a uniform formalization in PVS of various kinds of semantics of imp er

ative programming constructs is presented Based on a comprehensivede

velopment of xed p oint theory the of elementary constructs

of imp erative programming are dened as state transformers These state

transformers induce corresp onding predicate transformers providing a means to for

mally derivebothaweakest lib eral precondition semantics and an

in the style of Hoare Moreover algebraic laws as used in renement calculus pro ofs

are validated at the level of predicate transformers Simple reformulations of the state

transformer semantics yield b oth a style semantics and rules similar to

those used in Structural Op erational Semantics

This formalization provides the foundations on which formal sp ecication of program

ming languages and mechanical verication of compilation steps are carried out within

the Verix pro ject

This research has b een funded in part by the Deutsche Forschungsgemeinschaft DFG under pro ject

Verix

Contents

Intro duction

Related Work

Overview

A brief description of PVS

Mechanizing

Denotational Semantics for Statements

State Transformers

State Transformer Semantics

Predicate Transformers

Relating Various Styles of Semantics

Weakest Lib eral Precondition

Hoare Calculus

Algebraic Laws

Structural Op erational Semantics

Intro ducing Variable Declarations

Example A Simple

Conclusions

App endix

A Denotational Semantics

State transformers A

A Program State

A State Transformer Semantics

A Predicates

A Predicate Transformers

A Predicate Transformer Semantics i

B Various Styles of Semantics

B Weakest Precondition

B

B Algebraic Laws

B SOS

B Continuation

B Putting it Together

C A Simple Programming Language

C Simple Commands

C Simple Declarations

C The Language

D Pro of of Lemma while strans adm ii

Mechanized Semantics of Simple Imperative Programming Constructs

Intro duction

Formal verication of compiler implementations requires the semantics of the programming

languages involved b e mo deled adequately in a formal system Dep ending on the asp ect of a

programming language or its compilation one wants to describ e certain styles of semantics

are more suitable than others A mathematically precise denition of a language for

example would often b e accomplished using denotational semantics SS Ten Sto

On the other hand if one is interested in developing a prototyp e implementation one might

describ e the semantics of the language using an op erational style while an axiomatics

semantics Flo Hoa would b e most useful if verication of programs is of concern

In this pap er we present a generic mo delling in PVS of dierent kinds of semantics of the

basic imp erative programming constructs Starting from a denotational semantics based

on state transformers we show how to derive the characteristic rules of various semantic

styles including weakest precondition semantics Hoare logic continuationstyle seman tics

and structural op erational semantics The formalization is mo dular in the sense that there

are separate PVS sp ecications for each programming construct

In addition the comp onents of a programming language such as expressions statements

and variable declarations are identied with their semantics Thus only the abstract struc

ture of the languages comp onents is laid down and the formalization can hence b e applied

to every programming language that consists of one or more of the constructs covered in

this pap er

The mathematical theory underlying the work presented here is well understo o d This

pap er adds nothing new in this resp ect in fact most of the theorems can be found in

standard textb o oks such as Win Sch Bes However we think that the main

contribution of our work is a uniform treatment of dierentstyles of semantics in a formal

system This allows for doing formal reasoning ab out b oth programs and their compilation

within the same framework Moreover since manyinterchangeable forms of semantics are

available the reasoning can b e carried out selecting that semantic formalism suiting b est

All theorems presented here have b een proved within PVS Most of the theories are

reprinted in the App endix The complete sp ecications and pro ofs are available from

the authors up on request

Related Work

There havebeenseveral rep orts related to the mo delling of semantics of programming lan

guages in a theorem prover including Sok Mas Cam HM and there are stan

dard techniques for formalizing various styles of semantics For example our presentation

regarding predicate transformers and algebraic semantics is comparable to a formalization

in the HOL system of a guarded command language with weakest precondition semantics

by BackandvWright BvW

The work presented here is most closely related to that of Gordon Gor and Nipkow

Nip since in contrast to the pap ers mentioned ab ove they deal with several forms of

semantics Gordon uses the HOL system to mechanically derive the rules of Hoare logic of

Mechanized Semantics of Simple Imperative Programming Constructs

a simple whilelanguage from their denotational semantics Gor Furthermore he de

scrib es how to HOL tactics to generate verication conditions based on the derived

Hoare rules Nipkow Nip presents a formalization of the rst chapters of Winskels text

book on programming language semantics Win in the theorem prover Isab elleHOL

He denes op erational denotational and axiomatic semantics of a simple imp erative pro

gramming language and proves their equivalence Additionally pro ofs of soundness and

completeness of a verication condition generator are sketched

In contrast to Nipkow we do not dene dierent forms of semantics for the same language

but follow Gordon and showhowtoderivethecharacteristic rules of the various semantic

formalisms from a denotational semantics This saves us from having to prove explicitly

the equivalence of the dierent semantics

Overview

The remainder of the pap er is organized as follows after giving a brief overview of the

sp ecication and verication system PVS in Section the remaining sections describ e

the various PVS theories develop ed The overall structure of these theories is illustrated

in Figure Each no de in this hierarchy graph represents one PVS theory and the edges

represent imp orting relations Theories towards the b ottom are used imp orted bythose

ab ovethem

In order to b e able to dene the denotational semantics of lo ops and recursive pro cedures

we have develop ed a rather comprehensive formalization of the theory of xed p oints in

PVS This formalization is only briey summarized in Section a detailed description can

b e found in a companion pap er BDvH Consequently the b ottom entry in Figure

is to b e regarded as standing for a whole cluster of theories

the concept of state transformers that Climbing up the hierarchy Section describ es

are dened in theory srel Next the denotational semantics of imp erative programming

language constructs based on state transformers is presented in Section The de

nitions are split into several theories and are combined in theory statements Predicate

transformers as dened in the theories ptrans and mpt are intro duced in Section State

transformers and predicate transformers provide the basis for a uniform treatmentofvar

ious styles of semantics such as weakest precondition semantics Hoarestyle semantics

and algebraic laws see Section The corresp onding theories can b e found further up in

the theory hierarchy and are comprised by the theory semantics

The denitions in the theories mentioned so far abstract from the state on which programs

op erate A concrete implementation of such a state is given in Section Finally as an

example Section describ es how the formalizations can b e used to dene the semantics

of a simple while language

Mechanized Semantics of Simple Imperative Programming Constructs

simple_program

simple_commands simple_declarations

semantics vardecl

continuation_lems wp_hoare sos laws

hoare_logic wp assert_assume continuation

statements stmt_mpt

state control_structures assignment mpt

ptrans var_environment sequence skip expr

location srel bexpr

finsets relation

deterministic

(Fixed−Point Theory)

Figure Hierarchy of PVS theories formalizing various kinds of semantics of simple con

structs in imp erative programming languages

Mechanized Semantics of Simple Imperative Programming Constructs

A brief description of PVS

This section gives a brief overview of PVS More details can b e found in ORSvH

The PVS system combines an expressive sp ecication language with an interactiveproof

checker that has a reasonable amount of theorem proving capabilities It has b een used

for reasoning in domains as diverse as micropro cessor verication proto col verication

and algorithms and architectures concerning faulttolerance ORSvH

The PVS sp ecication language builds on classical typ ed higherorder logic with the usual

base typ es bool nat rational real among others and the typ e constructor

A B The typ e system of PVS is augmented with dependent types and abstract data

types A distinctive feature of the PVS sp ecication language are predicate subtypes the

subtyp e fxA Pxg consists of exactly those elements of typ e A satisfying predicate

P Predicate subtyp es are used for instance for explicitly constraining the domains and

ranges of op erations in a sp ecication and to dene partial functions

In general typ echecking with predicate subtyp es is undecidable the typ echecker gener

ates pro of obligations socalled type correctness conditions TCCs in cases where typ e

conicts cannot immediately b e resolved A large numb er of TCCs are discharged byspe

cialized pro of strategies and a PVS expression is not considered to b e fully typ echecked

unless all generated TCCs have b een proved If an expression that pro duces a TCC is used

many times the typ echecker rep eatedly generates the same TCC The use of judgements

can prevent this There are two kinds of judgements

JUDGEMENT HASTYPE even even even

JUDGEMENT continuous SUPTYPEOF monotonic

The rst form a constant judgement asserts a closure prop erty of on the subtyp e of

even natural numb ers The second one a subtyp e judgement asserts that a given typ e is

asubtyp e of another typ e The typ echecker generates a TCC for each judgementtocheck

the validity of the assertion but will then use the information provided further on Thus

many TCCs can b e suppressed

PVS sp ecications are packaged as theories that can b e parametric in typ es and constants

A builtin prelude and loadable libraries provide standard sp ecications and proved facts

for a large numb er of theories

Pro ofs in PVS are presented in a sequent calculus The atomic commands of the

PVS prover comp onent include induction quantier instantiation automatic conditional

rewriting simplication using arithmetic and equality decision pro cedures and typ e infor

mation and prop ositional simplication using binary decision diagrams The SKOSIMP

command for example rep eatedly intro duces constants of the form xi for universal

strength quantiers and ASSERT combines rewriting with decision pro cedures

Finally PVS has an LCFlike strategy language for combining inference steps into more

powerful pro of strategies The strategy GRIND for example combines rewriting with prop o

sitional simplication using BDDs and decision pro cedures The most comprehensive

strategies manage to generate pro ofs fully automatically

Mechanized Semantics of Simple Imperative Programming Constructs

Mechanizing Domain Theory

In order to b e able to dene the denotational semantics of lo ops and recursive pro cedures

we have develop ed a rather comprehensive formalization of the theory of xed points in

PVS In this section we only summarize the main concepts needed in this pap er A much

more detailed description can b e found in BDvH

The formalization consists of a collection of PVS theories that can be used as a library

The most imp ortant theorems are the wellknown schemes of xedp oint induction on



monotonic and continuous functions

fpinductionmono THEOREM

FORALL Padmissible fmonotonic

Pbottom AND FORALL xD Px IMPLIES Pfx

IMPLIES Pmuf

fpinductioncont THEOREM

FORALL Padmissible gcontinuous

Pbottom AND

FORALL inat Piterategibottom

IMPLIES Piterategi bottom

IMPLIES Pmug

Throughout this section weusef and g to denote a monotonic and a continuous function

resp ectively over some D The least element of D with resp ect to

the ordering relation is called bottomWe use the term precpo for cp os without such

a least element For convenience we rep eat the denitions concerning cp os let b be of

typ e D and a partial order on D

bottomb bool

FORALL xD b x

precpo bool FORALL C ChainD lubexistsC

pCPO TYPE precpo

cpob bool

precpo AND bottomb

CPO TYPE cpo

Sometimes we use a sp ecial kind of precp os where the ordering relation is simply the

identitySuch precp os are referred to as discrete precpos Note that every function from

a discrete precp o into a precp o is continuous

The denition of the least xed point op erator mu makes use of the predicate subtyp e

concept of PVS by restricting the op erator to only those functions for which the least

xed p oint exists Thus when typ echecking expressions such as muf PVS generates a

corresp onding typ e correctness condition

PVS notation For predicates P over some typ e A the expression P is an abbreviation for the predicate

subtyp e fxA Pxg

Mechanized Semantics of Simple Imperative Programming Constructs

f VAR monotonic this is a comment

g VAR continuous

leastfixpointf setD

fxD fixpointxf AND FORALL yD fixpointyf IMPLIES x yg

LFPf TYPE leastfixpointf

muexistsf bool nonemptyleastfixpointf

mufmuexists LFPf

chooseleastfixpointf

muisfixpoint LEMMA

FORALL fmuexists fmuf muf

Monotonic functions mapping into a cp o always have least xp oints thisisknown as the

Knaster Tarski Theorem In the case of continuous functions the least xed p oint can

th

b e calculated as the least upp er b ound of all i iterations of the function applied to the

b ottom element of the cp o

KnasterTarski THEOREM

muexistsf

fixpointtheorem THEOREM

mug lubfx EXISTS inat x iterategibottomg

Denotational Semantics for Statements

State Transformers

The notion of state transformers provides the basis for the denotational semantics of

statements State transformers are dened in theory srel In order to b e able to deal with

nontermination we use relations rather than functions the latter have to b e total in PVS

A relation R A B is mo deled as a function mapping elements of typ e A to a set of

elements of typ e B Partial functions can also b e describ ed by restricting the range to sets

with at most one element

Relation TYPE A setB

deterministicSsetB bool emptyS OR singletonS

PartialFunction TYPE A deterministic

Let R be a relation S a set of elements of typ e AandT a set over typ e BWe dene the



image of S under R and the inverse image of T under R by



In PVS sets are identied with their characteristic predicates and thus the expressions predsigma and

setsigma are interchangeable Hence the notation sS also means that s is an element of set S

Mechanized Semantics of Simple Imperative Programming Constructs

imageRS setB fyB EXISTS sS memberyRsg

inverseimageRT setA fxA subsetRxTg

In order to keep the denition of state transformers as general as p ossible the state on

which programs op erate is left uninterpreted here Instead uninterpreted typ es sigma

and tauprovided as theory parameters are used for representing the domain and range

typ es of state transformers resp ectively The parameters are usually instantiated with a

concrete implementation of the program state such as the one describ ed in Section

In the most general case nondeterministic state transformers are relations b etween sigma

and tau We use the typ e srel for such relations while deterministic state transformers



havetyp e stransobviously a subtyp e of srel

srel TYPE Relationsigmatau

strans TYPE PartialFunctionsigmatau

A partial ordering on srel is dened by p ointwise lifting set inclusion As this mecha



nism is often used a small theory pointwise is dened It is parameterized with twotyp es

D and R and a partial ordering leq on R The theory denes a new partial ordering on

the function space D R bya pointwise extension of leq

pointwiseD R TYPE

leq partialorderR THEORY

BEGIN

fg VAR D R

fg bool FORALL xD leqfx gx

JUDGEMENT HASTYPE partialorderD R

END pointwise

The partial ordering on srel is obtained by imp orting the theory pointwise The parame

ters are instantiated with the domain and range of srel The partial ordering on the range

of srel is set inclusion which is itself dened by instantiating pointwise appropriately

IMPORTING pointwisetaubool

IMPORTING pointwisesigmasettaupoin twise tau boo l

The state transformer mapping every state to the empty set is the least element with

resp ect to and is called abort Since every typ e sigma forms a discrete cp o and sets

together with set inclusion are a cp o functions of typ e srel are continuous Moreover

srel and form a cp o with b ottom element abort



OF srel It is even obvious to the typ echecker a corresp onding judgement JUDGEMENT strans SUBTYPE

is rejected as it do es not provide any additional information



The theory p ointwise is contained in the library for xedp oint theory

Mechanized Semantics of Simple Imperative Programming Constructs

abort srel

LAMBDA ssigma emptyset

JUDGEMENT HASTYPE pCPOsrel

JUDGEMENT abort HASTYPE bottom

State Transformer Semantics

This section describ es the formalization of a denotational semantics based on state trans

formers for basic statements of imp erative programming languages The denitions are

split into several theories one for each construct The theories are parameterized with

resp ect to some typ e sigma which is intended to mo del the state on which programs

op erate

Since it do es not add anything interesting we do not distinguish dierent kinds of ex

pressions Instead expressions are identied with their semantics and are mo deled as a

valuation function

exprsigma Value TYPE THEORY

BEGIN

Expr TYPE sigma Value modeled as semantic function

END expr

In addition Bo olean expressions BExpr are dened as predicates on sigma

BExpr TYPE predsigma

Primitive Statement skip

The simplest statement is skip which do es not change the current state and hence is

mo deled as the function mapping a state s to the singleton set fs g

skip sigma TYPE THEORY

BEGIN

IMPORTING srelsigmasigma

skip srel

LAMBDA ssigma singletons

JUDGEMENT skip HASTYPE strans

END skip

Sequential Comp osition

Sequential comp osition of two state transformers f and g denoted by f g is dened

by relational comp osition

Mechanized Semantics of Simple Imperative Programming Constructs

f g srel

LAMBDA s imagegfs

sequencestransclosed LEMMA

FORALL fgstrans deterministicf gs

JUDGEMENT HASTYPE strans strans strans

Sequential comp osition is monotonic in b oth arguments

sequencemonotonicleft LEMMA

f g IMPLIES f h g h

sequencemonotonicright LEMMA

f g IMPLIES h f h g

Assignment

The theory dening the semantics of assignment statements has some additional param

eters the typeofvariables and values a predicate for deciding whether or not a variable

is declared in the current state and a function update for assigning a new value to a

previously declared variable

assignment Vars Value sigma TYPE

declared sigma predVars

update ssigma declareds Value sigma

THEORY

The semantics of assigning the value of an expression e to some variable x denoted by

x e is a new state with x b eing b ound to eifx is declared Otherwise the assignment

statement is undened

IMPORTING exprsigma Value

s VAR sigma x VAR Vars e VAR Expr

xe srel prefix notation of infix operator

LAMBDA s IF declaredsx

THEN singletonupdatesxes

ELSE emptyset

ENDIF

JUDGEMENT HASTYPE VarsExpr strans

Conditional Branching and Lo ops

The semantic function for the conditional IFTHENELSE is obtained by lifting the b o olean

IFexpression

IFbBExpr f gsrel srel

LAMBDA s IF bs THEN fs ELSE gs ENDIF

Mechanized Semantics of Simple Imperative Programming Constructs

Again wehave monotonicity in b oth recursive arguments and IF is deterministic provided

the branches are

IFmonotonicleft LEMMA

f g IMPLIES

IF b THEN f ELSE h ENDIF IF b THEN g ELSE h ENDIF

IFmonotonicright LEMMA

f g IMPLIES

IF b THEN h ELSE f ENDIF IF b THEN h ELSE g ENDIF

IFstransclosed LEMMA

FORALL fgstrans deterministicIF b THEN f ELSE g ENDIFs



The semantics of the while lo op is dened as usual as the least xed p oint of a functional

describing one iteration of the whilelo op As the domain of mu is dened by a predicate

subtyp e see typ echecking the denition of while yields a typ e correctness condition

One has to prove that the ab ove functional do es have a least xp oint which is done using

monotonicityof IF and and the KnasterTarski theorem

whilefunctionalmonotonic LEMMA

monotonicLAMBDA xsrel IF b THEN f x ELSE skip ENDIF

whileb f srel

mu xsrel IF b THEN f x ELSE skip ENDIF

As an example we step through the pro of of the lemma while strans closed It states

that the while lo op is deterministic provided the body is It is used for proving the

judgement following right after

whilestransadm LEMMA admissibleLAMBDA y srel FORALL s sigma

deterministicys

whilestransclosed LEMMA

FORALL fstrans FORALL ssigma deterministicwhilebfs

JUDGEMENT while HASTYPE BExpr strans strans

For presentation purp oses we slightly edit the PVS output e g by deleting unnecessary

formulae

whilestransclosed

FORALL b BExpr f strans

FORALL s sigma deterministicwhileb fs

The prop osition is proved using xedp oint induction In order to prepare the formula for

the application of the induction theorem some of the quantiers are eliminated followed

by unfolding the denition of while



The notation mu xT fx is an abbreviation for muLAMBDA xT fx

Mechanized Semantics of Simple Imperative Programming Constructs

Rule THEN SKOLEM EXPAND while

whilestransclosed

FORALL s sigma

deterministicmu x srel

IF b THEN f x ELSE skip ENDIFs

Now the theorem of xedp oint induction for monotonic functions see is applied with

the predicate P instantiated appropriately This pro of step yields three subgoals The rst

one is the induction rule itself whereas the other ones see below are typ e correctness

conditions These are generated since the xedp oint induction theorem is constrained to

admissible predicates P and monotonic functions f

Rule USE fpinductionmono SUBST

P LAMBDA ysrel FORALL ssigma deterministicys

whilestransclosed

FORALL s sigma deterministicaborts

AND

FORALL x srel

FORALL s sigma deterministicxs IMPLIES

FORALL s sigma

deterministicIF b THEN f x ELSE skip ENDIFs

IMPLIES

FORALL s sigma

deterministicmuLAMBDA x srel

IF b THEN f x ELSE skip ENDIFs

FORALL s sigma

deterministicmu x srel

IF b THEN f x ELSE skip ENDIFs

Prop ositional simplication of the rst subgoal yields another two subgoals corresp onding

to the induction base and the induction step

Rule PROP

whilestransclosed

FORALL s sigma deterministicaborts

The induction base is simply proved by unfolding denitions and prop ositional reasoning

Rule GRIND

This completes the proof of whilestransclosed

whilestransclosed

FORALL x srel

FORALL s sigma deterministicxs

Mechanized Semantics of Simple Imperative Programming Constructs

IMPLIES FORALL s sigma

deterministicIF b THEN f x ELSE skip ENDIFs

The pro of of the induction step is accomplished using the corresp onding prop erties of the

dening expressions of while that is IF and the sequencing constructor Conditionals

strans closed are deterministic given the branches are However using the lemma IF

yields only one subgoal for the THEN branch This is due to the judgement in the

typ echecker already knows that skip is of typ e strans and therefore suppresses this

subgoal

Rule THEN SKOSIMP REWRITE IFstransclosed

whilestransclosed

FORALL s sigma deterministicxs

FORALL s sigma deterministicsigmaf xs

Next lemma sequence strans closed is applied Again only one subgoal is generated

since by denition f is of typ e strans

Rule SKOSIMP REWRITE sequencestransclosed

whilestransclosed

FORALL s sigma deterministicxs

FORALL s sigma deterministicxs

Finally the induction hyp othesis is used to complete this part of the pro of

Rule SKOSIMP INST

This completes the proof of whilestransclosed

This completes the proof of whilestransclosed

whilestransclosed TCC

monotonicLAMBDA x srel IF b THEN f x ELSE skip ENDIF

We have still to prove that the application of the xedp oint induction theorem is valid

First monotonicity of the dening functional of while has to be shown As this is also

whichis required in the denition of while a sep erate lemma has b een established

itself proved using monotonicityof IF and and the KnasterTarski theorem

Rule REWRITE whilefunctionalmonotonic

This completes the proof of whilestransclosed

whilestransclosed TCC

admissibleLAMBDA y srel

FORALL s sigma deterministicys

Mechanized Semantics of Simple Imperative Programming Constructs

The pro of that the predicate used in the xedp oint induction is admissible is rather

technical At this p oint we simply use an appropriate lemma and refer to App endix D for

a complete pro of script

Rule USE whilestransadm

This completes the proof of whilestransclosed

QED

Finallytwo useful lemmata are provided The rst one while def describ es the unfolding

of a while lo op the second one states that while is monotonic in its recursive argument

whiledef LEMMA

whilebf IF b THEN f whilebf ELSE skip ENDIF

whilemontonic LEMMA

f g IMPLIES whilebf whilebg

The pro ofs are by rewriting theorems provided by the xedp oint theory such as the

KnasterTarski theorem or Parks Lemma

Predicate Transformers

This section briey describ es the formalization of predicate transformers In PVS predi

cates over some typ e sigma are as usual b o oleanvalued functions on sigma Some simple

predicates are obtained by lifting the standard b o olean connectives see theory predicates

TRUE predsigma LAMBDA s TRUE

FALSE predsigma LAMBDA s FALSE

NOTp predsigma LAMBDA s NOTps

pq predsigma LAMBDA s ps AND qs

pq predsigma LAMBDA s ps OR qs

pq predsigma LAMBDA s ps IMPLIES qs

pq predsigma LAMBDA s ps IFF qs

Implication on b o olean values is extended pointwise to obtain a partial ordering on

predicates Since every typ e sigma is a discrete cp o and the typ e of b o olean expressions

bool together with implication is a cp o wehavepredsigma b eing a cp o As pred

icates and sets are interchangeable can also b e interpreted as set inclusion

Ordering on predicates

the next IMPORT defines a partial ordering on predicates as

p q FORALL s ps IMPLIES qs

IMPORTING pointwisesigmabool

JUDGEMENT HASTYPE pCPOpredsigma

Mechanized Semantics of Simple Imperative Programming Constructs

In theory ptrans predicate transformers are dened as functions with domain predtau

and range predsigma for some typ es sigma and tau Again we use a lifting mechanism

to dene basic predicate transformers and a partial ordering

ptrans TYPE predtau predsigma

abort ptrans LAMBDA q FALSE

magic ptrans LAMBDA q TRUE

NOTF ptrans LAMBDA q NOTFq

FG ptrans LAMBDA q Fq Gq

FG ptrans LAMBDA q Fq Gq

FG ptrans LAMBDA q Fq Gq

Ordering

next IMPORT defines partial ordering on predicates transformers

as F G FORALL q Fq Gq

IMPORTING pointwisesettausetsigma poin twise sig mab ool

JUDGEMENT HASTYPE pCPOptrans

JUDGEMENT abort HASTYPE bottom

We generalize conjunction and disjunction of predicate transformers and dene op erators

for greatest lower b ounds and least upp er b ounds of sets of predicate transformers that

is meets and joins

M VAR setptrans

M ptrans LAMBDA q LAMBDA y FORALL F MF IMPLIES Fqy

M ptrans LAMBDA q LAMBDA y EXISTS F MF AND Fqy

The typ e MPT constrains predicate transformers to monotonic predicate transformers

MPT TYPE fFptrans monotonicFg

JUDGEMENT abort HASTYPE MPT

JUDGEMENT magic HASTYPE MPT

JUDGEMENT HASTYPE MPTMPT MPT

JUDGEMENT HASTYPE MPTMPT MPT

Next we relate state transformers and monotonic predicate transformers by dening an

op erator mapping every state transformer to a corresp onding predicate transformer cf

theory mpt Both state and predicate transformations can be viewed as b eing applied in

one of two directions forward transformations map initial states and preconditions to

nal states and p ostconditions resp ectively while backward transformations do it the

other way round Since our goal is to dene a weakest pre condition semantics we adopt

the view of applying predicate transformers backwards while thinking of state transformer

as op erating forwards

The op erator PT takes a state transformer f of typ e sigma settau and yields a

predicate transformer of typ e predtau predsigmaGiven a p ostcondition T

denotes the set of all states s of typ e sigma such that all states the expression PTfT

in fs satisfy T

Mechanized Semantics of Simple Imperative Programming Constructs

PTfsrel ptrans

LAMBDA Tpredtau inverseimagefT

The op erator PT is shown to b e universally conjunctive and to map state transformers to

monotonic predicate transformers Moreover lemma lifting describ es the relationship

between state transformers and predicate transformers

JUDGEMENT PT HASTYPE srel MPT

PTuniversallyconjunctive LEMMA

FORALL Msetpredtau

PTfM

fppredsigma EXISTS mM p PTfmg

lifting LEMMA

f g IFF PTg PTf

Relating Various Styles of Semantics

After having formalized the foundations for denotational semantics of imp erative pro

gramming language constructs we can nowdevelop other styles of semantics based on the

state transformer and predicate transformer styles In this section a weakest lib eral pre

condition semantics and Hoarestyle semantics are develop ed and shown to b e equivalent

Moreover we describ e how algebraic laws as utilized e g in renement calculus pro ofs

are validated Last we briey sketch the relationship b etween state transformer semantics

and b oth structural op erational semantics and continuation semantics

Weakest Lib eral Precondition

The op erator PT dened in section see obviously maps a state transformer f to

a predicate transformer F that applied to some predicate q yields the weakest liberal

precondition of f with resp ect to q

wpfq predState PTfq

In order to demonstrate the correctness of this denition some basic facts ab out wp are

proved First wpfq is indeed the weakest precondition

wpchar LEMMA

wpfq fp p PTfqg

The wellknown rules of weakest preconditions of basic imp erative programming language



constructs can easily b e proved from the denition of wp



Function subst is dened in theory state see App endix A

Mechanized Semantics of Simple Imperative Programming Constructs

wpskip LEMMA

wpskip q q

wpassign LEMMA

wpx e q substq x e

wpif LEMMA

wpIF b THEN f ELSE g ENDIF q

IF b THEN wpf q ELSE wpg q ENDIF

wpseq LEMMA

wpf g q wpfwpgq

wpwhile LEMMA

wpwhileb h q

IF b THEN wph whileb hq ELSE q ENDIF

Hoare Calculus

This subsection intro duces the denition of Hoare triples and shows how the rules and

axioms of Hoare Logic are derived from the denotational semantics denition We use the

notation pfq to denote the Hoaretriple fp gf fq g Its denition is just a translation

of the informal description into PVS syntax fpgffqg holds if whenever f is executed in

a state satisfying p and if the execution terminates then f yields a state where q holds

That is a program segment f must map the set p into q

p f q bool imagefp q

The wellknown rules for statements are proved easily In fact PVS can do most of the

pro ofs with a single strategy called GRIND that rep eatedly rewrites denitions lifts

IFexpressions and simplies with decision pro cedures

skiprule LEMMA

p skip p

assignrule LEMMA

substp x e x e p

seqrule LEMMA

p f q AND q g r

IMPLIES

p f g r

ifrule LEMMA

p b f q AND p NOTb g q

IMPLIES

p IF b THEN f ELSE g ENDIF q

whilerule LEMMA

p b h p

IMPLIES

p whileb h p NOTb

Mechanized Semantics of Simple Imperative Programming Constructs

Moreover useful rules concerning strengthening resp ectively weakening are proved

preconditionstrengthening LEMMA

p p AND p f q

IMPLIES

p f q

postconditionweakening LEMMA

p f q AND q q

IMPLIES

p f q

ruleofconsequence COROLLARY combination of the above

p p AND p f q AND q q

IMPLIES

p f q

Equivalence of Hoare logic and weakest precondition semantics can also be proved quite

easily using GRIND

hoarelogicequivwp THEOREM

p f q p wpf q

Algebraic Laws

Back Bac Bac intro duced the renement calculus as a formalization of the stepwise

renement approach to systematic program construction Dij Wir A program state

ment S is said to rene S denoted S S if and only if S satises every assertion that

S do es Program renements S S are often proved using several highlevel renement

rules that express certain laws of the programming language cf HHJ These laws

are justied using monotonic predicate transformer semantics Bac

The formalizations presented so far are sucientto prove some typical laws In fact the

denition of program renementasstated ab ove has already b een intro duced cf lemma

lifting in sp ecication and the denition of PT in

refinementdef LEMMA

f g IFF FORALL qpredsigma wpg q wpf q

Some of the laws following next can be proved at the level of state transformers while

others have to b e lifted to the domain of predicate transformers However PVS provides a

useful mechanism of overloading together with implicitly applied typ e conversions such

that this dierence can b e hidden in the sp ecications In order to exploit this feature we

dene additional predicate transformers enco ding sequential and conditional comp osition

mpt see theory stmt

FG VAR ptrans

FG ptrans F o G o is function composition

IFbFG ptrans LAMBDA q IF b THEN Fq ELSE Gq ENDIF

Mechanized Semantics of Simple Imperative Programming Constructs

Using the op erator PT as implicit typ e conversion rule it is p ossible to mix state trans

formers and predicate transformers within the same expression For example for a state

transformer f and a predicate transformer p we can write f p instead of PTf p

CONVERSION PT

Assertion and assumption of some Bo olean expression b are dened using the conditional

predicate transformer

assertb ptrans IF b THEN skip ELSE abort ENDIF

assumeb ptrans IF b THEN skip ELSE magic ENDIF

Some typical laws as used for example in HJS MO are as follows

Seqassoc LEMMA f g h f g h

Sequnitleft LEMMA skip f f

Sequnitright LEMMA f skip f

Seqleftzerobottom LEMMA abort f abort

Seqleftzerotop LEMMA magic f magic

iftrue LEMMA IF TRUE THEN f ELSE g ENDIF f

iffalse LEMMA IF FALSE THEN f ELSE g ENDIF g

ifsame LEMMA IF b THEN f ELSE f ENDIF f

assigncondrightw LEMMA

x e IF b THEN f ELSE g ENDIF

IF substb x e THEN x e f ELSE x e g ENDIF

assertionassumption LEMMA assertb assumeb assertb

assumptionassertion LEMMA assumeb assertb assumeb

assertskip LEMMA assertb skip

assumeskip LEMMA skip assumeb

combineassumption LEMMA assumep assumeq assumep q

combineassertion LEMMA assertp assertq assertp q

assumptionconsequence LEMMA p q IMPLIES assumeq assumep

assertionconsequence LEMMA p q IMPLIES assertp assertq

voidassumption LEMMA assumeTRUE skip

voidassertion LEMMA assertTRUE skip

assumptionassign LEMMA

e x e x e assumeb assumesubstb x

assertionassign LEMMA

x e assertb assertsubstb x e x e

conditionscondtop LEMMA assumeb F IF b THEN F ELSE magic ENDIF

conditionscondbot LEMMA assertb F IF b THEN F ELSE abort ENDIF

These kind of laws have heavily b een used in a formal verication of compilation theorems

of Sampaios normal form approach Dol

Mechanized Semantics of Simple Imperative Programming Constructs

Structural Op erational Semantics

If one slightychanges the presentation of the denotational semantics based on state trans

formers given in Section one obtains a semantics description resembling structural

Plo Kah

Rename state transformers commands represented bytyp e CmdandletaConfiguration

be a pair consisting of a command and the actual program state Accessor functions for

the comp onents of a conguration with resp ective names are dened

Cmd TYPE srel

Configuration TYPE Cmd State

cmdconf Cmd projconf

stateconf State projconf

The state transition relation is now dened as a binary relation between actual

congurations conf and successor states s A state s is an admissible successor of conf

written as conf siftheevaluation of the actual command cmdconf in the current

state stateconf may end in state s

confs bool memberscmdconfstateco nf

For presentation purp oses we redene prop ositional implication

predboolbool IMPLIES

pbool bool p

This notation allows a reformulation of the denitions in Section as SOSstyle rules

For example the rules for skip and sequential comp osition now read

skiprule LEMMA

skips s

seqrule LEMMA

fs t AND gt u

f g s u

In order to provide similar rules for assignment conditional and whilelo op further de

nitions havetobeintro duced In particular overloading of is used to denote expression

evaluation

Mechanized Semantics of Simple Imperative Programming Constructs

BConfiguration TYPE BExpr State

EConfiguration TYPE Expr State

bconf VAR BConfiguration

econf VAR EConfiguration

bv VAR bool

v VAR value

bexprbconf BExpr projbconf

statebconf State projbconf

expreconf Expr projeconf

stateeconf State projeconf

bconfbv bool bv bexprbconfstatebconf

econfv bool v expreconfstateeconf

The following lemmas are again only reformulations of the corresp onding denotational

semantics denitions Most of them are simply proved by the strategy GRIND

assignrule LEMMA

declaredsx IMPLIES

es v

x e s updatesxv

iftruerule LEMMA

bs TRUE AND fs t

IF b THEN f ELSE g ENDIF s t

iffalserule LEMMA

bs FALSE AND gs t

IF b THEN f ELSE g ENDIF s t

The pro ofs of the rules concerning while use the corresp onding ifrules after applying

lemma while defsee

whilefalserule LEMMA

bs FALSE

whilebf s s

whiletruerule LEMMA

bs TRUE AND fs t AND whilebf t u

whilebf s u

Mechanized Semantics of Simple Imperative Programming Constructs

Continuations

The style of denotational semantics presented in Section is often called direct semantics

and emphasizes the comp ositional structure of a language If control is of concern for

example in imp erative languages with unrestricted branching goto a dierentstyle of

semantics namely continuation semantics is more appropriate

The basic elements of continuation semantics are dened at the level of state transformers

acontinuation simply is astate transformer

continuation TYPE srel

The op erator C describ es the continuationstyle semantics of some state transformer fIt

is obtained by simply comp osing f and a given continuation c

Cfc continuation LAMBDA s imagec fs

JUDGEMENT C HASTYPE strans strans strans

In the case where the continuation is simply the identity continuationstyle semantics

and direct semantics coincide and a transfer lemma is proved providing a way carry over

theorems established for one style to the other

contsingleton LEMMA

Cfsingleton f

transfer LEMMA

FORALL P predsrel

PCfsingleton Pf

For completeness the continuation semantics for simple statements are stated below

skipcontinuation LEMMA

Cskipc c

assigncontinuation LEMMA

Cx ecs imagec x es

seqcontinuation LEMMA

Cf g Cf o Cg

ifcontinuation LEMMA

CIF b THEN f ELSE g ENDIFc IF b THEN Cfc ELSE Cgc ENDIF

Intro ducing Variable Declarations

So far wehave only considered statements op erating on some abstract state In this section

a concrete implementation of such a program state is describ ed followed by the denition

of the denotational semantics of variable declarations

Mechanized Semantics of Simple Imperative Programming Constructs

The state on which programs op erate consists of two parts a variable environment rho

and a store sigmaThe former is a mapping variable names to abstract

lo cations the latter maps lo cations to the values assigned to variables Since a store should

only assign values to those lo cations actually in use the state is mo deled as a dep endent

record typ e

State TYPE rho VarEnv sigma Storerho

Variable environments are mo deled as injective partial functions from the typeofvariables

Vars to lo cations

preenv VAR PartialFunctionVarsLocation

finiteinjectiveenvironmentp ree nv bool

isfiniteimagepreenvful lset Vars s etLo cati on AND

FORALL xyVars llLocation

x y AND preenvxl AND preenvyl IMPLIES l l

VarEnv TYPE finiteinjectiveenvironmen t

The Store maps the lo cations in use to values

usedlocsrho finitesetLocation imagerhofullsetVars

UsedLocrho TYPE usedlocsrho

Storerho TYPE PartialFunctionUsedLocrhoV alue

Lo cations are mo delled as natural numb ers and the function nextloc takes a nite set of

lo cations and yields a lo cation not already contained in the set

Location TYPE nat

locs VAR finitesetLocation

nextloclocs Location

IF emptylocs THEN ELSE maxlocs ENDIF

nextlocnew LEMMA

NOT membernextloclocslocs

The empty state used as the initial state in the semantics denitions of a programming

language is given byanemptyenvironment and an empty store

emptyenv VarEnv

LAMBDA vVars emptyset

emptystore Storeemptyenv

LAMBDA lUsedLocemptyenv emptyset

emptystate rho VarEnv sigma Storerho

rho emptyenv sigma emptystore

Mechanized Semantics of Simple Imperative Programming Constructs

Based on these denitions the sets of declared and initialized variables resp ectivelycan

be characterized Avariable x is declared in some state s if there is an entry for x in the

currentenvironment rhos

declaredsx bool singletonrhosx

DeclaredVars TYPE declareds

newvarsx bool NOT declaredsx

NewVars TYPE newvars

Analogously declared variables for which there is a value in the store are of typ e

InitializedVars

initializedsxDeclaredVar s bool

singletonsigmaschooser hos x

InitializedVars TYPE initializeds

Next functions for reading and writing values of variables and for the intro duction of new

variables are dened Note that update and the lo okup function are only dened on

declared and initialized variables resp ectively

updates DeclaredVarsValue State

LAMBDA xDeclaredVars vValue

rho rhos

sigma sigmas WITH chooserhosx v

sState InitializedVars Value

LAMBDA psStateInitializedVars

LET sx p IN

sigmaschooserhosx

introsxNewVars State

LET newloc nextlocusedlocsrhos IN

rho rhos WITH x newloc

sigma sigmas WITH newloc emptyset

The semantics of the declaration of a variable cf theory vardeclisnow dened using the

intro function describ ed ab ove If the variable x is a new variable declarexs yields

a new state with the environment b eing extended accordingly

declarex srel

LAMBDA s IF newvarsx

THEN singletonintrosx

ELSE emptyset

ENDIF

Mechanized Semantics of Simple Imperative Programming Constructs

Example A Simple Programming Language

In this section it is describ ed how the denitions presented so far can b e applied in order

to dene the semantics of a simple programming language Weleavevariables values and

the various kinds of expressions uninterpreted They are mo deled as theory parameters

as are the semantic functions for expression evaluation

simpleprogram Vars Value Expr BExpr TYPE

IMPORTING stateVarsValue

eval Expr State Value

evalB BExpr State bool THEORY

Variable declarations are simply lists of variables and the abstract syntax of commands

is dened by an inductive datatyp e Programs are then pairs consisting of a declaration

and a command

VarDecl TYPE listVars

SimpleCommand DATATYPE

BEGIN

skip skip

seqfirstsecondSimpleComman d seq

assignvaridVars expExpr assign

ififcond BExpr thn els SimpleCommand if

whilewhilecond BExpr body SimpleCommand while

END SimpleCommand

SimpleProgram TYPE decl VarDecl body SimpleCommand

By imp orting the denitions presented in the previous sections the semantics of the com

mands are dened inductively using the corresp onding semantic functions

IMPORTING semanticsVarsValue

c VAR SimpleCommand

Expr State Value eval

BExpr State bool evalB

c RECURSIVE srel prefix variant of c

CASES c OF

skip skip

seqfg f g

assignxe x e

ifbfg IF b THEN f ELSE g ENDIF

whilebf while b f

ENDCASES

MEASURE c BY

The semantic function for declarations creates a new entry for each of the variables in

sequence

Mechanized Semantics of Simple Imperative Programming Constructs

dVarDecl RECURSIVE srel

IF nulld THEN skip ELSE declarecard cdrd ENDIF

MEASURE lengthd

The semantics of a program is then dened straightforward evaluating the declarations

in the empty state leads to an environment in which the commands are evaluated

p VAR SimpleProgram

p setState

bodyp declp emptystate

Conclusions

We have presented a uniform formalization in PVS of various kinds of semantics of the

basic constructs in imp erative programming languages Based on a comprehensivedevel

opment of xed p oint theory the denotational semantics of the constructs were dened as

state transformers These state transformers induce corresp onding predicate transform

ers providing a means to formally derivebothweakest lib eral precondition semantics and

axiomatic semantics in the style of Hoare Moreover algebraic laws as used in renement

calculus pro ofs have b een validated at the level of predicate transformers A simple re

formulation of the state transformers semantics yields a continuationstyle semantics and

rules similar to those used in structural op erational semantics

Since the various semantics are derived rather than dened manyinterchangeable forms of

semantics are available Thus formal reasoning ab out b oth programs and their compilation

can b e carried out within the same framework

The theories comprise semantic denitions for the basic constructs of imp erative program

ming languages This will b e further extended by additional denitions for other constructs

suchasmutually recursive pro cedures in order to b e applicable to a wider range of pro

gramming languages Besides the fact that this requires some additional technical work

concerning the mo delling of underlying mathematical structures such as simultaneous

xp oints of a set of functions this should not imp ose ma jor diculties

The formalization presented in this pap er provides the foundations on which formal sp ec

ication of programming language semantics and mechanized verication of compilation

steps are carried out within the Verix pro ject The theories have b een used in the sp ec

ication and verication of a generic compilation of imp erative programming constructs

DvHPR

Future investigations will b e concerned with howmoving b etween dierentstyles of seman

tics can b e exploited in verifying compilation steps For example very often the semantics

of the source and target language of a compiler are given in a denotational and an op er

ational style resp ectively One way of proving the correctness of the compiler in such a

case is to derive rst a denotational semantics of the target language from its op erational

semantics NN We conjecture that a systematic supp ort of these kinds of derivations

would help to reduce the pro of eort of such correctness pro ofs

Mechanized Semantics of Simple Imperative Programming Constructs

References

Bac R J R Back Correctness Preserving Program Renements Proof Theory

and Applications volume of Mathematical Centre Tracts Mathematical

Centre Amsterdam

Bac R J R Back On Correct Program Renements Journal of Computer and

System Sciences August

Bac R J R Back Renement Calculus Part I Sequential Nondeterministic Pro

grams In J W de Bakker and WPdeRoever editors Stepwise Renement

of Distributed Systems REXWorkshop volume of LNCS Springer Ver

lag

BDvH F Bartels A Dold FW von Henke H Pfeifer and H Rue Formalizing

FixedP oint Theory in PVS Ulmer InformatikBerichte Universitat

Ulm Decemb er

Bes E Best Semantik Theorie sequentiel ler und paral leler Programmierung

Lehrbuch Informatik ViewegVerlag

BvW R J R Back and J v Wright Renement Concepts Formalised in Higher

Order Logic Formal Aspects of Computing

Cam A J Camilleri Mechanizing CSP Trace Theory in Higher Order Logic IEEE

Transactions of Software Engineering

Dij E W Dijkstra Notes on Structured Programming In E D Dahl and

C Hoare editors Structured Programming Academic Press

Dol Axel Dold A Formalization of the Normal Form Approach to Compilation

Verix working pap er Verix Uni Ulm Universitat Ulm July

DvHPR A Dold FW von Henke H Pfeifer and H Rue Generic Sp ecication

of Correct Compilation Ulmer InformatikBerichte Universitat Ulm

Decemb er

Flo R W Floyd Assigning Meaning to Programs In J T Schwartz editor

Mathematical Aspects of pages American Math

So cietyProvidence Rho de Island

Gor M J C Gordon Mechanizing Programming Logics in Higher Order Logic In

G Birtwistle and P A Subrahmanyam editors Current Trends in Hardwar e

Verication and Theorem Proving SpringerVerlag

HHJ C A R Hoare I J Hayes H Jifeng C C Morgan A W Rosco e J W

Sanders I H Sorensen J M Spivey and B A Sufrin Laws of programming

Communications of the ACM August

HJS C A R Hoare H Jifeng and A Sampaio Normal Form Approach to

Compiler Design Acta Informatica

Mechanized Semantics of Simple Imperative Programming Constructs

HM P V Homeier and D F Martin A Mechanically Veried Verication Con

dition Generator The Computer Journal

Hoa C A R Hoare An Axiomatic Basis for Computer Programming CACM

Kah G Kahn Natural Semantics In Proc STACS volume of LNCS

pages b erlin Springer

Mas I A Mason Hoares Logic in the LF Technical Rep ort Lab oratory

for Foundations of Computer Science University of Edinburgh

MO M MullerOlm Modular Compiler Verication PhD thesis Christian Al

brechts Universitat zu Kiel

Nip Tobias Nipkow Winskel is almost Right Towards a Mechanized Semantics

Textbook In V Chandru and V Vinay editors Foundations of Software

Technology and Theoretical Computer Sciencevolume of Lecture Notes

in Computer Science pages Springer Verlag

NN H R Nielson and F Nielson Semantics with Applications A Formal Intro

duction Wiley Professional Computing Wiley

ORSvH S Owre J Rushby N Shankar and F von Henke Formal Verication

for FaultTolerant Architectures Prolegomena to the Design of PVS IEEE

Transactions on Software Engineering February

Plo G Plotkin A Structural Approach to Op erational Semantics Rep ort DAIMI

FN Computer Science Department Aarhus University

Sch D A Schmidt Denotational Semantics Wm C Brown Publishers Dubuque

Iowa

Sok S Sokolowski Soundness of Hoares Logic An Automated Pro of Using LCF

ACM Transactions on Programming Languages and Systems

SS D Scott and D Strachey Towards a Mathematical Semantics for Computer

Languages In J Fox editor Computers and Automata pages J Wiley

New York

Sto J E Stoy Denotational Semantics The ScottStrachey Approach to Pro

gramming Language Theory MIT Press Cambridge MA

Ten R D Tennent The Denotational Semantics of Programming Languages

CACM

Win G Winskel The Formal Semantics of Programming Languages Foundations

of Computing Series MIT Press Cambridge Massachusetts

Wir N Wirth Program Development byStepwise Renement Communications

of the ACM

Mechanized Semantics of Simple Imperative Programming Constructs

Mechanized Semantics of Simple Imperative Programming Constructs

App endix PVS Source Files

Mechanized Semantics of Simple Imperative Programming Constructs

Mechanized Semantics of Simple Imperative Programming Constructs

A Denotational Semantics

A State transformers

srel sigma tau TYPE THEORY

BEGIN

FP LIBRARY Fixpoints

Nondeterministic State transformers

IMPORTING relationsigmatau FPpredicatecpotau

srel TYPE Relationsigmatau ie srel sigma settau

s VAR sigma

S VAR setsigma

T VAR settau

fg VAR srel

least state transformers

abort srel LAMBDA s emptyset

Ordering on state transformers

the next IMPORT defines a partial order on state transformers

as f g FORALL s fs IMPLIES gs

IMPORTING FPdcpotoprecposigmasettau po intwi set aub ool

IMPORTING FPcpodefssrel

JUDGEMENT HASTYPE pCPOsrel

JUDGEMENT abort HASTYPE bottompredsrel

importing definitions and theorems about fixpoints on srels

IMPORTING FPfixpointscontsrelabort

Deterministic state transformers

strans TYPE PartialFunctionsigmatau

END srel

A Program State

Variable environment

varenvironment Vars TYPE THEORY

BEGIN

IMPORTING location relation finitesetsfinitesetsdef Locat ion

Mechanized Semantics of Simple Imperative Programming Constructs

locs VAR setLocation

preenv VAR PartialFunctionVarsLocati on

finiteinjectiveenvironment pre env bool

isfiniteimagepreenvfullset Var s setL ocat ion AND

FORALL xyVars llLocation

x y AND preenvxl AND preenvyl IMPLIES l l

VarEnv TYPE finiteinjectiveenvironment

END varenvironment

Lo cations

location THEORY

BEGIN

Location TYPE nat

IMPORTING finsetsLocation

locs VAR finitesetLocation

nextloclocs Location

IF emptylocs THEN ELSE maxreclocs ENDIF

nextloc yields a new location

nextlocmax LEMMA

FORALL llocs l nextloclocs

nextlocnew LEMMA

NOT locsnextloclocs

END location

Program State

state Vars Value TYPE THEORY

BEGIN

IMPORTING varenvironmentVars deterministicValue

CONVERSION singleton selectLocation selectValue

rho VAR VarEnv

x VAR Vars

v VAR Value

l VAR Location

usedlocsrho finitesetLocation imagerhofullsetVars

Mechanized Semantics of Simple Imperative Programming Constructs

UsedLocrho TYPE usedlocsrho

Storerho TYPE PartialFunctionUsedLocrhoV alue

emptyenv VarEnv

LAMBDA vVars emptysetLocation

emptystore Storeemptyenv

LAMBDA lUsedLocemptyenv emptyset

emptystate rho VarEnv sigma Storerho

rho emptyenv sigma emptystore

State TYPE rho VarEnv sigma Storerho

JUDGEMENT emptystate HASTYPE State

s VAR State

declared variable has a location assigned to it

declaredsx bool singletonrhosx

DeclaredVars TYPE declareds

newvarsx bool NOT declaredsx

NewVars TYPE newvars

declared variable is initialized if theres a value

assigned to it

initializedsxDeclaredVa rs bool

singletonsigmasselectrho s x

InitializedVars TYPE initializeds

update value of declared variables

updates DeclaredVarsValue State

LAMBDA xDeclaredVars vValue

rho rhos

sigma sigmas WITH selectrhosx v

updateinitializes LEMMA

FORALL s State xDeclaredVars vValue

initializedupdatesxv x

read value of declared variables

sState InitializedVars Value

LAMBDA psStateInitializedVar s

LET s projp x projp IN

sigmasselectrhosx

properties

Mechanized Semantics of Simple Imperative Programming Constructs

updateaccess LEMMA

FORALL s State xDeclaredVars vValue

updatesxvx v

equalupdates LEMMA

FORALL s State xDeclaredVars vvValue

updateupdatesxvxv x v

nonequalupdates LEMMA

FORALL s State xDeclaredVars xDeclaredVars vvValue

x x IMPLIES updateupdatesx vx vx v

introduce new variable

extendvarenv LEMMA

FORALL sStatexNewVars

LET newloc nextlocusedlocsrhos IN

finiteinjectiveenvironmentr hos WITH x newloc

introsxNewVars State

LET newloc nextlocusedlocsrhos IN

rho rhos WITH x newloc

sigma sigmas WITH newloc emptyset

Substitution

substp predState xVars sv State Value predState

LAMBDA s IF declaredsx THEN pupdatesxsvs ELSE TRUE ENDIF

Independence

independentp predState x Vars bool

FORALL s State svState Value substpxsvs ps

END state

A State Transformer Semantics

Bo olean Expressions

bexprsigma TYPE THEORY

BEGIN

FP LIBRARY Fixpoints

IMPORTING FPpredicatessigma

BExpr TYPE predsigma

END bexpr

Mechanized Semantics of Simple Imperative Programming Constructs

Expressions

exprstate value TYPE THEORY

BEGIN

Expr TYPE state value

IMPORTING bexprstate

END expr

Skip

skip sigma TYPE THEORY

BEGIN

IMPORTING srelsigmasigma

s VAR sigma

Do Nothing

skip srel LAMBDA s singletons

JUDGEMENT skip HASTYPE strans

END skip

Assignment

assignment Vars Value sigma TYPE

declared sigma predVars

update ssigma declareds Value sigma

THEORY

BEGIN

IMPORTING exprsigmaValue srelsigmasigma

s VAR sigma

x VAR Vars

e VAR Expr

Assignments

xe srel

LAMBDA s IF declaredsx

THEN singletonupdatesxes

ELSE emptyset

ENDIF

JUDGEMENT HASTYPE VarsExpr strans

END assignment

Mechanized Semantics of Simple Imperative Programming Constructs

Sequential Comp osition

sequence sigma TYPE THEORY

BEGIN

IMPORTING srelsigmasigma

s VAR sigma

fgh VAR srel

ffgg VAR srel

Sequencing

f g srel LAMBDA s imagegfs

sequencestransclosed LEMMA

FORALL fgstrans deterministicf gs

JUDGEMENT HASTYPE strans strans strans

sequencemonotonicleft LEMMA

f g IMPLIES f h g h

sequencemonotonicright LEMMA

f g IMPLIES h f h g

sequencemonotonic LEMMA

f f AND g g IMPLIES f g f g

END sequence

Conditional and While Lo op

controlstructures sigma TYPE THEORY

BEGIN

IMPORTING sequencesigma skipsigma bexprsigma

b VAR BExpr

fgh VAR srel

s VAR sigma

Conditionals

IFb f g srel

LAMBDA s IF bs THEN fs ELSE gs ENDIF

IFmonotonicleft LEMMA

f g IMPLIES

IF b THEN f ELSE h ENDIF IF b THEN g ELSE h ENDIF

IFmonotonicright LEMMA

f g IMPLIES

IF b THEN h ELSE f ENDIF IF b THEN h ELSE g ENDIF

Mechanized Semantics of Simple Imperative Programming Constructs

IFstransclosed LEMMA

FORALL fgstrans deterministicIF b THEN f ELSE g ENDIFs

while loop

whilefunctionalmonotonic LEMMA

monotonicLAMBDA xsrel IF b THEN f x ELSE skip ENDIF

whilebf srel

mu xsrel IF b THEN f x ELSE skip ENDIF

admissibility needed in proof of judgement

whilestransadm LEMMA

admissibleLAMBDA y srel FORALL s sigma deterministicys

whilestransclosed LEMMA

FORALL fstrans FORALL ssigma deterministicwhilebfs

JUDGEMENT while HASTYPE BExpr strans strans

whiledef LEMMA

whilebf IF b THEN f whilebf ELSE skip ENDIF

whilemontonic LEMMA

f g IMPLIES whilebf whilebg

END controlstructures

Semantics of Simple Statements

statements Vars Value TYPE THEORY

BEGIN

IMPORTING stateVarsValue

IMPORTING controlstructuresState

IMPORTING sequenceState

IMPORTING assignmentVars Value State declared update

END statements

A Predicates

predicates sigma TYPE THEORY

BEGIN

Lifting boolean connectives to predicates over sigma

s VAR sigma

pqb VAR predsigma

S VAR setsigma

Mechanized Semantics of Simple Imperative Programming Constructs

TRUE predsigma LAMBDA s TRUE

FALSE predsigma LAMBDA s FALSE

NOTp predsigma LAMBDA s NOTps

p q predsigma LAMBDA s ps AND qs

p q predsigma LAMBDA s ps OR qs

p q predsigma LAMBDA s ps IMPLIES qs

p qpredsigma LAMBDA s ps IFF qs

PP setpredsigma predsigma LAMBDA s FORALL p PP ps

PP setpredsigma predsigma LAMBDA s EXISTS p PP ps

IFbpq predsigma LAMBDA s IF bs THEN ps ELSE qs ENDIF

END predicates

Predicate CPOs

predicatecpo sigma TYPE THEORY

BEGIN

booleans with implication form a cpo

IMPORTING cpodefs

IMPORTING predicatessigma

IMPORTING boolcpo

bottom predsigma FALSE

top predsigma TRUE

Ordering on predicates

the next IMPORT defines a partial order on predicates as

p q FORALL s ps IMPLIES qs

predicates are functions from a type ie a discrete cpo sigma

into a cpo viz bool hence predicates with form a cpo

IMPORTING dcpotoprecposigmabool

bottompred LEMMA

bottom sigma boolpointwisesigmabool bo ttom

IMPORTING cpo predsigmabottom

PP VAR set predsigma

predlub LEMMA lub PPPP

predlubexists LEMMA lubexistsPP

predlubis LEMMA lubPP PP

END predicatecpo

Mechanized Semantics of Simple Imperative Programming Constructs

A Predicate Transformers

ptrans sigma tau TYPETHEORY

BEGIN

FP LIBRARY Fixpoints

predS THEORY FPpredicatecposigma

predT THEORY FPpredicatecpotau

Ordering

next IMPORT defines partial order on predicates transformers

as F G FORALL q Fq IMPLIES Gq

IMPORTING FPfunctioncpopredtaupred sigm apo intw ise bo ttom

IMPORTING FPmonotonicpredtaupred sigm a

predicate transformers and monotonic predicate transformers

ptrans TYPE predtau predsigma

MPT TYPE Fptrans monotonicF

JUDGEMENT HASTYPE pCPOptrans

Basic Predicate Transformers

q VAR predtau y VAR sigma M VAR setptrans

abort ptrans LAMBDA q FALSE

magic ptrans LAMBDA q TRUE

NOTF ptrans LAMBDA q NOTFq

F G ptrans LAMBDA q Fq Gq demonic choice

F G ptrans LAMBDA q Fq Gq angelic choice

F G ptrans LAMBDA q Fq Gq

IMPORTING FPcpodefsptrans

JUDGEMENT abort HASTYPE bottompredptrans

Generalized Meet and Join

M ptrans LAMBDA q LAMBDA y FORALL F MF IMPLIES Fqy

M ptrans LAMBDA q LAMBDA y EXISTS F MF AND Fqy

END ptrans

A Predicate Transformer Semantics

Monotonic Predicate Transformers

mpt sigma tau TYPE THEORY

BEGIN

IMPORTING ptranssigmatau bexprsigma

Mechanized Semantics of Simple Imperative Programming Constructs

define monotonic predicate transformer induced by srel

IMPORTING srelsigmatau

b VAR BExpr T VAR settau

fg VAR srel FG VAR ptrans

PTf srel ptrans LAMBDA T inverseimagefT

JUDGEMENT PT HASTYPE srel MPT

CONVERSION PT

some properties of PT

lifting LEMMA

f g IFF PTg PTf

PTuniversallyconjunctive LEMMA

FORALL Msetpredtau

PTfM ppredsigma EXISTS mM p PTfm

monotonic pred trans as used eg by Back Sampaio and others

JUDGEMENT abort HASTYPE MPT

JUDGEMENT magic HASTYPE MPT

JUDGEMENT HASTYPE MPTMPT MPT

JUDGEMENT HASTYPE MPTMPT MPT

END mpt

Monotonic Predicate Transformers for Statements

stmtmpt sigma TYPE THEORY

BEGIN

IMPORTING mptsigmasigma skipsigma

b VAR BExpr

FG VAR ptrans

q VAR predsigma

do nothing

skip ptrans PTskip

JUDGEMENT skip HASTYPE MPT

sequential composition

FG ptrans F o G

JUDGEMENT HASTYPE MPTMPT MPT

Mechanized Semantics of Simple Imperative Programming Constructs

conditional

IFbFG ptrans LAMBDA q IF b THEN Fq ELSE Gq ENDIF

END stmtmpt

B Various Styles of Semantics

B Weakest Precondition

wp Vars Value TYPE THEORY

BEGIN

IMPORTING statementsVars Value mpt

fgh VAR srel

x VAR Vars

e VAR Expr

b VAR BExpr

pqr VAR predState

Weakest Precondition

wpfq predState PTfq

properties

wpchar LEMMA

wpf q p p PTfq

wpskip LEMMA

wpskip q q

wpassign LEMMA

wpx e q substq x e

wpif LEMMA

wpIF b THEN f ELSE g ENDIF q

IF b THEN wpf q ELSE wpg q ENDIF

wpseq LEMMA

wpf g q wpfwpgq

wpwhile LEMMA

wpwhilebf q

IF b THEN wpf whilebfq ELSE q ENDIF

END wp

Mechanized Semantics of Simple Imperative Programming Constructs

B Hoare Logic

hoarelogicVars Value TYPE THEORY

BEGIN

IMPORTING statementsVars Value

b VAR BExpr

e VAR Expr

x VAR Vars

p p p

q q q

r VAR predState

f g h VAR srel

s VAR State

Hoare triple

p f q bool imagefp q

Characteristic Lemmas

preconditionstrengthening LEMMA

p p AND p f q

IMPLIES

p f q

postconditionweakening LEMMA

p f q AND q q

IMPLIES

p f q

ruleofconsequence COROLLARY combination of the above

p p AND p f q AND q q

IMPLIES

p f q

rules for statements

skiprule LEMMA

p skip p

assignrule LEMMA

substp x e x e p

seqrule LEMMA

p f q AND q g r

IMPLIES

p f g r

ifrule LEMMA

p b f q AND p NOTb g q

IMPLIES

Mechanized Semantics of Simple Imperative Programming Constructs

p IF b THEN f ELSE g ENDIF q

needed in proof of whilerule

whileadm LEMMA

admissibleLAMBDA f p f p NOTb

whilerule LEMMA

p b h p

IMPLIES

p whileb h p NOTb

END hoarelogic

Equivalence of Hoare Logic and Weakest Precondition Semantics

wphoare Vars Value TYPE THEORY

BEGIN

IMPORTING wpVarsValue

IMPORTING hoarelogicVarsValue

f VAR srel

pq VAR predState

Equivalence of Hoare Calculus and Weakest Precondition

hoarelogicequivwp THEOREM

p f q p wpf q

END wphoare

B Algebraic Laws

lawsvars value TYPE THEORY

BEGIN

IMPORTING statementsvars value

IMPORTING assertassumeState

b VAR BExpr

x VAR vars

s VAR State

e e e VAR Expr

f g h VAR srel

p q r VAR predState

FG VAR ptrans

Sequential Composition

Seqassoc LEMMA f g h f g h

Sequnitleft LEMMA skip f f

Mechanized Semantics of Simple Imperative Programming Constructs

Sequnitright LEMMA f skip f

Chaos Miracle and Top

Seqleftzerobottom LEMMA abort f abort

Seqleftzerotop LEMMA magic f magic

Conditionals

iftrue LEMMA IF TRUE THEN f ELSE g ENDIF f

iffalse LEMMA IF FALSE THEN f ELSE g ENDIF g

ifsame LEMMA IF b THEN f ELSE f ENDIF f

seqcondleftw LEMMA

IF b THEN f ELSE g ENDIF h IF b THEN f h ELSE g h ENDIF

assigncondrightw LEMMA nur deterministische Zuweisung

x e IF b THEN f ELSE g ENDIF

IF substb x e THEN x e f ELSE x e g ENDIF

Loops and Fixpoints

whiledef LEMMA

whilebf IF b THEN f whilebf ELSE skip ENDIF

Assumptions and Assertions

assertionassumption LEMMA assertb assumeb assertb

assumptionassertion LEMMA assumeb assertb assumeb

assertskip LEMMA assertb skip

assumeskip LEMMA skip assumeb

combineassumption LEMMA assumep assumeq assumep q

combineassertion LEMMA assertp assertq assertp q

assumptionconsequence LEMMA p q IMPLIES assumeq assumep

assertionconsequence LEMMA p q IMPLIES assertp assertq

voidassumption LEMMA assumeTRUE skip

voidassertion LEMMA assertTRUE skip

assumptionassign LEMMA

x e assumeb assumesubstb x e x e

assertionassign LEMMA

x e assertb assertsubstb x e x e

condassertionthen LEMMA

PTIF b THEN f ELSE g ENDIF IF b THEN assertb f ELSE g ENDIF

condassertionelse LEMMA

PTIF b THEN f ELSE g ENDIF

IF b THEN f ELSE assertNOTb g ENDIF

assumeb F IF b THEN F ELSE magic ENDIF conditionscondtop LEMMA

conditionscondbot LEMMA assertb F IF b THEN F ELSE abort ENDIF

END laws

Mechanized Semantics of Simple Imperative Programming Constructs

B SOS

sos varsvalue TYPE THEORY

BEGIN

IMPORTING statementsvarsvalue

Cmd TYPE srel

Configuration TYPE Cmd State

BConfiguration TYPE BExprState

EConfiguration TYPE ExprState

b VAR BExpr e VAR Expr x VAR vars

bv VAR bool v VAR value

stu VAR State cfg VAR Cmd

conf VAR Configuration

bconf VAR BConfiguration

econf VAR EConfiguration

cmdconf Cmd projconf

stateconf State projconf

bexprbconf BExpr projbconf

statebconf State projbconf

expreconf Expr projeconf

stateeconf State projeconf

bconfbv bool bv bexprbconfstatebconf

econfv bool v expreconfstateeconf

confs bool memberscmdconfstatecon f

predboolbool IMPLIES

pbool bool p

skiprule LEMMA

skips s

assignrule LEMMA

declaredsx IMPLIES

es v

x e s updatesxv

seqrule LEMMA

fs t AND gt u

f g s u

iftruerule LEMMA

bs TRUE AND fs t

IF b THEN f ELSE g ENDIF s t

Mechanized Semantics of Simple Imperative Programming Constructs

iffalserule LEMMA

bs FALSE AND gs t

IF b THEN f ELSE g ENDIF s t

whilefalserule LEMMA

bs FALSE

whileb f s s

whiletruerule LEMMA

bs TRUE AND fs t AND whilebf t u

whilebf s u

END sos

B Continuation

continuationsigma TYPE THEORY

BEGIN

IMPORTING srelsigma sigma

continuation TYPE srel

s VAR sigma

c VAR continuation

f VAR srel

Cfc continuation LAMBDA s imagec fs

contsingleton LEMMA

Cfsingleton f

transfer LEMMA

FORALL P predsrel

PCfsingleton Pf

END continuation

continuationlemsvars value TYPE THEORY

BEGIN

IMPORTING statementsvars value

IMPORTING continuationState

x VAR vars b VAR BExpr e VAR Expr

s VAR State

c VAR continuation

pq VAR predState

fg VAR srel

skipcontinuationeq LEMMA

Mechanized Semantics of Simple Imperative Programming Constructs

Cskipc c

assigncontinuationeq LEMMA

Cx ecs imagec x es

seqcontinuationeq LEMMA

Cf g Cf o Cg

ifcontinuationeq LEMMA

CIF b THEN f ELSE g ENDIFc IF b THEN Cfc ELSE Cgc ENDIF

END continuationlems

B Putting it Together

semantics Vars Value TYPE THEORY

BEGIN

IMPORTING sosVarsValue

continuationlemsVarsValue

wphoareVarsValue

lawsVarsValue

END semantics

C A Simple Programming Language

C Simple Commands

simplecommands Vars Value Expr BExpr TYPE

IMPORTING stateVarsValue

eval Expr State Value

evalB BExpr State bool

THEORY

BEGIN

syntax

SimpleCommand DATATYPE

BEGIN

skip skip

seqfirstsecondSimpleCommand seq

assignvaridVars expExpr assign

ififcond BExpr thn els SimpleCommand if

whilewhilecond BExpr body SimpleCommand while

END SimpleCommand

semantics

IMPORTING semanticsVarsValue

Expr State Value eval

Mechanized Semantics of Simple Imperative Programming Constructs

BExpr State bool evalB

cSimpleCommand RECURSIVE srel

CASES c OF

skip skip

seqfg f g

assignxe x e

ifbfg IF b THEN f ELSE g ENDIF

whilebf while b f

ENDCASES MEASURE c BY

END simplecommands

C Simple Declarations

simpledeclarations Vars Value TYPE THEORY

BEGIN

syntax

VarDecl TYPE listVars

semantics

IMPORTING stateVarsValue

IMPORTING vardeclVars Value State newvar intro

CONVERSION deterministicStateselect

d VAR VarDecl

s VAR State

dVarDecl RECURSIVE srel

IF nulld THEN skip ELSE declarecard cdrd ENDIF

MEASURE lengthd

END simpledeclarations

C The Language

simpleprogram Vars Value Expr BExpr TYPE

IMPORTING stateVarsValue

eval Expr State Value

evalB BExpr State bool THEORY

BEGIN

syntax

IMPORTING simplecommandsVarsValue Expr BExp rev alev alB

IMPORTING simpledeclarationsVarsVa lue

CONVERSION deterministicStateselect

SimpleProgram TYPE decl VarDecl body SimpleCommand

Mechanized Semantics of Simple Imperative Programming Constructs

semantics

p VAR SimpleProgram

p setState

bodyp declp emptystate

END simpleprogram

D Pro of of Lemma while strans adm

In section an example pro of by xedp oint induction is illustrated However wehave

omitted the pro of that the used predicate is admissible for xedp oint induction For

completeness the pro of script of the corresp onding lemma is printed b elow The main idea

is to characterize the least upp er bound of the chain C of functions of typ e srel As

such functions map states to a set of states the least upp er b ound of C is the function

mapping a state to the union of all images of the functions in C

AUTOREWRITEDEFS

STOPREWRITE partialorder

ASSERT

SKOSIMP PREDS T

PROP

INST

CASEREPLACE

lubClambda ssigma predicatesfsetimageC s

EXPAND

EXPAND chain

SKOSIMP PREDS T

EXPAND fsetimage

SKOSIMP PREDS T

INST SUBST x f y f

EXPAND

EXPAND

PROP

INST s x INST SUBST x f REDUCE

INST s y INST SUBST x f REDUCE

REWRITE funclubis DIR RL SUBST S C

APPLYEXTENSIONALITY HIDE T

REWRITE predlubis

USE srellesseqpTCC PROP