• Aucun résultat trouvé

Cont ent s

N/A
N/A
Protected

Academic year: 2022

Partager "Cont ent s"

Copied!
208
0
0

Texte intégral

(1)
(2)
(3)
(4)
(5)

.+1

NationafLibril/Y

ofGana,ja Bii)liolheQuenahona!c

do"""""

Acquisitionsand DirectiondesaCQuis~ionsat BibliographicsevceeBranch des servicesbibliOg:aphiQuc s JIl5~s.-. 39S.""'~

~0"CatIll ~QrI.ylgI

NOTICE AVIS

Thequalityof thismicrofo rm Is heavily dependent upon the quality of the origin al thesi s sub m itted for microfilming. Everyeffort has beenmadeto ens u re the high est quality of repro duction possible.

Ifpag esaremissin g, co nta ct the university which grant ed the deg ree .

Somepage s may have in distinct print especiall y if the origin al pages weretyped withapoor type write r ribbon or if th e university sent us an Inferi or photocopy.

Reproducti onin full or In partof this microform is governed by Ihe Cana dia n Copyright Ael, R.S.C. 1970, e. C-30, and subs equent amendm ent s.

Canada

Laqualitede cette micro forme dependgrandam e"tde1a qualite de la these sou mis e au micro fllm age. Nou s avo nstout fait pour assurer une quallte super leurede repro d uctio n.

S'i1manquedespage s, veuillez commuoi que r avec j'unlv erslte quia co nferelegrad e.

La quente d'impression de cert aine s pag espeut lai sser it desirer, surtout si les pages

orig in ales ont ete

dactyloqraphlees iiiI'ai de d'un ruban useousll'univereltenous afailparv enirunepholo c opiede quallt e lnterieure.

Lareproduction,memepar ti elle, de cette microforme estsoumis e

a

laLo ican adie nne surIedro it d'aute ur,SRC1970,c.C~30,et ses ame nde me n tssubse q uents.

(6)

FORMALSOFTWAREDEVELOPMENTUSI NG Z ANDTHE REFINEMENT CALCU LUS

BY

©DennisJu-XiengWee

Athesissubmitt edto theSchoolof Graduat e Studies inpart ialfulfillmentof the

requirementsforthe degree of Masterof Science

DepartmentofComputerScience Memorial UniversityofNewfoundland

July1993

St.John's Newfoundland

(7)

Abstract

This thesis is astud,.of a Cormalsertwaeedevelopmentpro.~CllSthalJunen formal speeifleatlenlangu:l.~ecalled Z(421andtheCor lnol dt"vdoplllf'otlIIel hml calledthe IT};"'''' ''I I('"lrl/".~(31).Thesoftware dcveloJllllcntprocessis.livid.'!:1 intofivestages;forma lspecificationinZ,dat a refinement,translntion into lilt' refinement calculus,cpcraticnrefinement,and trnn811\li onintothe largdIlrQ. grammi nglanguage(251.In thisthesis ,many oftheimporta ntresultsCorunder- standingandusingthis processmecollectedtogetherundnumerous cxnlllpl,,-s are givento illustrate theiruse .Tbrougha casestu dyofthel'fI'~'!I/lI}J"1',1'/'/'/II [5, 31].we showhow formality may bea.ppro p rialel ycmployedtomanage1I11:

algorithmiccomplexi tyin a development,andindicate directions onIlIlwpeerh-.

fined programminglanguageand libraryrouti nt!Smay be introduced intoa formal development.Thelhellis concludeswith somesuggestion sfatfurtherrcsca r~h.

(8)

Acknowled gm ents

1wouldlike tothan kHelmu tRothandlieXufor theircompanionshipduring these two yean ofsharinsanoffice.Itmusthavebeenhard for them toput up wit h my quirks andidioliym:ra sies.

Iwouldalsoliketothank Robert Ma chinfor proofreadinsadraftofthisthesis, andJohn RochesterandPatrickMarti n for helpingwithsome ofthetypesetting.

Iwould like10acknowledgeDr.TonyMiddlet on,theDepartm entofCompu ter Science,andtheSchoolofGraduateStudiesforprovidingthe fina ncialsupport during the courseofmyM.Sc.degree.

Most sincerethlLnkstoToddWa.rehll.mfor hismanyusefulsuggest ions,crit- icislOs, andcomments.Hiliwillingnesstoreadthisthesis at averyshod notice isgreatlyapprecia ted.

Iam alsogratefulto thetechnical and&dmi nistrativeItall'attheDepar tment ofComputerSciencefor creating andmaintainin&a cond ucive environme nt for learn ing.In particular,theChairofCompu terScience,Dr.PaulGillard,hu helpedandencouragedme inmorewaysthanIcanremember.

Iammostgratefultomythesis supervisor,Dr.Tony Middleton,forintroduc- ing metotheworldof formal sp ecification.Icherishhispatience,underst anding, sound advice, endhumor.His greatnessisapparentfromhisabilityto putup withIllyobsrinecy,

L;u;t butnot least ,Imust thankroyfavorit e mu. icians:AUred Brendel,Zino iii

(9)

Francescet ti,Murizio Pollini,Pa~calRoge.Andra.Schiff,RudolfScrkin.nllli Tl\mu \I&sary,forcontri buting toIlly menta lstability.Billpcrhap~mOllt ofnil.

Iam indebtedto thelateClaudioArrau(orhispillni_ticIl"!tact;if itwert"not forhisBeet hoven, Chopin .Debussy.Mozart,Liast,and Schumann,I 'm uM not havebeenable toretainmyu.nityduringtheladmonthofthcsi~writin".

(10)

Cont ent s

Ab~tract.

Acknowl~d gmenh ,

Contenta . ,

List ClfTablL'S LidofFigures,

] Intr oduct ion

1.1 For malMethodsin SoftwareDevelopment 1.1.1 Form a.lSpecification . 1.1.2 FormalDevelopment .

1.1.3 Verification versusValidation 1.2 A FormalDevdopmentProcess

1.2.1 FormalSpecificat ion inZ. 1.2.2 DataRefinement

1.2.3 Transl n.tionintotheRefinementCalculus•. 1.2.4 OperationRefinement . .•.

iii

xiii xiv

(11)

1.2.5 Translat ion intothe TargetProgram mingLallg1Ia~l'. 1.3 An Application

1.4 Summary

2 Formal SpecificationinZ 2.1 Schema s . 2.2 Sta.tes

2.3.2 ShowingExist enceofInitial St atCli 2.4 Operat ions. . ..

2.4. 1 The.6. and:=:Conventions. 2.2.1 Sets,Types and Ba.sicTypes . 2.2.2 Axiomati cDescription s. 2.2 .3 ModelingStates 2.3 InitialStates .

2.3.1 Schema.Reference .

III

11 11 12 J:t I:t 11 Iii

2.4.2 Specifying Operations 2.5 Preconditions

2.5.1 CalculatingPrecondition s 2.5.2 Simplifying Precondition s 2.6 Proving Propertie sofSystems. 2.7 Errors . .

2.7.1 Reporting Errors

'f, 1 .

10 20 22 21 25

(12)

2.7.2 Sch ema Calc ulus

2.7.3 Building Stronger Specification s. 2.8 Summary and Bibliographic-atNotes.

2.8.1 Som eUsesofZ.

:1 Ollt.n Refinement

3.1 From Specifications toDesigns..

26

27 29 29

32 32

::1.1.1 AbstractSpecifleatl on s. 33

3.1.2 Conc rete Desigrll . 35

3.1.3 Retrieve Relations 37

3.1.1 ProofObligations. 38

3.1.5 ProofObligations (or FunctionalRetrieve Relation 44 3.1.6 ProvingRetrieveRelationsto be Functional 45 3.2 CnseSt ud y

3.2.1 ConcrdeS tat cs. 3.2.2 RetrieveRelat ion . 3.2.3 Ini t ial ConcreteStates 3.2.4 Proof Obligation (or Initial State 3.2.5 ConcreteOperations

46 46 47 47 48 .. . . .. . .... 48 3.2.6 ProofObligations (orConcrete Operations..

3.3 Summary andBibliograp hicalNotes.

vii

'1

(13)

4Tra nsla ti onint o the Refine me nt. Calculus r.i

4.1 TheNotationof the RefinementCalculus. !ill.

4.1.1 SpecificationStatements r,ll

4.1.2 Assign me nts.

... . . .. . .. . . .

a\1

4.1.3 Alterna tions.. en

4.1.4 Iteration s 61

4.1.5 Sequentia lCompositions 61

4.1.6 Local Blocks,Variables. Invari ants,and Procedur es 62

4.2 Using theRefinement Calculus. fir,

4.2. 1 AbstractPrograms

.. .

fif,

4.2.2 Executable Programs. 66

4.2.3 ALibera lViewof Programs li(l

4.2.4 Refinement 67

4.2.5 Some Simple Laws 69

4.3 ComparingtheNotations of Z andtheRefinemen t Calcul us 71

4.3.1 St alr'll 71

4.3.2 Operat ions. 72

4.3.3 Before-andAfter-StaleVariables 74

4.3.4 Renami ng VersusSubst itutio n. 75

4.4 RulesforChangeof Notation 76

4.4.1 BasicRules

. ..

76

viii

(14)

01.4.2 SpecificationstoAb~tractPrograms. 01.4.3 SimplifyingSpecificationStatements 4.4.01 Some DerivedRules

4.5 Case Study

4.5.1 States and Operations 4.5.2 Main Progra m. 4.6 Summaryand BibliographicalNotes.

77 80

81 88 88 88 94

5.2.7 Iterati on

5.3.1 Proced ures. 5.2.5 Sequential Composition

5.3 Case Study •. ..

98 98 97 99 99 100 101 102 104 lOS 107 110 114 114

Procedure .

Logical Consta nt

Alternation 5.2.4

5.2.8 5.2.6

5.2.2 Local Block. . ,. 5.2.3 Skip.. 5.1 Feasibility.•. .

5.1.1 Pathologica lSpecifications 1:'.2 Some Basic Laws

5.2.1 Assignment ti Ope r ntlcn Raftnemeut

(15)

5.3.2 Main Program. 5.4 Summaryand BibliographicalNotes.

6 Case Study:ThePar-agr-aphProblem 6.1 EvenParag ra phs

6.2 Abshr.ctSpecification 6.2.1 State SpaceandIniti al Sta tes 6.2.2 Operati ons.

6.3 Concrete Design. .

6.4 RetrieveRela tion andProof Obligations 6.4.1 Correct ness ProofforJI',·jk/'WYIIJI1I/I/,(: 6.5 Using PredefinedPascalRout ines . 6.6 Operat ionRefinement

Ilfi 120

125 1211 12(j

136

I~ (}

1~4

6.6.1 6.6.2 6.6.3 6.6.4

Comput ingMinimumWasteArr ay Writin gaLine .

Writingan EvenParagraph Comp uting an EvenPara grap h

111 14!J 14\)

1M 6.7 Summary

7 Con cl u ding Remark s 7.1 Directionsfor FurtherResearch

7.1.1 SystemDevelopment ToolSupport

1M

]5 0 IS7 157

(16)

7.1.2 Librariesof Specification s andRefinemen ts for DataStruc-

lllres. 158

7.1.3 Calculat ing Data Refinement 159

7.lA TranslationRulesforOtherZConstructs. 159 7.1.5 DataRefinementintheRefinem ent Calc ulus. 160 7.1.6 OperationRefinementfor DynamicDataStru ctures. 161

A A Glossaryof Z Notat.lo n A.l Logic .

A.2Sels A.3 Relations.

AA Funct ions A.S Seque n ces.

167 167 167 168 168 169

B SomeDefin itions,Abbreviatio ns,andLawsof theRefinem ent Calculus

8.1 Definition s . B.1.1 Feasibi lity . B.2 Abbreviations. . B.3 Laws .

B.3.1 B.3.2 B.3.3

AssumptionandCoercion Pre-and Postcondi tion..

Frame

170 170 170 . .. .. . 170 171

171 173 173

(17)

8.3.4 LocalBlock 8.3.5 LogicalCon.tallt

174

'"

8.3.6 Assignment 8.3.7 Alterna tion 8.3.8 Itera tion. .

175 176

8.3.9 Seq uential Composition 117

8.3.10Procedure. . . 177

8.3.11Invariant. 179

8.3.12 Skip 179

C A Pasca lPro gr a mthat ComputesEvenParilgr a llhs Iso

xii

(18)

Li st of Tables

2.1 ThepreconditionsofPIl.~lt Ok,Pop Ok ,andTopOk . 22 2.2 The preconditionsof,S'!arkfo"lIl1,S/nckBIU/Jly,Pop,Pll.~h,and'fop. 29

3.1 The preconditionsof theoperat ionsEnter,Filld},fIlX, Ellie/-C,and

HildA/ruG. 41

3.2 Theprecondition sof the concrete operation softhest ack.. .,. 51

4.1 Abbreviationsfor thestate,inputandout put variables of Exam-

pie3.2.. ... . • ... ... 78

1.2 Abbreviationsforthestate, input andoutput variablesof thestack. 88 4.3 The precondi tionsofPII.~h Colllma 'l d,PopCQm m rllld ,and TopC om m and.92

G.l Abbreviations for thestat evariables ofoper ationsl~eadlnJj ld :and 142

xiii

(19)

Li s t of Figures

1.1 Stages ofsoftware developm entusing Zand the n-jil/l'/IIr nlf·fdl"ldl'.~. .j

4.1 The skeletonofa samp le progr a m.

"

4.2 Nestedblocks. ea

4.3 An abstr actprogram. 65

4.4 Anexec utableprogram. ue

4.S An abstract prog ram contai ningbothspecificationstate me nts and executableconst ructs.

"

4.• An abstractprogramtranslatedfromtheconcrete designofEx-

ample3.2. 79

4.7 An abstr actprogram translatedfromtheconcretedesign ofthe

stack.. . 89

5.1 An abst ractprogramof the stack with refinedprocedures. 115 5.2 An abstractprogramtranslatedfrom theschema1/tIIlI IOr/l pl/I.. liB 5.3 Codecalculatedfromtheabstra ct programofthestack. 121

(20)

6.1 Asimpl eparagraph.

6.2 Allevenparag raph.

124

... . ...•. .... • ...•124 6.3 Apossible refinementofthe pro cedureCOIn/HlleMill Wnsle Jil·my ..150 6.4 Apossiblerefinement ofthepro cedureWrilcLill(;.

6.5 Code from the refinementofprocedure W,.i1eEvell.

6.6 Arefinementofprocedu reIl'l'ilcPruYlgmJlbCthat usesprocedures COlllfJUlrMilllVIlRleArmyandWr ilrEu,;Il..

151 153

154

(21)

Chapter 1

Introduction

fbi'll/a!md/lCll.~in softwa.re develo pmentare mathetunticaltechuiqueswhichmay be used to specify,developandverifysoftwareIy~tem~inIl.sys tcnnuicnndorga- nized fashion.The mathem aticalbasisofaformalmethod is,inprin ciple, given by a!OI'/I1f11'~JH:cjfica l-io ll!rlllyllllyr,witha well-definedsyntax nnd sem a ntics.

1.1 Formal Met hods in Software D e velo pment

Someofthe adva ntagesofusing for malmethodsin softwaredevelop mentan:

givenbelow.

1.1.1 FormalSpe cification

Afor mal methodis common ly usedtospecify softwaresystems.ItJbasis languag e is used as a notationto write form a l specifications.Sincethe notatio nis precise,

(22)

theresulting form al descri ption is clear and unambiguous.

There areseveraladvantag esto usingformalrather thaninformal langua ges tospecifysoflware. Wit han inform al specification,thoroughreasoningisoften hard orimpossible; aformalspecification, on the otherhand, maybe subjected to rigorous mathematicalanalysiswhicheasilyexp osesambigl/iJiesandmcom-

pld l:l /f s....Since aformalspecificati onis essentially amat he maticaltheory ,its

rOlls i..lntC/}canalsobechecked.Aninconsistent specificationis undes ira blesince itcontainscontradicting fact s[44]anda pr ogramba sedonit cannotberealized.

Themathematicalnatureofa formalspecification alsoleis th especifier formally prove important properties ofthe systemto the custo mer,therebyensuring that the specifierhas agoodapproximationofthe custo mer's requirementsfor the system.

1.1.2 Form alDev el opment

Aprogrammay bemathem atically derivedfrom th e program's formalspecifica- tion.A programderivedin t!lisman nerisguaranteed tosatis fyitsdescriptio n.

Onesuchdevelopmentmethodcalled,'Cjinc/IIcll tinvolvesdevelopin g programs insmnllsteps.A st epmay consistofdefiningamodule as acollectionofmod u les ata lowe rlevel, or choosingarepresentationforIldatatypethatismoreefficie nt ormoreeasilyconstructableinthe targetprogramm inglangu age,Sta rtingfrom aspecification, each refinement stepyieldsanotherspecification tha.t contains

(23)

moreimplementationdetails.This latterspecificationmustin tu r nbe shown10 sd isfythe formerin ordertoensure correceneee.Suchproofofsfl.t i~rllclio ncncu generates proofobliga t ions whichcanbe preciselystiltedami diac hetgcd within the frameworkof a formalmet hod144].

1.1.3 Verificationver -sus Valldatlon

Follow ing Wing[4.4]andHayesandJones[17),Il."r";ji'·/llitJIIis1\ rOTllIl\. \pwo[

that an implementationsatisfiesitsspecification , while1\1!lI/iJtlliotlis1\11info rmal checkof correctness,e.g., testing . When a program is notformall y developed, it may be desirabletover ifyits correctness.Onlywhenthe specificationisexpressed mathematicallycana formalproof be carriedout;withoutsuch a specification , onlyvalidatio n is possib le[44,171.

Anin-dep th discussionof the merits offormalmethods is1I0ta.nobject iveuf this thesis;the interested read e risreferredto[15,26 ,44).Fromhere onwards, weconcern ourselves witha softwaredevelopmentprocess thatrel ies011formal methods 125].

1.2 A Formal DevelopmentProce ss

Asoftwarede velopmen t processthatusestheformal specificationlangu ageZ, and theformaldevelopment me thodcalledthe n:jillcmcrdrl1lcl!l1t.~,ildceceihcd in[25,451.Thisprocess (seeFigure 1.1)maybe viewedas hav ingfive stagt'll:

(24)

1

Formll.lspecfjlcationin Z Abst ract Specification

1

Datare finerneat Contrel l!Design

!

Tlanslationinto therefine meat eeleulue AbstractProgra m

1

Opct&tionrefinemen t Code(Guarded Comma n d.)

!

nao.lat io ninto theIllJgd proglll,mminglang u a ge Code (Pascal,C, ... )

Figure1.1:Stagesofso ft ware developmentusingZ andth ertjin c71lcrllcalcniue.

forma lspecificationinZ,datarefinement,translat ion intotherefinementcalcu- Ius,operation refinement , andtr a nslatio nintothetarget programminglang uage, Allove rviewofthese stagesis givennext.

1.2.1 FormalSpecificationinZ

The Znotation [42)isused tofor mally specifytheproposedsyste m.Theformal specificat ionobtainedis celled anabsf racl specificafionasitcontainsabstract mathe matic al models ofdatat.yp esandcperatione.. Alt hough the se modelsare typicallydifficultto construct usi ng the primiti ve datatype.!ofthe targetpro-

(25)

gramrninjlanguage,they are wellsuited Cor describing andreasoningaboutthe propert iesofthesystem.

In Chapter2,abriefaccount oCthe Z specificationlanguage and a convention forspe cifyingsoftwaresyste msisgiven.This exposition isillustratedbyncnse studyinwhichsomeoperat ionsofthe abstract data type ..'!f/l'~'are specified.

1.2.2 DataRefin ement

Deta,y;ji IlCIIlCII/istheprocess oftra nsformin ganabstract specificationintoII

specificationofthe system which containsdata typesthatareeitheravailable oreasilyconst ructedinthe target progra mming language.TIleproduct ofthis refinement is calledaCOlluc/edcxiYIIsinceitusesdata. typestlllltmay bedi- rectlyrealizedinthetargetprogramminglanguage.Animportanttaskhere isto formulate avc tricec,.cfa/inlltorelatetheabs tractspecification nnd theconcrete design.ProoCobligations whichuse this relationmaybedischargedto showthat thisconcretedesign satisfiesthe abstract..pcciflcetion.

The process ofproducingaconcretedesign{rom anabstractspecificationis thesubjectofChapter3.Thepurpose of data refinementisillust ratedthrough severalexamplesandthe casestudyofthesta ckstartedinChapter2.

(26)

1.2.3 Translation into the RefinementCalcu lus

The concrete designis thentranslatedinto thenotation oftherefinementca/cullLS [311to obtain ana/HI/mel I,ro.r/mlll .Whilethe Znot ation is moresuita ble forthe purposeofspecificat ion,therefinementcalculus ismoreappropriatefor progra m developmen t.

Thenecessityofandstra tegies fortran slationare discussedinChapter4.

Rulesareformulat edtoallowthetransla tion proc essto be performedina st raightforwa rdma nner, Theserulesindicat ehow thecommon structures in n.Z specifica tion may betransformedinto the refinementcalculus.

1.2.4 Operation Reflnemer-t

Codewrittenina languagebasedon Dijkstr a 'sgllflnlcdcom m ands[13Jis calcu- latedfromthedesignbyperformingrefineme ntsteps . Thesesteps arecarried outaccordingtoth e lawsoftherefinementcalculus , whichguaranteethatthe derivedcodesatisfiesits specification.

SOllie elementarylaws of tilerefinementcalculus aregiven inChapter5.Ex- amplesincluding thestackcasestudy are presentedtoillustratetheiruse,

1.2.5 Translationinto theTargetProgrammingLanguago Sincethestagesof dala andoperat ion refinem enttakeintoconsideration the characteristicsof the targetprogramming la n guage,the resultin g codeisreason-

(27)

ablyclose10allowII.sim pleand intuiti ve conversio ninto the tlltgct programming langu age,Hen c e, thecodefromthepreviousstepmaybeeasily trall81aledinto an imperativeprogramminglan guagelike C or Pascal.

Due to itsla nguagespecificityandrelative ease,II.rev iew ofthis stnge isnot given. Howeve r,inCh apter6,the translationofsomegu ardedcommandsinto Pascalmay beobserved.

1.3 An Application

In Chapte r6, theform al softwaredevelopment processdescribedhereis usedLa producea program for computingcncn /lam,rlm/lft J<[5,at]. Allnim

or

constructing this program is to collectusefulexperiencetha t maybe employedto construct largerandmorecomplicated prog rams. Besidesillustr ating manyof theconcepts thatare conta inedin the earlie r part ofthisthesis, lois case5111(1yalsoehows howformality may be appropriatelyexploited to managethe complexityof the refinementwhi chmayariseduri ng thedevelopment ofa sortwaresyste m.Since this programusespred efinedroutines,we alsogive directio nson how thesemllY beintegratedinto the formal developmentframe work.

(28)

1.4 Su m mary

Thisthesisreportsonthe pra cti cal aspectsof asoftwaredevelopm entprocess thatuses Zandtherefinementcalculus.Theaimis tocollecttogether inone placemany oftheimportanttheoreticalresultsthatareneeded to unders tand /Irdusc suchadevelopmen t process.Eachstageoftheprocessis documentedin a chapter with examp lestoillustrateitspurpose.Thisthesisconcludeswitha non-t rivialcasestudyandsugg estionsforfuture research.

(29)

Chapter 2

Forrnal Specifi cation in Z

Zis a formalspeci ficationlanguagebased ontypedset theorynndfret-order pr edicatecalculus [19, 40, 42],ThischapterpresentsSOUleofthefc ntllrcHofZ, andhowZ maybeusedto specifysoftware systemsinthe sta ndardconvention as describedin[42J. Sinceacomplete descrip t ionofthenotationisnolIloHsihlc.

a glossaryisincluded in AppendixA.

2 .1 Schemas

CentraltoZis alan guageconstruct calleda.~dlr.lllliwhich may bediugmnuunt- ically representedintwo eq uivalent ways:ver tically andhorizontally.Aschema na medSchell/awri t te nvert icallyis asfollows.

(30)

1 : ;:' :' ,;:;"-- -- - - -- - -

t;,

fJ~

: :

I'. _

A schema consists of twoparts:theflu/amlin"and theIlredi cQlc.The decla- rationiscon ta ined in thepartof asche maabovethedividingli ne, which.inthe case ofS('1I1'1II11,hasunri"Mu;Ill .1!2, ••••lJ.,ofIYJlr.~TIlT~• ..,T.,Thesevariables arcalsoknown asthecOII/fJO/l el/lxofthe schema.

Below the lineareII/'f dicfl l cr PI,1'1, ....Pi ,whichareimplicitly conjuncted (~andcd" )togive therelation whichmustholdamongthevaluesofthe variables.

Thepredicate pn.rlofa schema maybe empty,inwhichcase,itis a box with no dividingline,contain ingonlythe signature.

The same schemaiswrittenhorizon tally asfollows.

2.2 St a tes

The style ofZspecificationused hereissuit ablefor sequential,imperativepro- grammingand itinvolvesviewing asoftwaresystemas anabsf racldai a type.

Simply put,an abstractda t a type consists of asetof states , called theslate 10

(31)

.</UI('(,IInon-emptysetofioitielstotc.•,andanumberoff>/lf m ' itHl.~whichtran s- formone stateinto anot he r [42J.Inthis sect ion, weshowhow thestatespaceof asyste mmay bedefined.

2.2.1 Set s,Typesand Basi cTypes

The spe cificationof a state spac e involves identifyingsomeobjects of interest Eachsuc h obj ect has a typewhich iscomposedfrom sets. Z contains stan da rd mathemati cal setslike thena t ur al numbers(Iiand the integers Z, etc.In general, any set may beused as a type,and com plextypes like seq ue nces andcar tesilUl prod uctsmay be const r ucted fromsimp leronesby usingstandardZ operators.

A part icularl yusefulconstru cti on in Zis that ofa~" ."if·I!I/'"whichallowslL

set tobe declaredwithoutmentioningwhat is conta ined in it .Thedeclaration

[OI3.IECT I

indicates the existence of a setofobjectsca lledOUJII'C'J',althoug hwedonot know it sst r uct ure orcont ent .

2.2.2 Axio matic Desc r ipt io n s

Globalconst ant sandfunction smaybedeclaredanddefined usinglui/mw li/' dc.<cripliolls.Thesedescription sallowsthedeclar at ionanduse of globalvariables.

Thescopeof a globalvariableextendsfrom the point of declaration to theend of the specificati on.

11

(32)

1 -",",-,-,,- -

~

forexample,a global variabl e1/1111oftypenatur alnumb eris declared.Acon- strai ntonitsvalue is included ,which restrictsmnrto a valueof 20.

2.2.3 Mode lingSta t e s

The ...11I1f',",/fl er.ofasystemisthe set of allowablestates.Thissetmaybedefined withaschemaby decla ring.../Ilfr1I(11·i(lblc.~ascomponents oftheschemaand constrainingtheirvaluesusingtheschema predicates.Theconjunctionofthese predicatesgivesthesy ste mill/JUl'illlll,and the values thatmay betakenupby thevariables representthe allowablestatesof thesystem.Forexample,apossible state spaceofa systemthatmaintains aratherlimited versionof theabst ract dl\ta type."'(It:~.is

Sllll'~' _

,..Itick :seqOIJJBCT

#.../nf'k:5mar

Theschema.'ilrlf-l'mod els a stackwhich maybeused to store objects fromthe setOIJ.JECT,Ithas a statevariable$/ackwhichisa finite sequence (seq) of ()IU/:,(~'I',and its invariantrequiresthat thelengthofthe stack benot more than20.In thispap er, theconventionofwrit ingschema nameswiththe first lettercapitalized, andcomponent nameswiththefin t letter inlower caseis used.

12

(33)

2.3 In it ial States

Theinifialsilliesofasyste mmay he docume nted by describingthevnlues that thestateva riab les mudtakewhenthesyste m is sta rted up.Asystem typicall y has onlyonesuchstate, but there maybe more.Theinitia lstaleofour slack sys tem isgivenin{ll iISl ar k.

Ill ifSlfld ---== = = _

slnck': seqOBJeCT

#!<lf1f~k':5mer ,. Iac k'= ()

The eigniflcenceofthedash (') is explainedinII.latersect.ion. Since () isthe empty sequence,/" jISIrlf'k requiresthatthestack isinitially empty.

2.3 .1 Schema Reference

TheIl! itStllc~'sche ma mayberewrittenusing amechani sm cal ledS,.f/f"/II/l"F,.·

CflCCwhich enablesZspecifica tions tobeslr uclu red in a modularIaahicn.Below, twofeat uresof this mecha nism,df'I'om/iflllandi"dll.~iIJlj,aredcacrlbed .

Systemati cDecor at ion

Within therevised version ofIIIitS/III:!.:shown below,the schema nameSlll,k appearswithaprime ('); this is anoperatio nonschemescalled,kf'{Jl"/l/ifJII,Es- eentially, anydecora tionthatisapplied on thename of nsche me.isinherit edhy

13

(34)

itscomponents.

SchemaInclusion

By includingSilld..'in111ilSlflck,the variablesand predicates of the former are includedin the declarationandpredicateparts of the latter ; thevariablesare merged and the predicateeareconjun cted.

Usingthesefeatu res, theschema/lliISI_tlckmay be alternat ively andmore economicallyspecifiedas

~

Shick'.~I (l d·'=()

2.3.2 Showing Existenceof InitialStates

Itismeaningful to check that an initial state does exist,and wemaydo so by first expressingitas a theorem.

3Sluck'.h,i fS/rlck

Thisis equivalent to proving

3.~II/ck':seqOIJJECT#.~Iflck':::;ma.Aslack'

=()

whichis triviallytruewhenslack'isanempty sequence.

14

(35)

2.4 Operations

Anoperationismodeled as a8111lrrlw ",qrbydeclarin gILsche maconta ining before-andaflcl'•.~lalr v(ll'iablr.~.which ind icate't hestatesofthesystembefore and aft er the operationhas takenplace.Byconventio n, the before-va riable snrc unprim ed whilethe afte r-variab les areprimed ('),andthe slatechangeoflUI opera t ion is speci fiedbydescribing therelationshipbetween these variables.

2.4.1 Th e .6. and E Conventions

Before specifying any operatio n,itis co nve nient towrite schemes lhlLlsuggest a possib lechan geand no change inthe stateofthesystem.Dy conventio n,tile na mes of these schemesst art-tit h t:J. andErespectively.

[" SIOOk Slack Slack'

The schema6.$lacksuggestsa changeofthestoc ksincetheschemadocs not contai nanypredi cat eto const rain the val ues ofthestate '..ariable s.

'E.Slnck

~ $'OOk

Stack'

sIack'=sta_,k _' _

Theschema'E.Sla ckindicates a no cha nge during the ope ra tionsince the sche ma contai nsapredi cat ethat requirestheaf te r-valueofthe stackbethesameallits

15

(36)

before-value.These schemes are usefulas short-hands for specifying opera tions onthestack.

2.4 .2 Specifying Operations

Using6Sl llf :1.:and3.Sl m:l.:,theflush, llOP,and'011operationsof the stac k may

/lOWhe succinctlyspecified.

Pus h ing nilEleme ntOlltotheStack

The eym bolC isthe operator for sequenceconcate nation,and(object?) is the sequen cecont aining onlyobjrd?

f"I .~II ()J.: _

liStrlck obj.-rf?:OIJ.JEC'I'

#.~tal'J.:<II/II.!

,~I ,II'/.:'

=

,~lllrk'"(obj rd ?)

The schema1'111'1101.:describes theopera tionofpushingobjed?onto astack.

The va riables in/'1I,~h ()1.:consistof thebefore- andafter-variable swhich are included withli.Strll'k, andan input variabl eobjccl1which,byconvention ,ends with a questionmark.

Itisoflen recommen dedthat thespeci fication ofanoperation document ex- plicitly theplH'ollllifioll, whichstates thecondition under which the operation IIIlLybeused. Typically,thepreconditionappearsas the first predicat einthe

16

(37)

schema. ForI'rll<1101',this requires thatthestackcontainslessthnnmu.rcle- ments,i.e.,thestackmustnorbefull.

Theactualpus hopera tionisdescribed asthe after-st ackbeingtilesntuell~

thebefore-stack with theinputobjrd?concatena te d toitsend.

PoppinganElementoffthe St ack

~~;'~~.---_._----

s/tlck

t

0

sltlck'= I/'QIII sl llc k

The Z specification lan gu ageincludesaIIIrlllH'lIwfinl!I"nlhlwhich is n (··llt"C- tionof predefinedmath em aticaltyp es and primiti vesthat allowslIpcc ificntio ns tohe bu ilt inacompact way.For sequences, thetoolkitconta insnfunction11\"'" ' thattakes a non -empty sequence and returnsthe sameseq uence withthelast elementremoved.Using/1"0111,poppingan clementoITthestackisdescribedas takingawayits IMl element.

17

(38)

Inqui ringtheTopElementoftheStack

'I't']IOi.' _

2.Sltlr k nbjcr:f!:OfJJeC T .~l/lr.i.''I:0

tlfJj rr/ l =/al</ fll a ck

TheschemaTopOl.:describesthe operationofreportingthevalueofthe top elementinanon-emptystac k. Therequirement that thestacknot hechanged is sta tedby includingas/ucl.:.Theoperatio n isspecifiedusingthefastoperato r, whichlakes anon-empt ysequenceandretu rnsthe valueofthelas telement of thesequence. Thisvalue isrecordedinthe output variableobjecl! which,by convention,endswith anexclamationmark.

2.5 Preconditions

The precondi tionofan operat ionmustbeproperlydocumented sinceitsta tes exactly when anopera.tionshould beused.When an operat ionisinvokedunder it:; precondition,thespecificationrequiresthat itter minat es in a statethatsat- isfteethepredicateswritteninthe schema;ot herwise, itdoesnot say what is to happen,i.e.,the operation'sresult isunpred ictable.

The precondition of anoperation describesallthose before-sta tes fromwhich nn after-stateisgunranteed. Often,animple mentationofan operat ionassume s

18

(39)

thatitsprecondi tion holdsonthebefore- stales,whichIllca n5thatthe result ing programmaybeusedappropriately only under thecircumstan ces depictedin theprecondition. This stressesthe importanceofcorrectlydocurnent jngthe precondition [461.

2.5.1 Calc u lat in g Preconditions

InZ,thepreconditionofan operation0/1isdeno tedpre0f"andis calcllln.tclll,y IIirliligthe after-state and outputvaria bles.Thisisaccomp lished by exidentinlly quanti fyingthesevariablesin thepredicat epart ofOJ!.As an iIlnslmlioll,thc precondit ion ofthe operationOJ!iscalculated below.

FF s

v:ino

""

V _

0"

~ "s;;,;

x?:y!:PrcdXy _

Assu mingthatSinleisthe staleschemaofthe system, pre 0/1isthe schema obtainedbyexistentially quanti fyingtheafter-andoutputvariables,,' lind,IJ!.

19

(40)

When mentioningtheprecondition of anop eration, wecommonlyrefer to the predicate in the preconditionschemaofthe operatio n.In the case ofOp,thisis

3Slfl lc ' jy!: Y.P1'cll

whichis equivalentto

3v': ViU!: YIi/ltl'.PI'"rI

wherei/lll'isthe sta leinvariantwith allthesta te variablesprimed".

2.5 .2 SimplifyingPreconditions

Precondit ionscalculated inthis way oftencontainext raneous detail s whichmay beeasilyeliminated , Wood cock suggests two strategiesfor simplifyingthese predi cat es {461.

TheOne- P ointRule

The first tactic uses theso-calledone-poi ntndcwhich states thatthedefinition ofa variable may besubstit ut ed forthe variable itself,Insymbols,thismay be exp ressedas

wit h thecondi tionthat.ris not free interm, I Note thaltile liseof thedlLSh (')rori"vb notstn nd n rd.

20

(41)

For sim plifyingprecondi tions,thisruleis often used when en OUtPl1torafter- va riablehasan equalityconstraini ng itsvalue.Thisvalue may be eystemnticnlly substituted (or allits occurrencesand its quantificationisthendropped.

AheConditional-Rewrite Ru le

Thesecond tacticis sum marized in the following"lI llIlilioll ll/ - 'l 'll'l'i /I'1'1111,.

IrAQ) .. I'

Thisrulesaysthat,forpredicatesPandq,ifI':=?qis !.rue,1I1cIIJ'IIqmay be rewrittenasP.

Simp liflingthe Precond it ionof"oeO!.:

'I'hepreconditionofPopOI.:is calculatedand simplified usingUl(~one-poi ntand conditional-rewriterulesasshown below.Bydefinit.ion,preI'II//O!.:is

3slflCk':seqOB./EC1'II

#.q/fl/:k' :5WflJ: II.~/fI('!.:i= 0II.,I IIf·to'= jlYml., I//r-/.:.

Sincesi nckis free,itmaybe moved outsidethe quantification , andwe have

.;::. (3s/nck':seqOIJJEU T•

slflck'=!mll/..,/m ·kII#J</flI'k' SIIIfU )II,,/1lf·k'I ().

Usingthe one-point rule,,~I(lc!.:'may be substitutedwithits definitionof/111111.~IIIf:k, and we have

21

(42)

Table2.1:Thepreconditi ons ofPll.~h Ok ,PopOk,andTopOk.

¢} #([mllfRinck):::m/lrA"'Incki:

O.

From thesystem invariant,weknow that#$/nck :::maXitherefore, it iseasily proved. UlI!. t.~/flf'ki-

0

=>#UIUIII.slnek):::I/IfU.Usin gthisin conj unction with theconditional-re writerule,thepredicat e#(fmllt.<l/lck)$maz AsIne/,:i: () may be simplified as.~Ir/{·ki- (),andthe final step ofourproofis

¢} i<larki- {}.

Similarly, thepreconditionsforPI1.~" OkandTopOkarecalculat edand they are collecte d in Table2.1.

2.6 Proving Properties of Systems

Allmentionedin theprevious chapter, a formalspecificationmay beusedto prove importantproperti es of thesystem.In this section , we describehowthe last-in-first-outproperty ofthe stackmaybe shown.Thisuses thesequential compositionoperator;which is describednext.

22

(43)

SequentialComposition

The sequentialcomposit ionoftwooperationschemes,(jilland01111IILaybe understood as a schemadescribing the operationofperforming firstOf/land then0p2.Theschema.0/11 ;DpJis obtained by"comb ining"O}IIandO"'llwhere the after-variablesof 0PI andthebefore-variables of(}IIJnrcbothCq llll.te tlwith someintermed iatestatevariables.IfSIIIII'is thesche madescribingthesysLem sta te,OPI ;Ol'lisdefinedas

3Slfll c".

(3SI /llc'.[Opl;SIIlII'"1OS/oil"

=

(JS/II"'''])1\

(3SI /lf c.[OfJJ'SIIIII'''1OSIIIII'=1' :"/" , .,,,])

whereOSIIlicmay be thoughtof as thetupleformedfromtheslatevariahl(~s['121.

ShowingtheLast-In-First-Out Proper tyoftheStnck

Thelast-in-first-outpropert yofthestack maybe shownbyprovingthatthestnd isrestoredtoitsoriginal conte ntinasequenceofl'I/.~1dJkandJ'III,Okopera tions, provided thatthestack isnotfulltobeginwith.Insymbols, thisill

VShlCk,SI/lde'1#.~{IU:J..·<1l1a J'. P!l.~hOk;PO/10k=>1</1/1'1:=.~llIrk'.

Assumin gthe invariantsin.<il'll,kand 81111'1.:',andthe conditionI/-.,'lfu"; <

" 'fiX,theproofmayproceedwithstating

PII••hOI.:;PO,nOI.:

23

(44)

which,by definition,is eq uivalent to {:} 3,"'1,1/"":"_

(3Slar:k'_[P'IfIOk j 8/(I(;/':"I,'( Uf'/.;'

=

.~la,:k"J)A (3Slfll:~·IPUHhOkjS/ud·1IIslad

=

.,tuck" ]).

Aflcrmultiple application s oftheone-pointandconditio nal-rewrite rule,wearrive .t

whichmnyhe simplified as

since,byhypoth esis,$la,·I,·i-

0

is true.

2.7 Errors

The schemesI'rt.,/,m·,flopO~',and TopOkdescribeonlysuccessfuloperations.

Forinsta nce,forI'II.,/,Ok,the specificatio nsays whathapp en swhen thestackis not full,but itdoesnotindicatewhattheprogramshould doifitisfull.Inthis sense,the operat ionsareil/cOIllII/e/c.

Sometimes,itis desira bleand possibleto specifyoperat ions50that they ruemo re ap plicable,end thisoften requiresthe specificat ion toinclude what should happenwhen anoper atio n isinvokedunder condi tions forwhichitis not intended.Typically,thisis achievedby making theoper ation do somesort of I'rm ,. /t llll d lill ! / .

24

(45)

2.7.1 Reporting Errors

Theoperationsofthestackcanbemodifi ed sothatthe stntU$oftheexecution ofeac h ope rat ion isreportedinavariab le1'f.~II/I !.'Threetypesof messagesarc used:(l~'tosignifyasuccessfuloperation,l'//ljllyandf,,1/torepurtemp tyand full stack respectively.

Free TypeDefinit ion s

A[rcctype dcfillitiQ/Iallows Ztodefineasetwit hcertai nobjects.Thisis\'~ry usefulfor defininga typeand itselements. For example,wctunydcflnethe set REPOR7'consist ingofthree elementsfI~"rllIl"!J,andflillwiththefollowi ng Ircc typedefinition.

RBPOIlT::=okIr:mp/yIt-u.

Reporting a SuccessfulOperatio n

The setIlEPOfl 7'may nowbeIISedin the sehemuSllf'f'!'I'I' ,whichdcscrillCsthe operationofreport ingasuccessfuloperation.

SIlC('r.~s

~'=POI/T

~- '

- - - - - - - - - - - - - -

Report inga Full Stack

Forexample, wecan rep orta fullstackasfollows.

25

(46)

Slw:kFitll _ zsi;«

1l:,<"l!1!:UB/'OIl T

#"~lrj/;k=/(w:r.

1T'.'1Il1t!=/rtll

InS/rll"k FlIll,IY',~II/1.!isgiven the value/ fi/fwhen thestack reachesits maximum capacity.Itfurther requiresthat thereshould benochange in the stack.

H.eporting an EmptyStack

Similarly,reportinganem ptystackcan bewritt enas

_SIIlf' kHw ply _

S,','IIIf:I..·

1"\~ II II!:IlE:POll T .~/(lrk= ()

2.7.2 Sche maCalculus

Dneof thepowerfulfeaturesof Zthat makesitappropria tefor writingspecifica- tions of large systemsisitsechruia mlcviuswhichenableslargerschemes tobe formed by combiningsmallerschemes usingIlchcma connccti ocs.In the following, twoof theseconnectives,Aand V.areusedtobuild astrongerspecificati on of the stac k operation s.Using theIIoperato rontwoschemas mergestheir declarations

26

(47)

andconjunctatheir predicates,whilethe Voperation hasthesnmeeffectexcept that thepredicatesare disj unct ed.

Schema connectives areusefuloperato rs inthntthey allowpartsofnspecifica- tionto beconsideredsepa rately. For instance,forour stack, thespccilicnt ionsor successful operation s anderrorhandlingare consideredseparately andtheseIUl' thencombined,usingschemaconnect ives,toform a morecompletespecificntio n.

2.7.3 BuildingStrongerSpecifications

Usingschemadefinition(::::), the newschema1'0/1isformed,lirstbymaking a SdlC1ll11cmrcesionfromthe conjunctingof "(}/iOkandSI/f'/'/",_,whichisthen disj uncted withSlackBlIl/lly ,

The schemaPopismade expli citbelow,

POI' , - _

Slack Slack' rt.mll!:HEPOR?,

((,'oc' " ().,

slac k'=11'0111 "lllckA l'('Sllll!=Ok) V (.,'l/llck={) A

stric k'

=

'SluckA l'C"ull!=cm rll y))

Thespecificationsaysthat whenthestac kisnot empty,it ispopp ed anda 27

(48)

messageindicatinga successfulopera tio nisreported, andthat when thestackis empty,it stays the sameduring theopera tionanda message indicat inganempty stackisreported. Similarschemes for thepushandpop operatio nsare defined

l' u.4.==(I'11I,1I0 kAStl rcf.~fI)VSlackPllll TOile('trIIIOk ASIl.:r;cs.~)VSlackEm"ly

Precondit ion sRevi sited

Itwould be convenientifthepreconditic.rofthe larger schemascould be eeleu- latedfromthepreconditionsof thesmalleronesfrom whichit isbuilt.In this sect ion,wegiveafew suggestio ns on howthismay be done.

Sincetheexistentialquantificatio n distributes throughdisjun ction ,the pre- condit ionoperatordistributes throughdisjunctionaswell.Hence, thefollowing equivalenceistrue.

The situationisnotso simp leinthe case of conj unctionsince theexistential quan tificutioudoes not generally dist ribu t e throughconjunct ion. However,ifthe predi cates in0/1,andOP1areP,andPl ,and the variablesconta inedinPIare disjoint from thoseinP2,a simila requivalencemaybe established.

28

(49)

Operati on SlocH'ull Slllr~' /~'/IIp'U POll

I'll.'"

Top

~~,~~~.}~

.4f1I'k= O 11'111 //'I/I trur

Table2.2: Thepreconditionsof.'iIIUk" 'U",Sl m-kHII'I'l y,I'nll,I'll .•h, ami'li'I'.

Usingthese results,thepreconditi onsfor theremaining operatio nsarc cnlcn- luted andrecorded in Table2.2.Not ethat thepreconditionsof1'''/'' l'II., h , ami T01)areall[I'IIC,implyingthattheymay beinvokedinany stat einthe stale spaceofthesystem;such operati onsarc knownas/01111operation s.

2.8 Summa ryand Bibliogra phicalNote s

In thischapt er.wehave attempted to give a practicalguidetotheZspcciflcntiou language.In particular ,wehave presenteda convention ofepeciflcatic n which views a systemas anabst ractdata type.Usefulinform ationon provingsystem properties,calculatingpreconditions,and error-hand lingisalsogiven.

2.8.1 SomeUs esof Z

In recentyears, therehavebeen numerousreports of thesuccessfulusc of Z [8,1:q.

Inthefollowing,wehighlightsomeoftheserecent efforts.

29

(50)

SpecifyingNew Syst ems

Z hasbeenusedtodescribethe developmentof bothsoftware andhardware systems [3, 11, 12]. In[6], Z isusednot onlyto designnetwork services, itis alsoused to producethe documentati on.Bowenindicated thatthe use of formal metho ds canlead.to a simplerdesignand morethoroughdocumenta ti on [6].

~ifyingExistingSystems

By thespecificationofexistingsyste ms, Z hasalsobeenusefulin revealing incon- sistency and incompleteness.In thepost-h oc specification ofareal-t imekernel, Spiveydiscoveredadesign errorwhichcould havebeen easily avoided by using formaltechniques [41J. Thespecification of window syste ms by Bowenrevealed omissionsand ambiguitiesinthe documenta tion [7,9].

The existence of a formal syntax andsemantics for Z implies that it may be amenabletomachineanalysisandmanipulation. This suggeststhat Z,ora subsetofit,in conjunct ionwith anll/!imll/ol' couldbeused as apmlot ypillgtool, Althoughthere are some argumentsagainst making specifications executable(17], therehasbeensome effortto provi deZ with an animator \14,23).

30

(51)

Even when a program is mathematicallycalculatedfrom a Ionun lepeeificatiou, unless the development steps are guarantee d to have been performedcorrectly, thereisalways aneed to performIr.,lilly.Hayes and HallsuggestSOIllCtechniq ues for testingbasedon Z specifications[rs,16).Hallalsodiscussesthepossibility ofautomatic allygeneratingtest casesfrom specifications writteninZ

1 1 61 .

31

(52)

Chapter 3

Data Refinement

Thespecificationin Chapte r2modelsa.stack withasequence.Alt houghmathe- maticaldat a types, likesequences,are ver y expressive,their operators maynotbe readily available inthe target progra mmi ng lan guage.This chaptershowshow, using dat a refinement , datatypes thatare moresuitable forimplementation ma.y beintrodu cedinto thespecificat ionof asyste m.

3.1 From Specifications to Des ign s

In our approach to softwaredevelopment.thetask of produ cing a concretedesign from anabstractspecificationisknown asdataI'cjillemCllt.A proced ureforda ta refinin ganabstractspecification in Z isgiven in[42,45].Thisinvolvesprop os- ingconcretestates andoperat ions,and proving thattheysatisfy theabstr act specificat ion.

(53)

3.1.1 Abstract Specifications

Specificati ons like theonein thepreviouschap te rare1111.~lnll'Illlwl'ijit·t1li/lIl.~since theycontai n datatypeswhichusuall yare notdirectly implement able. Toget her with the ir pred efined ope rato rs, thesedatatype s allow thefeetures ofsoftware syste msto bedescribedcompactly.Furthe rmore,sincetheir math emati calprop- ertiesarewell-known, they allow easy comp rehe nsionofand reasoning aboutrho characte risticsofsyste ms.

Alth oughabs t ractspecificatio nsare usefulin providin gagood understand ing ofthesystem,theyaregenerallynot goodsour cesfro m whichto produ cenn implement at iondirectly. Thisis sobecausethey cont ain mathematical dat il.types which are inefficient, or arenot easily ccnstruct ablein thetargetprogram ming languag e.

Ex ample 3.1Considerasystem that isusedtocalcula tethemaximum of a setofint egers ,whosestatespaceandinitia lsta tes may be specified asMil./'and /1Ii1M":l.

Mox_---:-, - _

[lIumbcrs:PZ

/JlitMax I;i~~;--

~-' {}=---

Theset of integersmaintained by theaystem iscont ained in'1II11tllr.r.~whereP 33

(54)

is the power setoper ator,andPZisthe set of allsetsof int egers.Operati onsfor entering a number and findingthemaximumaredescribed ineulerandFimlM(/. x respectively.

I,,'nl ,'r

~

1Il1/llbl:r ?: Z

IIllIn!Jr:rH'=

1I11mbcl'J;U{1l.11111i1r,.? }

HIIIIA!n3 _

EAhu I/uu:iuw/1l!:Z munbcr«of:.{}

IIIfui mllm !=1/1(/.3llllm bers

o

The operatio nsin Example3.1are describedusing thesetop erato rsU(set union )andII/(/.J(maximum numb erin aset).Sincetheproperties ofsets and theirope rators arefamiliartomany,the features of thesystemmay be understood quicklyand clearly.

Althoughsets are very expressive,theyarenotreadily available in some pro- greuuninglanguages[e.g., C).Thesyste m asspecifiedabovealsohasan ineffl- ciency:since weareonly interest edin themaximumof theset,there isnoneed tustore theothernumbers.To overcomethis inefficiency,anothe rspecificatio n calledII.designmay beproduced.

34

(55)

3.1.2 Concrete Des igns

Like anabstr act sp ecification,1\('fllllTflr11"l'i!/11gives n descript ionoCthe sY5tcm;

however,italso conta ins da tatypes thatareoriente d towards compute r process- ing.The statesandoperatio nsdescribedina designarc concretesincetheycan berea.lizedinthe targ etprogramminglanguage.

Inthenext exam ple,weshow howthe concret estal esamioperat ions ora concretedesignmay beproposed.

Exa m p le 3.2Assu ming thatthetarget programminglanguageallowsImolean and integervariab lesto bedeclared.aconcre te designferthenbstrl~ctepcciflcu- tion of Example3,1is givenbelow. The concretestatespace andiuilill.1 slalesof thesystemare describ ed inMarCand luillllllrG ,respectively.

BOO/JEAN::=lmeIftll.~I:

M", C '-,_ -=- _

I"

;~~NlJlllbe7':Z

~"'IIIy :nOOfJSAN

/lI illlfll:tC _

r ;w;;,C;- --

~=-"'-'''---

Asmentioned previously,the syste m needstokeeptrackoConly onenumber, which theconcrete version stores intheinteger variabl e1Il1uNul/lbn'.TheSYII- tern alsomaint ainsa booleanvariable.~d Bmptytoindicate whether any number

35

(56)

has been inputinto the system.SchemesE" /tT Ca.ndPi/IdA/ru edescribethe concreteoperationsofenter inganumber and findingthemaximum.

8/1l c/-(,' _

6MtUC /llIl11b",.?:Z (.~r.l811111Iy=f/'llCA .~c1BllllJl yl=f(II.~"A IIU/:1:N ll lll bm"""l!tllllber?)

(sd81/tIJly=[olsc A sdEwl/ly '

=

.~r.lE:/Il IJlyA

(( Illlll/VCI'?>IIlll.lN'lfIlbel'AmnJ:Nll mvcr'

=

lIltIllVer?) V

(,III/11I,t:I'? ::;fIIt1rNumvcl'/II/InJ:N lt mber'=JlUI.l'NulIlbcr »))

Theconcreteoperat ionBlllcl{.'checks whethera new numberisgreate rthan the current maximum,Ifso, thenewinputisretainedas thenew current maximum.

~~~:~~~rC---_

IlIf U ;/11 11111!:Z

IlW rilll lllll!=;mu N lImbtT

The operation of outputtingthe maximumissimply to reportthestored number . o

The incorporationof implementationdetails makr-sII.specificationa ..-kwerd as isapparent from comparingBII/crand BIlIClCofExamples3,1and 3.2.The main advantagesgained from a datarefinementare storage and algorithmicefficiency

36

(57)

and thegreatereaseofimplementingthe datatypl'Sin the targetIlrOp atll1u illg langu age.

3.1.3 RetrieveRelations

i!ll1al'i all l.is a schema whichformally documentstherelationship betweenthc abstractand theconcretest ates{451,Itcontains boththeabstractandconc rete states and further includespredicatestodescribethe relati on between their :;tatt' variables.

Examp le3.3 A retrieverelationMllrllforthe abstractandconcretestatesIIr

Examples3,1and 3.2is givenbelow.

The retrieverelation says thattheboolean variable.~d HIllf!I!Jisused to iudi- cetewhe therthesetis empty.Italso states thatthemaximum nmnher inthe set is the valuestoredin concrete variab leIllIU N llmlxI',

Document ingthe retrieve relationis importantas it containsthedesigndcci- sienathat aremade during datarefinemen t andthesedecisio ns allow the alJlIlmcl

37

(58)

to berecoveredfromtheconcrete.Using thisrelation,we can prove thattheeon- cretedesign satisfies the abst ractspecification.

3.1.4 Proof Obll gatlc.is

The proofobligationsrequired to showthata concretedesigncorrectl yimple- mente an abstract specificat ion aregiven inthissection.Forthis,assumethat theabstr act specificat ioncons istsof ast atesche maIlS.aninitialstat eschema III;I/IS,and anoperation schema 110 /1,andthat thecorrespondingdesign con- lain sastateC:"aninitial st ateIlIilCS,andanoperationCOp.Bothofthe ope ra tions110 /1andCOlihave inputx1 :Xand output y!:Y,and theabstract and the concretespecificationsare relatedbytheretrieverelationlictr,

The proofobliga.tionsforda.ta refinementmaybedividedinto three kinds:

i/lil/u/."'n'!'.,,,II/lplirn b;lifyandrOrlY.'c1/1ess .The proof for initial statesneedsto beperformedonly once,whiletheproof sfor applicabilityandcorrect ness must be performedforeachoperation.Theseproofrequirem entsare describedbelow.

Theimplement ed syr te m must startinoneof thestates thatare prescrib edin the abstractspecification;assuch,each possible initialconcrete state must repr esent a possible initialabst ract state.Symbolically,thisiswrittenas

VC,'.

I/li/C ,=>31lS'.'lIilASAHar', 38

(59)

The dashes are necessary because,by convention,the stll.tevariablesin1,,;t('S and!1I ;tA Sarc dashed.

Notethatwith thisrequirement , weare allowing fewerconcreteinitial stall'S thanabstract states. Thisis accep tablebecause ournbstrec tspecificat ion insists onlytha tthe syste mstart in(//Irorthe initialstates;as such,wedemandonly thateachconcreteinitialstat erepresentsalegal abstr actinitialsta te.

An im plementedoperat io n mnst be atleastasapplicableas its specifica tion.

This mea ns that whenever thepreconditi on orthe abslractoperat ion is satisfied, the preco nditionof itsconcreteversion,asrelat edby theretrieverelation,must alsobetrue. Symbolically,thisis writte nas

VAS;CSjx? : X_ preAO/JARell '=*preCO/I.

Sincetheprecon ditionof the concreteoperationmay bemore generalthan the preconditi on ofthe abstract ope rat ion, the concre teoperat ion may heused in more sit u ations.As such,the concrete operation mayhemore applicablethan its abst ractcounterpart .

Since theprecondition ofan oper ationdescribeswhenaterminatingsta te is guaranteed, the applicabili tyrequire ment says that irtheabstract operati ontee-

39

(60)

minatea,its concrete ver sionmust also doso.An additionalrequir ement forthe concre teoperat iontobecorrectisforitto term inate inII.state thatis agreeable toits ahstract specification. Sym bolically, this iswrittenas

VAS;CStG~";x1 : X; y!:y_

pre110 11AHct rfICOi':::}(3AS'_IIOpARei,.' ).

Thecondition may be underst ood1L5:if theconcreteoperation wer eto beinvoked undertheprecond ition ofitsabstract specification,itmust produce aresult that is withinthe requireme nt s ofitsabstractspecification.

Exa m ple3.4The cond itio nsrequired toprove thesatisfiability of the con crete design in Exampl e 3.2are given below.For the initial states,the requiredcondl- nonis

VMII.rC'_

III;rM n.lC :::}3Mnz'_l"ifMfI:!'AMnxR'.

tilorder to show theapplicabilit y of theconcrete operation s,we needto show

vMfUjMlu C;llumber? :Z• pre Bill eI'AMn.lR:::}preEllierG

and

VMil,,;l\ huC.

preFi;IIIMn.rAA!nxR ::::}prePillniHn;rG.

Thereq uirements for thecorrec t nessof both theoperations are 40

(61)

Ta.ble3.1:Thepreconditio nsofthe operations1~'IIIl.,.,filltli\l ll.l:,1~'II'r r(',nud FilldMa,rC.

VMllx ;uoc , IlliuG';IIIll11brr?:Z.

preEllierIIAhullII1~'/ll f;l'C ~(3MII,r'.I~'II"'"IIMIIJ'Jl' )

and

VMaT; MaTe;1\1(1xG';1I/11,1';IIIII/I/!:

z ,

preFilldMaxIIMa:rU1\"'il/tlA/tuG:;:;}(3MI/:r'.Fi"rli\I,l.I:IIMill'''').

a

Examp le3.5Wedemonstrate how theproofobligationsfor theconcreteopcr- ationEnlel 'Gmaybedischar ged.Its precondit ionmaybefoundinTable3.1.

Sincethe precondition ofEIII.erG'is true,thecondition

preEllieI'IIMruR::::;. preBltlc,-{]

istriviallysat isfiedand theapplicabilityofEllled}is established .

41

(62)

To prove correct nessofEnICl'C,we needtoshowthat

"IMllr; Milr e iAftlrC';Ill/llllier?:Z.

preBlIlel'AMWEUAElilerC=>(3MIII'EnterAMllx/i').

Fir st ,we simplify the consequent of the conditionwhich is 3Mar'.Elllel'A/I·faxR'.

When expanded, thisyields

<=} 31III1I1bcl~~':Z•

1IItIll IicI"~'""1Ium ber..U{lIl1l11bcI'? }A IIf:lBm ,JI,,' ""lnle<=}1I11I11bc1"j"= {}A mar'""I/ ben'

=

IIlIu:Num bel".

Usingthe one-pointrule,we may elimina tenllmbers'andarrive at

~ RdElll p l,,'=!-I I"lC/\

IU,U(Will/be/'llU{liltln ocl' ?})=IIIflxN ,lm bel".

Thissimpllhed form of theconsequentis substit utedintothe originalcondition to yield asimpler requirementfor correctness,which is asfollows,

MarH/\

eo-«:

=>

IIrfBmJlly':f.II'/If1\ma.r.(llIllllbC1~~U{I/ll mb er ?})=maxNtHliber'

We have omitted preEuterfromthe conditionsince it istrue.

Wemay nowproceed to establishthe new correctness requirement .Analyzing the differentcasesinelltrrC,the premiseofthe requir ementmay berewritt en as thefollowing three disjuncts after a few stepsof logicalmanipulation.

42

(63)

(MIuRA sciEm ply

=

IntrA sdElIlpl,,'=frd.~(;A IIlflrNltl/lber'=III1IUI,e,.?)

(MarR A srl ElIll'ly=fafsr1\

sriEmply'

=

_~clf~'m/II!JA IIIWd,CI'?>marNIIIIII,rl -A lIla:tNllllll,c'.t= IlIIlIIbr,.?)

(MarR A selEmllly=[else1\

srlEmply'=sclElII lllyA '111m/itT?:=;maxNllIllbr,· A maxNlI mlicl.t=IIIfl.r:NlllllbeI·)

Separate ly, eachofthesedisjuncts may beshownto imply theconseque nt .We show theexerciseforonlythefirst.Fully writin g outthefirs tdisjunct , weget

(sclEJ/I/lty=true~lIWIiI,c".~:=0)A lIIaxIlIllIlber."=II/1lxNlIlIIbr.I·A sclE lIlp l.y =lrnc/I seIElII]/ty'=falseA lliuxN umbel-' =TWlIlller?

Substitut ing thedefiniti onof.~rlEl1lplyan dleavi ngoutthesecondconjunct, we have

selBmply'=falseA Illtmbe I'8={}A lflaxNu mbcI" =/III/fiber ?

Using the propertie sofJIlruandsets,weha ve 43

(64)

,~d E"qll y'=ftdw:1\

lIulIIbtf'N={}I\

IIlfUN1l1ll br.I"

=

mllX{1I1Imlwr?} .

Usingapropertyofset, weget IIt:lBlII/Jly'=fRl~ r.1\

11"IIIIIr.l"~={}A

IIlfuNllmbtr'

=

IUIi X ({}U{" umber?}).

Substit uting{}for11111I1bc,;~,wearriveat :> .•dEl/iI1l y'

=

fal,~c1\

rl/lu:N lllllbn,1

=

IIlIlX(ul/ lll bcr8U{/lu mber?} ).

And,since 11'11(:=Ffllliu~,thisim plies :> .~dBlIl l! l y'=F11'IIt 1\

!JIIIxNllmbt,r'

=

mllx(1IIIIIIbcl'8 U{llIImbel'?}) whichisexactly whatweneed.

3.1.5 Proof Obligations forFunctionalRetrieve Relation

Each concrete statefrequently represent sexactl y oneabstr actstate,andthe retrieve relationmaybe viewedas a total function fromconcrete statesto abstract states.Whenthishappe ns, the retrieverelation is termedasbeingjUllctional.

Simp lerproof obligatio nsmaybeusedwhentheretrieverelati onisfunctional [42,45). Theeendi rionsfor initial statesandcorrectness areeasiertoprove althoughtherequirementfor applicabilityremainsthesame.

44

(65)

VAS';CS'.

Ill il es1\!/rll"=>l"il,IS

VtiS ; CS;J? :X• pret10 p l\lirl,.=>preCOp

VtiS;AS' ; CH;CS'i-.r:1 : Xi y! : \'• preAOp1\ReiI'1\COp1\"df'=>tlO/1

The mainbenefitforusing these isthattheexist entialquantifiersmay beavoided.

3.1.6 ProvingRe t r ieveRela tions tobeFunct io n al Inorderto show thata retrieverela tionisfunctionalwe need to prove

'rICS.31AS.Rctr,

As indicatedin[451.a sufficient con dition forprovingthata retrieverelat ionis functional is toshow that there is an equat ion thatdefineseachabstractcornpo- nent 'svalueintermsof concretecomponents and total(unctions,

45

(66)

3.2 Case St u d y

In the follo win g, wedescribethe da.tarefinem ent of theabst ractspecificat ion of thestac k fromCha pte r 2. This exam ple complemen ts th eone inthe earlierpar t of thischapterasitcontai nserro r han dlin ganduses schemaconnect ives. For convenience, we assumetha t thedatatype s used heremay befoundin the target pro gram minglanguage.

3.2 .1 ConcreteStates

Thestackis implemen tedby usingan array ofmax cells,eachof whichstores an element of typeOBJECT.An integervari abl eis also inclu dedtokeep track of the indexofthe topelement inthestack.This conc retesta teisdescrib edin Starke ,

SllJckC --,----,----,-- _

.~lackC:l..max->OBJECT lopC

.z

os/ ope :::;mar

The array inourstack ismodeled asatot alfundionwhosedomain is theset ofconsecut ive integersfrOID1tomax.Theindexof the topelementof thest ack isgivenbylopewhichshouldcont ain 0 whenthestack isempt y.

46

(67)

3.2.2 RetrieveRe la tion

The next ste pis torelatethe abstract and concretestates .Thisis done inthe schemaSiackR.

~:::Zli---

__--- - - - - - - --

SlackC

slack

=

1../opC<I.~lackG

Usingthedomain restri ction symbol<I,theexpr ession1..111/1(:<I.~IIlI:k(.'yields a functionwhichis thesameas.~lackC,except tha tit is onlyvalid forthedomain l.,lop C.Sincea seque ncein Zis define dasa.functionwhosedom ai nisaset of consecutivenon-zeronatura lnumbersstartingat one, thepredica te inHilu H f requiresthesequenceslacktohavethe sameeleme ntsasthe firstillJIGcells of arraystackC.

Note that exactlyonevalueofsiad :may bederivedforeve ry value ofthe concre tecomponentstopeandslarke .Hence,weknowfrom thediscussionin Section 3.1.5 that theretrieverelation isfunct ional.As such,thesimplerset of proof obligations maybeused.

3.2.3 InitialCon cret eStates

TheschemaIniiS lackCwhichdescribestheinitialconcreteslatesrequires that theindex oCthetop elementbeO.

47

(68)

F$¥S-

' f1S/ru:k C'tOll C 'iISIIlCkC=0 _

3.2.4 Pr oo fObligat ion forInitialState Theproofobligat ionfortheinitial stateisstated below.

VSlrlCk'jStncke '.

hi/SftlekeASlackR'=>lnitSlack

The proofmaybecon ducted asfollows .Fromlui/Stacke1\StackR',weknow thatlop(,"

=

0 A.~I(lck'

=

I..fope ' <l.d ackC '. Substi t uti ng0for10pG'in the equation for slack' ,we arriveatthevalue of an empty setfor~I(lck'.Thisimplies

that.~ I (lck'isanempt ysequence and this is exactlythe predicateinInifSlack.

3.2.5 Conc reteOper ations

Asfor the abstract specification,the schemest::.SlackCandBSlackCare also definedfor theconcreteoperations.

ASlllr~'C _

[ SIIlt:k C

~flll~kC'

25/(lI:I.:C _

ASfllCkC .~lfu:kC=';/(lcI.:C' /opC=lopC'

48

Références

Documents relatifs

If an abstract graph G admits an edge-inserting com- binatorial decomposition, then the reconstruction of the graph from the atomic decomposition produces a set of equations and

Therefore, the web service response time behavior is modeled us- ing software performance curves, which are automatically generated using monitoring data collected during software

Receptor Likely Substance Suggested reference standards Surface Water Ecological &amp; Chemical Status. Aquatic ecosystem Any pollutant which causes risk to a surface

Historical materialism, thoroughly modernist in formation and outlook, conceives history from the point of view of the oppressed and defeated, those whose life possibilities have

This report is about recent progress on semi-classical localization of eigenfunctions for quantum systems whose classical limit is hyperbolic (Anosov systems); the main example is

or differ from a scalar density only by a pure divergence expression (the latter must be a divergence expression without assuming any relation between all field

So far this approach has been sufficient enough when striving to secure a product’s quality from a task and goal perspective (classic usability view from HCI), but still no

The Youth Programme of the Family Planning association of Kenya (FPAK) was initiated in 1988. Two youth centres were established one in Nairobi, and other in Mombasa. A review of