Hermes: A Tutorial and Reference Manual - Researcher - IBM
Hermes: A Tutorial and Reference Manual - Researcher - IBM
Hermes: A Tutorial and Reference Manual - Researcher - IBM
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
DavidF.BaconArthurP.GoldbergAndyLowry <strong>Hermes</strong>:A<strong>Tutorial</strong><strong>and</strong><strong>Reference</strong><strong>Manual</strong><br />
<strong>IBM</strong>T.J.WatsonResearchCenter1 RobertE.Strom<br />
June27,1990 DanielYellin<br />
1POBox704,30SawMillRiverRoad,YorktownHeights,NY10598
1([Mor80]) theconductorofthedeadtoHades;identiedwiththeRoman godMercury.1 <strong>Hermes</strong>GreekMythology.Thegodofcommerce,invention,cunning,<strong>and</strong>theft,whoalsoservedasmessenger<strong>and</strong>heraldfortheothergods,aspatronoftravelers<strong>and</strong>rogues,<strong>and</strong>as<br />
i
Preface Thisdocumentcontainsatutorial,areferencemanual,<strong>and</strong>someappendices.<br />
thatyouhavesomeexperiencewritingapplicationprogramsinahigh-level importantinnovationinstaticchecking|typestateanalysis.Weassume tem.Wethendiscussadditionalusefulfeaturesof<strong>Hermes</strong>,includingan <strong>and</strong>continuethroughmorecomplexexamples,endingwithawindowsys-<br />
examples.Webeginwithasimpleprogramwhichoutputs\Helloworld", procedurallanguage,suchasC,Pascal,orAda.Wewillhighlightthedifferencesbetweenprogrammingin<strong>Hermes</strong><strong>and</strong>programmingintheother<br />
Thetutorialintroducesyouto<strong>Hermes</strong>byguidingyouthroughasetof languages.Thiswayyouwillgetafeelingfor\idiomatic<strong>Hermes</strong>".Atthe endofthetutorial,youwillknowthebasicvocabularyof<strong>Hermes</strong>.Youwill beabletowritesome<strong>Hermes</strong>programsbyimitatingtheexamples.You<br />
intabularform.Theyareproducedfromthesamemachine-readableles thepreciserulesof<strong>Hermes</strong>|thesearecoveredinthereferencemanual. willbeabletocompare<strong>Hermes</strong>tootherlanguages.Butyouwillnotknow<br />
thatareusedtoproducethecompileritself. programs. inthereferencemanualillustratethelanguagerules.Theyhighlightthedifferencebetweenlegal<strong>and</strong>illegalprogramsratherthanillustrate\typicalamplesinthereferencemanual,butwithadierentpurpose.Theexamples<br />
Thisdocumentdoesnotdescribehowtouseanyoftheexisting<strong>Hermes</strong> Theappendicesarethemostformal.Theycontaintherulesof<strong>Hermes</strong> Thereferencemanualismoreformalthanthetutorial.Wealsogiveex-<br />
sendelectronicmailtohermes-request@ibm.comorU.S.mailtooneofthe authorsattheaddresslistedonthetitlepage.<strong>Hermes</strong>currently(March 1990)runsonSun3<strong>and</strong>Sun4systemsrunningSunOS,<strong>and</strong><strong>IBM</strong>RTs tation. runningBerkeley4.3Unix. istobefoundinthe<strong>Hermes</strong>UsersGuidedistributedwiththeimplemen-<br />
implementations,nordoesitdescribetheiridiosyncrasies.Suchinformation Readerswishingtoobtainanexperimentalworking<strong>Hermes</strong>systemshould
Contents<br />
1Introductionto<strong>Hermes</strong> Preface I<strong>Tutorial</strong> 1.1Introduction:::::::::::::::::::::::::::3 1.2GettingStarted|ASimple<strong>Hermes</strong>Program::::::::5 1.3ASecondProgram:::::::::::::::::::::::10 1ii<br />
1.4PuttingProcessesTogether::::::::::::::::::12 1.5Declarations<strong>and</strong>Denitions::::::::::::::::::18 1.6ASimpleServer::::::::::::::::::::::::25 1.5.1Declarations:::::::::::::::::::::::18 1.5.2Denitions:::::::::::::::::::::::21 3<br />
2AMiniatureSystem 2.6TokenizerProcedure::::::::::::::::::::::41 2.7TheWindowManager:::::::::::::::::::::43 2.4WindowSystemShell:::::::::::::::::::::36 2.5Front-endProcess:::::::::::::::::::::::37 2.3Interfaces::::::::::::::::::::::::::::33 2.2Design::::::::::::::::::::::::::::::32 2.1Requirements::::::::::::::::::::::::::31 2.7.1Denitions:::::::::::::::::::::::43<br />
2.8CreatingaWindowApplication::::::::::::::::48 2.9Summary::::::::::::::::::::::::::::53 2.8.1ApplicationBuilder::::::::::::::::::49 2.8.2Adapter<strong>and</strong>QuitDispatcher:::::::::::::51 2.7.5Creating<strong>and</strong>KillingWindows::::::::::::47 2.7.3Refocussing<strong>and</strong>WritingOutput:::::::::::45 2.7.4DispatchingLinestoaParticularWindow::::::45 2.7.2Skeleton:::::::::::::::::::::::::44
iv3Type<strong>and</strong>TypestateChecking 5ResearchDirectionsin<strong>Hermes</strong> 4Additional<strong>Hermes</strong>Constructs 4.4Polymorphs:::::::::::::::::::::::::::64 4.3Variants:::::::::::::::::::::::::::::61 4.2Send:::::::::::::::::::::::::::::::60 4.1ExpressionBlocks:::::::::::::::::::::::59 67 55<br />
II<strong>Hermes</strong><strong>Reference</strong><strong>Manual</strong> 8Resolution 6Introduction 7Lexical<strong>and</strong>SyntacticRules 69<br />
8.2TypeNames:::::::::::::::::::::::::::77 8.1VariableNames:::::::::::::::::::::::::75 8.1.2ComponentNames:::::::::::::::::::77 8.1.1BaseVariables:::::::::::::::::::::76 73<br />
71<br />
10TypestateChecking 9TypeChecking<strong>and</strong>Inference 8.6ProcessNames:::::::::::::::::::::::::79 8.4ExceptionNames::::::::::::::::::::::::78 8.5ExitNames:::::::::::::::::::::::::::79 8.3AttributeNames::::::::::::::::::::::::78<br />
10.3ValidTypestates::::::::::::::::::::::::86 10.6Constants::::::::::::::::::::::::::::88 10.4OrderingofTypestates:::::::::::::::::::::87 10.2FormalTypestates:::::::::::::::::::::::85 10.5Coercions::::::::::::::::::::::::::::87 10.1SyntaxofTypestates::::::::::::::::::::::84 80<br />
10.7HowtoApplytheTypestateRules::::::::::::::88 10.8TheCheckingAlgorithm::::::::::::::::::::90<br />
11<strong>Hermes</strong>Operations 11.3ControlFlowOperations::::::::::::::::::::96 11.1UbiquitousOperations:::::::::::::::::::::93 11.4ScalarOperations::::::::::::::::::::::::101 10.9TypestateErrors::::::::::::::::::::::::91 11.2TheDepletionException:::::::::::::::::::95 11.5RecordOperations:::::::::::::::::::::::107
11.8ProcessCreation<strong>and</strong>CommunicationOperations::::::118 11.9PolymorphOperations:::::::::::::::::::::125 11.7VariantOperations:::::::::::::::::::::::115 11.11Constraints:::::::::::::::::::::::::::131 11.6TableOperations::::::::::::::::::::::::107 11.10ProgramOperations::::::::::::::::::::::128 v<br />
B<strong>Hermes</strong>Operations A<strong>Hermes</strong>ConcreteSyntax B.1OperationDescriptions:::::::::::::::::::::150 A.2SyntacticRules:::::::::::::::::::::::::138 A.1LexicalRules::::::::::::::::::::::::::135 B.1.1DescriptionHeader:::::::::::::::::::151 B.1.3Preconditions::::::::::::::::::::::152 B.1.2TypeRules:::::::::::::::::::::::151 150 134<br />
B.4PreconditionFunctions:::::::::::::::::::::155 B.3InferenceFunctions:::::::::::::::::::::::155 B.2TypeClasses::::::::::::::::::::::::::153 B.4.1TypestatePreconditions::::::::::::::::155 B.4.3ConditionalExceptions::::::::::::::::158 B.4.2ContextPreconditions:::::::::::::::::157 B.1.6OperationSemantics::::::::::::::::::153 B.1.5SpecialRules::::::::::::::::::::::153 B.1.4Postconditions:::::::::::::::::::::152<br />
CPredenedModule B.6OperationDescriptions:::::::::::::::::::::160 B.5PostconditionFunctions::::::::::::::::::::158 C.1<strong>Reference</strong>s::::::::::::::::::::::::::::211 194
<strong>Tutorial</strong> PartI<br />
1
<strong>Hermes</strong>isanexperimentallanguagedevelopedatthe<strong>IBM</strong>TJWatson 1.1Introduction 1Introductionto<strong>Hermes</strong><br />
storedinthecomputerasanarray,alinkedlist,ahashtable,asplaytree, tableofname-addresspairs.Youdon'tworryaboutwhetherthistableis fromtheprogrammer<strong>and</strong>giveittothecompilerimplementor.<strong>Hermes</strong>is asimplelanguageforexpressingcomputation<strong>and</strong>programcomposition. The<strong>Hermes</strong>compilerchoosestheimplementationinsteadofyou.Forexample,ifyouwishtobuildalistofnames<strong>and</strong>addresses,youjustdeclarea<br />
ResearchCenter.Itreectsourresearchgroup'sopinionofhowcomplex<br />
oradiskle|thatisthecompiler'sjob.Insteadoftheapproximately120 systemsshouldbeprogrammed([BS89,SY83,PS83,SYB87c]).<br />
systemcallsinatypicalUNIX([KP84]),youhavejust10<strong>Hermes</strong>statementswhichdealwithcreatingprograms,connectingthemtogether,<strong>and</strong><br />
canbuildarbitrarysystems,includingsomewhichinUNIXwouldrequire machinelanguageisevenleaner!<strong>Hermes</strong>alsostressestheabilitytobuild munication,orcopingwithfailures.Withjustthesetenstatements,you superuserprivilegetobuild.<br />
Thebasicideabehind<strong>Hermes</strong>istotakeasmuchworkaspossibleaway<br />
communicatingbetweenthem.Youdon'tworryaboutdistribution,com-<br />
requireprogrammerstowritemoredocumentation,e.g.declarations<strong>and</strong> systemsoutofseparatelydeveloped,compiled,<strong>and</strong>testedmodules.We mismatches.Inexchangeformodularity<strong>and</strong>checkabilitywearewillingto checkingaspossibletodetectnonsensicalprograms<strong>and</strong>todetectinterface systemasitdidwhentestedinisolation.Wewantasmuchcompile-time shouldbehavethesamewhencombinedwithothermodulesintoalarger expectnon-interferencebetweenmodules|thismeansthatamodule Ofcourse,aleanlanguageisn'tallthat'srequired.Afterall,theTuring<br />
interfacedenitions.<br />
lelexecutionstatements(e.g.cobegin),semaphores,monitors,guardians, concurrent<strong>and</strong>distributedenvironments,youdonotneedtowriteparaltialcontrolstructures.Although<strong>Hermes</strong>isexplicitlydesignedtorunieratingsystemlikeUNIX,MS-DOS,orVMS.Willyouhavetocompletelguage.<strong>Hermes</strong>hasvariables,assignmentstatements,<strong>and</strong>theusualsequen-<br />
changeyourconceptofprogramming areusedtoprogramminginalanguagelikeC,Pascal,orAda,underanop-<br />
Notreally.Inmanyrespects,<strong>Hermes</strong>isatraditionalimperativelan-<br />
Howdoesthisaectyou,theprogrammerWeareassumingthatyou
ortransactions.A<strong>Hermes</strong>moduleisastraightforwardsequentialprogram 41.1.Introduction ingseveral<strong>Hermes</strong>modules<strong>and</strong>connectingtheoutputofsomemodulesto theinputofothers. withinputs,outputs,<strong>and</strong>localmemory.A<strong>Hermes</strong>systemisbuiltbytak-<br />
systemsprogrammerisusedto: Butsomeaspectsof<strong>Hermes</strong>areverydierentfromwhatatraditional Therearenopointers.Noaddressvariables,noaddressarithmetic,no Thereisnoshareddata.Notviapointers,sincetherearenopointers, suchdetailswhichmayvaryfrommachinetomachineareinvisible addressesperiod.Youhavenocontrolofhowdataisstoredinmemory.Thatmeansthatbitorder,byteorder,alignment,<strong>and</strong>allother<br />
toyou. notvianestingofinnerprocedureswithinouterprocedures,notvia globalorexternaldeclarationsofanykind.Everyvariablebelongs toexactlyonemodule.Thereisnoaliasing|thatis,twodistinct Youwillusemanyprocesses.<strong>Hermes</strong>isaprocess-orientedlanguage. withthous<strong>and</strong>sofUNIXprocesses,butyoumaywellbuildasystem withthous<strong>and</strong>sof<strong>Hermes</strong>processes.Mostofthetime,communicationbetween<strong>Hermes</strong>processesisatleastasfastasaprocedurecall.<br />
Buteventhoughtherearemanyprocesses,thereisnoshareddata| onlyqueuedcommunication.Soyoucanstillanalyzeeachprocess inprocedurallanguages.Youwouldn'tdreamofbuildingasystem Thismeansthat<strong>Hermes</strong>processestakeontherolethatmoduleshave variablenamesalwaysdenotetwodistinctvariables.<br />
Thereisnolanguagevs.systemduality.WhenyouprograminC, duresusingCALLs.Intheoperatingsystemworld,dataisstoredin buersorinles,<strong>and</strong>passedfromoneapplicationtoanotherusing pipes,sockets,orles.Dataisuntyped|itisinterpretedasstrings asscalars,arrays,structs,orpointers,<strong>and</strong>passedbetweenproce-<br />
VMSworld.IntheCworld,dataisstoredintypedvariablessuch independently<strong>and</strong>viewitasasequentialprogram.<br />
ofbytes.Somedata(e.g.pointers,leh<strong>and</strong>les)cannotbepassedto youhavetothinkabouttheCworld<strong>and</strong>theUNIX,MS-DOSor<br />
<strong>Hermes</strong>hasmuchmorecompile-timechecking([SY86]).Muchmore newerlanguages.Thebenets:(1)moreerrorsarediscoveredearlier, thaninC,<strong>and</strong>somewhatmoreeventhanAda,Modula-3,orother on.In<strong>Hermes</strong>,thereisonlyoneworldtothinkabout|the<strong>Hermes</strong> world. local,whatisremote,<strong>and</strong>oftenwhatkindofmachineyou'rerunning demarshalled.Indistributedprograms,youmustbeawareofwhatis otherprocessesorstoredinles.Thisdatamustbemarshalled<strong>and</strong><br />
<strong>and</strong>(2)dierentuserscansafelyruninthesameaddressspace,even
1.2GettingStarted|ASimple<strong>Hermes</strong>Program another.Thereissomecost:youhavetowritemoredeclarations. thoughsomeprogramsmayhavebugs<strong>and</strong>theusersdon'ttrustone 1.Introductionto<strong>Hermes</strong>5<br />
Let'sstartwithourrst<strong>Hermes</strong>program. siblytypedenitions.We'llshowyouinalatersectionhowtowritethem. receiveParmsfromInit;<br />
Pascal Let'sassumefornowthatyouhavealreadywrittenthemorthattheyhave alreadybeensuppliedforyou. doesitdierfromthecorrespondingprograminC,Ada([SYW85]),or Beforeyoucompilethisprogram,youhavetoadddeclarations<strong>and</strong>pos-<br />
ThisprogramcanbeusedtodisplaythemessageHello,World!.How callParms.PutLine("Hello,World!"); returnParms;<br />
PutLine.In<strong>Hermes</strong>,PutLineisaparameter;itscounterpartsintheother languagesareconstants. mesversionofthissimpleprogram<strong>and</strong>alltheothers|thelatebindingof syntax,thereisneverthelessanimportantdistinctionbetweentheHer-<br />
Althoughatrstglancetheprogramsappeartodieronlyinsupercial write("Hello,World!")fAPascalprogramg printf("Hello,World!");/*aCprogramtodotheabove*/<br />
IntheCprogram,printfhasaxedbinding|itdenotesalibraryprogramwhichwritesthecharacterstringtothest<strong>and</strong>ardoutput.Theonly<br />
Ifyoudothis,youwillalsochangethebindingofprintfforallthemod-<br />
([KR78]),functionsarenotvariables.Ifyouwanttocontrolthebindingof ulesofyourprogram.TousetheterminologyoftheCreferencemanual afunctionwithaCprogram,youmustsimulatefunctionvariablesusing pointerstofunctions.(SimilarlyinPascal([Coo83])<strong>and</strong>Ada,functionsare notvariables.Intheselanguagesthereisawaytoachievealimiteddegree ofdynamicbinding.) of<strong>Hermes</strong>:(1)nothingisglobal,<strong>and</strong>(2)everyfunctionorprocedurename referstoavariablewhosevalueisdeterminedatrun-time,notcompiletime.<br />
asParms.PutLine.<strong>Hermes</strong>isdesignedthiswaybecauseitassumesyou receivetheparameterlistParms<strong>and</strong>becausewemustrefertothefunction Soeveninthistiny<strong>Hermes</strong>program,youcanseetwoimportantfeatures<br />
PUT("Hello,World!")--AnADAprogram<br />
waytochangethebindingistolinkyourCprogramtoadierentlibrary.<br />
WhydowedothisAfterall,theprogramislongerbecausewemust
61.2.GettingStarted|ASimple<strong>Hermes</strong>Program<br />
User address spaces<br />
arewritingamulti-userormulti-applicationsystemratherthanasingle application. FIGURE1.1.Atraditionaloperatingsystemwithmanyapplications<br />
Kernel<br />
theaddressspace.Joe'sapplication<strong>and</strong>Jane'sapplicationcaneachhave dierentbindingstotheirrespectiveprintffunctions. plicationtohaveasingleglobalmeaning,because\global"meanswithin kernelmaintainsmultipleaddressspacesinwhichyourunyourapplicationprograms.YourCapplicationisaprogramrunninginasingleaddress<br />
space.Resourcesoutsidetheaddressspace(e.g.terminals<strong>and</strong>printers) Lookatgure1.1,whichdepictsatraditionalsystemsuchasUNIX.A aremanagedbytheoperatingsystem,<strong>and</strong>assignedtotheaddressspace asawhole.Itmakessenseforalltheprintfstatementswithinanap-<br />
application,Jane'sapplication,modulesavailabletobothusers,<strong>and</strong>moduleswrittenbyoneuserbutaccessibletosomemodulesofanother.(See,<br />
forexample,gure1.2.)Inthissituation,itisclearthatnofunctionname canbeglobaltothewholesystem.AlthoughJoe'sapplication<strong>and</strong>Jane's applicationmaybothbepartofasinglelarge\program",itdoesnotmake Butsupposemyapplicationisanentiresystem,whichmayincludeJoe's
1.Introductionto<strong>Hermes</strong>7<br />
FIGURE1.2.Amulti-applicationsystemviewedasasinglehigh-levellanguage \program"
81.2.GettingStarted|ASimple<strong>Hermes</strong>Program senseforJoe'sprintfstatementtodenotethesameconsoleasJane's. 1.2,ratherthangure1.1.Thedierencesare:(1)thedistinctionbetween kernel. intra-user<strong>and</strong>inter-usercommunicationdisappears;(2)accesstoresources iscontrolledatthelevelofindividualmodules,ratherthanaddressspaces; <strong>and</strong>(3)accesscontroldecisionsaremadebyprograms,notbyaxed bindingdoneProgramHelloWorldillustratesthesimplestwayofdoing thebinding|makingthefunctionPutLineaparametertotheprogram. <strong>Hermes</strong>encouragesyoutothinkofsystemsfromtheviewpointofgure<br />
codeforprogramHelloWorldiscalledaprocessmodule.Aprocessmodule canbeinstantiatedtocreateaprocess|anactiveentitywithstate,which executesthestatementsoftheprocessmodule.Parms,Parms.PutLine,<strong>and</strong> Giventhat<strong>Hermes</strong>avoidsstaticbinding<strong>and</strong>globalvariables,howisthe<br />
operationstheyallow.Forexample,Parms.PutLineisoftypefamilyoutputport.Outputportssupporttheoperationcall.Thevalueofanoutput<br />
thestatementcallParms.PutLine.Thecallparameters(inthiscase,the portisaconnectiontoaninputport,whichisamessagequeueinanother process. Everyvariablenamehasastaticallyknowntype.Avariable'stypedeter-<br />
Initarevariablenames. oper<strong>and</strong>smusthave.Typesareorganizedintotypefamiliesbasedonthe mineswhatoperationsonthevariablearelegal<strong>and</strong>whattypestheother Thisisagoodtimetobeginusingthe<strong>Hermes</strong>terminology.Thesource<br />
singleparameter"HelloWorld!")arebundledintoacallmessage,which isthenqueuedontheinputporttowhichtheoutportportisconnected. Thecallingprocesswaitsuntilthecallmessageisreturned. ProgramHelloWorldcommunicateswithitsoutputprocessbyexecuting<br />
initializedvariableistheinputportnamedInit,whichwasdesignatedas timeasatypeerror.. connectto.Thetypeofaninputport,inturn,determinesthetypeof statement'sargumentlistmustcontainasinglecharacterstring.Acall withthewrongnumberortypesofargumentswillberejectedatcompile callmessagewhichcanbesenttoit.Inthisexample,theinputportexpectsacallmessagewithasinglecharacterstringparameter.Thecall<br />
WhenprogramHelloWorldstartsupafterbeinginstantiated,theonly Thetypeofanoutputportdeterminesthetypeofinputportitcan<br />
theinitializationport.Byconvention,thecreatorofaprocess|whichwe calltheparent|sendsthenewlycreatedprocess|thechild|acallmessageoveritsinitializationport.Thecallmessagecontainstheparametermunicatewiththeoutside.Inthisexample,weassumethatHelloWorld's<br />
GetProgramareportstoservicestoobtaininputlines<strong>and</strong>loadprograms, <strong>and</strong>ParmStringisacomm<strong>and</strong>string.Theseotherparametersaren'tused thechildneedstogetstarted,includingwhateverportsitmayneedtocom-<br />
namedPutLine,GetLine,GetProgram,<strong>and</strong>ParmString.GetLine<strong>and</strong> parent|perhapsashellprocess|passesacallmessagewithparameters
It'seasytowriteashellin<strong>Hermes</strong>.Inalatersection,wewillseehowto writeone. Init<strong>and</strong>storesitinthecallmessagevariableParms.Nowtheparameters, <strong>and</strong>weareassumingacommoninterfacebetweentheshell<strong>and</strong>itschildren. bytheHelloWorldprogram,buttheywillbeusedinotherexampleslater, Thereceivestatementdequeuesthecallmessagefromtheinputport 1.Introductionto<strong>Hermes</strong>9<br />
withvalue\Hello,World!".Thismessageissenttotheinputportatthe later. callParms.Putlineislegalhere.ItwouldhavebeenillegaltocallParms. namedParms.PutLine,Parms.GetLine,etc.,areinitialized.Thestatement<br />
otherendoftheconnectionParms.PutLine.WhichportisthatItdepends uponthevalueofparameterPutLinewhichwaspassedbytheparent Putlinebeforethereceivestatement,becauseParms.Putlineisuninitializedatthebeginningoftheprogram.Suchacallwouldberejectedat<br />
process.Wedon'tknowwhichportitis,<strong>and</strong>wedon'tcare.Itmaybea servicewhichwritesthelineonanoutputdevice.Ortheportmaybelong ofstaticcheckingwhichisnewto<strong>Hermes</strong><strong>and</strong>willbediscussedindetail compiletimeasatypestateerror.Typestatechecking([SY86])isaform<br />
toa<strong>Hermes</strong>processwhichlterstheoutput<strong>and</strong>passesitalongtoanother port.Whenwelookattheprograminisolation,wecareonlythatthe caller<strong>and</strong>receiveragreeuponwhatissent<strong>and</strong>returnedinthecall.Inthis Thecallstatementcreatesacallmessagewithasinglestringcomponent<br />
Afterthereturnofthecallmessage,variableParmsbecomesuninitialized. processwhichoriginallymadethecall|inthiscase,theparentprocess. inParmsusingareturnstatement.Thecallmessageisreturnedtothe thatParms.PutLinewillbeboundonlytoinputportsexpectingtoreceive string<strong>and</strong>theparametertypestatemustbeinitialized.<strong>Hermes</strong>guarantees callmessagescontainingasingleinitializedcharacterstringparameter.. case,theinterfacewillsaythattheparametertypemustbeacharacter<br />
statements,theprocessterminates. ifyouthinkofmakingacall<strong>and</strong>returningacallassending<strong>and</strong>returning acallmessage,ratherthanastransferofcontrol.Thinkofboththecaller ItwouldbeillegaltocallParms.PutLinehere.Sincetherearenomore Because<strong>Hermes</strong>isaprocess-orientedlanguage,itwillbelessconfusing Afterthecallcompletes,programHelloWorldreturnsthecallmessage<br />
<strong>and</strong>receiverasactiveprocesses.Thecallersendsacallmessage<strong>and</strong>waits fortheanswer.Thereceiverreceivesthecallmessage,processesit,possibly storessomereturnvaluesintothecallmessage,<strong>and</strong>thenreturnsit.1 executesthereturnstatement.Inotherlanguages,whereareturnstatementcan procedure.Buta<strong>Hermes</strong>processmaypossiblycontinueexecutionafterissuing beviewedasatransferofcontrol,executionofareturnstatementterminatesthe return.Wewillseesomeexamplesofthislater. ProgramHelloWorldistypicalofwhatwecallaclientprogram.A 1Notethata<strong>Hermes</strong>programterminateswhenitreachestheend,notwhenit
101.2.GettingStarted|ASimple<strong>Hermes</strong>Program<br />
aserver<strong>and</strong>aclient.Clientsarethemostcommontypeofprocess<strong>and</strong> theeasiesttowrite.Inlatersections,we'llseehowtouse<strong>Hermes</strong>towrite connectotherprocesses.Someprogramsmayplaymultipleroles,e.g.both them.Also,theyareusersofservices|notprovidersofservices.Roughly speaking,clientsmakecalls,serversreceivecalls,<strong>and</strong>shellscreate<strong>and</strong> parentprocess|typicallyashellorsystembuilder|dothebindingfor clientcorrespondstoanapplicationsprogramonconventionaloperating increatingprocesses,orbindingoutputports.Theyarecontenttolettheir shells<strong>and</strong>servers. systems.Clientprogramshaveaspecicjobtodo|they'renotinterested<br />
quenceofthefactthata<strong>Hermes</strong>programisanentiredynamicsystem,not simplyyourapplication.Youhavelearnedthefollowing<strong>Hermes</strong>nomenclature:processmodule,process,variable,type,typefamily,typestate,input<br />
program:rstreceiveaparametercallmessagefromtheinitializationport; port,outputport,callmessage,initializationport,initialized,uninitialized, client,server,<strong>and</strong>shell.Youhaveseenthestructureofatypicalclient Summary:Inthissection,youhaveseenthatin<strong>Hermes</strong>,thereisno ports)arevariables,notconstants.Youhaveseenthatthisisaconse-<br />
globaldata,<strong>and</strong>inparticularfunctionnames(which<strong>Hermes</strong>callsoutput<br />
return. 1.3ASecondProgram Beforemovingontothesystemsprogrammingconstructsin<strong>Hermes</strong>,let's thenusetheoutportportspassedinthatcallmessagetoaccessservices.<br />
lookatonemoreclientprogram,whichweshallcallEcho: Youhavelearnedthefollowing<strong>Hermes</strong>statements:receive,call,<strong>and</strong><br />
block receiveParmsfromInit; declare begin Line:Charstring;--linereadfromst<strong>and</strong>ardinput while('true')repeat callParms.GetLine(Line);<br />
type,togetherwithitsassociatedcallmessagetypeiscalledaninterface, programHelloWorld.Therefore,thevariableParmswillhavethesame componentnames<strong>and</strong>typesasinprogramHelloWorld.Aninputport WeassumethattheinitializationportInitisofthesametypeasin returnParms; on(GetLineInterface.EndStream) endblock; endwhile; callParms.PutLine(Line);
iswrittenoutinfullinsection1.5. sowecansaythatprogramEcho<strong>and</strong>programHelloWorldhavethesame initializationinterface.Thisinterfaceisshownpictoriallyingure1.3.It <strong>and</strong>thataninitializedresultispassedbackonreturn.PutLine,onthe ever,GetLineassumesthatitsargumentisuninitializedpriortothecall, GetLine<strong>and</strong>PutLinebothtakeasinglestring-valuedargument.How-<br />
1.Introductionto<strong>Hermes</strong>11<br />
theseassumptionsarerecordedintheinterfacedenition.Bothclients<strong>and</strong> serversarecheckedatcompile-timetomakesurethatthecodeagreeswith theinterfacewithrespecttobothtype<strong>and</strong>typestate.Typecheckingof interfacesmaybefamiliarfromotherlanguages,suchasAda<strong>and</strong>Pascal. Typestatecheckingisnew.Everycallinterfacehasapre-call<strong>and</strong>post-call typestate.Thecompilerchecksthatacallerputseachargumentinthe correctpre-calltypestate.Thecompilerchecksthatareceiverputseach otherh<strong>and</strong>,assumesthatitsargumentisinitializedpriortothecall.All<br />
withtheEndStreamexception.Foreachexception,theremaybeadierent parameterincorrectpost-calltypestatepriortoreturn.Inthisexample,<br />
post-calltypestatespeciedintheinterface.Inthisexample,theinterface GetLine'sinterfacedenitionspeciesthatthecallargumentisuninitializedbeforecall<strong>and</strong>initializedafterreturn.Ifthecompilercan'tdeduce<br />
willspecifythattheargumenttoGetLinewillnotbeinitializedinthe endofthestreamhasbeenreached,theserverwillreturnthecallmessage theserveriscalledtogetaline<strong>and</strong>therearenomorelinesbecausethe thataprogramreceivingacallwillalwaysinitializeitsparameter,itwill generateanerrormessage<strong>and</strong>refusetocompiletheprogram. eventofanEndStreamexception. GetLine'sinterfacealsodenesanexceptionnamedEndStream.When<br />
empty,sotheblocksimplyterminates,<strong>and</strong>thereturnfollows. statement.Aclauseissimplyasetofstatements|inthiscase,thesetis tothenearestmatchingexceptionh<strong>and</strong>lerclauseinanenclosingblock obtainastring<strong>and</strong>storeitintovariableLine,<strong>and</strong>thencallingPutLineto putoutthestring.WhentheEndStreamexceptionisraised,controljumps tivestatementsmayraiseexceptions;user-denedoperationsimplemented viacallsmayraiseuser-denedexceptions.Insomelanguages,arun-time Exceptionh<strong>and</strong>lingisveryimportantinalanguagelike<strong>Hermes</strong>.Primi-<br />
ThestructureofprogramEchoisaninniteloop,callingGetlineto<br />
errorsuchasanoverowordivisionbyzerocausestheentireprogram<br />
bereturneduninitializedwhentheEndStreamexceptionisreturned.This tohalt<strong>and</strong>anerrormessagetobeprinted.In<strong>Hermes</strong>thisisobviously thatyoumightfailtotestthem.A<strong>Hermes</strong>exceptioncan'tbeignored afteranexceptionreturn.ThecompilerwillknowthatLineisuninitializedbecauseGetLine'sinterfacedenitionspeciesthatitsargumentwill<br />
becausecontroljumpstoanewlocation. unacceptable|remembertheprogramisn'tjustyourapplication,butthe wholesystem.ReturncodessuchasareusedinChavethedisadvantage Typestatecheckingguaranteesthatyoucan'tuseavariablelikeLine
121.4.PuttingProcessesTogether<br />
thecallmayberewrittenusingthefamiliarfunctionnotation.Likeother availablelanguages(asof1989)oer. degreeofcheckinggoesbeyondwhateventhemostmoderncommercially Incidentally,thecalltoGetLinemayalsobewritten: Line:=Parms.GetLine(); Wheneveracallhasnarguments,<strong>and</strong>thelastargumentisareturnvalue, FIGURE1.3.Interfacetoourtypicalclient<br />
expressions,functionsreturnanonymousvalueswhichmaythemselvesbe<br />
Client<br />
usedasoper<strong>and</strong>s.Inthiscase,theresultissimplyassignedtothevariable<br />
seenexamplesofthefollowing<strong>Hermes</strong>statements:assignment,function Line,sothereisnoparticularadvantagetothefunctionnotation.<br />
call,while,block. terface,typestatechecking,exception,exceptionh<strong>and</strong>lerclause.Youhave aboutexceptions.Youhavelearnedthefollowing<strong>Hermes</strong>terminology:in-<br />
denitionsdenewhichparameterspassedascallargumentsfromthecaller <strong>and</strong>whichparametersreturnedtothecallerareexpectedtobeinitialized. Theseexpectationsareenforcedbytypestatechecking.Youhavelearned callmessage.(Thisiscalledpassingparametersbyvalue-result.)Interface Summary:Youhavelearnedthatcallsareprocessedbyexchanginga<br />
intheinitializationcallmessage.Nowyou'regoingtolearntodoyourown otherprocesses<strong>and</strong>bindtheoutputportofonetotheinputportofthe sumedthatallportswereboundbytheparent<strong>and</strong>passedasparameters Sofar,wehavewrittensimpleone-processprograms.Theseprogramsas-<br />
second. systemsprogramming.Wewillwriteaprocessthatwillinstantiatetwo 1.4PuttingProcessesTogether<br />
PutLine,GetLine,<strong>and</strong>GetProgram,sotheyaredepictedasboxeswith threearrowsrepresentingthreeconnectionstotheenvironment. isdepictedingure1.3.Theseprogramsareinitiallypassedthreeports: willconsistofourclientprogram(eitherprogramHelloWorldorprogram Echo|itdoesn'tmatter),connectedtoalterprogram.Thelterhasone TheinterfacewehavebeenusingforprogramsHelloWorld<strong>and</strong>Echo We'regoingtobuildacompositeprogramtothesameinterface.It<br />
GetProgram<br />
GetLine<br />
PutLine
1.Introductionto<strong>Hermes</strong>13<br />
FIGURE1.4.Interfacetothelter<br />
FIGURE1.5.Twointerconnectedprocesses<br />
PutLine<br />
1.3.Itcreatestheoriginalclient,thelter,<strong>and</strong>connectsthemtogether interfaceastheoriginalsingleclientprocess,itcanbefurthercomposed. initiallypasseditsoutputport<strong>and</strong>theprexstring. asshownbelowingure1.5.Sincethecompositeprogramhasthesame inputport<strong>and</strong>oneoutputport,asshowningure1.4.Thelterprogram receivesacallasifitwereaPutLineservice.Eachtimeitiscalledon theoriginallineprecededbyacharacterstringcalledPrefix.Thelteris itsinputportwithalineasparameter,itcallsitsoutputportpassing Thecompositeprogramisaprogramwiththesameinterfaceasingure<br />
thedataisnotrestrictedtobeingbytestreamsincontiguousbuers|it socket.Unlikethepipes,les<strong>and</strong>socketsoftraditionaloperatingsystems, typecheckingguaranteesthataroundplugisneverpluggedintoasquare tionsastherstbox.Theinterfacecorrespondstotheshapeoftheplugs; samethreeplugs,<strong>and</strong>canthereforebepluggedintothesameconguranentswithplugs<strong>and</strong>sockets.Wecanthinkoftheprocessingure1.3<br />
oneplug<strong>and</strong>onesocket.Thecombinationingure1.5isaboxwiththe asacomponentwith3plugs,<strong>and</strong>theprocessingure1.4asaboxwith Wemakeananalogybetween<strong>Hermes</strong>processes<strong>and</strong>electricalcompo-<br />
canbeanydatatypesupportedbythelanguage. Let'slookatthelterprogramrst: --initialization receiveParmsfromInit; Out:=Parms.PutLine; Prefix:=Parms.Prefix;<br />
GetProgram<br />
GetLine<br />
PutLine<br />
Client<br />
Filter<br />
PutLine<br />
Filter<br />
PutLine
141.4.PuttingProcessesTogether newIn; connectParms.ClientPutLinetoIn;<br />
aftertheparentinstantiatesthelter<strong>and</strong>callstheinitializationport.The returnParms;<br />
secondsectionisexecutedrepeatedlyeverytimeacallmessagearriveson --mainloop<br />
thelter'sIninputport|thiswillhappenwhentheclientmakesacallon endwhile; Thelterprocesshastwosections.Therstsectionisexecutedjustonce while('true')repeat<br />
itsPutLineoutputport. receivePutLineCMfromIn;<br />
Let'sbeginwiththeinitialization.Thelter'sinterfaceisdierentfrom returnPutLineCM; callOut(Prefix|":"|PutLineCM.Line);<br />
outputport|theconnectiontothePutLineservices|asParms.PutLine, passedthreeoutputports<strong>and</strong>astring.Thelter'sparentwillpassone theonewehaveseeninHelloWorld<strong>and</strong>Echo.Thoseprocesses'parents <strong>and</strong>aprexstringasParms.Prefix.Itexpectstoreceivebackanoutput<br />
variableParms.ClientPutLineaconnectiontotheinputportIn,using In.Thisisdonewiththenewstatement.Itthenassignstheoutputport port,Parms.ClientPutLine,connectedtothelter'sinputportIn.<br />
aconnectstatement.Theconnectstatementisthe<strong>Hermes</strong>primitivefor examples,thelterhasrealworktodoafterreturningtheinitialization nolongerbeinitializedafterthereturnstatement.Unliketheprevious call|itmustservicePutLinecallsfromitsclient. intolocalvariables.ThisisnecessarybecausethecallmessageParmswill Aftersavingthetwovariablesitneeds,ittheninitializesitsinputport TheinitializationcoderstcopiesParms.PutLine<strong>and</strong>Parms.Prefix<br />
creatingconnectionsbetweenoutputports<strong>and</strong>inputports.Itnowreturns connectedtothelter'sinputportIn. theinitializationcallmessage.Thiscallmessagewillcontainanoutputport control"asitwouldinalanguagewithoutmultipleprocesses.Thereturn thesecallswithtransformeddata.Wecodethisasaninnitewhileloop. statementmarkstheendoftheinitializationsectionofthelter,<strong>and</strong>the beginningofitsmainsection. withanargumentcomputedbyprexingtheoriginalstringwithastring Ateachiterationoftheloop,wedequeueasinglecallmessageintovariable PutLineCM.Thenweservicethecallbycallingthe`real'PutLineservice Recallthatthereturnstatementreturnsamessage;itdoesnot\transfer<br />
prex<strong>and</strong>acolon.Finally,wereturntheoriginalcallmessage.Thelterwill runindenitelyuntilitsconnectionissevered.We'llseeinalatersection howthisisdone. ThemainjobofthelteristoreceivecallsoninputportIn,<strong>and</strong>reissue Nowlet'slookatthecodeoftheparentprocess,Compound.Thisprocess
createstheclient,createsthelter,<strong>and</strong>connectsthetwotogether.The clientmaybeanyprogramwithourst<strong>and</strong>ard3-pluginterface,suchas HelloWorld,Echo,orevenCompounditself.We'llassumethattheinput clientprogram,<strong>and</strong>itsarguments,separatedbythedelimiter`/'. stringParms.ParmStringreceivedbyCompoundcontainsthenameofthe receiveParmsfromInit; 1.Introductionto<strong>Hermes</strong>15<br />
ofCMark); blockbegin ClientName:="filter"; Arguments:=everyofCinParms.ParmStringwhere(position ClientName:=everyofCinParms.ParmStringwhere(position Filter:=createofParms.GetProgram(ClientName);<br />
on(NotFound) Client:=createofParms.GetProgram(ClientName); callFilter(Parms.PutLine,"TheFilter",CliToFil); callClient(Parms.GetLine,CliToFil,Parms.GetProgram,Arguments); Mark:=positionofCinParms.ParmStringwhere(C='/');<br />
on(InterfaceMismatch) on(GetProgramInterface.NotFound)<br />
callParms.PutLine("compound:SyntaxError."); callParms.PutLine("compound:"|ClientName|"notfound.");<br />
assourcetext.Therearethreewaystoobtainvaluesoftypeprogram: statementsofaprocessmodulestoredasstructuredvaluesratherthan ofthepredened<strong>Hermes</strong>datatypeprogram|asetofdeclarations<strong>and</strong> TheresultreturnedbyGetProgramisaprogram.Aprogramisavalue characterstringnameofaprogramtobefetchedfromtheprogramlibrary. returnParms; TheprogrambeginsbycallingtheserviceGetProgram,passingitthe endblock; "interfacemismatch.");<br />
value\on-the-y".Inthiscase,weareusingtherstapproach.Wehave (2)bywritinga\programliteral",<strong>and</strong>(3)bydirectlybuildingaprogram (1)bypassingthesourcetextofa<strong>Hermes</strong>processthroughthecompiler, savingtheresultinaprogramlibrary,<strong>and</strong>retrievingitwithGetProgram, assumedthattheprogramnamed"filter"hasbeenpreviouslycompiled <strong>and</strong>thatthecompiledprogramhasbeenplacedinalibrarymanagedby theGetProgramservice. notsupporton-the-yprogramcreation.Someweaklytyped2languages <strong>and</strong>run-timecheckingfortypeviolations. (Note:Stronglytypedlanguages,likeAlgol,Ada,Pascal,C,etc.,do 2Thetermsstrongly-typed<strong>and</strong>weakly-typeddenoterespectivelycompile-time
fullycheckedfortype<strong>and</strong>typestateerrorsbeforebeinginstantiatedas Algol-likelanguages.<strong>Hermes</strong>programs,evenwhendynamicallybuilt,are likeLisp,Scheme,<strong>and</strong>APL,allowprogramsasrst-classvalues.<strong>Hermes</strong> combinestheexibilityoftheselanguageswiththestaticcheckingofthe processes([SYB87a,SYB87b,SY86]). 161.4.PuttingProcessesTogether<br />
oftypeprogram..(Note:thesyntaxcreateofexpressionisusedrather thancreate(expression)todistinguishprimitiveoperationsfromfunction calls.RememberthatfunctionnameslikeParms.GetProgramarevariables, whereascreateisnot.)Thecreateoperationinstantiatesanew(child) boundtotheinitializationportofthelterprocess. theprogramlibrarybyGetProgram.Theresultofcreateisanoutputport process.Thecodeofthechildprocessisgivenbythevalueoftheoper<strong>and</strong> tocreate.Inthiscase,thatwillbetheFilterprogram,obtainedfrom Tocreateanewprocess,youapplytheoperationcreateoftoavalue<br />
toobtaintheprogramfromthelibrary,<strong>and</strong>thenweapplytheoperation createoftothisprogram.Theonlydierenceisthatthistime,theprogramnameisnotaconstant,butmustbeextractedfromParms.ParmString.<br />
delimeter'/',asecondobtainsallcharacterstotheleftofthedelimiter, Wewillnotexplainthisextractionindetail|onestatementlocatesthe thethirdobtainsallcharacterstotherightofthedelimiter.Theoperationspositionof<strong>and</strong>everyofareexplainedindetailinsection2.6.<br />
Bothprocesses|client<strong>and</strong>lter|havenowbeencreated. Wecreatetheclientprocessinthesameway:rstwecallGetProgram<br />
ment,weneedtosupply3outputports,<strong>and</strong>astring.Fortwooftheoutput nowcalltheinitializationportsofthetwochildprocesses. string.Wewillreceivebackanoutputportconnectedtothelter'sinput programsyou'lleverwrite)beginwithreceiveParmsfromInit.Sowe port.WestorethisportasavariableCliToFil.InthecallClientstate-<br />
initialized,<strong>and</strong>theydependfortheirinitializationonreceivingacallfrom theirparent.Rememberthattheseprograms(<strong>and</strong>probablymostofthe ForFilter,weneedtosupplythePutLineoutputport,<strong>and</strong>aprex Thenewlycreatedprocessescannotdoanythingyet.Theyneedtobe<br />
ports|GetLine<strong>and</strong>GetProgram,wesupplytheportswhichweourselves sameservicewhichwecanaccess.Instead,wewanttogivetheclientthe portCliToFil|theoutputportwejustobtainedfromFilter,<strong>and</strong>which received.ButforPutLine,wedon'twanttogivetheclientaccesstothe isconnectedtoFilter'sinputport.Wealsohavetogivetheclientaparameterstring,sofornow,let'sjustsendanemptystring.Aftermaking<br />
ofintheeventthereisnodelimiter.Thesecondclauseh<strong>and</strong>lesanexceptionanticipatedbytheGetPrograminterface|namelythattherequestedlesaNotFoundexceptionwhichcanberaisedbytheoperationposition<br />
programisnotfoundinthelibrary.Thethirdclauseh<strong>and</strong>lesthebuiltinex- work. bothcalls,wearenished|thetwochildprocesseswillnowdoallthereal Wehavewrittenthreeexceptionh<strong>and</strong>lerclauses.Therstclausehan-
ceptionInterfaceMismatch,whichcanberaisedbythecreatestatement. InterfaceMismatchisoneofthefewtypecheckingerrorsthatcannotbe detectedatcompile-time,butonlyatrun-time.Forexample,thesecond createstatementinstantiatesachildprocess,<strong>and</strong>returnsanoutputport boundtotheinitializationport.Itisknownstatically(thatis,atcompile time)thatthetypeofthisoutputportmustbecompatiblewiththeoutput 1.Introductionto<strong>Hermes</strong>17<br />
exceptionwillberaised. anarbitraryprogram.Ifthisprogramdoesn'thavetheproper3-pluginterface(as,forexample,Filterdoesnot),thentheInterfaceMismatch<br />
portClient.Butitisnotknownstaticallywhethertheinitializationinput portoftheprogramisofamatchingtype,sinceGetProgrammayreturn<br />
akernelhackerorasuperusertowriteaccesscontrolpolicies.Youcannot Anytypeofcallcanbereboundprovideditistoaserviceofmatchingtype. ThinkoftheexibilityofUNIXpipesextendedtoanykindofcalls. tionofports.Thetechniqueisveryexible.ProgramslikeCompoundcan containarbitrarypoliciesforbindingtheportsoftheprogramsitcreates, therebycontrollingtheiraccesstootherprocesses.Youdon'tneedtobe systemsprogrammingondynamicprocesscreation<strong>and</strong>dynamicconnec-<br />
Becausemodulesaren'thard-wiredtospecicservices,theycanbereused.<br />
accidentallyorintentionallycircumventsomeoneelse'saccesscontrol.You cannotaccessanotheruser'sglobalvariables,sincetherearenoglobalvariables.Youcannotaccessaservicebyguessingitsname,orbyusingsome<br />
Althoughthisexampleisverysimple,itillustratestheeleganceofbasing<br />
undenedvalueasaname.YoucanonlygetabindingtoaninputportP if(1)youownPyourself<strong>and</strong>connecttoit,(2)Pistheinitializationport primitivesintothelanguage.Type-checkingguaranteesthatyoucan'tcopy aninteger,string,orotherinappropriatedatatypeintoacapability(output ofaprocessyoucreate,or(3)someoneelsegivesyouabindingtoP. port)variable.Typestate-checkingguaranteesthatyoucan'tuseanuninitialized<strong>and</strong>possiblygarbagevalueofacapability.Butyoumaycreate<br />
oldideainoperatingsystems.Itisnotwidespread,becauseitspremise| thatcapabilities(accessrights)areeasytostore<strong>and</strong>passaround,but impossibletoforge|isoftendicult<strong>and</strong>expensivetoimplement.Her-<br />
Thisapproachtosystemcongurationiscalledcapability-based.Itisan messolvesthisprobleminexpensivelybyintegratingtheoperatingsystems<br />
processes,<strong>and</strong>settingupportconnectionsbetweenprocesses.Youhave learnedthat<strong>Hermes</strong>isacapability-basedoperatingsystemencapsulated aserveristypicallydividedintoaninitializationpartwhichimports<strong>and</strong> Youhavelearnedhowtoimplementthebasicfunctionsofashell|creating aprogramwhichwasbothaclient<strong>and</strong>aserver.Youhavelearnedthat exportsports,<strong>and</strong>aserviceloopwhichh<strong>and</strong>lesrequestsfromitsclients. sagesasmuchasyouplease. capabilitieswithconnect,<strong>and</strong>copythemorpassthemaroundinmes-<br />
withinaprogramminglanguage.Youhavelearnedthefollowing<strong>Hermes</strong> Summary:WehavestudiedtheprogramFilter|ourrstexampleof
constructs:thenewinput-port,connect<strong>and</strong>createstatements,<strong>and</strong>the InterfaceMismatchexception.Congratulations!Younowknowsixofthe 1.5Declarations<strong>and</strong>Denitions ten<strong>Hermes</strong>systemprogrammingstatements! 181.4.PuttingProcessesTogether<br />
morphic <strong>and</strong>howmuchshouldbeinferredbythecompilerShouldtypesbepoly-<br />
muchshouldtheprogrammerhavetowriteoutasexplicitdeclarations, averyimportantlooseendmentionedearlier|declarations<strong>and</strong>denitions. checking.Shouldtypecheckingbedoneatcompile-timeorrun-timeHow Let'stakeabreakfromlearningnewkindsof<strong>Hermes</strong>statements,<strong>and</strong>tieup <strong>Hermes</strong>takesthefollowingpositions: Thereismuchdebate<strong>and</strong>dierenceofopinionabouttheroleoftype Allprogramswillproducesemanticallywell-denedlocalizedeects| Programmingerrorswillbedetectedatcompiletimewhereverpossible.<br />
Programmersmustdeclarethetypesofallvariablesexceptexpression Infact,aprocesscanaccessonlythedatabelongingtoit. eitheranormalresultoranexception.Thismeansprogrammingbugs<br />
Therearenopolymorphictypes.They'renotneededasmuchwhen can'tcrashthesystem,orwriter<strong>and</strong>omgarbageintoanotherprocess.<br />
itlyintroducingpolymorphism.(<strong>Hermes</strong>hasapolymorphtype,which samegoal|namely,reusablesourcecodepackages|withoutexplic-<br />
insteadwritesatemplate<strong>and</strong>thencreatesspecicsortprogramsby substitutingspecictypesintothetemplate.Thisaccomplishesthe writingapolymorphicsortprogramwhichcansortanytype,one youhavetheabilitytocreateprogramobjectsonthey.Insteadof temporaries.Thecompilerinfersthetypesofexpressiontemporaries.<br />
statementsweshowedyouearlier. 1.5.1Declarations Wewillnowshowyouthecompletetextoftheprogramswhoseexecutable HelloWorld:using(St<strong>and</strong>ard)process(Init:St<strong>and</strong>ardIn) allowsavariabletoholdavalueofanytype,therebydeferringtype<br />
declare checkinguntilrun-time.)<br />
begin Parms:St<strong>and</strong>ardInterface;--callmessagereceivedfromparent receiveParmsfromInit;
typename.InHelloWorld,wedeclaretwoidentiers|Init(theinitializationport),<strong>and</strong>Parms(thecallmessage).Atypenameiseitherapredened<br />
calleddeclarations.Adeclarationconsistsofanidentier,acolon,<strong>and</strong>a ThestatementsInit:St<strong>and</strong>ardIn<strong>and</strong>Parms:St<strong>and</strong>ardInterfaceare endprocess callParms.PutLine("Hello,World!"); returnParms; 1.Introductionto<strong>Hermes</strong>19<br />
compileadenitionmodule<strong>and</strong>placeitintoalibrarybeforeyoucanimport thedenitionsofthetypesyounameinyoursourceprogram.Youmust denitionsmodules.Youmustimportthedenitionsmodulescontaining areuser-dened.Youmaygroupcollectionsofdenitionsintolescalled typename(suchasinteger,charstring,program,etc.),orauser-dened<br />
<strong>and</strong>thepredenedtypesaresaidtobevisiblewithinthesourceprogram. introducedbythewordusing.Thetypesdenedintheimportedmodules, themodule. Youimportadenitionsmodulebyincludingitsnameonanimportslist Sometypes,likeCharstringarepredened.Others,likeSt<strong>and</strong>ardIn<br />
!St<strong>and</strong>ardInterface,<strong>and</strong>thiswouldhavebeennecessaryifSt<strong>and</strong>ardInterface dierentimportedmodules,orasapredenedtype<strong>and</strong>inanimported nameSt<strong>and</strong>ardInterfacecouldoptionallyhavebeenwrittenasSt<strong>and</strong>ard module),thatnamemustbedisambiguatedbyprexingitwiththename ofthedenitionsmoduleorwithpredefined. othertypenames.Ifatypenameisdenedmorethanonce(e.g.intwo willcontaindenitionsforSt<strong>and</strong>ardIn<strong>and</strong>St<strong>and</strong>ardInterface.Thetype Noothertypesarevisible|thatis,thecompilerwillnotunderst<strong>and</strong>any<br />
hadalsobeenthenameofapredenedtypeorifanotherimporteddenitionsmodulecontainedatypenamedSt<strong>and</strong>ardInterface.<br />
Intheexample,thedenitionsmodulenamedSt<strong>and</strong>ardisimported.It<br />
internal,<strong>and</strong>appearbetweenthekeywordsdeclare<strong>and</strong>begin. anyprocesswishingtoinstantiatethisprocess.Theotherdeclarationsare parenthesesafterthewordprocess.That'sbecausetheinitializationport typeispartoftheinterfacetotheprocess|itneedstobeknownby Echo:using(St<strong>and</strong>ard)process(Init:St<strong>and</strong>ardIn) HereistheentireprogramEcho: Thedeclarationoftheinitializationportappearsinaspecialplace|in declare begin Parms:St<strong>and</strong>ardInterface;--callmessagereceivedfromparent block receiveParmsfromInit; declare begin Line:Charstring;--linereadfromst<strong>and</strong>ardinput
201.5.Declarations<strong>and</strong>Denitions while('true')repeat<br />
twoareidenticaltoHelloWorld.Itwouldbeeasyforaneditororother Noticethatexceptfortheprogramname,therstvelines<strong>and</strong>thelast endprocess returnParms; on(GetLineInterface.EndStream) endblock; endwhile; callParms.GetLine(Line);<br />
tooltoinserttheselinesautomaticallyasboilerplatearoundanyst<strong>and</strong>ard callParms.PutLine(Line);<br />
<strong>Hermes</strong>doesn'tallowyoutohideanouterdeclarationbydeclaringanew intheregionofvisibilityofavariable.Thisruledoesnotexistinmost variablewiththesamenameinaninnerblock.Thisavoidshaving\holes" onlywithintheblock.Thisruleisfoundineveryblockstructuredlanguage. one-lineprogram,<strong>and</strong><strong>Hermes</strong>doesn'tappearsoverbose. tion.Ifavariablenameisdeclaredwithinablock,thenthatnameisvisible clientprogram.Ifthisisdone,thenHelloWorldonceagainbecomesa<br />
conictsifyoucopycodecontainingblocksfromoneprogramtoanother. otherblockstructuredlanguages.Youmayhavetowatchoutforname HerearetheprogramsFilter<strong>and</strong>Compound.Thistime,we'lljustshow Inthisexample,thereisaninnerblockstatementcontainingadeclara-<br />
theheader<strong>and</strong>declarationswithoutrepeatingthecode: Filter:using(St<strong>and</strong>ard,Filter)process(Init:FilterIn) line begin declare<br />
endprocess Prefix:Charstring;--stringtoprependtoeachoutputline --codeforprocessFilter PutLineCM:PutLineInterface;--callmessagecontainingthe Out:PutLineOut;--outputport:boundtoputlineservice Parms:FilterInterface;--initializationcallmessage In:PutLineIn;--inputport:requestsfromclient<br />
Compound:using(St<strong>and</strong>ard,Filter)process(Init:St<strong>and</strong>ardIn) declare begin Client:St<strong>and</strong>ardOut;--porttoinitializeclient Mark:integer;--positionof"/"delimitingname/parameters Filter:FilterOut;--porttoinitializefilter Parms:St<strong>and</strong>ardInterface;--initializationcallmessage CliToFil:PutLineOut;--outputportconnectedtofilter ClientName:charstring;--nameofclientprogram Arguments:charstring;--argumentstoclientprogram
ecords<strong>and</strong>callmessages)containpartscalledcomponentswhicharenamed usingthedotnotationcommontomanyprocedurallanguages.Thetype names.Theseidentiersarecalledbasevariables.Structuredvariables(e.g. endprocess Youonlyneedtodeclarethetypeofsimpleidentiersusedasvariable --codeforprocesscompound1.Introductionto<strong>Hermes</strong>21<br />
ofacomponentlikeParms.GetLineisinferredfromthetypeofthebase variableParms.<br />
writedownischeckedagainstthetypethatisinferred. maywriteboolean#'true'insteadof'true'.Inthatcase,thetypeyou maywriteatypespecierevenwhenitisnotnecessary|forexample,you usinginferencerules.Incertaincases,thetypeofanexpressioncannotbe inferred,<strong>and</strong>youmustprecedetheexpressionwithatypespecier.You raryvariabletoholdtheresultofthatexpression.Examplesofexpressions arefunctioncalls(e.g.Parms.GetLine()),arithmeticoperations(e.g.A+B) <strong>and</strong>literals(e.g.'true').Thecompilerinfersthetypeofanexpression Whenyouwriteanexpression,youareimplicitlydeclaringatempo-<br />
denitionsdescribingwhatast<strong>and</strong>ardclientispassedoninitialization,<strong>and</strong> theinterfacestothest<strong>and</strong>ardservicesGetLine,PutLine,<strong>and</strong>GetProgram: 1.5.2Definitions Nowlet'slookatthedenitionsmodules.Let'sbeginwithSt<strong>and</strong>ard|the St<strong>and</strong>ard:using()definitions PutLineInterface:callmessage( Line:Charstring) constant(Line)<br />
GetLineIn:inportofGetLineInterfacefg; GetLineInterface:callmessage( PutLineOut:outportofPutLineIn; PutLineIn:inportofPutLineInterfaceffullg; Line:Charstring) exitfinit(Line)g exceptionEndStreamfg; exitffullg;<br />
St<strong>and</strong>ardInterface:callmessage( GetLineOut:outportofGetLineIn; PutLine:PutLineOut, GetProgram:GetProgramOut, ParmString:Charstring) constant(GetLine,PutLine,GetProgram,ParmString) GetLine:GetLineOut,
221.5.Declarations<strong>and</strong>Denitions St<strong>and</strong>ardIn:inportofSt<strong>and</strong>ardInterfaceffullg; GetProgramInterface:callmessage( St<strong>and</strong>ardOut:outportofSt<strong>and</strong>ardIn; exitffullg; Name:Charstring, TheProgram:Program)<br />
onlyrefertotypesdenedwithinSt<strong>and</strong>arditself,ortopredenedtypes. GetProgramOut:outportofGetProgramIn; enddefinitions ModuleSt<strong>and</strong>arddoesnotimportanyotherdenitionsmodules.Itmay GetProgramIn:inportofGetProgramInterfacefinit(Name)g; exceptionNotFoundfinit(Name)g; constant(Name)<br />
Thismoduledenesfourcallinterfaces.Inourpreviousanalogyofprocessesaselectricalcomponentswithplugs<strong>and</strong>sockets,interfacesdenitions<br />
exitfinit(Name),full(TheProgram)g<br />
informationthatcanbecommunicatedbetweentwoprocesses. describetheshapesoftheplugs<strong>and</strong>sockets.Acallinterfacedenesthe facesmustbedenedindefinitionsmodules<strong>and</strong>processesinprocess modules.Thisseparationmakesaninterfaceavailabletoanyprocessthat wantstouseit.Thecompilerrequiresthataprocessmodulewhichuses evenmoreinformationonainterface. inoutparameters([Ada83]).<strong>Hermes</strong>allows(<strong>and</strong>requires)youtospecify <strong>and</strong>typeofaprocedure'sparameters.Pascalalsoletsaprogrammerdistinguishconstant<strong>and</strong>varparameters;Adaletsyoudistinguishin,out,<strong>and</strong><br />
Youdeneaninterfaceseparatelyfromtheprocessesthatuseit;inter-<br />
Mosthigh-levellanguagesprovideamechanismfordeningthenumber<br />
conformtothesameinterfacecancommunicate. thecallerexpectstoreceiveuponreturn).Anycaller<strong>and</strong>receiverwhich ilarlyitdeneswhatareceiverpromisestoreturn(<strong>and</strong>thereforewhat promisestosend(<strong>and</strong>thereforewhatthereceiverexpectstoreceive);sim-<br />
aninterfaceconformtotheinterface.Theinterfacedeneswhatacaller sage,aninputport,<strong>and</strong>anoutputport. eachparameter.Inthecallingprocess,youmustsupplyalistofarguments selectedcomponentnotation,e.g.Parms.PutLine. ofmatchingtype.Inthecalledprocess,younametheparametersusing alistofthoseparameterswhosevaluesmustnotchangeduringthecall. Eachinterfacetypicallyincludesthree<strong>Hermes</strong>typedenitions:acallmes-<br />
calledprocess. Acallmessagedenitioncontainsadeclarationofthename<strong>and</strong>typeof<br />
fortypestatechecking.Atypestateisasetofprogramattributesknown Youmayincludeaconstantslistinthecallmessagedenition.Thisis Younowneedtosupplytheadditionalinformationwhichisrequired Youmustsupplyalistoftheexceptionswhichmaybereturnedbythe
callydenedbytheprogrammer. taintypestateattributesarealwaystracked|suchaswhetheravariableis initializedoruninitialized.Otherattributesareonlytrackedwhenspeci-<br />
knownstatically.Likestates,theyvaryfromstatementtostatement.Cer-<br />
staticallytoholdataparticularprogrampoint.Liketypes,typestatesare Fornow,let'sjustlookatinitializationtypestates.Whentheattribute 1.Introductionto<strong>Hermes</strong>23<br />
tatetheparametersmusthaveifthecallcompleteswiththatexception. Linewillbereturned.Foreachexception,youmustsupplythetypesmalexitfromtheGetLineisinit(Line),whichmeansthataninitialized<br />
init(X)appearsinatypestatethismeansthatthevariableXisinitialized. haveonnormal(non-exception)returnfromthecall.Forexample,thenor-<br />
staticallyknowntobeinitializedoruninitialized;itisneverconditionally initialized.3 Wheninit(X)isabsent,itisuninitialized.A<strong>Hermes</strong>variableisalways<br />
ceptionEndStreamisreturned,thenLinewillnotbeinitialized,because Thenormal<strong>and</strong>exceptiontypestatesmaybedierent.Forexample,ifex-<br />
init(Line)isnotpresent. Aninputportdenitionspeciesthetypeofcallmessagewhichwillbe Youmustsupplytheexittypestate|thetypestatetheparametersmust<br />
denesaninputporttypewhichwillholdcallmessagesoftypeGetProgramInterface. itissenttotheinputport(theentrytypestate).Forexample,GetProgramIn senttothatinputport,<strong>and</strong>thetypestatethatcallmessagewillhavewhen becausetheentrytypestateisinit(Name). TheProgram.AcallmessagearrivingataportoftypeGetProgramInisexpectedtohavecomponentNameinitialized,butnotcomponentTheProgramstatesatlength.Forexample,typeprogramisarecordwithcomponents<br />
Thesecallmessageshavetwocomponentsorparameters,namedName<strong>and</strong> intheinterfaceinsteadofthemuchlonger isfullyinitialized.SotheexittypestateofSt<strong>and</strong>ardInterfacecouldhave DefinitionsModules,MainProgram,<strong>and</strong>Programs.Wewritefull(TheProgram) Theabbreviationfullisusedtoavoidwritingoutfullyinitializedtype-<br />
beenwrittenas Wherefullappearsallbyitself,itmeansthattheentirecallmessage init(TheProgram),init(TheProgram.DefinitionsModules), init(TheProgram.MainProgram),init(TheProgram.Programs)<br />
conditionalinitialization. tributecheckedappliestoaprogramvalue<strong>and</strong>itmeansthattheprogram isnotonlyfullyinitialized,butalsothatitisfreeofcompile-timeerrors. Uncheckedprogramsmustbecheckedbeforetheymaybeinstantiatedwith Thereareothertypestateattributesbesidesinit.Forexample,theat-<br />
init(GetLine),init(PutLine),init(GetProgram),init(ParmString) 3Youcanuseavarianttype,describedinsection4.3,togettheeectof
whichtheoutputportconnects|calledthematchinginputporttype.The 241.5.Declarations<strong>and</strong>Denitions thecreateofstatement.ThedenitionGetProgramInterfacespecies thatprogramsreturnedbyGetProgramhavealreadybeenchecked. callmessagetype<strong>and</strong>typestaterequiredforsendingontheoutputportare determinedfromthatinputporttype. calling<strong>and</strong>calledprogramsareseparatelycompiled.Whencompilingthe caller,thecompilerchecksthattheentrytypestateholdsbeforethecall, <strong>and</strong>computestheexit<strong>and</strong>exceptiontypestatesusingtheinterface.When Anoutputportdenitionsimplyspeciesthetypeoftheinputportto<br />
theentrytypestate,<strong>and</strong>checksthatthecorrectexittypestateholdsatthe pointofareturnstatement. mustlooklike.Thencheckyourselfagainstthedenitiongiven: compilingthecalledprogram,thecompilerusestheinterfacetodeduce Theinterfacedenitionsmaketypestatecheckingpossibleeventhough SeeifyoucanworkoutforyourselfwhatthedenitionsmoduleFilter Filter:using(St<strong>and</strong>ard)definitions<br />
FilterOut:outportofFilterIn; FilterInterface:callmessage(<br />
enddefinitions FilterIn:inportofFilterInterfacefinit(PutLine),init(Prefix)g; Prefix:Charstring, ClientPutLine:PutLineOut) constant(PutLine,Prefix) exitffullg; PutLine:PutLineOut,<br />
usedinthesamecontexts,besuretodeclarethemasthesametype. theyaretreatedastwodierenttypes.Ifyouintendtwovariablestobe havethesamestructure|samecomponenttypes,sameexceptions,etc.| denedinSt<strong>and</strong>ard.St<strong>and</strong>ardrefersonlytopredenedtypes<strong>and</strong>types example,thatifyoudenetwodierentcallmessagetypeswhichhappento denedwithinitself. Summary:In<strong>Hermes</strong>,allbasevariablesmustbedeclared.Alluserdenedtypesmustbedenedinseparatemodules.Onlythenamesof<br />
visible.Youhavelearnedhowtowriteprocessheaders,declarations,<strong>and</strong> predenedtypes<strong>and</strong>oftypesdenedinimporteddenitionsmodulesare Note:<strong>Hermes</strong>usesnameequivalencefortypedenitions.Thismeans,for NoticethatFilterhastoimportSt<strong>and</strong>ard,sinceitusesatype(PutLineOut)<br />
putports,<strong>and</strong>callmessages.Youknowwhenyouneedtoputatypespec-<br />
ieronanexpression.Youhavelearnedthefollowingterminology:type specier,denitionsmodule,import,visible,predened,entrytypestate, denitionsmodules,<strong>and</strong>thesyntaxfortypedenitionsofinputports,out-<br />
theentireskeletonofthe<strong>Hermes</strong>language<strong>and</strong>canwrite<strong>and</strong>executeHer- exittypestate,checkedattribute,nameequivalence.Younowunderst<strong>and</strong>
1.Introductionto<strong>Hermes</strong>25<br />
1.6ASimpleServer <strong>Hermes</strong>datatypes<strong>and</strong><strong>Hermes</strong>statements. mesprograms.Theonlythingyoudonotknownowaresomeadditional FIGURE1.6.Aboundedbuerprocess<br />
allykeepanylocalstate,butinsteadpassedallrequeststhroughtoanother service. typicalserver,sinceitmadeonlyasingleoperationavailable,<strong>and</strong>didn'tre-<br />
Wehaveseenoneexampleofaserver,namelytheFilter.Thiswasn'ta<br />
operation,Quitwhichissimplyacomm<strong>and</strong>toterminate.Figure1.6shows theinterface. Ifthequeueisempty,callstoGetLinewillblockuntilthequeuebecomes orientedlanguages.Ourserverwillimplementabuer.Abuersupports rst-in,rst-outqueue;callstoGetLineremovethedatafromthequeue. theoperationsGetLine<strong>and</strong>PutLine.CallstoPutLineinsertdataintoa non-empty.Foraboundedbuer,callstoPutLinewillblockifthenumber oflinesinthequeueexceedssomecapacity.Wewillsupplyoneadditional Let'slookatamoretypicalserver|onemoreliketheobjectsofobject-<br />
Hereisthesourcemodule: Naturally,weimplementaboundedbuerin<strong>Hermes</strong>withaprocess. BoundedBuffer:using(St<strong>and</strong>ard,BBExternal,BBLocal,Quit) process(Init:BBIn) declare Put:PutLineIn;--PutLineservice Parms:BBInterface;--initializationcallmessage Get:GetLineIn;--GetLineservice Queue:Lines;--orderedsetoflines Quit:QuitIn;--Quitservice Capacity:integer;--maximumnumberofmessages<br />
PutLine<br />
Quit<br />
Buffer<br />
GetLine
261.6.ASimpleServer begin QuitCM:QuitInterface; newPut;connectParms.PuttoPut; --initialization receiveParmsfromInit; newGet;connectParms.GettoGet; PutCM:PutLineInterface; Running:boolean;--trueifprocesshasnotbeenshutdown<br />
newQuit;connectParms.QuittoQuit; GetCM:GetLineInterface;<br />
newQueue; returnParms; --serviceloop Running:='true'; while(Running)repeat Capacity:=Parms.Capacity; select<br />
eventQuit eventGet<strong>and</strong>where(sizeofQueue>0) eventPut<strong>and</strong>where(sizeofQueue
Ifallalternativesaredisabled,thentheotherwiseclauseisexecuted.If oneormorealternativesareenabled,oneofthemischosen,<strong>and</strong>control transferstothatalternative.However,analternativewithaneventguard canonlybechosenifthatinputporthasatleastonewaitingcallmessage. ports,theselectstatementblocksuntilamessagearrivesatoneofthese Ifalltheenabledalternativeshaveeventguardsreferringtoemptyinput 1.Introductionto<strong>Hermes</strong>27<br />
buer.JustleaveoutthequeuesizetestfromthePutservice. whichcontainsdenitionsfortypesusedinternallybyBoundedBuffer(in nativeisenabledprovidedthenumberoflinesinthequeueislessthan inthequeue.Theotherwiseclause,althoughsyntacticallym<strong>and</strong>atory, canneverbereached.Itiseasytomodifythisprogramintoanunbounded ports.<br />
thiscase,thetypeLinesusedtoimplementthequeue),(2)BBExternal, Capacity,<strong>and</strong>theGetalternativeisenabledprovidedthereareanylines Theboundedbuerprocessusesfourinterfaces:(1)BBLocal(notshown), Inthisexample,theQuitalternativeisalwaysenabled;thePutalter-<br />
buer. languagefeatureswe'vealreadydescribed.Trytowriteityourself<strong>and</strong>then checkwiththedenitionhere: ules,becausetheywillbereusedinapplicationsotherthanthebounded whichdenesthePutLine<strong>and</strong>GetLine,<strong>and</strong>(4)Quit,whichdenesthe interfacefortheQuitoperation.St<strong>and</strong>ard<strong>and</strong>Quitareinseparatemod-<br />
whichdenestheinitializationinterfacefortheboundedbuer,(3)St<strong>and</strong>ard, Theinterfacedenition,BBExternal,isstraightforward,<strong>and</strong>usesonly BBInterface:callmessage( BBExternal:using(Quit,St<strong>and</strong>ard)definitions<br />
BBIn:inportofBBInterfacefinit(Capacity)g; BBOut:outportofBBIn; Capacity:integer,--maximumnumberofmessagesallowed<br />
enddefinitions Put:PutLineOut,--portforwriters<br />
TheQuitdenitionisevensimpler: Get:GetLineOut,--portforreaders<br />
Quit:using()definitions constant(Capacity) exitffullg; Quit:QuitOut)--portforshutdown<br />
object-orientedlanguageslikeSmalltalkInbothcases,wehavetheability enddefinitions Howdoes<strong>Hermes</strong>dierfromdataabstractionlanguageslikeAdaor QuitIn:inportofQuitInterfacefg; QuitInterface:callmessage()exitfg; QuitOut:outportofQuitIn;
281.6.ASimpleServer towritedataabstractionswhichexportaspecicsetofoperationswhile notexposingtheimplementationdetailstothecaller.Therearesomedifferences:<br />
<strong>Hermes</strong>processesareactive.Iftherearemultiplecallers,thecalls arequeued<strong>and</strong>processedserially.Theprocesscanchoosenotto<br />
Icontrolaccessin<strong>Hermes</strong>onaport-by-portbasis.InAdaorin Icanwritedierent<strong>Hermes</strong>processeswiththesameinterface<strong>and</strong> ofthesameprivatetypewiththesamespecication(interface)<strong>and</strong> receivecertaincallsatcertaintimes.Thereisnoneedformonitors dierentprivateparts. orsemaphoresorothermutualexclusionmechanisms.<br />
callGetLinecouldalsocallPutLine<strong>and</strong>Quit.Thisisundesirable, accesstoanobjectautomaticallygivesaccesstoallitsoperations.In thecaseofaboundedbuer,thiswouldmeanthatanyonewhocould object-orientedlanguages,Icontrolaccessonanobjectbasis.Having dierentinternals.InAda,forinstance,Ican'thavetwovariables<br />
totallyordered|thatis,eachelementhasanassociatedposition.Positions thetable,thelastpositionisk1. anorderedtable.Atableissimplyacollectionofvaluesofthesametype aredenotedbyintegers.Therstpositionis0.Iftherearekelementsin (mathematically,abag).Anorderedtableisatablewhoseelementsare TheQueueisanexampleofatypefamilywehaven'tstudiedbefore| <strong>and</strong>infactIdon'twantthereaders<strong>and</strong>writersoftheboundedbuer<br />
Youhavealreadyusedorderedtableswithoutknowingit,sincethepredenedtypeCharstringisanorderedtableofelementsoftypeChar.<br />
toevenhavetoknowthattheQuitoperationexists.<br />
whichisatablewhoseelementsareoftypeT.Inourexample,wewant todeneatypeLinesasanorderedtablewhoseelementsareoftype initionsmoduleBBLocal: Charstring.Thetypedenitionlookslikethis<strong>and</strong>willappearinthedef-<br />
In<strong>Hermes</strong>youc<strong>and</strong>enetablesofanytype|tablesofintegers,tablesof callmessages,etc.Youcanevendenearecursivetabletype|atypeT<br />
fromthetablehavetypestateinit.Noticethatlikeothertypedenitions tablewithaparticularcontent,insertelementsintothetable,removeelementsfromthetable,mergeonetableintoanother,extractorcopyouta<br />
in<strong>Hermes</strong>,<strong>and</strong>unliketypedenitionsinmanyotherlanguages,tabletype aCharstring,<strong>and</strong>thatelementsinsertedinto,removedfrom,orcopied le),<strong>and</strong>nothingabouthowmuchstoragetoallocate. denitionssaynothingabouttherepresentation(e.g.array,linked-list,disk ThedenitionsaysthatLinesisanorderedtable,thateachelementis Lines:orderedtableofCharstringfinitg; Alltablessupportthefollowingoperations:inspectanelementinthe
inspectanelementormergeatableataparticularposition,locatethe subtablefromatable,ndthesizeofthetable,<strong>and</strong>iterate(repeataset ofstatementsonceforeachelementofthetable). positionofanelementwithparticularcontents,<strong>and</strong>iterateinorder. Orderedtablesadditionallysupporttheseoperations:insert,remove,or InBoundedBuffer,thesingleactionofthePutserviceconsistsofinsertingthedesignatedlineintotheendofthetableQueue.Theinsert<br />
1.Introductionto<strong>Hermes</strong>29<br />
ifyouwish,bywriting: isordered.However,youmayinsertelementsatanypositioninthetable statementinsertsanelementintotheendofatablebydefaultifthetable<br />
toinsertsomethingatposition3,theremustbeanelementatposition2, anelementpreviouslyatposition3,itmovestoposition4,<strong>and</strong>similarly orelseyouwillgetaRangeErrorexception. allelementsathigherpositionshavetheirpositionsincremented.Ifyoutry youspecifyposition3,thenewelementappearsatposition3.Iftherewas insertElementintoTableat(Position); Inthiscase,youmustsupplyaninteger-valuedposition.Forexample,if<br />
thepositionsofalltheotherelementsmoveupbyone,sotheprevious wewrotetheexpressioncopyof. inGetCM.Line.Whenyouremovetherstelementfromanorderedtable, discardPutCM.Line|inthedenitionofPutLineInterface,parameter intothetable,ratherthancopyingit.Thismeansthatafterthestatement Lineisconstant|wemustmoveacopyofPutCM.Line.Thatexplainswhy isexecuted,thesourceoper<strong>and</strong>isdiscarded.Sincewe'renotallowedto TheGetserviceclauseremovestherstentryfromthetable<strong>and</strong>placesit Onemoretechnicalpointaboutinsert:thestatementmovesitsoper<strong>and</strong><br />
meanssimplythrowingitaway.Callmessages<strong>and</strong>portsaretreatedspecially:Whenacallmessage,oranyvaluewhichcancontaincallmessages<br />
TheQuitservicecallterminatestheloop,<strong>and</strong>henceterminatesthe nalized|thatis,theirvaluesarediscarded.InBoundedBuffer,thatwould bethequeue,thebooleanvariableRunning,thethreeserviceports,<strong>and</strong> secondelementnowbecomesrst. theinitializationport.Formost<strong>Hermes</strong>datatypes,discardingthevalue process. executingitslaststatement.Allvariableswhichremaininitializedare-<br />
discarded,thecallmessagesarereturned.EachcallmessagetypehasadefaultDiscardedexception,e.g.GetLineInterface.Discarded.Whenan<br />
Disconnectedexception.Anyprocesswhichbecomesisolatedbecauseall itsconnectionstotheoutsideworldarebrokenisequivalenttoaterminated inputportisdiscarded,connectionstothatportarebroken;attemptsto (e.g.aninputportwhichmayhaveseveralcallmessagesonitsqueue)is Let'slookmorecloselyatprocesstermination.Aprocessterminatesafter<br />
process<strong>and</strong>canbesafelygarbage-collectedbytheimplementation. sendmessagesoverthoseconnectionswillfail<strong>and</strong>thecallerwillreceivea
toaservice,whileretainingtheabilitytorevokeaccess,giveoutaconnectiontoalterprocesswhichalsosupportsaQuitservicethatyoucall<br />
Summary:Wehaveshownthestructureofatypicalserver:anin-<br />
Thishasthefollowingconsequences:Togiveaprocesstemporaryaccess whenyouwanttorevokeaccess.Ifyou'reprogrammingashellwhichis mightrunwild,makesurethatoninitialization,youonlypassrevocable 301.6.ASimpleServer<br />
outputports.Thenifyourevokealltheports,theprocesswillbecome isolated,eectivelycancellingtheprocess. goingtocreateprocessesrunningarbitraryprogramswhichyou'reafraid putportperservice,somelocalstate,<strong>and</strong>aniteratedselectstatement. informationhidingofdataabstraction<strong>and</strong>object-orientedlanguagesbut Booleanguardsmaybeusedtoprioritizethecallsortoconditionallydisablecertainservices.Wehaveclaimedthatserverprocessesachievethe<br />
withadditionaladvantages.Youhavelearnedaboutthetable<strong>and</strong>ordered tabletypefamilies.Youhavelearnedwhathappenswhenprocessesterminate,<strong>and</strong>thatyoucanusetheabilitytoterminateltersasameans<br />
foraccessrevocation<strong>and</strong>terminationofchildprocesses.Youhavelearned booleanguard,eventguard,Discardedexception,Disconnectedexception,RangeErrorexception,processtermination,theselect,insert<strong>and</strong><br />
thefollowing<strong>Hermes</strong>concepts:alternativeclauses,enable<strong>and</strong>disable, removestatements,thecopyof<strong>and</strong>sizeofoperations.
2AMiniatureSystem Sincetherealpurposeofthissectionistoillustratesystemsprogramming with<strong>Hermes</strong><strong>and</strong>nottodesigntheidealwindowsystem,wewilleliminate thehairydetailsofgraphics,tiling,etc.,<strong>and</strong>striptheproblemtothebare bones. Ournalexamplewillbeadynamicsystem|asimpliedwindowsystem.<br />
SupposeIhaveaterminaldevice.Let'sassumethatitusesthesameoversimpliedterminalinterfacewehavebeenusinginthepreviousexamples:<br />
Mostofthe<strong>Hermes</strong>constructsusedinthisexamplearealreadyfamiliar; howeverwewillintroduce<strong>and</strong>explainafewnewconstructsaswegoalong. 2.1Requirements GetLine<strong>and</strong>PutLine.Inowwouldliketomultiplexthisterminalsothat<br />
withtheapplicationrunninginit. startupanewapplicationinanewwindow,or(3)killawindowtogether window.Inputfromtheterminalwillbedirectedtothewindowcurrently infocus.Fromtheterminal,Icanalso(1)changethecurrentfocus,(2) initsownwindow.Outputfromanapplicationwillbedirectedtoits writtentousetheterminaldevice,sotheyusetheGetLine<strong>and</strong>PutLine Icanrunseveralclientapplications.Eachclientapplicationwasoriginally<br />
line-at-a-timeinterface,asfollows:Everywindowwillhaveacharacter interfaces,too.<br />
stringname.Whenalineiswrittenoutbyanapplication,itwillappear Inthisexample,wewillimplementthesefunctions,usingourlimited, Iwanttodividemyterminalintologicalwindows.Eachapplicationruns<br />
areveescapesequences: byanescapecharacteristreatedspeciallybythewindowmanager.There (!)isassumedtobetypedintothecurrentwindow.Everyinputlineheaded ontheterminalintheform:.Toremindtheuser typedoutasaprompt.Everyinputlinenotheadedbyanescapecharacter whichwindowisinfocus,thenameofwindowcurrentlyinfocuswillbe !Cwindownameapplicationparms-createawindowwindowname !Fwindowname-changefocustowindowname !!line-dispatch!linetothewindowcurrentlyinfocus.Thisis howyousenddatawhichbeginswithanescapecharacter. runningapplication
322.1.Requirements<br />
PutLine<br />
PutLine<br />
GetLine<br />
GetProgram<br />
frontend<br />
Kill<br />
Create<br />
Dispatch<br />
Refocus<br />
windowmanager<br />
InputToWindow<br />
WriteToWindow InputToWindow Quit<br />
Window Application<br />
Window Application<br />
quitdispatcher<br />
quitdispatcher<br />
beusedasaguidetobuildingsomethingmorepractical.Itwouldn'tbe hardtomodifythecodetouseagraphicalscreen,<strong>and</strong>tousemouseclicks FIGURE2.1.Structureofthewindowsystem<br />
ratherthanescapesequencestochangethefocus<strong>and</strong>tocreate<strong>and</strong>destroy windows.Thebasicstructureofthesystemremainsthesame. Thisisobviouslynotarealisticwindowmanager,butitsstructurecan !Q-quitwindowsystem !Kwindowname-killwindowname<br />
Buffer Client Adapter<br />
Buffer Client Adapter<br />
2.2Design Thestructureofthesystemisshowningure2.1.
2.AMiniatureSystem33<br />
FIGURE2.2.StructureofaWindowSystemApplication<br />
GetProgram<br />
vokesoneoftheservices:Refocus,Kill,Create,orDispatch.Thefront-<br />
endalsokeepstrackofwhichwindow(ifany)iscurrentlyinfocus. applicationrunninginthatwindow,<strong>and</strong>(2)Quittoshutdownthewindow. managerhasapairofports:(1)InputToWindow,fordirectingdatatothe frontend.ThewindowmanagerprocessservicesWriteToWindowcallsfrom applicationssendinglinestotheirwindow.Foreachwindow,thewindow Thewindowmanagerprocesssupportsthesefourservicescalledbythe Afront-endprocessreadslinesfromtheterminal,parsesthem,<strong>and</strong>in-<br />
thewindow.WhenaQuitcallisreceived,theunboundedbuer<strong>and</strong>the passesGetProgramcalls.Boththeunboundedbuer<strong>and</strong>theadapterare preparedtoreceiveQuitcallswhenthewindowmanagerdecidestokill ItconvertsPutLinecallsintotheappropriateWriteToWindowcalls,<strong>and</strong> linestypedaheadtotheclient,<strong>and</strong>(3)anadapterprocess,Adapter.These processesareshownindetailingure2.2,TheadapterissimilartoFilter. buerprocess,similartotheBoundedBufferdescribedabovewhichstores thesamest<strong>and</strong>ardinterfacefamiliarfromHelloWorld,(2)anunbounded Eachapplicationconsistsofthreeprocesses:(1)theclientitself,with<br />
modules.Herearetheinterfacedenitionsforthewindowmanager: Oncewehavedesignedthemodulestructure,wecanwritethedenitions 2.3Interfaces adaptershutdown,isolatingtheclient<strong>and</strong>thusterminatingit. WMExternal:using(St<strong>and</strong>ard)definitions<br />
InputToWindow<br />
Quit<br />
Quit<br />
quitdispatcher<br />
WriteToWindow<br />
Quit<br />
Buffer GetLine Client PutLine Adapter<br />
GetProgram
342.3.Interfaces WMInterface:callmessage( --initializationinterfaceforwindowmanager<br />
GetProgram:GetProgramOut,--serviceforloadingprograms PutLine:PutLineOut,--writealinetothephysicalterminal Dispatch:DispatchOut,--dispatchalinetotheappropriate Refocus:WindowOut,--changethecurrentfocus<br />
DispatchInterface:callmessage( constant(GetProgram,PutLine) Kill:WindowOut,--killthespecifiedwindow<br />
WindowName:Charstring,---windowtowhichtextisbeingsent --interfacetooperationDisptach WMOut:outportofWMIn; WMIn:inportofWMInterfacefinit(GetProgram),init(PutLine)g; exitffullg; Create:CreateOut)--makeanewwindow<br />
WindowInterface:callmessage( --interfacetooperationsRefocus,Kill DispatchOut:outportofDispatchIn; DispatchIn:inportofDispatchInterfaceffullg; Line:Charstring)--texttodispatch<br />
WindowName:Charstring)--nameofwindowoper<strong>and</strong> constant(Line)<br />
constant(WindowName) exitffullg<br />
exitffullg exceptionNotFoundffullg;--nosuchwindow<br />
CreateInterface:callmessage( WindowOut:outportofWindowIn; --interfacetooperationCreate WindowIn:inportofWindowInterfaceffullg; ParmString:Charstring)--parameterstoclientprogram ProgramName:Charstring,--nameofclientprogramtorun WindowName:Charstring,--nameofwindowbeingcreated exceptionNotFoundffullg;<br />
WriteToWindowInterface:callmessage( CreateOut:outportofCreateIn; --interfacetooperationWriteToWindow CreateIn:inportofCreateInterfaceffullg; constant(WindowName,ProgramName,ParmString) exceptionCreateFailureffullg; exitffullg exceptionDuplicateffullg
WriteToWindowOut:outportofWriteToWindowIn; WriteToWindowIn:inportofWriteToWindowInterfaceffullg; constant(WindowName,Line) Line:Charstring)--outputstring WindowName:Charstring,--nameofwindowbeingoutputto exitffullg; 2.AMiniatureSystem35<br />
accesstotheWriteToWindow<strong>and</strong>GetProgramservices,<strong>and</strong>thenameof tothebuerprocess<strong>and</strong>tothequitservice.Soherearethedenitionsfor theinitializationofanapplication: thewindow(neededbythelter).Theapplicationmustexportconnections (neededbytheapplicationbuilder)<strong>and</strong>parameters(neededbytheclient), enddefinitions<br />
Quit) StartWindowApplication:using(St<strong>and</strong>ard,BBExternal,WMExternal, Eachwindowapplicationneedstobeinitializedwithaprogramname<br />
definitions WindowApplicationInterface:callmessage( window ProgramName:Charstring,--nameofclientprogramtorun<br />
WindowName) InputToWindow:PutLineOut,--forwritingintoinputbuffer GetProgram:GetProgramOut,--serviceforloadingprograms constant(ProgramName,ParmString,GetProgram,WriteToWindow, WindowName:Charstring,--nameofwindow ParmString:Charstring,--parameterstoclientprogram WriteToWindow:WriteToWindowOut,--forwritinglinestoa<br />
WindowApplicationIn:inportofWindowApplicationInterface<br />
exitffullg exceptionNotCreated<br />
Quit:QuitOut)--forkillingtheapplication<br />
gramwhichhadbeenwrittentocommunicatewiththeterminalcanrun lowsfromtheoriginalproblemstatementwhichspeciedthatanypro-<br />
buer,<strong>and</strong>theadapter.TheclientwillhaveinterfaceSt<strong>and</strong>ard.Thisfol-<br />
Thethreeprocessescomprisinganapplicationare:theclient,thebounded WindowApplicationOut:outportofWindowApplicationIn; enddefinitions init(GetProgram),init(WriteToWindow),init(WindowName)g; finit(ProgramName),init(ParmString),<br />
Sincetheadapterislikethelter,wewilldesignitsinterfacebymaking theadapterhasinterfaceAdapter.WehavealreadydesignedBBExternal. withinasinglewindow.TheboundedbuerhasinterfaceBBExternal,<strong>and</strong>
asmallchangetotheinterfaceFilter.Recallthattheadapterexportsa 362.3.Interfaces porttoitsQuitserviceaswellasaClientPutLineport: AdapterInterface:callmessage( Adapter:using(St<strong>and</strong>ard,WMExternal,Quit)definitions ClientPutLine:PutLineOut,--portfromclienttoadapter ClientGetProgram:GetProgramOut)--portfromclienttoadapter Quit:QuitOut,--porttoshutdownadapter AdapterToWindow:WriteToWindowOut,--porttowindowmanager WindowName:Charstring,--windownamefordirectingoutput GetProgram:GetProgramOut,--porttoGetProgramService<br />
GetProgramports,<strong>and</strong>theportstothefourfront-endaccessibleservices AdapterIn:inportofAdapterInterface constant(AdapterToWindow,WindowName,GetProgram)<br />
ofthewindowmanager.Itsinterfaceis: AdapterOut:outportofAdapterIn; enddefinitions Finally,thefrontendprocessmustbegiventheGetLine,PutLine,<strong>and</strong> exitffullg;<br />
FEPExternal:using(St<strong>and</strong>ard,WMExternal)definitions finit(AdapterToWindow),init(WindowName),init(GetProgram)g;<br />
window FEPInterface:callmessage( Refocus:WindowOut, Kill:WindowOut, Create:CreateOut) constant(GetLine,PutLine,GetProgram,Dispatch,Refocus,Kill, PutLine:PutLineOut, GetProgram:GetProgramOut, Dispatch:DispatchOut,--dispatchalinetotheappropriate GetLine:GetLineOut,<br />
2.4WindowSystemShell Create) FEPIn:inportofFEPInterfaceffullg; FEPOut:outportofFEPIn; enddefinitions exitffullg;<br />
process<strong>and</strong>thewindowmanager.Theoutershellissimilartotheprogram Let'sbeginwiththeoutershellofthesystem.Itsimplycreatesthefrontend Nowthattheinterfacesareallwritten,theprogramsarefairlyeasytowrite.
GetProgram<strong>and</strong>PutLine,whereuponitreceivesbackportstofourofthe initializesthefrontendprocess,passingGetLine,GetProgram,<strong>and</strong>the Compoundwhichwewroteearlier.Itcreatesthewindowmanagerprocess. Itcallstheinitializationportofthewindowmanager,givingitaccessto vewindowmanagerservices.(Thefthservice,WriteToWindow,isonly availabletocreatedapplications<strong>and</strong>nonehavebeencreatedyet.)Itthen 2.AMiniatureSystem37<br />
fourservices: WMSystem:using(St<strong>and</strong>ard,WMExternal,FEPExternal) process(Init:St<strong>and</strong>ardIn) begin declare Dispatch:DispatchOut;--dispatchserviceinWM call(WMOut#(createofParms.GetProgram("windowmanager"))) receiveParmsfromInit; Refocus:WindowOut;--refocusserviceinWM Kill:WindowOut;--killserviceinWM Create:CreateOut;--createserviceinWM Parms:St<strong>and</strong>ardInterface;--initializationcallmessage<br />
call(FEPOut#(createofParms.GetProgram("frontend"))) (Parms.GetProgram,Parms.PutLine,Dispatch,Refocus,Kill,<br />
2.5Front-endProcess endprocess returnParms; Refocus, (Parms.GetLine,Parms.PutLine,Parms.GetProgram,Dispatch,<br />
Thefront-endprocessisasimpleloopinwhichalineisread,<strong>and</strong>adecision Kill,Create);<br />
treeisfollowedtooneofthedecisionsDispatch,Refocus,Kill,Create, orerror.Hereistheprogram.Weleaveittoyoutollinthedeclarations. tokenizer:=procedureofParms.GetProgram("tokenizer"); running:='true'; receiveParmsfromInit; blockbegin WindowName:="";--nowindowinfocus while(running)repeat blockdeclare Line:Charstring;--linereadbyfrontend begin Escape:Char;--escapecharacterremovedfromline callParms.PutLine(WindowName|">");--promptuser
382.5.Front-endProcess callParms.GetLine(Line); ifsizeofLine=0<br />
elseifLine[0]'!' then<br />
blockdeclare removeEscapefromLine[0]; begin callParms.Dispatch(WindowName,Line);<br />
Cmd:Charstring;--comm<strong>and</strong>namefollowing! ifLine[0]='!' then else callParms.Dispatch(WindowName,Line); extractcmdfromLine[0]; select(cmd) where("F") blockdeclare begin FParm:Charstring;--parameterto!F FParm:=tokenizer(Line); callParms.Refocus(FParm);<br />
where("K") to"|FParm|"."); awindow."); endblock; on(WindowInterface.NotFound) callParms.PutLine("!wfe:"|FParm|"not WindowName:=FParm; callParms.PutLine("!wfe:Focuschanged<br />
blockdeclare begin KParm:Charstring;--parameterto!K<br />
where("Q") on(WindowInterface.NotFound) awindow."); endblock; callParms.PutLine("!wfe:"|Kparm|"not callParms.PutLine(Kparm|"killed."); KParm:=tokenizer(Line);<br />
running:='false'; callParms.Kill(Kparm);
where("C") callParms.PutLine("Quittingwindowmanager."); blockdeclare !CPName:Charstring;--programname CParm:Charstring;--windowparameterto 2.AMiniatureSystem39<br />
begin CParm:=tokenizer(Line); PName:=tokenizer(Line); blockbegin on(TokenizeInterface.noToken) Parm:Charstring;--programparameters<br />
on(CreateInterface.CreateFailure) create"|CParm| on(CreateInterface.Duplicate) "sinceitalreadyexists."); callParms.PutLine("!wfe:Cannotwindow endblock; callParms.Create(Cparm,Pname,Parm); WindowName:=CParm; Parm:="";<br />
applicationprocess" callParms.PutLine("!wfe:Unabletocreate<br />
"|cmd); endselect; otherwise endblock; --error:notF,Q,KorC callParms.PutLine("!wfe:Illegalcomm<strong>and</strong>: |PName|".");<br />
on(TokenizeInterface.noToken) --error<br />
endwhile; doesnotexist"); endblock; on(DispatchInterface.NotFound) callParms.PutLine("!wfe:Window"|WindowName|" endif;endif; endblock; callParms.PutLine("!wfe:Missingargument.");<br />
on(others)
402.5.Front-endProcess paringavalueagainstasetofvalues.Itisequivalentto: Temp:=Line[ColonPosition+1]; Theselectstatementintheexampleistheusualabbreviationforcom-<br />
returnParms; where(Temp='F')... endblock; callParms.PutLine("!wfe:othersexception");<br />
<strong>Hermes</strong>'abilitytoplug<strong>and</strong>unplugmodulesindierentcongurations.(2) e.g.onebaseduponpointing,ordialog,ormenu-selection.Thisexploits vantages:(1)Itiseasytousethecomm<strong>and</strong>swithanalternativefront-end, thecodewhichobeysthecomm<strong>and</strong>s.Thisstyleofwritinghasseveralad-<br />
endselect; Noticethatwehaveseparatedthecodewhichparsesthecomm<strong>and</strong>from otherwise... where(Temp='C')... where(Temp='K')...<br />
frontendfromasimpledescriptionofthecomm<strong>and</strong>syntax. Therearetoolswhichautomaticallygenerateprogramssuchastheabove<br />
havetoissueacreateoperationbeforeeachprocedurecall. afteritreturns. procedureoftomakeiteasytoinvokeprocedures.Withoutit,youwould aprocesswhichiscreatedjustforasinglecall,<strong>and</strong>whichterminatesright token(stringofcontiguousnon-blankcharacters)fromastring.Procedures tverynicelyintotheprocessparadigmof<strong>Hermes</strong>.Aprocedureissimply Hereishowprocedureofworks:Youcodeprocedureofwithaprogramoper<strong>and</strong>,justlikecreateof.Theresultisanoutputportconnectetionportofthenewprocess.<br />
toaninitializationport.However,eachtimeyoumakeacallonthatoutput port,anewprocessisinstantiated,<strong>and</strong>yourcallisgiventotheinitializa-<br />
Sinceproceduresaresocommon,<strong>Hermes</strong>providesaspecialoperation, Thefront-endprocessusesaprocedurenamedTokenizertoextracta<br />
automatically. of,thesecondcallwillnotblockbecauseanewinstancewillbecreated mentedwithcreateof,thesecondcallwillblock;ifyouusedprocedure thereexistsonlyoneactivationatatime,thenitdoesn'tmatterwhether youcreatearegularprocesswithcreateora\process-generator"with beingprocessed,thenitdoesmakeadierence:ifyourprocedurewasimple-<br />
procedure.Butifyouevermakeasecondcallwhiletherstcallisstill Processescreatedautomaticallywithprocedureofarestilllike<strong>Hermes</strong> Ifyouarenotusingaprocedurere-entrantlyorrecursively|thatis,<br />
statement,unlessthereturnisthelaststatement.IfyouwanttheequivalentofAlgolprocedures,besuretouseprocedureof<strong>and</strong>begineach<br />
processesineveryotherway.Inparticular,theystillpersistafterareturn
procedureprocesswithareceive<strong>and</strong>enditwithareturn. 2.6TokenizerProcedure HereisthecodeoftheTokenizerprocedure: 2.AMiniatureSystem41<br />
pNB); blockbegin receiveParmsfromInit; pNB:=positionofCinparms.stringwhere(C''); extractblanksfromBinparms.stringwhere(positionofB<<br />
on(NotFound) C
ationtable[expr].Wehaveencounteredthisabbreviationintheprogram positioninthetableisexpr."Thisformofselectorworksexactlylikearray indexing.Itissocommonthat<strong>Hermes</strong>allowsyoutousetheabbrevi-<br />
where(positionofelement=expr)means\selecttheelementwhose BoundedBuffer.ThestatementremovecmdfromLine[0]isashorth<strong>and</strong> 422.6.TokenizerProcedure<br />
\removetherstcharacterfromLine<strong>and</strong>storeitincmd." theelementbeingtestedbytheselector.Forexample,elementintable<br />
aspartofanotheroperator:e.g.remove,every,extract,position: forremovecmdfromCinLinewhere(positionofC=0),<strong>and</strong>itmeans Aselectorcanappeareitherbyitselfasanexpression,oritcanappear Aselectorallbyitselfinanexpressionreturnsacopyoftheselected thentheearliestoneischosenifthetableisordered,<strong>and</strong>anarbitrary oneischosenifthetableisunordered.ANotFoundexceptionisraised ifthereisnoselectedelement.Example:Line[0]evaluatestotherst characterofLine,ifLineisnon-empty,otherwiseitraisesaNotFound thenamethe-element.Ifthereismorethanoneselectedelement, exception.ItcanalsobewrittenCinLinewhere(positionofC =0). element.Youcanlookthisoperationupinthereferencemanualunder<br />
Theeveryofoperationgeneratesanewtableconsistingofevery Theremovestatementremovesasingleelement.Ifnoelementis selected,therstselectedelementischosenifthetableisordered, selected,aNotFoundexceptionisraised.Ifmorethanoneelementis otherwiseanarbitrarychoiceismade.<br />
Theextractstatementissimilartoeveryof,exceptthatitremoves wherethisoperationwasusedtoselectthosecharactersbefore<strong>and</strong> computesubsetsorsubstrings.(ReferbacktotheprogramCompound, elementswillhavethesamerelativeorder.Thisoperationisusedto selectedelement.Iftheoriginaltablewasordered,thetableofselected afterthe'/'.<br />
ble,<strong>and</strong>thepositionofoperatordiscussedabove,whichisappliedwithin Notethedierencebetweenpositionofselector,whichsearchesata-<br />
Thepositionofoperationwithaselector(e.g.positionofCin aNotFoundexceptionisgenerated. Linewhere(C=':'))returnsthepositionoftherstselectedelementwithintheorderedtable.Ifnoelementinthetableisselected,<br />
theelements. theselectedelementsfromitssourceoper<strong>and</strong>,ratherthancopying<br />
=':').ThisexpressionsearchesfortherstcoloninLineafterposition P,<strong>and</strong>returnsthepositionofthatcolon. aselectorpredicate.Thefollowingexpressionusesbothkindsofposition ofoperators:positionofCinLinewhere(positionofC>P<strong>and</strong>C
ports,<strong>and</strong>itsoutputport,whatstatedoesitneedThewindowmanagermustknowwhichwindowsexist,<strong>and</strong>howtodispatchlinestothose<br />
2.7TheWindowManager 2.7.1Definitions Nowlet'scodethewindowmanagerprocessitself.Besidesitsveinput 2.AMiniatureSystem43<br />
ofinformation:thewindow'sname,theportoverwhichwedispatchlines windows.<br />
type.HereiswhatweneedtowriteinWMInt,thedenitionsmodulefor thetableforeachcreatedwindow.Theelementwillconsistofthreepieces name<strong>and</strong>thetwoports,<strong>and</strong>atablewhoseelementsarerecordsofthis we'veusedsofar,thistablewillbeunordered.Therewillbeoneelementin destinedfortheapplicationinthatwindow,<strong>and</strong>theQuitportwhichwe needwhenwewanttokillthewindow<strong>and</strong>isolatetheclientprocess. Thenatural<strong>Hermes</strong>waytodothisistodeneatable.Unlikethetables<br />
typesusedinternallybythewindowmanager: Window:record( WMInt:using(St<strong>and</strong>ard,Quit)definitions Weneedtodenetwo<strong>Hermes</strong>types:arecordcontainingthewindow<br />
tableoftypeWindowsconsistsoffullyinitializedrecordsoftypeWindow. WindowName:Charstring,--thenameofthewindow<br />
seethatWindowdenesatuple<strong>and</strong>Windowsarelation.Thenotation Ifyouarefamiliarwiththeterminologyofrelationaldatabases,youwill Windows:tableofWindowffullgkeys(WindowName); enddefinitions Therecorddenitionisstraightforward.Thetabledenitionsaysthata InputToWindow:PutLineOut,--portforwritingintoinputbuffer<br />
keys(WindowName)saysthatnotwoelementsofthetablemayhavethe Quit:QuitOut);--portforkillingtheapplication<br />
samevalueofcomponentWindowName.Inrelationaldatabaseterminology, thereisafunctionaldependencybetweenthecomponentWindowName<strong>and</strong> theothercomponents.<br />
youwouldnotbeabletousethisabbreviation,becauseitwouldinstead tableonitskeycomponents.IftheWindowstabletypehadbeenordered, arecordwhoseWindowNamecomponentduplicatestheWindowNamecomponentofarecordalreadyinthetablewillfail.TheexceptionDuplicateKey<br />
T[N]isavailableasanabbreviationforEinTwhere(E.WindowName= Thereisalsoasyntacticeectofthekeysdeclaration:theshorth<strong>and</strong> Thesemanticeectofthekeysdeclarationisthis:anattempttoinsert willberaised. N).Thisabbreviationexistssimplybecauseit'sfairlycommontosearcha meanEinTwhere(positionofE=N).Theabbreviationforselecting
ishidden<strong>and</strong>innowayaectsthesemantics. 442.7.TheWindowManager<br />
2.7.2Skeleton We'renowreadytowritetheskeletonofthewindowmanager: anelementbypositiontakesprecedenceovertheabbreviationforselecting sothefactthatNisnotanintegerwillnothelp. anelementbykey.Abbreviationsareexp<strong>and</strong>edbeforetypesarechecked, Onceagain,weremindyouthatthephysicalrepresentationofthetable WindowManager:using(St<strong>and</strong>ard,WMExternal,WMInt,StartWindowApplication) process(Init:WMIn) declare RefocusCM:WindowInterface; WriteToWindow:WriteToWindowIn; WriteToWindowCM:WriteToWindowInterface; Refocus:WindowIn; Parms:WMInterface;--initializationparameters Dispatch:DispatchIn; DispatchCM:DispatchInterface; Create:CreateIn; CreateCM:CreateInterface; Kill:WindowIn;<br />
begin CreatedWindows:Windows;--statusofallwindows CurrentFocus:Charstring;--nameofwindowinfocus WriteToWindowCapability:WriteToWindowOut; KillCM:WindowInterface; GetProgram:GetProgramOut; PutLine:PutLineOut;<br />
GetProgram:=Parms.GetProgram; PutLine:=Parms.PutLine; receiveParmsfromInit; --initializationsection ApplicationBuilder:Program;<br />
ApplicationBuilder:=Parms.GetProgram("applicationbuilder"); newWriteToWindow;connectWriteToWindowCapabilitytoWriteToWindow; newRefocus;connectParms.RefocustoRefocus; CurrentWindow:Window;--awindowbeinginsert/deleted/searched<br />
newCreate;connectParms.CreatetoCreate; newKill;connectParms.KilltoKill; returnParms; newCreatedWindows; --servicesection newDispatch;connectParms.DispatchtoDispatch;
while('true')repeat --eventCreate... --eventDispatch... --eventWriteToWindow... select --eventRefocus... 2.AMiniatureSystem45<br />
BoundedBuffer.Onedierenceisthatwedonotgivethewindowmanager'sparentaconnectiontotheWriteToWindowservice.Thisconnection<br />
Sofar,thewindowmanagerhasthesamestructureasserverssuchas endprocess endwhile; endselect; --eventKill... willbegiveninsteadtothechildrenofthewindowmanager|thewindow applications. otherwise<br />
TheRefocus<strong>and</strong>WriteToWindowservicesarestraightforward.Refocus 2.7.3Refocussing<strong>and</strong>WritingOutput simplycheckswhetherthewindowexists. eventRefocus receiveRefocusCMfromRefocus; ifexistsofCreatedWindows[RefocusCM.WindowName]<br />
eventWriteToWindow WriteToWindowprependsthewindownametothetextline. else then<br />
receiveWriteToWindowCMfromWriteToWindow; endif; --erroraction returnRefocusCMexceptionNotFound; returnRefocusCM;<br />
tionifthedestinationwindowdoesnotexist. TheDispatchserviceinvolvesasimpletablelookup.Wereturnanexcep-<br />
2.7.4DispatchingLinestoaParticularWindow eventDispatch returnWriteToWindowCM; callPutLine(WriteToWindowCM.WindowName|":"|WriteToWindowCM.Line);<br />
blockbegin receiveDispatchCMfromDispatch; CurrentWindow:=CreatedWindows[DispatchCM.WindowName];
462.7.TheWindowManager callCurrentWindow.InputToWindow(DispatchCM.Line);<br />
ofanyothertypecontainingthesetypes(suchasarecordcontainingan <strong>and</strong>callmessagetypefamiliesarenotcopyable.Variablesofthesetypes,or selectorexpressiontocopyanelementfromthetableintoavariable.We shouldpointoutonesituationinwhichthisdoesnotwork.Theinputport Thisprogramillustratesonewaytolookupsomethinginatable|usea endblock; on(NotFound) returnDispatchCMexceptionNotFound; returnDispatchCM;<br />
inputportoratablecontainingacallmessage)cannotbecopied.Todoa tablelookupwhenthetableelementscannotbecopied,usetheinspect statement.Hereisthesameprogramfragmentrewrittenwiththeinspect<br />
blockbegin receiveDispatchCMfromDispatch; inspectWinCreatedWindows[DispatchCM.WindowName] begin<br />
anobjectofanydatatype,becausetheproblematicoperationsareillegal elementoftableCreatedWindows.<strong>Hermes</strong>doesnotallowmakingcopies returnwouldbecomecomplex.Howeverconstantcopiesmaybemadeof ofinputports<strong>and</strong>callmessages,becausethesemanticsofreceive<strong>and</strong> TheinspectstatementassignsWfromaconstantcopyoftheselected on(NotFound) endblock; endinspect; callW.InputToWindow(DispatchCM.Line);<br />
non-copyablecases. Thatway,youwillnothavetousetwodierentstylesforthecopyable<strong>and</strong> whenappliedtoconstants. fortablelookupallthetime,evenwhenthetableelementsarecopyable. declareCurrentWindow.Butintheversionusinginspect,youdon'twrite oftableCreatedWindows.Youmaywishtousetheinspectstatement newscopeinwhichWisdeclaredtohavetypeWindow|theelementtype aseparatedeclarationforthevariableW.Theinspectstatementdenesa Theinspectstatementselectsexactlyoneelement(orelseraisesan Intheprogramfragmentwrittenwithoutinspect,itisnecessaryto<br />
eachelementofatablewhichsatisestheselectorpredicate.(Thismaybe forstatementiterativelyexecutesthestatementswithinitsbodyoncefor exception).Toselectallelements,iteratively,useaforstatement.The example,hereisapieceofcodewhichprintsthenamesofalltheactive zerotimesifthetableisemptyorifnoelementsatisestheselector.)For windows: forWindowinCreatedWindowswhere('true')
foreyoudonotdeclareWindowexplicitly.Withinthatscope,thevariable Windowcontainsaconstantcopyofoneoftheselectedelementsofthetable.Fororderedtables,theiterationsoccurintheorderthattheselected<br />
elementsoccurinthetable.Forunorderedtables,theiterationsoccurin Liketheinspectstatement,theforstatementcreatesascope.There-<br />
inspect endfor; callPutLine(Window.WindowName); 2.AMiniatureSystem47<br />
anarbitraryorder.<br />
InputToWindow<strong>and</strong>Quit.Wegettheseportsbycreatinganapplication Thenewwindowrecordcontainsthewindow'sname,<strong>and</strong>thetwoports we'regoingtobuildanewwindowrecord,<strong>and</strong>insertitintothetable. viationisparticularlyusefulintheforstatement. Nowlet'sdocreation<strong>and</strong>destructionofwindows.Tocreateawindow, 2.7.5Creating<strong>and</strong>KillingWindows Theconstructwhere('true')maybeabbreviatedas[].Thisabbre-<br />
processes,<strong>and</strong>returnthetwodesiredports.Wehavetopasstheapplicationbuildertheseparameters:theprogramname<strong>and</strong>parameterstring,<br />
aconnectiontoGetProgram,<strong>and</strong>aconnectiontoWriteToWindow.The structuresdened: codeisverystraightforwardnowthatwehavealltheinterfaces<strong>and</strong>data eventCreate else receiveCreateCMfromCreate; ifexistsofCreatedWindows[CreateCM.WindowName] then blockbegin returnCreateCMexceptionDuplicate; --erroractionbecausewindowalreadyexists newCurrentWindow; CurrentWindow.WindowName:=CreateCM.WindowName; call(WindowApplicationOut#(createofApplicationBuilder))<br />
builderprocess.Theapplicationbuilderwillcreatethethreeapplication<br />
endblock; on(WindowApplicationInterface.NotCreated) returnCreateCMexceptionCreateFailure; insertCurrentWindowintoCreatedWindows; returnCreateCM; --erroractionifunabletocreateprocess (CreateCM.ProgramName,CreateCM.ParmString, CurrentWindow.InputToWindow,CurrentWindow.Quit); GetProgram,WriteToWindowCapability,CurrentWindow.WindowName,
name.Ifwewaitedtobuildtheapplicationrst<strong>and</strong>thencheckfora DuplicateKeyexception,theillegalapplicationmayhavealreadystarted 482.7.TheWindowManager exceptionbycheckingrstfortheexistenceofawindowwithidentical running<strong>and</strong>mayhavealreadyproducedoutput.Theexistsofoperator checksforthiscase.Thisoperationtakesaselector<strong>and</strong>evaluatestotrue if<strong>and</strong>onlyifoneormoreselectedelementsexist. TheonlytrickybitisthatwemustavoidthepossibilityofaDuplicateKey Todestroyawindow,wesimplyremovethewindowdescriptorfromthe endif;<br />
application.ThisservicewillcallQuitonthebuerprocess<strong>and</strong>theadapter process,withtheresultthattheclientprocesswillshutdown. tableofcreatedwindows<strong>and</strong>thencalltheQuitportassociatedwiththat eventKill receiveKillCMfromKill;<br />
endblock; on(NotFound) blockbegin callCurrentWindow.Quit(); returnKillCMexceptionNotFound; --erroraction discardCurrentWindow; returnKillCM; removeCurrentWindowfromCreatedWindows[KillCM.WindowName];<br />
eventGetFocus receiveGetFocusCMfromGetFocus; then ifCurrentFocus""<br />
portsfromprocesstoprocess. thiscodewhenyouhavetables,exceptionh<strong>and</strong>ling,<strong>and</strong>theabilitytopass Thisnishesthewindowmanager.Noticehowconvenientitistowrite endif; else returnGetFocusCMexceptionNotFound; returnGetFocusCM; GetFocusCM.Focus:=CurrentFocus;<br />
isastraightforwardvariationofFilter. 2.8CreatingaWindowApplication orWMSystem,itshouldbeeasytobuildApplicationBuilder.AndAdapter Allthatisleftaretheapplicationbuilder,theadapter,<strong>and</strong>thequitdispatcher.Theseprogramsusenonewprinciples.IfyoucanbuildCompound
2.8.1ApplicationBuilder unboundedbuer,aninstanceoftheadapter,<strong>and</strong>aninstanceoftheclient. ItalsobuildsaprocesswhichinterpretstheQuitcallmessagebycalling theQuitserviceinboththebuer<strong>and</strong>theadapter. HereisthecodeofApplicationBuilder.Itcreatesaninstanceofthe Hereistheonlytrickypart:ApplicationBuildertruststhebuer,the 2.AMiniatureSystem49<br />
thismightbeanarbitrarymodule,whichmightnotevenreturnfromits initializationcall.SoApplicationBuildershouldbesuretocalltheclient adapter,<strong>and</strong>thequith<strong>and</strong>lerprocesses.Itdoesn'ttrusttheclient,since window.ThiswillcausethequitdispatcherprogramtocallQuitinthe thewindowmanagerwillstillberunning.Theendusercanthenkillthe last.Iftheclientgoesintoaloopordeadlocks,wearestillsafe,because client<strong>and</strong>theapplicationbuilderprocessesbecomeisolated,<strong>and</strong>theywill begarbagecollected. buer<strong>and</strong>theadapter.Whenthebuer<strong>and</strong>theadapterterminate,the ApplicationBuilder: Quit,QuitDispatcher) using(St<strong>and</strong>ard,StartWindowApplication,BBExternal,Adapter,<br />
Adapter process(Init:WindowApplicationIn)<br />
begin declare Parms:WindowApplicationInterface;--initializationcallmessage<br />
block receiveParmsfromInit; Client:St<strong>and</strong>ardOut;--clientprocess ClientGetLine:GetLineOut;--GetLinefromClienttoBuffer ClientGetPgm:GetProgramOut;--GetProgramfromClientto ClientPutLine:PutLineOut;--PutLinefromClienttoAdapter ParmString:Charstring;--parametertoclientprocess declare begin AdapterQuit:QuitOut;--adapter'squitport BufferQuit:QuitOut;--buffer'squitport<br />
Client:=createofParms.GetProgram(Parms.ProgramName); call(BBout#(createofParms.GetProgram("unboundedbuffer"))) call(QuitDispOut#(createofParms.GetProgram("quitdispatcher"))) ParmString:=Parms.ParmString; call(AdapterOut#(createofParms.GetProgram("adapter"))) (Parms.WriteToWindow,Parms.WindowName,Parms.GetProgram, AdapterQuit,ClientPutLine,ClientGetPgm); (0,Parms.InputToWindow,ClientGetLine,BufferQuit); (AdapterQuit,BufferQuit,Parms.Quit);
502.8.CreatingaWindowApplication returnParms; blockbegin<br />
Notetheon(others)exceptionh<strong>and</strong>ler.Thisisashorth<strong>and</strong>notation, endprocess on(others) endblock; ParmString);<br />
returnParmsexceptionNotCreated; callClient(ClientGetLine,ClientPutLine,ClientGetPgm,<br />
clientwithinaninnerblockwithanullon(others)h<strong>and</strong>ler. tocauseaNotCreatedexception.Therefore,weenclosethecalltothe theclientiscreated,wedon'twantexceptionsreturnedbytheclientitself tocreatetheclient.Theh<strong>and</strong>lerwillreturnaNotCreatedexception.Once Inthisexample,thish<strong>and</strong>lerwillbeenteredifanythinggoeswrongtrying signifying\h<strong>and</strong>leallexceptionswhicharenotalreadyexplicitlyh<strong>and</strong>led".<br />
guages,sowedidn'tbotherexplainingthem. process.Forexample,supposethatinsteadofloadingQuitDispatcher literals,like'true'.Theseliteralsarejustliketheliteralsoffamiliarlan-<br />
stringliterals,like"Hello,World!",integerliterals,like0,<strong>and</strong>boolean compile-time,weneednotcallGetProgramtoloadtheseprogramsfrom theprogramlibraryatruntime.Wedothisusingaprogramliteral. Aprogramliteralisjustprogramtextdelimitedbyprocess<strong>and</strong>end Aliteralisanexpressionwithacompile-timeknownvalue.Wehaveused Sincethecodeofthequitdispatcher,adapter,<strong>and</strong>buerareknownat<br />
fromthelibrary,weusedaprogramliteralinstead.Hereistherelevant fragmentofmoduleApplicationBuilder: call(QuitDispOut#(createofprocess(Init:QuitDispIn) begin declare Quit1:QuitOut; Quit2:QuitOut; Quit:QuitIn; QuitCM:QuitInterface; newQuit;connectParms.QuittoQuit; receiveParmsfromInit; Quit1:=Parms.Quit1; Parms:QuitDispInterface;<br />
Quit2:=Parms.Quit2; returnParms; receiveQuitCMfromQuit; callQuit1(); callQuit2();
printfhasaccesstothesameconsole.Butifyou<strong>and</strong>IeachhaveaprogramliteraldenotingtheQuitDispatcherprogram,wewillstillnothave<br />
have.Aswestatedearlyinthetutorial,everyonewithastaticbindingto Don'tconfuseprogramliteralswithstaticbindings,which<strong>Hermes</strong>doesn't endprocess)) (AdapterQuit,BufferQuit,Parms.Quit); returnQuitCM; 2.AMiniatureSystem51<br />
literalisacompletelyseparateprogramwithacompletelyseparateset accesstothesameprocess.Ifweeachinstantiatetheprogram,we'llhave<br />
asaseparatemodule.Itevaluatestoaninitialized,checkedvalueoftype ofdeclarations.Theprogramliteralistreatedasifithadbeencompiled turedlanguages.Inblockstructuredlanguages,nestedprocedurescanre-<br />
fertovariablesintheouterprocedure.Thisisnottruehere.Aprogram twoseparateprocessesrunningthesamecode.Theonlywaywecanshare outputporttotheother. predefined!program. aprocessisifoneofusinstantiatestheprocess,<strong>and</strong>passesacopyofthe Don'tconfuseprogramliteralswithnestedproceduresinblockstruc-<br />
programtextappearsasaprogramliteralinseveralprograms.Youdon't wanttomaintainmultiplecopiesofthesameprogramliteral,incaseyou refertoitbynamewithinanotherprogram.Thisisconvenientifthesame wishtomodifytheprogram. Hereisthesamecodewiththeprogramliteraloutofline: linking(QuitDispatcher) ... Youmaywriteaprogramliteraloutofline,separatelycompileit,<strong>and</strong><br />
call(QuitDispOut#(createofprocessQuitDispatcher))<br />
Testyourselftryingtowritetheadapter<strong>and</strong>quitdispatcherprocesses. 2.8.2Adapter<strong>and</strong>QuitDispatcher whichappearsrightaftertheimportslistatthebeginningofthesource writinglinking(QuitDispatcher). module.Inthisexample,wemakethenameQuitDispatchervisibleby Anout-of-lineprogramnameismadevisiblebymeansofalinkinglist, (AdapterQuit,BufferQuit,Parms.Quit);<br />
Hereisthecode: process(Init:AdapterIn) Adapter:using(St<strong>and</strong>ard,Adapter,WMExternal,Quit) declare Put:PutLineIn;--PutLineservice Parms:AdapterInterface;--initializationcallmessage Get:GetProgramIn;--GetProgramservice Quit:QuitIn;--Quitservice
522.8.CreatingaWindowApplication<br />
begin QuitCM:QuitInterface; --initialization Running:boolean;--trueifprocesshasnotbeenshutdown WindowName:Charstring;--nameofwindow GetProgramCM:GetProgramInterface; PutCM:PutLineInterface; Window:WriteToWindowOut;--accesstowindow<br />
receiveParmsfromInit; GetProgramOut:GetProgramOut;--accesstoGetProgramservice<br />
newPut;connectParms.ClientPutLinetoPut; newGet;connectParms.ClientGetProgramtoGet; GetProgramOut:=Parms.GetProgram; WindowName:=Parms.WindowName; Running:='true'; returnParms; --serviceloop while(Running)repeat newQuit;connectParms.QuittoQuit; Window:=Parms.AdapterToWindow; select eventPut<br />
eventQuit eventGet returnGetProgramCM; callWindow(WindowName,PutCM.Line); receivePutCMfromPut; receiveGetProgramCMfromGet; returnPutCM;<br />
endselect; otherwise--shouldnotoccur receiveQuitCMfromQuit; Running:='false'; returnQuitCM; callGetProgramOut(GetProgramCM.Name,GetProgramCM.TheProgram);<br />
QuitDispatcher:using(QuitDispatcher,Quit)process(Init:QuitDispIn) declare Quit1:QuitOut; Quit2:QuitOut; Parms:QuitDispInterface; endprocess endwhile;
egin Quit:QuitIn; QuitCM:QuitInterface; newQuit;connectParms.QuittoQuit; receiveParmsfromInit; Quit1:=Parms.Quit1; 2.AMiniatureSystem53<br />
Quit2:=Parms.Quit2; returnParms; receiveQuitCMfromQuit; callQuit1(); callQuit2();<br />
simplied,butitillustratesmanyfeaturesofrealsystems.Forexample, 2.9Summary Inthissection,wehavebuiltacompleteminiaturesystem.Thesystemis endprocess returnQuitCM;<br />
itisafunctionalenhancement|windows|whichcanoperatewithclient programswhichweredesignedpriortotheenhancement.Itistransparent| thatis,theclientprogramsdonotneedtobechangedtousewindows. Itachievesthistransparencybyexploiting<strong>Hermes</strong>'abilitytorebindany outputporttoaninputportofmatchinginterface.Furthermore,because windowsystemitselfwithinoneofitsownwindowstogetnestedwindows. thewindowsystemasawholelookslikeast<strong>and</strong>ardclient,wecanrunthe<br />
<strong>and</strong>deleted. namically.Inthiscase,clientapplications<strong>and</strong>theportstothemareadded terminatingtheadapter. clientcanbeconstrainedtowriteonlyintotheappropriatewindow.And outputporttoanadapterwhichcallsaparticularwindow|thereforethe thewindowmanagercanrevokeanerrantclient'saccesstothewindowby Thisexampleillustrateshowwedividetheresponsibility<strong>and</strong>knowledge Thewindowmanagerillustrateshowsystemsaddordeleteservicesdy-<br />
Theapplicationbuilderillustratesaccesscontrol.Theclientispassedan<br />
convertbetweendierentinterfaces,<strong>and</strong>alsoallowaservicetobecut Thewindowmanagerh<strong>and</strong>lesthesetofwindowapplications|itprimarily dealswiththetableofactivewindows.Theadapter<strong>and</strong>buerprocesses amongtheprocessesofasystem.Thefrontenddealswithinputfromthe enduser.Itdoesstringh<strong>and</strong>ling,<strong>and</strong>convertsstringcomm<strong>and</strong>stocalls. o.Thewindowsystem<strong>and</strong>applicationbuilderprocessesload<strong>and</strong>link togetherotherprocesses. st<strong>and</strong>theessentialconcepts<strong>and</strong>usesof<strong>Hermes</strong>.Itshouldbeastraightfor- Ifyouunderst<strong>and</strong>howthewindowmanagersystemisbuilt,youunder-
examplesillustratedhere. errorh<strong>and</strong>ling.Youmaywishtotrywritingimprovementsonsomeofthe windowsfortheirchildprocessestorunin.Youmaywantmorerealistic styleofclients,whichhaveaccesstotheCreateservice<strong>and</strong>cancreatenew 542.9.Summary wardexercisetowritemorecomplexsystemsbyapplyingthesameprinciples.Forexample,youmaywantthewindowsystemtosupportanew<br />
beinstructivetoestimatehowmuchthinkingyouhavetodotoensure surenottoforgettofreeunuseddynamicallyallocatedstorage.Itwould gramsinyourfavoriteprogramminglanguage.Don'tforgetthatthepro-<br />
system.Thesystemmayberunningforalongtime|soyoumustmake loopholes|likeopening/dev|whichmightcircumventthesecurityofthe beabletowriteonwindowstheydon'town.Youhavetocloseallthe gramsmustberobust|theremustbenocrashesduetoexceedingastor-<br />
agelimit,forexample.Theprogramsmustalsobesafe|clientsmustnot Youalsomaywishtothinkofhowyouwouldhavewrittenthesepro-<br />
<strong>Hermes</strong>exceptamorecompletelistofprimitiveoperations,<strong>and</strong>amorere- acorrectimplementationinanotherlanguage<strong>and</strong>compareittowhatis<br />
neddescriptionofwhathasbeendiscussedinformally.Goodluck! on(others)notation.Fromhereon,youhavenothingmoretolearnabout lectedelement),theinspectstatement,theDuplicateKeyexception,the tors,everyof,extract,positionof(withaselector<strong>and</strong>withase-<br />
inprevioussectionstoamorepracticalproblem.Wehaveintroduceda fewnewconstructs:recordtypedenitions,unorderedtables,keys,selec-<br />
involvedindoingthejobin<strong>Hermes</strong>. Summary:Inthissection,wehavemostlyappliedwhatwe'velearned
Clothes",calleduponlanguagedesignerstoenforcewhathecalledsecurity 3Type<strong>and</strong>TypestateChecking C.A.R.Hoare,inhis1981TuringAwardLecture,\TheEmperor'sOld inprogramminglanguages,<strong>and</strong>criticizedtherecentlyadoptedAdadesign fornotmeetingthisrequirement.Bysecurity,Hoaremeant\[t]heprinciple piler<strong>and</strong>thateverysyntacticallycorrectprogramshouldgivearesultor thateverysyntacticallyincorrectprogramshouldberejectedbythecom-<br />
anerrormessagethatwaspredictable<strong>and</strong>comprehensibleintermsofthe sourcelanguageprogramitself."Inasecurelanguage,abuginmoduleX shouldshowupasbadoutputfrommoduleX,notasacrash,orar<strong>and</strong>om<br />
guagerules.(We'rethatthelanguagehassomeconceptofmodularityin <strong>and</strong>theymustkeeponrunningthegoodprogramseventhoughsomebad programshavebeenallowedtoexecute. multipleusers,theymaydynamicallyloadarbitraryuntestedprograms, mes.Programsarelong-livedsystems,theyincludemoduleswrittenby implementation-dependentperturbationtoapossiblyinnocentmoduleY.<br />
whichitisillegalforonemoduletoaccesstheprivatedataofanother.) erroneousexecutions.Erroneousexecutionsareuncheckedviolationsoflan-<br />
Let'sadoptAda'sterminology<strong>and</strong>callexecutionswhichviolatesecurity SecurityinHoare'ssenseisextremelyimportantforalanguagelikeHer-<br />
Inpractice,erroneousexecutionsaretheresultof:(1)accessingundened values,or(2)accessingdataofthewrongtype. afteranotherhasalreadycheckeditsdiscriminant.Since<strong>Hermes</strong>hasno formedvalueoftheappropriatetype.Oroneprocessmodiesavariant dataofthewrongtype.Theremainingsecurityproblemsinlanguageslike sharing<strong>and</strong>noaliasing,thesepathologicalcasescannotarise. Adaaretheresultofaliasing<strong>and</strong>shareddata.Forexample,twoprocesses simultaneouslywriteintoasinglevariable,<strong>and</strong>theresultisapossibly interleavedsuccessionofbytesfrombothvalues,whichmaynotbeawell-<br />
Conventionaltypecheckingavoidsmostoftheproblemsofaccessing<br />
fromthedeclaration.Everyoperationhasclassrules,whichlimitwhich familiesoftypestheoper<strong>and</strong>smayhave|forexample,+mayonlybeused atypewhichisxedthroughoutitsscope,<strong>and</strong>whichisdirectlyderived withintegerorrealtypes.Everyoperationhastypeinferencerules,which determinethetypeofoneoper<strong>and</strong>asafunctionofthetypeofanother|for insertCintoS,CmustbeoftypeChar.Thedeclaredtypesofvariables exampleifSisaCharstring,denedasorderedtableofChar,thenin <strong>and</strong>theinferredtypesofexpressionsmust(1)determineauniquetypefor The<strong>Hermes</strong>typesystemisstraightforward.Everyvariablenamehas
563.Type<strong>and</strong>TypestateChecking<br />
anerroneousexecution. thereforemaynotbeinstantiated).A<strong>Hermes</strong>compilerwillrejectaprogram whosePascalorAdacounterpartwouldcompilesuccessfullybutproduce therbereadnorwritten),<strong>and</strong>whereaprogramvalueisunchecked(<strong>and</strong> everyexpression<strong>and</strong>(2)beconsistentwiththetyperules. notberead),whereavariantisinthewrongcase(<strong>and</strong>thereforemayneiing|ageneralizationofdataowanalysis..<strong>Hermes</strong>compilersusetypestatecheckingtotrackwhereavariableisuninitialized(<strong>and</strong>thereforemay<br />
Here'sanexampleoftypestatecheckingappliedtoasimple(<strong>and</strong>rather Theproblemofundenedvaluesissolvedin<strong>Hermes</strong>bytypestatecheck-<br />
meaningless)programfragment: begin block callParms.GetLine(L); declare L:Charstring; A:Char; B:Charstring; C:Charstring; ifsizeofL=0 then else callParms.PutLine(B); B:="EmptyLine"; A:='NUL';<br />
on(GetLineInterface.EndStream) insertAintoL;<br />
callParms.GetLine(L); endif; callParms.GetLine(C); A:=L[0];<br />
endblock; Fornow,letuslookonlyatthesimplestapplicationoftypestate| callParms.PutLine(L); callParms.PutLine(C);<br />
tributeinit(A)ispresentinthetypestate;otherwisetheattributeisab-<br />
sent.Typestateanalysiscomputesatypestateforeachprogrampoint.This initializedoruninitialized.WedonotallowAtobeinitializedalongsome meansthatatagivenprogrampointvariableAmustbeknowntobeeither avariableisinitializedoruninitialized.IfvariableAisinitialized,theat-<br />
asasetofattributesdescribingpropertiesofvariables,suchaswhether paths<strong>and</strong>notothers. keepingtrackofwhichvariablesareinitialized:Atypestateisrepresented
initialized.Attheendofthethenclause,aftertheassignmentstoA<strong>and</strong>B, thediscussion,wewilllookonlyattypestateattributesrelatingtothe initializedstateofvariablesA,B,C,<strong>and</strong>L. isempty.AfterthecalltoGetLine,thetypestateisfinit(L)g|onlyLis Letusfollowtheanalysisoftypestatesintheaboveexample.Tosimplify Onentrytotheblock,noneofthevariablesisinitialized,sothetypestate 3.Type<strong>and</strong>TypestateChecking57<br />
clause,thetypestateisfinit(L),init(A),init(C)g. thetypestateisfinit(L),init(A),init(B)g.Attheendoftheelse<br />
toberun-timetestsofinitializedness|avariablemusteitherbeknownto werepossiblyinitialized,<strong>and</strong>possiblynot.In<strong>Hermes</strong>,wedonotwishthere entrytothemerge.SoallyouwouldknowaboutB<strong>and</strong>Cwouldbethatthey analysis,youalwaysknowlessinformationatamergepointthanateither thiscase,thattypestateisfinit(L),init(A)g|variablesL<strong>and</strong>Awill atthemergepointiscomputedastheintersectionofthetypestates.1In beinitialized,B<strong>and</strong>Cuninitialized. Attheendoftheifstatement,thetwopathsmerge.Thetypestate<br />
beinitializedorknowntobeuninitialized.Theintersectionruleimplies <strong>and</strong>Careinfactuninitializedatthispointregardlessoftheexecutionpath taken,thecompilerinsertscoercionoperations.Inthiscase,thecompiler thatB<strong>and</strong>Cwillbeuninitializedatthemergepoint.TomakesurethatB Hereiswheretypestateanalysisgoesbeyonddataowanalysis.Indataow<br />
statementaftertheelseclause. willinsertadiscardBstatementafterthethenclause<strong>and</strong>adiscardC issaidtobelower.Coercionoperationsalwaysconvertfromahighertypestatetoalowerone.<br />
finit(L)g(thirdcall).Theintersectionisthetypestatefg.Thecompiler secondcalltoGetLinetotheh<strong>and</strong>ler,<strong>and</strong>itinsertsanoperationtodiscard automaticallyinsertsoperationstodiscardL<strong>and</strong>Aintothepathfromthe Atypestatewithastrictsubsetoftheattributesofasecondtypestate Therearethreepathstothath<strong>and</strong>ler|onefromeachcalltoGetLine.The threetypestatesarefg(rstcall),finit(L),init(A)g(secondcall),<strong>and</strong> Lintothepathfromthethirdcall. Asimilarsituationprevailsattheexceptionh<strong>and</strong>leron(GetLineInterface.Endstream).<br />
Parms.GetLine(A),theGetLineIndenitionrequirestheargumenttobe ment,itischeckedthatbothL<strong>and</strong>Aareinitialized.Inthestatementcall italsochecksforlegalityofprograms.Forinstance,attheinsertstate-<br />
operationdiscardAisinsertedsothatAwillbeuninitializedasexpected uninitialized,yetAisinitialized.Here,thetypestateistoohigh.Acoercion Typestateanalysisnotonlytracksthetypestate<strong>and</strong>performscoercions,<br />
typestateislowerthantheotherifitisasubsetoftheother;themeetoftwo structurewheretheelements(typestatesinthiscase)arepartiallyordered,<strong>and</strong> typestatesistheirintersection. whereeverypairofelementshasameetorgreatestlowerbound.In<strong>Hermes</strong>,one 1Mathematically,thesetoftypestatesisasemilattice|thatis,amathematical
583.Type<strong>and</strong>TypestateChecking Thereisnocoerciontomakeatypestatehigher,sothisstatementmustbe beforethecall.InthestatementcallParms.PutLine(L)intheh<strong>and</strong>ler, rejectedaserroneous.Thecompilerwillissueanerrormessagesayingthat attributeinit(L)wasrequiredbutnotpresent. Lisrequiredtobeinitialized,<strong>and</strong>itisnot,sothetypestateistoolow.<br />
ciency.Whenprogramsarewritteninunsafelanguages,eachuserhasto denedLcouldproduceunpredictableresults|possiblyevenaprogram trap.(ImagineLimplementedasapointertoastringbuer.)Thiswould Second,wegetearlydetectionofnonsenseprograms.Third,wegete-<br />
AllowingastatementlikecallParms.PutLine(L)toexecutewithanun-<br />
beputinaseparateaddressspacesothatoneuser'serroneousprogram befatal,especiallyifourprogramisamulti-usersystem.Andifwedidn't detecttheerroratcompile-time,we'dhavetocheckforitatrun-time. WhatbenetsdowegetfromtypestatecheckingFirst,wegetsecurity.<br />
maticallygenerateddiscardsofvalues.Forinstance,wesawthatwhenthe otherwisehave.Finally,wegetfreegarbagecollectionintheformofauto-<br />
EndStreamexceptionwasraised,theappropriatevariableswerediscarded beforeenteringtheexceptionh<strong>and</strong>ler. addressspace.Becausetheimplementationissecure,wegettheprotection ofaddressspacesattherun-timecostoflightweightprocesses.Andon can'thurtanotheruser.Butwecanrunmultiple<strong>Hermes</strong>processesinone machineslackingmemorymapping,wegetprotectionwhichwewouldnot<br />
youcankeeptheinterface\inyourhead",youmayconsiderwritingextra Ifyou'rewritingaprocedurewhichnoonebutyourselfisgoingtouse<strong>and</strong> systems,soitfavorstherstpointofviewoverthesecond. declarationsaburden.<strong>Hermes</strong>isdesignedprimarilyforlarge,long-lived someoneelse'smodules,theextradocumentationontheinterfaceisuseful. typestatesofcallparametersoninterfaces.Thiscanbeviewedaseithera burdenorabenetdependinguponyourpointofview.Ifyou'repickingup WhatpricedowepayYouhavetodeclarethepre-call<strong>and</strong>post-call
4Additional<strong>Hermes</strong>Constructs notyetbeendiscussed,sowewillbrieydiscussthemhere: Theexamplesinchapters1.1<strong>and</strong>2illustratemostofthenovel<strong>Hermes</strong> constructs.However,therearesomeuseful<strong>Hermes</strong>constructswhichhave 4.1ExpressionBlocks<br />
thisbyrewritingtheCreateserviceofthewindowmanager. ments.Wesupportthisin<strong>Hermes</strong>withanexpressionblock.We'llillustrate astheoper<strong>and</strong>ofanotherstatementorexpression.Alltheoper<strong>and</strong>sofan expressionexcepttheresultareunmodiedbytheexpression. seriesofoperationswhichcomputeasinglevaluewhichisimmediatelyused <strong>Hermes</strong>forthesakeofuniformsyntax.Anexpressionisanoperationor <strong>Hermes</strong>isastatement-orientedlanguage.However,expressionsaresoconvenient<strong>and</strong>sowidelyusedthatitwouldbefoolishtobarthemfrom<br />
receiveCreateCMfromCreate; ifexistsofCreatedWindows[CreateCM.WindowName] Sometimesitisdesirableforanexpressiontoincludeembeddedstate-<br />
else then blockbegin --erroractionifwindowalreadyexists insert (evaluateW:Windowfrom call(WindowApplicationOut#(createofApplicationBuilder)) newW; W.WindowName:=CreateCM.WindowName; GetProgram,WriteToWindowCapability,W.WindowName, (CreateCM.ProgramName,CreateCM.ParmString,<br />
returnCreateCM; endif; endblock; --erroractionifunabletocreateprocess on(WindowApplicationInterface.NotCreated) intoCreatedWindows; end) W.InputToWindow,W.Quit);
604.1.ExpressionBlocks anexpressionblockifyouneedtowriteastatement. blockwasn'treallynecessary.Theoriginalversionwasjustasconvenient. builtwithintheexpressionblock.Inthisparticularcase,theexpression However,insomecontexts,suchasafterwhereinaselector,youmustuse statement.Theoper<strong>and</strong>ofinsertistherecordCurrentWindowwhichis Inthisversionoftheprogram,theblockconsistsofasingleinsert<br />
4.2Send Anothercommonidiomistosendsomedatatoanotherprocess<strong>and</strong>not waitforareply.Youc<strong>and</strong>othisbydeninganinterfaceinwhichthedata youwishtosendisinitializedonentry<strong>and</strong>uninitializedonexit.However, thereisstilltheproblemthatthereceivingprocessmaychoosetowait<br />
statementsendvariabletoportcausesthevaluecurrentlyinvariableto indenitelybeforereceivingyourdata.Itmayevenrunforever<strong>and</strong>never process,<strong>Hermes</strong>providesanasynchronouscommunicationmechanism.The beremoved<strong>and</strong>senttothequeueattheinputportconnectedtoport. deadlocked,itisIwhoisblocked<strong>and</strong>notS. <strong>and</strong>returnstoS.ThenIcallstheeventualreceiverR.IfRisdelayedor receiveyourdata.<br />
Becauseofthesendoperation,inputportscanbedenedtoholdany intermediateprocessI.ScallsI,whichimmediatelyreceivesthedata, Ratherthanrequiringtheprogrammertoexplicitlycodeanintermediate Apossible<strong>Hermes</strong>solutionisthis:thesendingprocess,Screatesan<br />
datatype,notjustcallmessages. Herearetwopracticalusesofsend: Communicatingwithuntrustedprocesses:SupposeIwishtoload<strong>and</strong> Ieithermustspawnaprocesstoinitialize<strong>and</strong>calltheuntrusted willneverreturnmycallmessage,<strong>and</strong>Iwillblockforever.Tobesafe, thisifIdonottrusttheprocessIamloading.Perhapstheprocess statement. process,orImustdelivertheinitializationparametersusingasend aswedidinearlierexamples.However,thereissomerisktodoing someports.Icouldpassthisinformationwithacallstatement,just executeaprocess<strong>and</strong>passitsomeinitializationinformation|possibly<br />
Forwardingcalls:SupposeIamwritingaprocesswhosejobitisto tuallyservicethecall.Ifmyprocessreceivesthecallmessage<strong>and</strong>then receivecalls<strong>and</strong>routethemtoanappropriateprocesswhichwillac-<br />
callstheeventualdestination,itmustwaituntilthecallisserviced. originalcaller,<strong>and</strong>nottomyprocess. However,ifinsteadmyprocesstransfersthecallmessageusingsend, myprocessisfreetorouteothercalls.Whentheeventualdestination issuesareturnstatement,thecallmessagewillbereturnedtothe
compile-timeistooconstraining.<strong>Hermes</strong>supportsvariants<strong>and</strong>polymorphs Sometimestherequirementthatthetypeofeveryvaluebeknownat 4.3Variants toallowthisrequirementtobeweakened.Howeverwedonotgiveupthe fundamentalprinciplesthatmachine-levelimplementationdetailmustbe 4.Additional<strong>Hermes</strong>Constructs61<br />
forpurposesofthisexample,we'llassumetobejustacharacterstring ustalkaboutLISPobjects: hidden,<strong>and</strong>thatthelanguagemustbesecure. whohasprogrammedinLISP.ALISPobjectiseitheranatom(which printname),apair,ornothing(nil).Herearethe<strong>Hermes</strong>typeswhichlet LispPair:record(Car:LispObject,Cdr:LispObject); LispKind:enumeration('atom','pair','nil'); Weillustratevariantswithanexamplewhichwillbefamiliartoanyone<br />
LispObject:variantofLispKind(<br />
nents:L.PrintNameoftypeCharstring,L.PairoftypeLispPair,<strong>and</strong> varianttype. whichisusedconventionallytorepresentanullvalue.We'llexplainthe languages.Emptyisapredenedtype|anenumerationwithnovalues| SupposeLisavariableoftypeLispObject.ThenLhasthreecompo-<br />
Theenumeration<strong>and</strong>recordtypesarejustlikesimilartypesinother 'pair'->Pair:LispPairffullg, 'nil'->Nil:Emptyfg); 'atom'->PrintName:Charstringffullg,<br />
L.NiloftypeEmpty.Inthisrespect,avariantisjustlikearecord.But whereasaninitializedrecordmayhaveseveralcomponents,onlyonecomponentofavariantcanexistatanyonetime.Whichcomponentitisdependsuponthecaseofthevariant.Thecaseisanenumerationvalue|in<br />
thisexample,either'atom','pair',or'nil'.Eachcomponentisassociatedwithoneofthecasesofthevariant.Sothevalueofaninitialized<br />
whereintheprogramthevariantishidden,<strong>and</strong>whereitisrevealed.When itisrevealed,thecompilertracksitscase.SoifLisaLispObject,the variantisacasevalueplusexactlyoneofthevariantcomponents. isatypestateproperty.Thatmeansthatthecompilerwillkeeptrackof possibletypestatesofLare: thatwedon'tknowthecaseatcompiletime.Revealedmeanswedo.This Aninitializedvariantcanbeeitherhiddenorrevealed.Hiddenmeans<br />
initialized<strong>and</strong>revealedincase'pair' uninitialized initialized<strong>and</strong>hidden initialized<strong>and</strong>revealedincase'atom'
624.3.Variants<br />
thevariantcomponents.Theunitestatementsimultaneously:(1)setsthe assignmentstatementtocopythevalueofanothervariableofthesame youbuildanewvariant,youmustdecidewhichcasetoputthevariant in.Youmaynotdirectlyassigntoacomponentofanuninitializedvariant. Youmustinsteadusetheunitestatementtomoveavalueintooneof typewhichisalreadyinitialized.Oryoucanbuildanewvariant.When Therearetwowaystoinitializeanuninitializedvariant.Youcanusean initialized<strong>and</strong>revealedincase'nil'<br />
caseofthevariant,(2)movesthevalueofitsoper<strong>and</strong>intothevariant component,(3)tellsthecompilerthatthevariantisnowinitialized<strong>and</strong> revealed. 1.HereisanexampleofastatementwhichinitializesLintocase'atom': 2.ThisstatementputsLintocase'nil': 3.ThisstatementputsLintocase'pair': (EmptyvalisavariableoftypeEmpty.Itdoesn'tneedtobeinitialized, uniteL.NilfromEmptyval; uniteL.Printnamefrom"Foo"; sinceinthedenition,componentNilisexpectedtobeuninitialized.)<br />
example,whenvariantLisrevealedincase'atom',theattributecase(L, newPair; unitePair.Car.Printnamefrom"Foo";<br />
atypestateforeachvariantcomponent.Thisisthetypestatethevariant L.PrintName)ispresent.ThismeansthatL.PrintNameisthecomponent whichisknowntoexist. Thetypestateattributecaseispresentwhenthevariantisrevealed.For Whenyouwritethedenitionofthevarianttype,youhavetosupply uniteL.PairfromPair; unitePair.Cdr.NilfromEmptyval;<br />
timeitisrevealed|thatis,itmaybemademoreinitializedbutnotless. allwhenLisincase'nil'.` initializedwhenLisincase'pair',butL.Nilneednotbeinitializedat tively: isrevealed.Itisalsotheminimumtypestatethecomponentcanhaveany ThedenitionofLispObjectillustratedaboveshowsthatL.PrintName componentwillhave(1)justbeforeitbecomeshidden,<strong>and</strong>(2)justafterit mustbefullyinitializedwhenLisincase'atom',L.Pairmustbefully Thetypestateaftereachofthethreeunitestatementsaboveisrespec-<br />
1.finit(L),case(L,L.PrintName),init(L.PrintName)g
Noticethatincase'pair',L.Pair.Car<strong>and</strong>L.Pair.Cdrarethemselves 3.finit(L),case(L,L.Pair),init(L.Pair),init(L.Pair.Car), 2.finit(L),case(L,L.Nil)g case(L.Pair.Car,L.Pair.Car.PrintName),init(L.Pair.Car.PrintName), init(L.Pair.Cdr),case(L.Pair.Cdr,L.Pair.Cdr.Nil)g 4.Additional<strong>Hermes</strong>Constructs63<br />
theexample,theyarebothinitialized<strong>and</strong>revealed.Thisislegal,since fullyinitializedistheminimumtypestate,<strong>and</strong>initialized<strong>and</strong>revealedis revealed,bothL.Pair.Car<strong>and</strong>L.Pair.Cdrmustbefullyinitialized.In variantsoftypeLispObject.ThedenitionrequiresthatwhenL.Pairis ahighertypestate.Itwouldbeillegaltoperformanoperationtomake<br />
thecomponents,becauseonlyoneofthemreallyexists<strong>and</strong>youdon'tknow hideavariantexplicitlywiththehidestatement.Butusuallyvariantsbecomehiddenbecauseofacoercion.Forexample,ifyouwroteaprogram<br />
Whenthevariantisinitializedbuthidden,youmaynotaccessanyof Ifthecaseattributeisnotpresent,thenthevariantishidden.Youmay L.Pair.CaruninitializedwhileL.Pairisrevealed.<br />
whichoneitis.Forexample,supposethetypestateisfinit(L)g<strong>and</strong>you mentsmentionedabove,thenatthemergerofthepathsthetypestate whichtookthreedierentpaths,eachexecutingoneoftheunitestate-<br />
wouldbefinit(L)g.<br />
thevariantisinthewrongcase,youwillgetaCaseErrorexception.If youwanttoknowthecaseofavariantsoyouknowwhichcomponentitis thecomponentyouhopetoaccess.Ifthecomponentdoesnotexistbecause nentwithouttheappropriatecaseattribute. isimpossiblebecauseyoumaynothaveanyattributeofavariantcomposultinimpossibletypestate".Thetypestatefinit(L),init(L.PrintName)g<br />
trytodotheassignmentL.Printname:="Foo".Thiswillgenerateatypestateerrormessagesaying\addingattributeinit(L.PrintName)wouldre-<br />
CdrofaLispObjecttoarbitrarydepth: correcttoreveal,issuethecaseofoperation.Thisreturnstheenumeration valueofthecase.Here'safragmentofaprocedurewhichswapsCar<strong>and</strong> receiveParmsfrominit; Torevealavariant,usetherevealstatement.Theoper<strong>and</strong>ofrevealis<br />
blockbegin<br />
attributeswhichthedenitionsaiditwassupposedtohave.Youmayraise Afterthereveal,thecomponentoftherevealedvarianthasthetypestate endblock; returnParms; on(CaseError)--it'snotapair SwapCM.L.Pair.Cdr:=Temp; SwapCM.L.Pair.Car:=Swap(SwapCM.L.Pair.Cdr); revealSwapCM.L.Pair; Temp:=Swap(SwapCM.L.Pair.Car);--it'sapair
thetypestate(i.e.addattributes),butyoumaynotloweranyattributes. 644.3.Variants<br />
makesthetypestate ofLispObjectsaidthatincase'pair',componentPairisfull.This again,itwillhaveaknowntypestateregardlessofwhatyoudid.Sointhe aboveexample,Parms.L.Pairwillbefullyinitialized,sincethedenition Furthermore,anyattributesyouaddedwillbecoercedawaybeforethe variantishiddenagain.Thisguaranteesthatwhenthevariantisrevealed init(Parms.L.Pair),init(Parms.L.Pair.Car),init(Parms.L.Pair.Cdr)g finit(Parms.L),case(Parms.L,Parms.L.Pair),<br />
4.4Polymorphs beloweredbackautomaticallyassoonasyoutrytohideParms.L. plebyissuingrevealParms.L.Pair.Car.PrintName,thetypestatewill wouldyieldanimpossibletypestate.Ifyouraisethetypestate,forexam-<br />
wouldgetacompilererrormessagesayingthatattemptingtodropinit(Parms.L.Pair.Car) IfyouwrotediscardParms.L.Pair.Car,thiswouldbeillegal.You<br />
avariant. setofalternatives.Insuchacase,youhavetouseapolymorphinsteadof Avariantisusefulwhenyouknowaheadoftimeaxedsetofalternative types(ortypestates)avaluewillhave.Sometimesthereisanopen-ended<br />
typestateyouareexpectingmatchthetype<strong>and</strong>typestateappearingon mustbeunwrapped<strong>and</strong>itsvaluestoredbackintoavariableoftheappropriatetype.Atthistime,thereisarun-timecheckthatthetype<strong>and</strong><br />
insertedintoatableofpolymorphs,etc.Butnoneoftheoperationsofthe originaltypeareallowed.Inordertoissuetheseoperations,thepolymorph isalwaysstoredtogetherwithitstype<strong>and</strong>typestate.Thinkofthevalue tate.Whenthevalueiswrapped,itcanbestoredinapolymorphvariable, asbeingwrappedinanopaquewrapperlabelledwiththetype<strong>and</strong>types-<br />
Apolymorphisavariablewhichcanholdanytypeofvalue.Thevalue<br />
types.Youmayalsoinspectthewrappertoreadthetype<strong>and</strong>typestateof whichtheownerofaresource(e.g.aportintoaserver)maypostacopy thewrapper.<br />
oftheresource<strong>and</strong>aresourcename,<strong>and</strong>authorizedusersmayretrieve thewrappedvalue. theexceptionUncopyableifthewrappedvalueisoneoftheuncopyable intoatable.Itissyntacticallylegaltocopyapolymorph,butyouwillget <strong>and</strong>unwrappingarethoseoperationsallowedonalltypes,suchasinserting Hereisasimpleapplicationofpolymorphs|aresourcerepositoryinto Theonlyoperationsyoumayperformonapolymorphbesideswrapping<br />
Insteadwerequiretheownertowraptheresourceintoapolymorphbefore types,theinterfacetotherepositorycannotspecifyanyparticulartype. acopyofthatresourcebyname.Sincedierentresourcesareofdierent
username<strong>and</strong>theresourceoriginallyposted,<strong>and</strong>theneitherreturnsthe resourcebeinggrantedtotheuser,orreturnsaDeniedexception.1 gainaccess.Toprovideaccesscontrol,werequiretheownertoprovidea portintoanaccesscontrolfunction.Theaccesscontrolfunctionacceptsa postingtheresource.Therequestorofaresourcesuppliesaresourcename <strong>and</strong>receivesbackapolymorph,whichtherequestormustthenunwrap. Theownerofaresourcemaynotwishtoallowanyarbitraryuserto 4.Additional<strong>Hermes</strong>Constructs65<br />
Hereistheinterface: RepositoryExternal:using()definitions Resource:polymorph;<br />
PostOut:outportofPostIn; PostIn:inportofPostInterfaceffullg; PostInterface:callmessage( AccessFunction:AccessOut)--accesscontrolfunction constant(ResourceName,AccessFunction) exitffullg exceptionDuplicateNameffullg; PostedResource:Resource,--resourcebeingposted ResourceName:Charstring,--namebeinggiventoresource<br />
AccessInterface:callmessage( AccessIn:inportofAccessInterfacefinit(UserName),init(PostedResource)g; AccessOut:outportofAccessIn; constant(UserName,PostedResource) exitffullg exceptionAccessDeniedfinit(UserName),init(PostedResource)g; ReturnedResource:Resource)--theresourcegranted UserName:Charstring,--nameoftherequestor<br />
RequestInterface:callmessage( PostedResource:Resource,--resourceoriginallyposted<br />
RequestOut:outportofRequestIn; RequestIn:inportofRequestInterfacefinit(ResourceName)g; constant(ResourceName) Resource:Resource)--theresourcegranted exitffullg exceptionNotFoundfinit(ResourceName)g exceptionAccessDeniedfinit(ResourceName)g; ResourceName:Charstring,--nameofresourcebeingrequested<br />
ratherthantheportintotheresource. throughalter,forexample,inwhichcaseitwillreturnaportintothelter Theaccesscontrolfunctionmaydecidetograntlimitedaccesstotheresource 1Theresourcereturnedmayormaynotbethesameastheresourceposted.
accesscontrol{anyonecangetit. 664.4.Polymorphs Trivial:=procedureofprocess(Init:AccessIn) enddefinitions Here'saprogramfragmentwhichpoststheGetLineservicewithtrivial ...--otherinterfaces<br />
wrapcopyofGetLineasResource; callPost("GetLine",Resource,Trivial); begin declare<br />
Thewrapstatementremovesthevalueofitssourceoper<strong>and</strong>beforewrappingit.IfyouwanttouseGetLineafterthewrapstatement,besureto<br />
posted: wrapacopy. blockbegin HereisthecodetoobtaintheGetLineportwhichsomeoneelsehas callAccess("GetLine",Resource);<br />
endprocess; returnParms; Parms.ReturnedResource:=Parms.PostedResource; receiveParmsfromInit; Parms:AccessInterface;<br />
thanfinitg.Thesechecksarenecessarytopreservesecurity.Withoutthe mentifthetypeofthewrappedvalueofResourcedoesn'tmatchthe typeofvariableGetLine,orifthetypestateofthewrappedvalueislower ThePolymorphMismatchexceptionwillberaisedbytheunwrapstate-<br />
on(PolymorphMismatch) on(others) endblock; ... unwrapGetLinefromResourcefinitg;<br />
laterunwrapit<strong>and</strong>performdierentoperations. checks,youcouldwrapavaluesupportingonesetofoperations<strong>and</strong>then
5ResearchDirectionsin<strong>Hermes</strong><br />
buildotherprograms,butunlikeLISP,<strong>Hermes</strong>willchecktheseprograms cesscontrol([NS88,Str86]).LikeLISP,<strong>Hermes</strong>allowsrunningprogramsto unlikeobject-orientedlanguages,thereissupportforconcurrency<strong>and</strong>ac-<br />
languages,<strong>Hermes</strong>supportsinformationhiding<strong>and</strong>programreuse|but opment.Itcombinesexpressivepower,simplicity,portability,<strong>and</strong>safety, in<strong>Hermes</strong>. mergingthebestfeaturesofmanylanguageparadigms:Likeobject-oriented Ifyouhavefollowedtheexamplessofar,youshouldbereasonablyuent<br />
fortypeerrorsbeforeexecution.LikeAda<strong>and</strong>Modula,<strong>Hermes</strong>supports modularity<strong>and</strong>interfacespecication,butunliketheselanguages,<strong>Hermes</strong> Webelievethat<strong>Hermes</strong>isanexcellenttechnologyforlargesystemdevel-<br />
machine-independentsetofprimitivestodoit.And<strong>Hermes</strong>providesthe providescompletesecurityusingtypestatechecking.LikeC/UNIX,<strong>Hermes</strong>supportssystemsprogramming,butusesasimpler<strong>and</strong>completelplorenewerapproachestosimplifyingthedevelopmentofcomplexsystems:<br />
Asof1990,the<strong>Hermes</strong>projectat<strong>IBM</strong>Researchisusing<strong>Hermes</strong>toex-<br />
Amorerenedsemilatticestructure,whichallowsprogrammersto familiarsequentialprogrammingparadigmoftheimperativelanguages.<br />
Optimistictransformations,whichperformconcurrencycontrol([Jef85]), Transparentrecovery,whichmakesitunnecessaryforprogrammers FBSY87,SYB87d]). totreatprocessstateasvolatile<strong>and</strong>dotheirowncheckpointing <strong>and</strong>restart([SY85,SY84,YSB87,SBY88,SBY87,SYB87c,SYB88, allowadditionalcoercions([SY89,SY90]). trackmoreinformationaboutthevalueofvariables,<strong>and</strong>whichwould<br />
implementationsonparallel<strong>and</strong>distributedarchitectures. clientscodedasasingleserialprocess,aretransformedintoecient perciallyinecientprograms,suchasaserverwiththous<strong>and</strong>sof tocodethesecomplexprotocolsbyh<strong>and</strong>.Straightforwardbutsutiontransparently([SY87]).Suchoptimizationsmakeitunnecessary<br />
processreplication([GJ87]),call-streaming([BS90]),<strong>and</strong>paralleliza-
685.ResearchDirectionsin<strong>Hermes</strong>
<strong>Hermes</strong><strong>Reference</strong> <strong>Manual</strong> PartII<br />
69
6Introduction Thereferencemanualpresentstherulesof<strong>Hermes</strong>.Mostoftherulesare programs,compilation,BNF,etc. denedinmachine-readabletables.Weexplainhowtoreadthetables. Weexplaintheotherrulesinformallybutrigorously.Themanualcontains minglanguage.Therefore,wewillnotexplainbasicconceptssuchasstored examplesofhowtoapplytherules,buttheseexamplesarenotnecessarily typicalorpreferredusesof<strong>Hermes</strong>. torial.Wealsoassumethatyouhaveexperiencewithsomeotherprogram-<br />
Herearethestagesofwriting<strong>and</strong>executinga<strong>Hermes</strong>program. Weassumethatyouhavealreadyread<strong>and</strong>understoodthe<strong>Hermes</strong>tu-<br />
Youwritethecodeusingyourfavoriteeditor/programgenerator, Therststageofthecompilerconvertsyoursourceleintoa<strong>Hermes</strong> producingasourcele.<br />
Youstorethecheckedprogramintoaprogramlibrary. Youretrievethecheckedprogram,instantiateitasaprocess,<strong>and</strong> The<strong>Hermes</strong>compilerchecksthe<strong>Hermes</strong>program,producingachecked gramwillincludeitstranslationtomachinecode.Likeallinternal programvalue.Theinternalrepresentationofachecked<strong>Hermes</strong>pro-<br />
representations,thiswillbeinvisibletotheprogrammer.<br />
program.Thisbypassesthersttwostepsmentionedabove. producethesourcele.Theremainingstepsarebrokendownasfollows: Youmayalsogeneratea<strong>Hermes</strong>programvaluedirectlywithina<strong>Hermes</strong> Inthismanual,weignoretherststepbecausewedonotcarehowyou Lexicalanalysis:Thecharactersintheprogramaredividedintotokens.Space<strong>and</strong>commenttokensarethrownaway,<strong>and</strong>theother<br />
writteninaformalgrammar.Lexicalanalysisisexplainedinchapter 7. tureoftheprogram.Thesyntaxrulesarewritteninaformalgrammar inAppendixA.<br />
executeit.<br />
Syntaxanalysis:Thestreamoftokensisparsed,revealingthestruc-<br />
tokensarepassedasinputtosyntaxanalysis.Thelexicalrulesare
726.Introduction Conversion<strong>and</strong>resolution:Theparsedprogramisconvertedinto<br />
Typechecking<strong>and</strong>inference:Thetypeofeachvariablemustsatisfy deningoccurrence.Theresolutionrulesaredescribedinformallyin chapter8. rences.Resolutionmeansassociatingeachappliedoccurrencewitha adeningoccurrencewheretheidentierisassociatedwithitsdenition.Otherappearancesofoftheidentierarecalledappliedoccur-<br />
names.Namesaremadeupofidentiers.Foreachidentierthereis a<strong>Hermes</strong>programvalue.Thisrequiresthecompilertoresolveall<br />
Typestatechecking:Thetypestateateachpointintheprogramis typechecking<strong>and</strong>inferencealgorithmisexplainedinchapter9 oper<strong>and</strong>.Forvariableswithoutdeclarations(expressiontemporaries), thecompilerappliestypeinferencetogenerateadeclaration.Itis checkedthatexactlyonetypecanbeinferred<strong>and</strong>thatthistype satisesthetyperules.Thetyperulesaregiveninanappendix.The thetyperulesfortheoperationwherethevariableappearsasan<br />
Otherstaticrestrictions:Theseareconstraintsonthevalueofaprogramotherthanthosecapturedinthetable-drivenrules.Example:<br />
appendix.Thetypestatecheckingalgorithmisexplainedinchapter Thenumberofargumentstocallmustmatchthenumberofcom-<br />
aregeneratedwherenecessary.Thetypestaterulesaregiveninan sistentwiththetypestaterequirementsofthatoperation.Coercions computed.Itischeckedthatthetypestateateachoperationiscon-<br />
10. Execution:Wedescribethesemanticsofeachoperationrigorously butinformallyinchapter11. formallynexttotheconstructstheyrestrict. ponentsinthecallmessagetype.Theserestrictionsaredescribedin-
7Lexical<strong>and</strong>SyntacticRules lectionsofcharactersthatconstitutetheelementarysyntacticunits.The Lexicalanalysisseparatesthesourceprogramintotokens.Tokensarecol-<br />
dierentkindsoftokenin<strong>Hermes</strong>are:spaces,comments,integerliterals,<br />
asetofstatementlines,precedeeachlinewithadoubledash. thanalinetoseewhatisacomment<strong>and</strong>whatisnot.To\commentout" multiplelines.Becauseofthisrule,youneednotlookatacontextbigger realliterals,namedliterals,stringliterals,punctuation,<strong>and</strong>words. with\/".Commentsdelimitedwith\/"<strong>and</strong>\/"maynotextendacross umentation,buttothecomputertheyareequivalenttospaces.Thereare totheendoftheline.Commentswithinalinebeginwith\/"<strong>and</strong>end twocommentingstyles.Adoubledash\--"startsacommentthatruns Aliteraltokendenesacompile-timeknownvalue. Spacesareusedtoseparatetokens.Commentsareusedforhum<strong>and</strong>oc-<br />
Arealliteralconsistsofanunsignedintegerpart,adecimalpoint,a Anintegerliteraltokenisadecimalrepresentationofanunsigned toanintegerliteral. integer.Someexamplesofintegerliteralsare0,112358,<strong>and</strong>000. fractionpart,an\e"(upperorlowercase),<strong>and</strong>anoptionallysigned Noticethat-2isnotatoken.Itisparsedasaunaryoperatorapplied<br />
Anamedliteralisrepresentedbyanonemptystringofcharacters integerexponent.Theintegerpartmusthaveatleastonedigit,but raisedtothepowerof".Someexamplesare15.,0.,1.12358, thefractionpartcanbeempty.Thesymbol\e"means\timesten enclosedintwosinglequotessuchthat,insidethedelimitingquotes, 0.314159e+02<strong>and</strong>314.159e-02.<br />
Astringliteralisrepresentedbya(possiblyempty)stringofcharactersenclosedintwodoublequotessuchthat,insidethedelimiting<br />
ofconsecutivesinglequotesisregardedasonesinglequote.Thecase ofthecharactersissignicantinnamedliterals.Someexamplesof thestringofcharactersinsidethedelimitingquoteswhereeverypair singlequotesalwaysoccurinpairs.Thevalueofanamedliteralis namedliteralsare'true'<strong>and</strong>'Isn''t'.Anamedliteralcannot extendpastasingleline. everypairofconsecutivedoublequotesisregardedasonedouble literalisthestringofcharactersinsidethedelimitingquoteswhere quotes,doublequotesalwaysoccurinpairs.Thevalueofastring
Punctuationconsistofoneortwocharacters.Theyareusedforsomeoperatornames<strong>and</strong>forgrouping<strong>and</strong>delimitingsyntacticunits.Someexamplenotextendpastasingleline.<br />
he",<strong>and</strong>"A""symbolbeginsaquotation".Astringliteralcan-<br />
quote.Thecaseofthecharactersisalsosignicantinstringliterals. 747.Lexical<strong>and</strong>SyntacticRules<br />
ationtokensarepresentedinTableA.2inAppendixA. areparentheses{(<strong>and</strong>){<strong>and</strong>themoveoperator:
8Resolution name,attributename,exceptionname,exitname,<strong>and</strong>processname.Names ofanamemustberesolved. ingoccurrences,<strong>and</strong>rejectingundenedappliedoccurrencesorconicting deningoccurrences. Resolutionmeansmatchingappliedoccurrencesofnameswiththeirden-<br />
consistofoneormoreidentiers.Eachidentierinanappliedoccurrence Foreachclassofname,therearerulesspecifying: Thefollowingclassesofnamesappearin<strong>Hermes</strong>:variablename,type<br />
theregionswhereeachnamespaceisvisible|thatis,wherethe thenamespaceinwhichthenameisdened.Anamespaceisanassociationbetweenidentiers<strong>and</strong>theirdenitions.Withineachname<br />
er.(Rememberthatcaseisignored,sox<strong>and</strong>Xcannotappearinthe samenamespace.) spacetherecanbeonlyonedeninginstanceofaparticularidentidenition<strong>and</strong>thereisnodeningoccurrence.Forexample,thetypestate<br />
howtodisambiguateanameifthenamebeingresolvedisinmore identierscanbereferredtobyappliedoccurrences.<br />
saidtobepredenedifitisdenedinthepredefinedmodule,whichis attributeinit<strong>and</strong>theexceptionnameNotFoundarebuiltin.Anameis implicitlyimportedbyall<strong>Hermes</strong>modules.Forexample,thetypenames Anameissaidtobebuiltinifitsmeaningisgiveninthe<strong>Hermes</strong>language thanonevisiblenamespace.Itisaresolutionerroreitherifthere isnovisibledenition,orifthereismorethanonevisibledenition<br />
havetosupplydenitionsforeitherbuiltinorpredenednames. Charstring,integer<strong>and</strong>programarepredened.Programmersdonot <strong>and</strong>nodisambiguationispossible.<br />
asoper<strong>and</strong>s. Avariablenamedenotesacontainerforavalue.Variablenamesareused 8.1VariableNames variable{name ::=base{variable[.component{name]...
768.1.VariableNames 8.1.1BaseVariables Basevariablesaredenedwithinnamespacescalleddeclarationslists.The Examples:Foo,Foo.Bar,Foo.Bar.Baz. base{variable<br />
pearonlywithinexecutablecode|eitherprocessmodulesorconstraint regionofvisibilityofadeclarationslistiscalleditsscope.Scopesap-<br />
::=identier<br />
theprogrammerc<strong>and</strong>eclarebasevariables.Theselector,theinspect,the tializationportdeclaration<strong>and</strong>thebasevariablesdeclaredfollowingthe forstatement,<strong>and</strong>theexpressionblockalsointroducescopescontaining constraintdenition. denitions.Theoutermostscopeinthiscaseisthedeclarationlistofthe declarekeyword.Theblockstatementdenesaninnerscope,inwhich asinglebasevariabledeclaration.Scopesalsoappearwithinconstraint denitions.Scopescanbenested.Inanexecutablemodule,theprocess bodyistheoutermostscope.Thedeclarationslistcomprisesthetheini-<br />
declarationproducinga\hole"intheoutervariable'sscope.)Itispermissibleforthesameidentiertobedeclaredtwicewithinaprogramifthe<br />
scopesdonotoverlap.Example: block Itisillegalforthesameidentiertobedenedwithintwooverlapping scopes.(Inotherlanguages,thisinnerdeclarationwould\hide"theouter<br />
begin declare forXinT[]--illegalredeclarationofX X:integer; T:tableofintegers; inspect<br />
withinitsscope.Becausebasevariablescannothaveoverlappingscopes, forTinZwhere(T>0)--legalredeclarationofT Theresolutionruleforbasevariablesistrivial:Abasevariableisvisible endblock; inspect endfor; callPutLine(IntToString(T)); endfor; callPutLine(IntToString(X));<br />
variable. therecanbeamaximumofonevisibledeningoccurrenceofanybase
8.1.2ComponentNames eachhaveacomponentnamedX. havetwodierentcomponentsnamedX,buttwodierentrecordtypescan Componentnamesaredenedinrecord,variant,<strong>and</strong>callmessagetype namespaceforcomponentnames.ThisimpliesthatarecordtypeRcannot denitions.Eachrecord,variant,orcallmessagetypedenitiondenesa 8.Resolution77<br />
resolvedwithinthecomponentnamespaceassociatedwiththevariable's Firstthebasevariableisresolved.Thenthecomponentofavariableis typedenition.Forexample,inthenameX.Y.Z,IrstresolvethenameX. ThenIlookupX'stype.Ilookupthattype'sdenitiontondthename ofX.Ymightnotbevisible,becausethedenitionsmoduledidnotappear whenthetypenameitselfisnotvisible|e.g.intheabovecasethetype theprocesstoobtaintheresolutionofZ.Note:atypemaybeknowneven spacewithinwhichIcanresolveY.IcanthenlookupY'stype,<strong>and</strong>repeat Variablenamescontainingcomponentsareresolvedfromlefttoright.<br />
Typenamesareusedinvariabledeclarations,intypespeciers,<strong>and</strong>indefinitions.Typenamesarewritteneithersimpleidentiers(typeidentiers),<br />
intheusinglist. 8.2TypeNames ortheyaretypeidentiersprecededbyadenitionsmodulename.<br />
tionsmodulewrittenbytheuser,orthepredefinedmodule.Thesetof type{name::=denition{name<br />
names. typedenitionswithinadenitionsmoduleformsanamespace|thatis, twotypedenitionswithinthesamedenitionsmodulemusthavedistinct Typeidentiersaredenedwithinadenitionsmodule|eitheradeni-<br />
::=module{name!denition{name<br />
thoseofthedenitionsmoduleitself,(2)thoseinpredefined,(3)thosein Withinadenitionsmodule,thefollowingtypedenitionsarevisible:(1) ::=identier<br />
ofdenitionsmoduleswhosedenitionswillbemadevisible. denitionsappearingontheimportslist. denitionsofcategories(2)<strong>and</strong>(3)arevisible. isexactlyonevisibledenitionofthattype. Withinanexecutablemodule,therearenotypedenitions,soonlytype Theimportslistappearsattheheaderofeverymodule.Itliststhenames Atypenamenotprecededbyamodulenameislegalif<strong>and</strong>onlyifthere
788.2.TypeNames withinthespeciedmodule.Themodulenamemustbeeitherpredefined, Attributenamesareusedintypestates.Thesyntaxofattributenamesis oradenitionsmoduleontheimportslist. 8.3AttributeNames Ifamodulenameisspecied,thetypenamereferstothedenition<br />
denitions,soitislegaltodeneatypeT<strong>and</strong>aconstraintTinthesame constraintattributesThatnamespaceisdierentfromthespaceoftype identicaltothesyntaxoftypenames.<br />
module. namesarenamesofconstraintsdenedindenitionsmodules.Thesetof constraintdenitionsofeachdenitionsmoduleformsanamespace.of denotesabuiltinattributedescribedinsection11.10.Allotherattribute fullisabuiltinabbreviationforasetofinitattributes.Thename checkeddenotesabuiltinconstraintattribute.Thenamecheckeddefinitions Thenamesinit<strong>and</strong>casearebuiltintypestateattributes.Thename<br />
Exceptionnamesareusedinexceptionh<strong>and</strong>lers,<strong>and</strong>onthereturnstatement.Exceptionnamesareeitherbuiltin,oruser-dened.Thetwohave<br />
primitiveoperations.Abuiltinexceptionnameiswrittenasasimpleidentier.Theidentiermustbeoneofthenamesinthepredenedtype<br />
dierentsyntax. statements.Theyarewrittenas: predefined!builtinexception. Builtinexceptionnamesdenotetheexceptionsassociatedwith<strong>Hermes</strong><br />
rulesforattributenamesareidenticaltotheresolutionrulesfortypenames. 8.4ExceptionNames Exceptforthespecialtreatmentofthevebuiltinnames,theresolution<br />
written.Thereisanamespaceofexceptionidentiersforeachcallmessage User-denedexceptionnamesdenotetheexceptionsreturnedfromcall<br />
isresolvedsimplybyresolvingthetypename.Thetypenamemustbea asthetypeofthecallmessageoper<strong>and</strong>,soonlytheexceptionidentieris denition.Thatnamespacecontainstheuser-denedexceptions,plusthe automaticallydenedexceptiondiscarded.Auser-denedexceptionname Onthereturnstatement,thetypenameisunderstoodtobethesame exception{name<br />
callmessagetype.Thisdeterminesasinglenamespacewhichisusedto ::=type{name.user{exception{name<br />
resolvetheexceptionname.
ontheh<strong>and</strong>ler<strong>and</strong>usedontheexitstatement. withoutraisingabuiltinexceptionorissuingacall.Exitnamesaredened 8.5ExitNames Theexitstatementallowstheprogrammertojumptoah<strong>and</strong>lerclause Thedeningoccurrenceofanexitnameisah<strong>and</strong>lerbeginningonexit. 8.Resolution79<br />
Thenamespaceistheidentierlistappearingafterthewordexit.The visibilityforthesameexitname. nameisvisiblethroughoutthemainclauseoftheblockcontainingthe h<strong>and</strong>ler.Unlikebasevariables,therecanbeseveraloverlappingregionsof<br />
Aprocessnameisusedonlyintheprogramliteralconstruct: exitname,theinnermostvisibledenitionisused. 8.6ProcessNames resolvinganexitname,ifthereareseveralvisibledenitionsofthesame Theappliedoccurrenceofanexitnameisonanexitstatement.When<br />
Theidentierdenotestheprocessmoduleofthatname. programliteral:processidentifier Theidentiermustbepresentinthelinkinglistofthesourcemodule.
isconcerned.Allthe\noisewords",likeof,from<strong>and</strong>into,whichmakethe <strong>Hermes</strong>programvalue.Thisisamuchsimplerformasfarasthecomputer Afteramodulehasbeentokenized,parsed,<strong>and</strong>resolved,itisstoredasa 9TypeChecking<strong>and</strong>Inference programeasierforpeopletoreadbutlesssyntacticallyregular,aregone. Statementswithembeddedexpressionsareexp<strong>and</strong>edouttosequencesof statements.Names,likeX,whoseresolutionmaybecontext-sensitive,have beenremoved.Intheirplaceareuniqueidentiers. clauseisaseriesofstatements,<strong>and</strong>eachstatementisanoperator,alistof oper<strong>and</strong>s(variablenames),<strong>and</strong>a\qualier",whichiseverythingelse.By ofdeclarations,organizedinto\scopes";(3)acollectionofclauses.Each constraintdenitions,organizedintodenitionsmodules;(2)acollection declared. thistime,allbasevariablenamesexceptexpressiontemporarieshavebeen The<strong>Hermes</strong>programvalueis:(1)acollectionoftypedenitions<strong>and</strong><br />
inferencerulesareusedforbothinference<strong>and</strong>checking.Theclassrulesare rules.Therearetwofamiliesofrules:inferencerules,<strong>and</strong>classrules.The typesoftheoper<strong>and</strong>s. theexpressiontemporariessothateverybasevariablewillhaveaknown type;(2)typechecking:tocheckthattheoperationsarelegal,giventhe anextrasetofcheckswhichapplyaftertypeinferenceiscomplete. Bothtypeinference<strong>and</strong>typecheckingaredrivenfromasingletableof Thejobofthenextphaseis:(1)typeinference:tosupplydeclarationsfor<br />
thetypeoftheoper<strong>and</strong>ontheleft. theleft.Thesecondkindofruleisredwhenthetypeoftheoper<strong>and</strong>on therightbecomesknown.Theruleprovidesafunctionwhichdetermines inferencerule:oper<strong>and</strong> Therstkindofruleunconditionallyassignsatypetotheoper<strong>and</strong>on Therulesappearintheappendix.Thesyntaxofaninferenceruleis:<br />
insertat(table,element,position)absent Thetyperulesinthetableentryforthisoperationlooklikethis:<br />
rulename()<br />
table2orderedtable rulename(oper<strong>and</strong>)<br />
tointherulesastable,element,<strong>and</strong>position.Thereisnoqualier.The thattheoperationinsertathasthreeoper<strong>and</strong>s,whichwillbereferred Forexample,let'slookattheoperationinsertat.Theheaderlinestates<br />
element elementtypeof(table) predefinedinteger()
theelementwillalsobeknownbyapplyingthefunctionelementtypeof. Thethirdrulesaysthatifthetypeofthetableisknown,thenthetypeof headerlineisfollowedbythreetyperules.Therstruleisaclassrule,which unconditionallyinferredorcheckedtobeoftypepredefined!integer. statesthatthetypeoftablemustbeanorderedtabletype.Thesecondrule saysthattheoper<strong>and</strong>position|thisistheoper<strong>and</strong>afterthewordat|is 9.TypeChecking<strong>and</strong>Inference81<br />
sideoper<strong>and</strong>isknownarered.Eachtimeaninferenceruleisred,it infersthetypeoftheoper<strong>and</strong>onitsleftside.Ifthatoper<strong>and</strong>currentlyhas tion,theinferenceruleswithemptyright-h<strong>and</strong>sides,orwhoseright-h<strong>and</strong> typeisassignedbygeneratinganinferreddeclarationfortheoper<strong>and</strong>.Now matchisanerror.Iftheoper<strong>and</strong>currentlyhasunknowntype,theinferred resultswhichwereexplicitlymarkedwithatypespecier.Foreachopera-<br />
knowntype,theinferredtypeischeckedagainsttheknowntype.Amis-<br />
typesofthoseoper<strong>and</strong>swhicharevariablenames,<strong>and</strong>ofthoseexpression Thetypecheckingalgorithmbeginsbycomputingallknowntypes|the<br />
thatthetypeofthisoper<strong>and</strong>isknown,thismaycauseotherrulestore.<br />
example,thetestvariablesusedinif,while,select,<strong>and</strong>thepredicate unknowntypes,theprogramisinerror<strong>and</strong>thecompilerwillageach arenottable-driven.Theyarenotedintheappendixascomments.For occurrenceofsuchvariables. allvariablesshouldhavebeenassignedtypes.Ifanyvariablesstillhave eredoper<strong>and</strong>s,butareinsteadgroupedwiththequalier.Typeinference <strong>and</strong>typecheckingarealsoperformedforthesevariables,butthosechecks Typecheckingcontinuesuntilnoadditionalringsarepossible.Bynow,<br />
inaselector(theexpressionfollowingthekeywordwhere)areinferredas predefined!boolean.Becauseofthisinference,itislegaltowriteexpressionslikeif(a>b),whichotherwisewouldbeambiguoussincethe<br />
operation>canreturnaresultofanybooleantype.Thisinferencecan Therearesomevariableswhich,fortechnicalreasons,arenotconsid-<br />
messagethattheinteger-literaloperationcannotyieldaresultoftype<br />
leadtodetectionoftypeerrorselsewhere,e.g.if(3)...willproducea<br />
redundant. positionoper<strong>and</strong>isoftypepredefined!integer,aclassrulewouldbe itmaybeofanytype.Sinceaninferencerulealreadyguaranteesthatthe beanorderedtable.Thereisnoclassrulefortheelementoper<strong>and</strong>,since known.Forexample,thetableoper<strong>and</strong>oftheinsertatoperationmust isappliedregardlessofwhethertheoper<strong>and</strong>'stypewasinferredororiginally isaconstraintonthepossibletypesagivenoper<strong>and</strong>canhave.Theclassrule Note:Typechecking<strong>and</strong>inferencingisperformedafterresolution.Type Afteralltypeshavebeeninferred,theclassrulesareinvoked.Aclassrule<br />
Charstring. correctnessisneverusedasacriterionfordisambiguatinganame. thattypeCharstringisatableofChar,<strong>and</strong>thatQueueisatableof Herearefourexamplesillustratingtypeinference<strong>and</strong>checking.Assume
829.TypeChecking<strong>and</strong>Inference block declare begin newQ; X:Charstring; Q:Queue; I:Integer; insert"abc"|"cd"intoQ;--inferencefromtopdown X:="uvw";<br />
typeofthetable,(4)concatenation|therearetwosources<strong>and</strong>aresult,all I:=sizeof(X|"abc");--inferencefrombottomup<br />
ofthesametype,soifanyonetypeisknowntheothertwocanbeinferred. sourcetype;(3)insert|thetypeoftheelementcanbeinferredfromthe typemustbeastring,butthereisnoinferencerule;(2)sizeof|thereis aninferencerulefortheresulttype(predenedinteger),butnoneforthe Therelevantoperationsare:(1)stringliteral|theclassrulesaysthe endblock; I:=sizeof"abc";--noinference;illegal insertX|"abc"intoQ;--inferenceinbothdirections<br />
areinferredtobeCharstringbecausetherulesforconcatenationcannow bered. becausethetypeofQisknowntobeQueue.Thetypeof"abc"<strong>and</strong>"de" isnoinferenceruletoinferthesourcetype.ButsincethetypeofXisknown tobeCharstring,theruleforconcatenationdeterminesthatthetypesof "abc"<strong>and</strong>oftheresult,X|"abc"mustbeCharstring,too. sizeof,becauseeventhoughtheresulttypeisknowntobeinteger,there Inthesecondstatement,thetypeofX|"abc"cannotbeinferredfrom Intherststatement,thetypeof"abc"|"cd"isinferredtobeCharstring<br />
todeterminethetypeofX|"abc".Whicheverruleresrstwillsetthe type;whicheverruleressecondwillcheckthetype.Ifthetypesinferred X|"abc".BecausethetypeofXisknown,theruleforconcatenatecanre thetypeofQisknown,theruleforinsertcanretodeterminethetypeof inthetwodirectionshadbeendierent,anerrorwouldhaveresulted. Inthethirdstatement,theinferencecanworkinbothdirections.Because<br />
specieristoexplicitlydeclareatypeforanexpressionoper<strong>and</strong>.Whena Charstring#"abc". to"abc",thestatementisillegal|itneedstoberewrittenI:=sizeof noinferenceruleforthesourceoper<strong>and</strong>.Sincethereisnotypeassignment whetheronlyonelegaltypeisvisible.)Thesizeofoperationlikewisehas Ada-likerulewhichtriestosearchthespaceofallvisibletypestosee operationdoesn'tinferthetype|itonlyhasaclassrule.(<strong>Hermes</strong>hasno Theprexcharstring#iscalledatypespecier.Theeectofatype Inthefourthstatement,notypeinferenceispossible.Thestringliteral<br />
typespecierisused,thetemporaryvariableistreatedashavingknown typeratherthanunknowntype.Thisknowntypestillmustbeconsistent
documentationpurposesevenwheretheyarenotrequired. sometimesatypespecierisrequired.Typespeciersmayalsobeusedfor withtheinferencerules<strong>and</strong>classrules.Theexampleaboveshowsthat 9.TypeChecking<strong>and</strong>Inference83
Typestatecheckingassignsatypestatetoeachprogrampoint.Atypestate 10 TypestateChecking isamathematicalobjectwhichcanbeinterpretedintwoways:(1)asan assertionthatcertainpropertiesofprogramvariableswillbetruewheneverthatstatementisexecuted;(2)asapointinasemilattice1.Because<br />
by<strong>Hermes</strong>.Wewilldescribethetypestatecheckingalgorithmweuse.We dataowanalysiscanbeused. certainlanguagerulesexpressedintermsofthoseassertionsaresatised. Becausetypestatesformasemilattice,certainwell-knownalgorithmsfrom willtellyouhowtoreadthetablewhichdenestheparticulartypestate rulesforeachoperation. 10.1SyntaxofTypestates Inthissection,wewilldiscusstheparticulartypestatesemilatticeused typestatesareassertions,theycanbeusedtocheckatcompile-timethat<br />
Typestatesareexplicitlywritteninthefollowingsituations:(1)ininterfacedenitions(inputports,callmessages,<strong>and</strong>constraints),(2)intable<strong>and</strong><br />
variantdenitionstoindicatewhattypestateanelementorvariantcomponentmusthave,(3)intheunwrapstatement,toindicatewhattypestate<br />
apolymorphmusthave. enclosedincurlybraces.Anattributeisanattributenamefollowedbya listofvariablenamescalledattributearguments. Atypestateiswrittenasasetofattributesseparatedbycommas<strong>and</strong><br />
dened. Y)Ṫhefollowingattributenamesarebuilt-in:init,case,checked<strong>and</strong> checkeddefinitions.Constraintattributes,likegreaterthan,areuser-<br />
Examplesofattributes:init(X.A),case(V,V.A),greaterthan(X, typestate::=f[attribute[,attribute]...]g<br />
initmusthaveasingleargument,<strong>and</strong>casemusthaveexactlytwoargu- Theargumentsofbuiltinattributesarecheckedasfollows:Attribute attribute::=attribute{nameattribute{arguments<br />
tt1;tt2<strong>and</strong>foranyt0,(t0t1^t0t2))(t0t). ofelementst1<strong>and</strong>t2haveauniquegreatestlowerboundormeettsuchthat 1Asemilatticeisasetwithapartialorderrelationshipsuchthatanypair
ments.Therstargumenttocasemustbeavariantvariable,<strong>and</strong>thesecondmustbeacomponentofthesamevariantvariable.Attributechecked<br />
musthaveasingleargumentoftypepredefined!program.Attribute definitionsmodule. checkeddefinitionsmusthaveasingleargumentoftypepredefined! Allotherattributenamesareconstraintattributes.Whenyoumention 10.TypestateChecking85<br />
howmanyattributeargumentstheremustbe<strong>and</strong>whatthetypeofeach aconstraintattribute,therewillbeaconstraintdenitionwhichspecies mustbe. Forexample,ifthereisaconstraintdenition greaterthan:constraint(a:integer,b:integer)IS<br />
thisuseasanabbreviation,youmaynotdeneanattributenamedfull. X.AofX.Forothertypes,fullmeansthesameasinit.Fromnowon, we'llassumefullhasbeenexp<strong>and</strong>edoutwhereveritappears.Becauseof it'sthesameasifyouwroteinit(X)<strong>and</strong>full(X.A)foreachcomponent abbreviation.Ifyouwritefull(X),<strong>and</strong>Xisarecordorcallmessage,then argumentsoftypeinteger. thentheattributegreaterthanmustalwaysappearwithexactlytwo Thenamefullissyntacticallyanattributename,butitistreatedasan finit(a),init(b)ga>b;<br />
Herearethemeaningsofthetypestateattributes: checked(P)meansthatprogramPhasbeenchecked<strong>and</strong>isfreeof case(V,V.X)meansthatvariantVisrevealed,<strong>and</strong>componentV.X init(X)meansthevariableXisinitialized;otherwiseitisuninitialized.<br />
exists;theabsenceofcase(V,...)meansthatvariantVishidden. syntaxerrors,includingresolutionerrors,typeerrors,<strong>and</strong>typestate checked<strong>and</strong>assignedauniquename.(Seethediscussionofthecheckdefinitions errors. checkeddefinition(D)meansthatdenitionsmoduleDhasbeen<br />
10.2FormalTypestates attributename(arguments)meansthatthenamedconstraintpredicateisknowntobetrueofitsarguments.<br />
statement.)<br />
Sometimesatypestatemustbewrittenwithoutthebasevariables.For example,hereisthedenitionofarecord,<strong>and</strong>atableoftheserecords: R:record(A:integer,B:Charstring);
eforebeinginsertedintoatableoftypeTmustbefinit(V),init(V.A), 8610.2.FormalTypestates<br />
variablename.Ifthevariablenameisabasevariablewithnocomponents, V.Theresultingtypestateiscalledaformaltypestate.Aformaltypestate itisreplacedby*.Theargumentlist(*)canoptionallybeomitted. lookslikeatypestate,exceptthatweomitthebasevariablefromeach init(V.B)g.Whenwewritethedenition,weomitthearbitraryvariable argumentofeachattribute,turningitfromavariablenameintoaformal ThedenitionsaysthatthetypestateofanarbitraryvariableVoftypeR T:tableofRfinit(*),init(A),init(B)gkeys(A);<br />
eachformalvariablenamewiththegivenvariablename. inwhichthetypeofthearbitraryvariableisknown. finit(X.Y),init(X.Y.A),init(X.Y.B)g.YoucansubstituteX.Yinto intotheformaltypestateinthedenitionabove,<strong>and</strong>obtainthetypestate ponentsofanarbitraryelementofatable. Tosubstituteavariablenameintoaformaltypestatemeanstoprex Aformalvariablenameorformaltypestateisalwayswritteninacontext Forexample,ifvariablenameX.YhastypeR,thenyoucansubstituteX.Y Formalvariablenamesarealsousedinkeylists,wheretheydenotecom-<br />
attributes,noteverycombinationofattributesisvalid. Becauseofthemeaningofthe<strong>Hermes</strong>datatypes<strong>and</strong>themeaningofthe 10.3ValidTypestates thekey<strong>and</strong>obtainanactualkeyofX.Y.A.<br />
tionsasinvalid: Herearetheattributecompatibilityruleswhichdenecertaincombina-<br />
Ifinit(X)isnotpresent,nootherattributewithargumentXmay<br />
Ifcase(V,V.A)ispresent,thennootherattributecase(V,V.B) IfXhascomponents,<strong>and</strong>init(X)isnotpresent,thennootherattributewithanycomponentasargumentmaybepresent.Thisfollows<br />
havevalues. fromthefactthatcomponentsofstructuredvaluesonlyexistwhen bepresent.Thisfollowsfromthefactthatonlyinitvariablescan thestructuredvalueitselfexists.<br />
Ifcase(V,V.A)ispresent,thenV.A'scasetypestateattributesare Ifcase(V,V.A)isabsent,thennootherattributewithV.Aascomponentmaybepresent.Thisfollowsfromthefactthatyoucanaccess<br />
componentsofavariantonlywhentheyarerevealed. variantexistsatatime. ispresent.Thisfollowsfromthefactthatonlyonecomponentofa present.ThesearetheattributesobtainedbysubstitutingV.Ainto
Ifinit(CM)ispresent<strong>and</strong>CMisacallmessage,thentheattributes theformaltypestatedenedforcomponentAinthetypedenitionfor aninitializedbuthiddenvariant. typestateofarevealedvariantmustbehigherthanthetypestateof variantV.Thisfollowsfromthefactthatwerequiretheseattributes tobepresentwhenwehidethevariant,<strong>and</strong>werequirethatthe 10.TypestateChecking87<br />
intheminimumtypestateofCMmustbepresent.Theseattributes<br />
isitselfuninitialized. typestateareillegal|e.g.anassignmenttorecordcomponentR.AwhenR Otherwiselegaloperationswhoseeectwouldbetoproduceaninvalid areobtainedbysubstitutingCMintotheformaltypestatedenedor impliedastheminimumtypestate.(Seediscussionofcallmessages.) discardedbytheprocessreceivingthecall. thatcertaincallparametersmustremaininitialized<strong>and</strong>cannotbe Thisisbecausetheprogrammerisallowedtostateintheinterface<br />
typestatewhenthesetofattributesoftherstisasubsetofthesetofattributesofthesecond.Themeetoftwotypestatesissimplytheintersection<br />
Thesemilatticestructureissimple.Atypestateislowerthanasecond oftheattributesets. 10.4OrderingofTypestates<br />
10.5Coercions Coercionsaretypestate-loweringoperationswhichareinsertedautomaticallybythecompiler.Therearethreecoercions:<br />
hideVremovestheattributecase(V,V.X),alongwithanyother dropconstraint(P1,...,Pn)removestheattributeconstraint(P1, discardXremovestheattributeinit(X),aswellasanyotherat-<br />
...,Pn). attributesofV.X.<br />
init(V.B)gisfinit(V)g. finit(V),case(V,V.A),init(V.A)g<strong>and</strong>finit(V),case(V,V.B), Example:finit(A)gislowerthanfinit(A),even(A)g.Themeetof<br />
tributesofXorX'scomponents.
it.Avariableisconstantataparticularprogrampointif: 10.6Constants Althoughweusetheterm\variable"todenoteacellwhichcanholdavalue <strong>and</strong>appearasanoper<strong>and</strong>,sometimes\variables"are\constant"!Thatis, sometimesitisonlylegaltoaccessthevalueofavariablebutnottochange 8810.5.Coercions<br />
Itisabasevariable,<strong>and</strong>anenclosingblockstatementliststhatbase Itisacomponentofaninitializedcallmessage,<strong>and</strong>thecallmessage Itisabasevariablewhichwasinitializedtoaconstantcopy.(See Theprogrampointisinsideanexpressionblock<strong>and</strong>thebasevariable typedenitionliststhatcomponentasaconstant. selector,inspect,forstatements.) variableasconstant.<br />
typestatetoitssuccessorstatements: Herearethestepsincheckingasinglestatement<strong>and</strong>propagatinganew 10.7HowtoApplytheTypestateRules Itisacomponentofaconstant. wasdeclaredoutsidethatexpressionblock.<br />
2.Ifanyrequiredattributeismissing,thisisanerror. 3.Introducecoercionswhichdropattributeswhicharepresentbutare 1.Determinethepreconditionfortheoperation.Thereisatablegiving<br />
forbidden.Ifwecannotaddcoercionswithoutalsodroppingrequired exceptions. asetofpreconditionrulesforeachoperation.Theserulesdetermine:<br />
attributes,thenthisisanerror.Otherwise,wehavesucceededin (1)asetofrequiredattributes,(2)asetofforbiddenattributes,<br />
generatingatypestatewhichisconsistentwiththepreconditions. (3)theoper<strong>and</strong>smodiedbytheoperation,(4)possibleadditional<br />
4.Generateanerrorifanyvariablesmodiedbytheoperationareconstantseral\exception"outcomes.Thetableentryforeachoperationdenemal"outcomeforalloperations(exceptexit),<strong>and</strong>therecanbesev-<br />
whichexceptionoutcomestheoperationhas.Thetablemaylistaddi-<br />
5.Determinethesetofoutcomesoftheoperation.Thereisa\nortionalexceptionswhichtheoperationhasundercertaincircumstances
6.Determinethepostconditionsforeachpossibleoutcomeoftheoperation.Foreachoutcome,usetherulesgiveninthetabletodetermine<br />
exceptionoutcomeprovideditsoper<strong>and</strong>isakeyedtable. |forexample,itmaysaythattheoperationhasaDuplicateKey 10.TypestateChecking89 whichattributestoaddtoordropfromthetypestate. 7.Checkthatafteradding<strong>and</strong>droppingtheappropriateattributesthe 8.Wheneachtypestateiscomputed,propagatethattypestatetothe resultingtypestateisvalid.<br />
tions: NamedProgram:record(A:Charstring,B:Program); Let'sapplythesestepstoanexample.SupposeIhavethesetypedeniercionoperationstolowerthetypestatetothatmeettypestate.<br />
youhavejustcomputedforthispathtothatdestination.Insertco-<br />
destination.Ifthatdestinationalreadyhasatypestate,computethe<br />
ProgramRepository:tableofRffullgkeys(A); meet(asdenedabove)ofitsprevioustypestate<strong>and</strong>thetypestate<br />
init(R),init(P),init(P.A),init(P.B),checked(P.B)g.Supposethe oftypeProgramRepository.Supposethecurrenttypestateis:finit(I), therearethreerulesrelevanttotypestatechecking.Theseare:thepreconditionrules,thepostconditionrules,<strong>and</strong>theexceptionlist.Forinsert,<br />
statementbeingcheckedis: LookatthetableofoperationrulesinAppendixB.Aftertheclassrules, insertPintoR; NowsupposeIisoftypeinteger,PisoftypeNamedProgram<strong>and</strong>Ris<br />
thepreconditionrulesare (init(table),lowestelementstate(element,table),var(table), var(element),duplicatekey(table))<br />
attributesareforbidden.SectionB.4explainshowtoapplyeachpreconditionfunctiontodeterminetherequired<strong>and</strong>forbiddenattributes.<br />
attributesarerequired:finit(R),init(P),init(P.A),init(P.B)g.This attributeisforbidden:checked(P.B).Sincealltherequiredattributes init(P.B)g.AnyattributesofPorofitscomponentsotherthantheabove Ruleinit(table)saysthatthetableoper<strong>and</strong>mustbeinitialized.Rule SubstitutingPintothisformaltypestateyieldsfinit(P),init(P.A), lowestelementstate(element,table)saysthattheelementoper<strong>and</strong>must beinthelowesttypestateconsistentwiththeelementtypestateofthetable. isffullg,whichisanabbreviationoffinit(*),init(A),init(B)g. (Elementtypestateisdenedbelowinsection11.6.)Theelementtypestate Thersttwomembersofthelistaretypestatepreconditionfunctions.<br />
Asaresultofapplyingthepreconditionrules,itisdeterminedthatthese
thecompilertoforgetthattheprogramvalueP.Bhasbeenchecked,becauseitisbeinginsertedintoatablecontainingprogramvalueswhicever,thereisan\extra"attribute|checked(P.B).Thecoerciondrop<br />
9010.7.HowtoApplytheTypestateRules areinitializedbutnotchecked.Whenthevalueisremovedfromthetable,itwillbeassumedtobeunchecked.Thetypestateisnowfinit(I),<br />
arepresentinthetypestate,thereisno\missingattribute"error.How-<br />
init(R),init(P),init(P.A),init(P.B)g. iedbytheoperation.Fromthisrule,weinferthatP<strong>and</strong>Rmustnotbe constant.Iftheyare,thecompileragsanerror. Therulesvar(table)<strong>and</strong>var(element)tellsuswhichoper<strong>and</strong>saremod-<br />
checked(P.B)isinsertedtodropthechecked(P.B)attribute.Thiscauses<br />
TheDepletionexceptionwasdeterminedfromtheexceptionlist,because ofexceptionswhichcouldberaised. everyinsertoperationcanraisethisexception.TheDuplicateKeywas tableRwasdenedaskeyed,<strong>and</strong>ifso,toincludeDuplicateKeyintheset calreasons,itisincludedwiththepreconditionrules<strong>and</strong>evaluatedwhen preconditionsareevaluated.Theeectoftheruleistocheckwhetherthe derivedbyevaluatingthepredicateduplicatekey(table),becauseonly Thepossibleoutcomesofinsertare:normal,Depletion,<strong>and</strong>DuplicateKey. The\rule"duplicatekey(table)isnotapreconditionrule.Fortechni-<br />
insertionsintokeyedtablescanraisethisexception. rules.Forinsert,theserulesare: Thepostconditionfornormalexitisdeterminedbythepostcondition<br />
Therulekillconstraints(table)dropsanyconstraintattributesofthe executed.Sothetypestateassociatedwiththetwoexceptionoutcomes isalsofinit(I),init(R),init(P),init(P.A),init(P.B)g.Forthis reason,exceptionpostconditionsarenotshowninthetable. changedvalue<strong>and</strong>anunchangedtypestate|asiftheoperationhadnot tributesofP<strong>and</strong>itscomponents|namelyfinit(P),init(P.A),init(P.B)g. Therulemakeuninit(element)makesPuninitializedbydroppingallat-<br />
(makeuninit(element),killconstraints(table))<br />
table|therewerenone.ThepostconditionfunctionsareexplainedinsectionB.5.<br />
Exceptforthecallstatement,allexceptionoutcomesproduceanun-<br />
Theinitialtypestateisoneinwhichtheinitializationportisinitialized<strong>and</strong> init(R)g. 10.8TheCheckingAlgorithm noothertypestateattributesarepresent. Sothetypestateassociatedwithnormalcompletionofinsertis:finit(I),<br />
quired<strong>and</strong>forbiddenattributespriortotheoperation,<strong>and</strong>theadded<strong>and</strong> Ateachstatement,therulesinthetableareusedtodeterminethere-
droppedattributesafternormalcompletionoperation. Threetypesofstatementsareh<strong>and</strong>ledspecially: Thecompoundstatementshavemorecomplexpostconditionrules Thecallstatementisdierentbecausethenormal<strong>and</strong>exception postconditionscomefromtheinterfacedenition. 10.TypestateChecking91<br />
Similarly,everystatementcontainingaselectorisanalyzedasifit owgraph. manualwedescribethetypestatepostconditionresultingfromthis weretwostatements:aselectorfollowedbyaprimitivestatement. Therulesinthetabledenetheprecondition<strong>and</strong>postconditionrules booleanteststatement<strong>and</strong>theembeddedclauses.Inthereference anifstatementbehavesasifitwerecomposedofamoreprimitive becausetheyareequivalenttominiatureowgraphs.Forinstance,<br />
typestatepropagatedfromthestatementperformingtheforwardbranch. withinblock,if<strong>and</strong>selectstatementstotheendofthestatementare betweentheprevioustypestateassociatedwiththedestination<strong>and</strong>the forwardbranches.Whenaforwardbranchisencountered,themeetistaken Exceptions,exitstatements,<strong>and</strong>thebranchesfromtheendofclauses Eachloopconstruct(while,for)performsasinglebackwardbranchfrom selectors. fortheprimitivestatement;theserulesareappliedaftertherulesfor<br />
ofthelooparethenre-analyzed. typestatepreviouslyassociatedwiththetopoftheloop.Thestatements theendoftheloopislowerthanorincomparabletothetypestateatthe beginning,themeetistakenbetweenthetwotypestates.Thislowersthe isdoneexcepttointroduceanynecessarycoercion.Ifthetypestateat theendofthelooptothebeginning.Ifthetypestateattheendoftheloop isstrictlygreaterthanorequaltothetypestateatthebeginning,nothing<br />
Thepossibletypestateerrormessagesare: tate<strong>and</strong>noloopsneedtobere-analyzed.Inpractice,noloopwillneedto beanalyzedmorethantwice. 10.9TypestateErrors Analysiscontinuesuntilallprogrampointshavebeenassignedatypes-<br />
Deadcode:Astatementcannotbereached.Rememberthattypestatecheckingignoresthevaluesofvariables,sothatevenastatemenception.Thiserrorariseswhenyouwriteastatementafteranexit<br />
beginningif'false'then...doesnotgenerateadeadcodeex-<br />
statementorafteracompoundstatementallofwhosealternatives
9210.9.TypestateErrors<br />
Cannotcoerce:Theoperationrequiresanattributetobedropped, Attributenotpresent:Arequiredtypestateattributewasnotpresent. terminatewithexitstatements.Italsoarisesifyoucodeah<strong>and</strong>ler whichcanneverbebranchedto. Forexample,youcodedaninsertoperationbutthetablewasnot<br />
initialized<strong>and</strong>thesecondtobeuninitialized.SupposeParmsisa butthecoercionwhichdropstheattributewouldalsodropanother attributewhichisrequired.Example: callService(Parms.A,Parms.B); SupposetheinterfacetoServicerequirestherstargumenttobe initialized.<br />
callmessagewhoseminimumtypestaterequiresbothParms.A<strong>and</strong> Parms.Btobeinitialized.ThenthecallstatementrequiresParms.B<br />
Cannotdrop:Thepostconditionrulem<strong>and</strong>atesdroppingthisattribute,buttodosowouldproduceaninvalidtypestate.Forexample,<br />
Cannotadd:Thepostconditionrulem<strong>and</strong>atesaddingthisattribute, thismessage. tobemadeuninitialized,butthiscannotbedonewithoutdiscarding Parms,whichwouldthenmakeParms.Auninitialized. assignmenttoParms.AwithoutrstinitializingParmswouldproduce buttodosowouldproduceaninvalidtypestate.Forexample,an<br />
dependenterrorswhicharedetectedduringtypestatechecking: Thefollowing,whilenottechnicallytypestateerrors,arestaticcontext-<br />
Illegalposition:Youhavecodedthepositionofoperationina Illegalconstant:Youhavecodedastatementwhichmodiesoneof itsoper<strong>and</strong>s,buttheoper<strong>and</strong>isconstant. droppingacallmessagebelowitsminimumtypestate. contextwhereitisnotlegal.Thisoperatorislegalonlywhenthe tableelementoper<strong>and</strong>isaconstantcopy.
11 <strong>Hermes</strong>Operations Throughouttheremainderofthereferencemanual,syntacticruleswillbe includedintheexcerpts.Thegrammarispresentedinitsentirety,including Low-levelsyntacticelementsthatappearinrulebodiesgenerallywillnotbe excerptedfromAppendixAasspeciclanguageconstructsareintroduced.<br />
Ubiquitousoperationsarethosewhichapplytoallornearlyalltypes. 11.1UbiquitousOperations theselow-levelelements,inAppendixA.<br />
placesitinanother(thedestination).Ifthedestinationvariablehada Themovestatementremovesavaluefromonevariable1(thesource)<strong>and</strong> Move value,thatvalueisdiscarded.Thesourcevariablebecomesuninitialized. Example: simple{statement<br />
uses\name-equivalence"fordecidingwhethertwotypesmatch;therefore, R.A
Copy 9411.1.UbiquitousOperations<br />
Thecopyofstatementcopiesavaluefromonevariabletoanother.The thevalue<strong>and</strong>attributesofthesourcevariable.Thesourcevariablemay move,thedestinationvariablelosesitsoldvalue<strong>and</strong>attributes,butacquires sourcevariableretainsitsoriginalvalue<strong>and</strong>typestateattributes.Aswith simple{statement<br />
haveanytypestateexceptcompletelyuninitialized. secondary::=copyofsecondary ::=result{variable:=source{expression<br />
copyofX,orinanassignmentstatementlikeY:=X.ThelatterisequivalenttoY
Thediscardstatementremovesthevaluefromthevariable.Discardingan initializedcallmessagereturnsthecallmessage;thecallerwillreceivethe simple{statement ::=discardvariable{name11.<strong>Hermes</strong>Operations95<br />
rstbeloweredtotheirminimumtypestate|thisconceptisdenedlater, callmessagetype.Discardedexception.Thecallmessagecomponentswill inthesectiononcallmessages.Discardingavaluecontainingcallmessages| forexampleaninputportholdingenqueuedcallmessages|discardsthe callmessages.Discardinganyothertypeofvaluejustthrowsthevalueaway.<br />
limitedresources.TheDepletionexceptionisraisedwheneverduetoaresourcelimitationoranimplementationrestriction,thecorrectresultcannoitylimits,integeroverow.Implementationsareencouragedtoavoidgiv-<br />
Anideal<strong>Hermes</strong>machinehasunlimitedresources.Realmachineshave 11.2TheDepletionException Mostoperationscanraisethisexception,soitisdescribedhereratherthan repeatedlyundereachoperation. becomputed. don'trequireallimplementationstobethissophisticated,sowereserve ingDepletionexceptionsratherthantorequireprogrammerstodevelop theirowncircumventions.Forexample,integerswhichdon'ttinahardwareregistercouldberepresentedbydynamic-precisionintegers.Butwe<br />
Examplesinclude:runningoutofaddressspace,exceedingdiskcapac-<br />
theDepletionexceptiontoinformtheuserthattheimplementationis inadequatetorunthisparticularexecution. <strong>Hermes</strong>implementationsmustguaranteethatstoragedepletioncannotoccurwhilediscardingorhidingavalue.<br />
Coercionoperations|e.g.discard|cannotfailwithanyexception.
9611.2.TheDepletionException 11.3ControlFlowOperations Block compound{statement<br />
constant{section ::=block endblock [h<strong>and</strong>ler]... begin [declaration{section] [constant{section]<br />
declaration{section ::=constant([base{variable[,base{variable]...]) ::=declare[declaration;]... [statement;]...<br />
declarenewvariables,youcanspecifythatthevaluesofexistingvariables Ablockstatementintroducesanewscope.Withinthisscope,youcan h<strong>and</strong>ler::=on([exception{name[,exception{name]...]) ::=onexit([exit{name[,exit{name]...])<br />
bythenamesoftheexitsorexceptionsith<strong>and</strong>les.Theabbreviationothers Theotherclausesaretheh<strong>and</strong>lerclauses.Eachh<strong>and</strong>lerclauseispreceded mustremainconstant,<strong>and</strong>youcanprovideh<strong>and</strong>lersforexceptionsorexits withinthemainbodyoftheblock. Thestatementseriesafterthewordbeginisthemainclauseoftheblock. [statement;]...<br />
withinah<strong>and</strong>lerclausecannotcausecontroltotransfertoanotherh<strong>and</strong>ler clauseofthesameblock. totheh<strong>and</strong>leroftheinnermostblock.Rememberthatexceptionsraised Twoclausesofthesameblockcannoth<strong>and</strong>lethesameexitorexception. containingh<strong>and</strong>lersforthesameexceptionorexit,controlwilltransfer st<strong>and</strong>sforallexceptionswhicharenotexplicitlyh<strong>and</strong>led.Restriction:<br />
issuinganexitstatement,thentheclauseissaidtoexitnormally..Ifany Ifastatementiswithinthemainclausesoftwoormorenestedblocks controltotransfertotheclauseheadedbythatexceptionorexitname. Ifallstatementsofaclausecompletewithoutraisinganexceptionor Anexceptionorexitraisedwithinthemainclauseofablockcauses<br />
wordsblock<strong>and</strong>endblockdonotappear.Asecondblockwithanempty clauseofablockexitsnormally,thentheblockitselfexitsnormally. on(others)h<strong>and</strong>lerisimpliedaroundthisblock.Thisisnecessarysothat Thebodyofaprocessstatementisactuallyablock,althoughthe
Ifnoneoftheclausescanexitsnormally,theblockstatementcannotexit thetypestatesonnormalexitfromalltheclauseswhichcanexitnormally. normally.Theonlywayaclausecannotexitnormallyisifitendswith therewillalwaysexistatargetforexceptionsraisedwithinh<strong>and</strong>lersofthe processstatement. Thetypestateonnormalterminationofablockstatementisthemeetof 11.<strong>Hermes</strong>Operations97<br />
cannotexitnormally. Ifcompound{statement anexitstatementorifitendswithacompoundstatementwhichitself<br />
thethenclauseisthenexecuted;ifthevalueis'false',theelseclause Theifstatementcontainsanexpression|thetest|<strong>and</strong>twoclauses|the pressionisevaluatedtoaninitializedbooleanvalue.Ifthevalueis'true', then<strong>and</strong>elseclauses. ::=iftest{expression<br />
isexecuted.Anomittedelseclauseistreatedasanemptyelseclause. Itbehavesliketheifstatementofconventionallanguages:Thetestex-<br />
endif [else[statement;]...] then[statement;]...<br />
While statementcannotexitnormally. clausewhichcanexitnormally;ifnoclausecanexitnormally,thentheif onnormalexitoftheifstatementisthemeetofthetypestatesforeach sameasthetypestateafterexecutionofthetestexpression.Thetypestate musthavetypestateinit.Thetypestateonentrytoeitherclauseisthe isinferredtohavetypepredefined!boolean.Thetestexpressionresult Thetype<strong>and</strong>typestaterulesareasfollows:Thetestexpressionresult<br />
Thewhilestatementcontainsanexpression|thetest|<strong>and</strong>aclause|the repeatclause. compound{statement<br />
statementisre-executed.Ifitis'false',thewhilestatementterminates. expressionisrepeatedlyevaluatedtoaninitializedbooleanvalue.Ifthe valueis'true',thentherepeatclauseisexecuted,<strong>and</strong>thenthewhile Itbehaveslikethewhilestatementofconventionallanguages:Thetest ::=whiletest{expressionrepeat<br />
Thetype<strong>and</strong>typestaterulesareasfollows:Thetestexpressionresultis endwhile [statement;]...<br />
checkedtohavetypestateinit.Thetypestateonentrytothetestexpres- inferredtohavetypepredefined!boolean.Thetestexpressionresultis
sionisthemeetofthetypestatebeforeexecutionofthetestexpression<strong>and</strong> thetypestateonnormalterminationoftherepeatclause.Thetypestate 9811.3.ControlFlowOperations asthetypestateafterexecutionofthetestexpression. Select onentrytotherepeatclauseisthetypestateafterexecutionofthetest expression.Thetypestateonterminationofthewhileclauseisthesame compound{statement select{clause ::=select[select{expression] endselect [select{clause]...<br />
event{guard ::=boolean{guard[statement;]... ::=event{guard<strong>and</strong>boolean{guard[statement;]... ::=event{guard[statement;]... otherwise{clause<br />
boolean{guard ::=eventinport{variable<br />
Theselectstatementconsistsofanoptionalexpression,asetofselect clauses,<strong>and</strong>anotherwiseclause.Aselectclauseconsistsofaguard<strong>and</strong>a otherwise{clause select{expression ::=otherwise[statement;]... ::=where(test{expression)<br />
clause.Aguardcanbe abooleanguard, aconjunctionofabooleanguard<strong>and</strong>aneventguardnaminganinput port,or ::=expression<br />
eventinport1 Example: select where(x>0) aneventguardalone,whichistreatedasifabooleanguardof'true' y:=x+y; hadbeencoded.
Ifthereisanoptionalselectexpression,thenitisevaluated<strong>and</strong>the eventinport2<strong>and</strong>where(x
inport2,thethirdclausewillexecute;ifmessagesarriveatbothports, 10011.3.ControlFlowOperations<br />
thestatementwillblock. atinport1,thesecondclausewillexecute;ifamessagearrivesonlyat secondclausemaybeexecuted.Ifx0,thenif nomessageeverarrivesatinport1therstclausemusteventuallybe<br />
init.Thetypestateonentrytoanyclauseisthetypestateafterevaluatingallguards.Thetypestateonnormalterminationofthestatementis<br />
checkedtobeoftypefamilyinputport. sionsareinferredtobeoftypepredefined!boolean.Eventguardsare twoclauses. averagesalary,thenanon-deterministicchoiceismadebetweentherst behaveslikethechoicestatementsofotherlanguages.Iflowsalary= Allbooleanguards<strong>and</strong>alleventguardsmusthavetypestateattribute Herearethetype<strong>and</strong>typestatecheckingrules:Booleanguardexpres-<br />
Inthesecondexample,therearenoeventguards,<strong>and</strong>thestatement<br />
mally;ifnoneoftheclausescanexitnormally,thenneithercantheselect themeetofthetypestatesoncompletionofallclauseswhichcanexitnor-<br />
statement. ExpressionBlock<br />
able.Sinceexpressionsarenotsupposedtohavesideeects,allvariables clausecontainingstatementstocomputetheresultvariable. declaredoutsidetheexpressionblockareconstantwithintheblock. Anexpressionblock,orevaluateoperator,isawaytoembedstatements withinanexpression.Itcontainsadeclarationofaresultvariable,<strong>and</strong>a Theexpressionblockintroducesanewscopecontainingtheresultvari-<br />
secondary::=evaluatedeclarationfrom[statement;]...end<br />
normalexitfromtheblock.Itisa\deadcode"erroriftheclausedoesnot haveanormalexit.Theblockmustinitializetheresultvariable. Thetypestateafterexecutinganexpressionblockisthetypestateon forLispObjectinLispObjectswhere (evaluateStartsWithZ:booleanfrom blockbegin endblock; on(CaseError) revealLispObject.Pair; revealLispObject.Pair.Car.PrintName; StartsWithZ:=LispObject.Pair.Car.PrintName=Z; StartsWithZ:='false';
stmemberisanatomwithprintnamematchingZ.Thetestmustbe endfor; ThisprogramfragmentlooksuptheLispvariablewhichisapairwhose inspect end) callLispPrint(LispObject); 11.<strong>Hermes</strong>Operations101<br />
writtenasanexpressioninsidewhere().Toperformthetest,wemustwrite statementwithinanexpression. Exit arevealstatement,soweneedanexpressionblockinordertoenclosethis<br />
hadbeenraised.Ineect,anexitisalocallydenedexceptioncondition. Example: Theexitstatementterminatesexecutionofablockasifanexception blockbegin simple{statement ifX>200000 then exitTooBig; ::=exitexit{name<br />
inablockwhosemainclausecontainstheexitstatement.Ifthereismore thanonesuchh<strong>and</strong>ler,theinnermostoneischosen.(Thisruleisrepeated branchestoah<strong>and</strong>lerforthatexitname.Theh<strong>and</strong>lerchosenmustbe Thestatementincludesanidentierwhichisanexitname.Control onexit(TooBig) endblock;<br />
... endif;<br />
<strong>Hermes</strong>hasvescalartypefamilies:nominal,enumeration,boolean,integer,<strong>and</strong>real.Thescalartypesfamiliesaresimilartoscalartypesinother<br />
11.4ScalarOperations inthediscussionoftheblockstatement.)<br />
inthesefamilies,<strong>and</strong>thendiscussthescalaroperations. ScalarTypeDenitions Anominaldomainisasetofvalueswhichhavenorelationshipotherthan equality.Theyareusedtogeneratedistinctnames|hencethetermnominal.Youcangenerateanew,distinctnominalvaluewiththeuniqueop-<br />
procedurallanguages.Inthissectionwerstdescribehowtodeclaretypes
10211.4.ScalarOperations eration.Youcancopynominals<strong>and</strong>testthemforequality.Youcannot uesareequaliftheyarecopiesofthesamegeneratedvalue,otherwisethey areunequal.Anominaltypedenitioncreatesanewnominaldomain. performorderedcomparisonsorconversionstointegers.Twonominalval-<br />
anamedliteralwitheachvalue,e.g.'blue'.Thenamedliteralsofasingle enumerationtypedenitionmustbedistinct.Thisnamedliteralcanbe merationtypedenitiondenesanewenumerationdomain,<strong>and</strong>associates Example:::=nominal TransactionId:nominal; Anenumerationdomainconsistsofanitenumberofvalues.Anenu-<br />
type{construction<br />
usedinexpressionstogeneratethevalueitnames.Enumerationvaluesof course,thevalue'blue'inoneenumerationdomainhasnothingtodo withthevalue'blue'inadierentenumerationdomain,sinceonlyvalues thesametypeareequaliftheyareequaltothesamenamedliteral.Of ofthesametypecanbecompared. type{construction<br />
thekeywordorderedappearsinthedenition.Unorderedenumerations ::=[ordered]enumeration(<br />
supportcomparisonsonlyforequality<strong>and</strong>inequality,justlikenominals. Enumerationsareeitherorderedorunordered,dependingonwhether ::=variantofenumeration{type( )<br />
[case{declaration[,case{declaration]...] [named{literal[,named{literal]...]<br />
Orderedenumerationsalsosupporttheorderedcomparisons,=.Theyalsocanbeconvertedtointegers.Therstenumerationliteral Thefollowingaresomeexamples.<br />
theother\false".Abooleantypedenitionassociatesthetrue<strong>and</strong>false valueswithdistinctnamedliterals. thatcontainsallthecharactersoftheASCIIcharactersetinsortedorder. Aboole<strong>and</strong>omainconsistsoftwovalues,onerepresenting\true"<strong>and</strong> option:enumeration('present','absent'); color:enumeration('red','blue','yellow','green'); ThereisapredenedorderedenumerationtypecalledPredefined!Character quality:orderedenumeration('poor','fair','good','excellent'); type{construction ::=boolean(boolean{association)
types.Additionally,theoperations\<strong>and</strong>",\or",<strong>and</strong>\not"aresupported. Booleantypessupportthesameoperationsasunorderedenumeration Thereisapredenedbooleantypecalledpredefined!booleanwhose boolean{association ::=false:named{literal,true:named{literal ::=true:named{literal,false:named{literal 11.<strong>Hermes</strong>Operations103<br />
namedliteralsare'true'<strong>and</strong>'false'.Youc<strong>and</strong>eneyourownboolean typeswithdierentliterals.Example: typedenitiondenesanewintegerdomain. bit:boolean(true:'0',false:'1'); Anintegerdomainconsistsofthemathematicalintegers.Eachinteger<br />
orangesdomain.Butyoucanconvertbetweentwointegerdomainsusing Example:::=realofaccuracyinteger{literal/integer{literal apples:integer; oranges:integer; Asusual,5intheapplesintegerdomaincan'tbecomparedto5inthe type{construction<br />
theconvertoperation. ::=integer<br />
numberthatcantinawordofcomputermemory.Incontrast,<strong>Hermes</strong> usestheusualmathematicaldenitionofinteger.Theresultofaninteger operationisalwayseitherthemathematicallycorrectresult,orelseno discretesubsetofrealnumbersspacedsucientlyclosetogethertomeet asafenumbersuchthattherelativeerror(thedistancebetweenthesafe result<strong>and</strong>aDepletionexception. auser-denedaccuracyrequirement.Foreveryrealnumber,thereexists Insomelanguages\integers"aredenedmodulothesizeofthelargest<br />
number<strong>and</strong>therealnumberdividedbytherealnumber)islessthanor equaltotheaccuracyrequirement. Arealdomainconsistsofasetofsafenumbers.Safenumbersarea<br />
isidenticaltothatshownforintegersabove.Approximaterealarithmetic tegerbetweenthemmusthaveasafeintegerbetweenthem. \preferred"assafenumbers,i.e.anypairofsafenon-integerswithaningrammersaresupported:(1)Zeroisasafenumber,<strong>and</strong>(2)integersare<br />
Theusualrealarithmeticoperationsaresupported;theexpressionsyntax Twootherpropertiesofapproximatearithmeticoftenassumedbypro-<br />
velocity:realofaccuracy1/1000000; Theaccuracyisexpressedasafraction,e.g.1/1000000.Example:<br />
isperformedasfollows.Theresultiscomputed<strong>and</strong>asafenumbernearest theexactresultisusedastheresult.Ifthereismorethanonenearestsafe numbertoanumber,anondeterministicselectionismade.
10411.4.ScalarOperations Integer,Real,<strong>and</strong>NamedLiterals Literalsareexpressionswhichcomputearesultdenedatcompile-time.<br />
getatypeerror.Thecompilerwillnotscanthroughthesetofallvisible Examples:23,'blue',"Hello,World!". whetheritisaninteger,real,string,ornamedliteral.Forexamplethe Theyaretreatedasnullaryoperationsforthepurposeoftype-checking.<br />
typestoseeifthereisauniqueoneinwhichthisexpressionmakessense. rememberthatifyouwriteanexpressionlike'fair'
Less,Less-equal,Greater,Greater-equal relation::=concat=concat ::=concatconcat 11.<strong>Hermes</strong>Operations105<br />
Examples:X=2,Y3,A
10611.4.ScalarOperations For-enumerate<br />
thevariableisassignedthatvalue<strong>and</strong>theclauseisexecutedonce.Inside compound{statement<br />
theclause,thevariableisrequiredtobeconstant.Theorderinwhichthe merationtype.Foreveryvalueinthedomainoftheenumerationtype, wherethedeclarationspeciesavariablebelongingtoanunorderedenu-<br />
Theforenumeratestatementiteratesovertheelementsofanunordered enumerationtype.Thisstatementconsistsofadeclaration<strong>and</strong>aclause, ::=forenumeration{variable:enumeration{typerepeat<br />
valuesarechosenisnondeterministic.Thefollowingisanexample. endfor [statement;]...<br />
forthiscolor:colorrepeat<br />
Theconvertofoperatorhasonlyoneoper<strong>and</strong>.Itconvertsvaluesfrom Convert endfor secondary::=convertofsecondary sendcolortooutport;<br />
oneorderedtypetoanother.Anexampleofitsuseis: integerreal Thethreeordereddomainsarerelatedasfollows:orderedenumeration x
RecordTypeFamily 11.5RecordOperations type{construction ::=record( [component{declaration[,component{declaration] 11.<strong>Hermes</strong>Operations107<br />
Arecordisatupleofvaluescalledcomponents.Whenarecordisinitial-<br />
...]<br />
nentsareinitialized<strong>and</strong>allinitializedcomponentsareequal. ized,thecomponentvariablesexist.Thecomponentvariablesmaythem-<br />
selvesbeeitherinitializedoruninitialized.Whenarecordisuninitialized, thecomponentvariablesdonotexist,areconsidereduninitialized,<strong>and</strong>can-<br />
Tworecordsareequalforcomparisonpurposeswhenthesamecompo-<br />
) notbemadeinitialized. e.gċlause:record( Arecordtypedenitionspeciesthename<strong>and</strong>typeofeachcomponent,<br />
uninitialized.Thepreviousvalueoftherecord,ifany,isdiscarded. New Thenewoperationcreatesaninitializedrecordwhosecomponentsare );statements:statements simple{statement id:clauseid,<br />
uninitialized|issuethenewoperation,<strong>and</strong>theninitializethecomponents, 11.6TableOperations orassignormoveapre-existingrecordvalue. Note:thetwowaystoinitializearecordvariablewhichiscurrently ::=newvariable{name<br />
TableTypeFamily Atableisacollectionofvaluesofthesametype<strong>and</strong>typestate.Thevalues arecalledtheelementsofthetable,thetypetheelementtype,<strong>and</strong>the key::=([formal{variable[,formal{variable]...]) type{construction ::=[ordered]tableofelement{typeelement{typestate [keys[key]...]
strings,arrays,lists,<strong>and</strong>relations. representinganelementtypestate.Itcancontainthekeywordordered.A 10811.6.TableOperations<br />
canbecompared. typestatetheelementtypestate.Tablescanbeusedtorepresentbags,sets, tabletypedenitioncanalsocontainasetofkeys.Eachkeyiswrittenasa restrictionsguaranteethattableelementscanbecompared,<strong>and</strong>thatkeys initialized,(2)theelementtypestatemustnotbefullyuninitialized.These listofformalvariables.Restrictions:(1)Thevariablesofakeymustbe Atabletypedenitioncontainsanelementtype<strong>and</strong>aformaltypestate<br />
order. ofallkeys.Twoelementsdierinakeyiftheydierinanyvariableofthat key. etcṪwoorderedtablesareequaliftheycontainequalelementsinthesame ments.Therstelementofthetableissaidtohaveposition0,thenext1, Twounorderedtablesareequaliftheirelementscanbeputinone-to-one Thevalueofanorderedtableisanordered(possiblyempty)setofele-<br />
Ifatablehaskeys,anytwoelementsofthetablewillhavedierentvalues<br />
someexamplesoftabletypedenitions. correspondence<strong>and</strong>thecorrespondingelementsareequal.Thefollowingare stringset:tableofstringfinitgkeys(*); string:orderedtableofcharfinitg; intbag:tableofintegerfinitg; person:record(<br />
inconventionallanguages:itisatotallyorderedbag.Typestringset multipleoccurrencesofthesameinteger.Typecharstringislikeastring );id:integer persontable:tableofpersonffullgkeys(name,address)(id); Typeintbagisabag|itcanholdanynumberofintegers,including name:string,<br />
hastheadditionalspecicationthatnotwostringsmaybeequal|thus address:string,<br />
elementscanhavethesamevalueofid.Thistypeactslikeatwo-way mappingbetweenidnumbers<strong>and</strong>name-addresspairs. Newsimple{statement elementscanhavethesamestringsforbothname<strong>and</strong>address,<strong>and</strong>notwo itbehaveslikeaset.Typepersontablehasthepropertythatnotwo ::=newvariable{name
valueofthetable,ifany,isdiscarded. Theoperationnewcreatesaninitializedbutemptytable.Theprevious literalisanorderedtableofenumerationorbooleanvalues.Eachcharacter StringLiteral Astringliteralisaself-deningcharacterstringvalue.Thetypeofastring 11.<strong>Hermes</strong>Operations109<br />
Concatenate denedasorderedtableofBit. stringofatypewhichincludesvaluesnamed'0'<strong>and</strong>'1'|e.g.atype theenumerationorbooleantype. inthestringliteralmustcorrespondtoasingle-characternamedliteralof Soif"0011010"isusedasastringliteral,itsresolvedtypemustbea<br />
Thisoperationconcatenatestwoorderedtablestoproducearesultcontainingacopyoftheelementsoftheleftoper<strong>and</strong>followedbyacopyofthe<br />
Selector elementsoftherightoper<strong>and</strong>.Theelementsmustbecopyable. concat::=term<br />
selector::=base{variableintable{variable ::=concatjterm<br />
simplyabbreviationsforlongselectors. threesyntacticformspermittedbythesyntax.Therstformiscalled Theselectorisasyntacticconstructusedinseveraloperations.Thereare alongselector,theothersmappingselectors.Themappingselectorsare ::=table{variable[[expression[,expression]...]]<br />
where(selector{expression)<br />
inaselectoriscalledanelementdeclaration.Itdenesanewvariablename Thevariablename(tablevariable)isthenameofatable.Thebasevariable<br />
Thisvariablenameisvisiblewithinthewhereexpression.Theexpression iscalledtheselectorexpression.Itevaluatestoaresultwhichisinferred calledtheelementvariable,whosetypeistheelementtypeofthattable. table.Theelementvariableissetequaltoaconstantcopyoftheelement. Theelementsforwhichtheselectorexpressionaretruearesaidtobe tobeoftypepredefined!boolean. selected. selectors.Ifthemappinglistisempty,thenallelementsareselected|itis Atexecutiontime,theselectorisevaluatedonceforeachelementinthe Amappingselectorisashorth<strong>and</strong>representingsomecommonusesof
11011.6.TableOperations ashorth<strong>and</strong>forwhere('true').Ifthemappinglisthasasingleexpression, <strong>and</strong>thetableisordered,thenexpressionisassumedtobeaposition<strong>and</strong>the selectedelementistheelementatthatposition.Thust[n]isshorth<strong>and</strong>for eintwhere(positionofe=n).Iftheaboveruledoesnotapply,<strong>and</strong><br />
toselectasingleelement;thepurposeofothersistoselectanentireset. elementsdependsupontheoperation.Thepurposeofsomeoperationsis illegal. =x<strong>and</strong>e.address=y).Ifnoneoftheserulesapply,orifmorethanone keyhasthecorrectnumberofvariables,theuseofthemappingselectoris themappinglisthaskexpressions,<strong>and</strong>onekeyhaskvariables,thekexpressionsareassumedtobecomparisonvaluesforthosekeys.Thusifthas<br />
typepersontable,thent[x,y]isshorth<strong>and</strong>foreintwhere(e.name<br />
anarbitrarychoiceismade. Whenthepurposeistoselectasingleelement,<strong>and</strong>noelementisselected, tableisordered,theearliestelementischosen.Ifthetableisunordered, exceptionNotFoundisraised.Ifmorethanoneelementisselected,<strong>and</strong>the Theresultisacopyofthechosenselectedelement,orelseNotFoundis Aselectorbyitselfinanexpressionistheoperationcalledtheelement. Selectorsappearaspartofseveraloperations.Theuseoftheselected<br />
raised.Theresulthastheelementtype<strong>and</strong>elementtypestate.Theelement Every typemustbecopyable. Theeveryoperationreturnsatablecontainingacopyofalltheselected elements.Iftheoriginaltablewasordered,thecopiedelementsareinthe sameorder.Theresultofeverywillbeanemptytableifnoelementsare Exists,Forall selected.Theelementtypemustbecopyable. secondary::=everyofselector<br />
selected;elseitreturnsfalse.Theforalloperationreturnsatrueboolean Theexistsoperationreturnsatruebooleanvalueifatleastoneelementis valueifallelementsareselected;elseitreturnsfalse. Insert,Insert-at secondary::=existsofselector<br />
simple{statement ::=forallofselector ::=insertelement{expressionintotable{variable [atposition{expression]
thetableisordered,theelementisinsertedattheendofthetable.Ifthe tableiskeyed,theDuplicateKeyexceptionisraisediftheinsertionwould operationisillegal.Ifithasahighertypestate,thetypestateislowered.If Thevaluemusthavetheelementtypestate.Ifithasalowertypestate,the fromasourcevariable.Thesourcevariablemustbeoftheelementtype. Theinsertstatementaddsanewelementtoatablebymovinginavalue 11.<strong>Hermes</strong>Operations111<br />
actlylikeinsert,exceptithasanadditionaloper<strong>and</strong>oftypepredefined!integer haveviolatedtherequirementofuniquekeys. whichspecieswheretoinserttheelement.Ifthispositionisnegative,or greaterthanthenumberofelementsinthetable,theexceptionRangeError takesprecedence. mayberaisedexactlyasforinsert,exceptthataRangeErrorexception israised.Otherwise,theelementisinsertedatthedesignatedposition.The positionsofearlierelementsinthetableremainthesame.Thepositionsof laterelements(ifany)areincreasedbyone.TheexceptionDuplicateKey Theinsert-atstatementislegalonlyfororderedtables.Itbehavesex-<br />
sinceitsvalueismoved<strong>and</strong>notcopied. Remove Aftereitherinsertorinsert-at,theelementvariableisuninitialized,<br />
noselectedelement,theexceptionNotFoundisraised.Thepreviousvalue, removedfromthetable<strong>and</strong>movedintothedestinationvariable.Ifthereis Theremovestatementhastwooper<strong>and</strong>s:adestinationelement,whichappearsafterthewordremove,<strong>and</strong>aselector.Thechosenselectedelementis<br />
Examples: simple{statement ifany,ofthedestinationvariableisdiscarded. removeCharfromString[0]; ::=removeelement{variablefromselector<br />
one.Ifthereisnone,anexceptionisraised.Thesecondstatementremoves thesmallestintegerfromIntbag|theintegerIsuchthatallintegersin empty. Extract IntbagareatleastaslargeasI.Itwillraiseanexceptionifthetableis removeMinfromIinIntBag Therststatementremovestherstcharacterfromthestring,ifthereis where(forallofJinIntbagwhere(J>=I));<br />
appearsafterthewordextract,<strong>and</strong>aselector.Allchosenselectedele- Theextractstatementhastwooper<strong>and</strong>s:adestinationtable,which simple{statement ::=extracttable{variablefromselector
isdiscarded. Merge,Merge-At 11211.6.TableOperations mentsareremovedfromthetablenamedintheselector,<strong>and</strong>movedinto thedestinationtable.Ifnoelementsareselected,thedestinationtableis initializedtoanemptytable.Thepreviousvalue,ifany,ofthedestination<br />
thesourcevariablewillbeuninitialized.Ifthetableisordered,theelements(ifany)fromthesourcetablewillbeinsertedattheendofthe<br />
elementswillbeofthesametype<strong>and</strong>typestate.Onnormalcompletion, tinationtable.Thetwotablesareofthesametype|meaningthatthe Themergestatementmovesthecontentsofthesourcetableintothedes-<br />
simple{statement<br />
destinationtable,<strong>and</strong>theirorderwillbepreserved.Ifthetableiskeyed, ::=mergetable{expressionintotable{variable<br />
theDuplicateKeyexceptionisraisedifthemergewouldhaveviolatedthe [atposition{expression]<br />
requirementofuniquekeys.<br />
asformerge,exceptthataRangeErrorexceptiontakesprecedence. whichspecieswheretoinsertthesourcetableelements.Ifthisposition actlylikemerge,exceptithasanadditionaloper<strong>and</strong>oftypepredefined!integer ceptionRangeErrorisraised.Otherwisetheelementsareinsertedatthe designatedposition.Thepositionsofearlierelementsinthetableremain thesame.Thepositionsoflaterelements(ifany)areincreasedbythenumberofelementsmerged.TheexceptionDuplicateKeycanberaisedexactly<br />
isnegative,orgreaterthanthenumberofelementsinthetable,theex-<br />
Themerge-atstatementislegalonlyfororderedtables.Itbehavesex-<br />
table.Thiscopyisstoredintoanewvariable{theinspectvariablehaving Inspect-table Thisstatementmakesaconstantcopyofthechosenselectedelementofa thesamenameastheelementvariableoftheselector.Theinspectvariable isautomaticallydeclaredtobeoftheelementtypeofthetable,<strong>and</strong>tohave compound{statement<br />
ascopeincludingtheclausewithinthebodyoftheinspectstatement.If ::=inspectselectorbegin<br />
thereisnoselectedelement,theNotFoundexceptionisraised. endinspect [statement;]...<br />
be\dangerous"(receive,return)whenperformedonordinarycopiesare aconstantcopyofanyvalue.Thisisbecausetheoperationswhichwould sages,inputports,orvaluescontainingthem),itisalwayslegaltomake Whereasitisillegaltomakeordinarycopiesofcertainvalues(callmes-
notallowedonconstantcopies.Avariableholdingaconstantcopyisautomaticallymadeuninitializedwhencontrolleavesthescopeofthevariable.<br />
Thefollowingisanexampleoftheinspectstatement. inspectcharinstring begin where(char='X'<strong>and</strong>positionofchar>2) 11.<strong>Hermes</strong>Operations113<br />
tweentheinspectstatement<strong>and</strong>thesimilarstatementusingtheoperation the-element. mentasthevariableholdingtheconstantcopy.Notethedierencesbe-<br />
sionastheelementvariableofaselector,<strong>and</strong>(2)withintheinsertstate-<br />
c:=charinstringwhere(char='X'<strong>and</strong>positionofchar>2); endinspect; Notethedoubleuseofthevariablechar|(1)withinthewhereexpres-<br />
insertcopyofcharintostring2;<br />
copy.Itisillegaltoapplyinsertdirectlytocharbecauseitisconstant, operationcanbeappliedtoconstantcopiesbutnottoordinarycopies. butitislegaltoapplyinsertdirectlytoc.Theposition-of-element mentproducesaconstantcopy,whereasthe-elementproducesanordinary whereasthe-elementworksonlywithcopyabletypes.Theinspectstate-<br />
havebeenpreviouslydeclared.Theinspectstatementworksforalltypes, Thetypestateonentrytothemainclauseoftheinspectstatement Theinspectstatementintroducesadeclarationofchar,whereascmust insertcintostring2;<br />
normally. For-Inspect mainclause,exceptthattheinspectvariablebecomesuninitialized.Ifthe mainclausecannotexitnormally,thentheinspectstatementcannotexit fromtheinspectstatementisthesameasthetypestateonexitfromthe theinspectvariableisintheelementtypestate.Thetypestateonexit isthesameasthetypestatepriortotheinspectstatementexceptthat<br />
lectedsubsetofthetable.Thetablemustbeinitialized.Themainclause (theclausefollowinginspect)isexecutedonceforeachselectedelement. Avariablewiththesamenameastheelementvariableoftheselectorholds Thefor-inspectstatementiteratesovertheelementsofatableorase-<br />
compound{statement<br />
tothefor-inspectstatementisusedtodeterminetheselectedvalues; aconstantcopyoftheselectedelement.Thevalueofthetableonentry ::=forselectorinspect<br />
anychangestothetablemadefromwithintheiteratedclausewillnotaffectwhichvaluesareselected.Ifthetableisordered,theelementswillbe<br />
endfor [statement;]...
assumingitcanexitnormally.Thetypestateonexitfromthefor-inspect typestate<strong>and</strong>othertypestateattributesarethesameastheywerebefore themeetof(1)thetypestateinwhichtheinspectvariableisintheelement thefor-inspectstatement,(2)thetypestateattheendofthemainclause, 11411.6.TableOperations<br />
statementisthemeetofthetypestateonentrytothemainclause<strong>and</strong>the selectedinthatorder.<br />
unconditionalexit,sinceitispossibleforthemainclausetobeexecuted canalwaysterminatenormally,evenifthemainclauseterminatesinan typestatepriortothefor-inspectstatement.Afor-inspectstatement Thetypestateonentrytothemainclauseofafor-inspectstatementis<br />
Theoperatorsizeofevaluatestoanintegercontainingthenumberof elementsinthetable.Thetablemustbeinitialized. zerotimes. Size Position-of-element secondary::=sizeofsecondary<br />
Thisoperationcanbeappliedonlytoconstantcopiesofelementsselected fromanorderedtable.Theseconstantcopiesareproducedonlywithina whereexpressionofaselector,aninspect,orafor-inspectstatement. elementwhichwasusedtoproducetheconstantcopystoredintheelement variable.Positionsbeginat0. Theoperationevaluatestoanintegerwhichisthepositionoftheselected secondary::=positionofelement{variable<br />
thestring. Example:<br />
Position-of-selector string
thereisnoselectedelement,aNotFoundexceptionisraised. VariantTypeFamily 11.7VariantOperations 11.<strong>Hermes</strong>Operations115<br />
Avariantisavaluewhichwillhaveoneofaxed,pre-speciedsetof type{construction ::=variantofenumeration{type(<br />
adierentcomponentnametodesignateeachdierenttypeofvalue.A types.Sincein<strong>Hermes</strong>,everyvariablenamehasexactlyonetype,weuse case{declaration ::=named{literal!component{declaration component{typestate )[case{declaration[,case{declaration]...]<br />
variantVcanbeeither initialized<strong>and</strong>revealed:exactlyonecomponenthasavalue.Thepro-<br />
initialized<strong>and</strong>hidden:exactlyonecomponentexists.Theprogram uninitialized:ithasnovalue<strong>and</strong>therearenotypestateattributes<br />
ponent<strong>and</strong>noother.Thetypestateisinit(V),case(V,V.X).There gramknowswhichcomponenthasavalue<strong>and</strong>canaccessthatcom-<br />
ponentisaccessible.Thetypestateisinit(V). doesn'tknowwhichcomponentexists<strong>and</strong>whichdonot,sonocom-<br />
involvingvariableV<br />
componentsareequal. thecasesofthevariant,<strong>and</strong>theenumerationtypeisthecasetype. thenamedliteralsofanenumerationtype.Thesenamedliteralsarecalled literalofthecasetype,acomponentname,componenttype,<strong>and</strong>aformal Twovariantsareequaliftheyhavethesamecase<strong>and</strong>iftheirexisting Thecomponentsofavarianttypeareinone-to-onecorrespondencewith Avarianttypedenitionspecies:(1)thecasetype,(2)foreachnamed maybeothertypestateattributesinvolvingvariableV.X.<br />
lower. casetypestate.Thecasetypestateisthetypestatethecomponentwillhave revealed,thetypestatemaybecomehigherthanthistypestate,butnever justbeforeitishidden<strong>and</strong>justafteritisrevealed.Whilethevariantis Thefollowingisanexampleofavarianttypedenition. id:charstring; lisptype:enumeration('nil','atom','pair');
11611.7.VariantOperations sexpression:variantoflisptype( );'pair'->pair:conscellffullg conscell:record( 'atom'->atom:idfinitg, 'nil'->null:emptyfg,<br />
sexpressioncontaincomponentsoftypeconscell,whichinturncontaincomponentsoftypesexpression.<br />
beenrevealedtobeincase'pair',thenthetypestatewillbe );cdr:sexpression Notethatthesetypedenitionsaremutuallyrecursive|variablesoftype Inthisexample,ifVisavariableoftypesexpression,<strong>and</strong>ithasjust car:sexpression,<br />
Unite untiltheyarerevealedinturn.ItisnotlegaltodiscardV.Pair.Car,leavingapartiallyinitializedpair.Itis,however,legaltoreplacethevalueof<br />
init(V),case(V,V.Pair),init(V.Pair),init(V.Pair.Car),init(V.Pair.Cdr) Innercomponents,suchasV.Pair.Car.Pair.Cdr,willnotbeaccessible<br />
Theunitestatementinitializesavarianttoaparticularoneofitscases. Itstwooper<strong>and</strong>sareavariablenamedesignatingavariantcomponent, component.Thetypestateoftheexpressionmustbeatleastashighasthe <strong>and</strong>anexpressionevaluatingtoavalueofthesametypeasthatvariant casetypestateofthevariantcomponent.Ifitishigher,itiscoerceduntil itisexactlyequaltothecasetypestate. simple{statement<br />
Ifthevarianthadavalue,thatvalueisdiscarded.Thevalueofthe ::=unitevariant{componentfromsource{expression<br />
thevariantwillberevealed<strong>and</strong>thevariantcomponentwillbeaccessible. Thedissolvestatementreversestheeectoftheunitestatement.The Dissolve expressionisthenmovedintothevariantcomponent.Aftertheoperation,<br />
rstvariablenamedesignatesavariantcomponent.Thesecondvariable namedesignatesavariableofthesametypewhichwillreceivethevalueof thatvariantcomponent. destinationvariableisdiscarded.Thevalueofthevariantcomponentis Thevariantcomponentmustberevealed.Anypreviousvalueofthe simple{statement ::=dissolvevariant{componentintoresult{variable
willbeuninitialized,<strong>and</strong>thedestinationvariablewillhavethetypestate thenmovedintothedestinationvariable.Aftertheoperation,thevariant attributesofthevariantcomponent. Reveal 11.<strong>Hermes</strong>Operations117<br />
Therevealstatementrevealsahiddenvariantcomponent.Theoper<strong>and</strong> coercedbacktohidden. exists,thenthatcomponentisrevealed.Ifthecaseofthevariantissuch thatthecomponentbeingrevealeddoesnotexist,theexceptionCaseError isavariantcomponent.Thevariantmustbehidden|ifitisrevealed,itis Ifthecaseofthevariantissuchthatthecomponentbeingrevealed simple{statement<br />
israised,<strong>and</strong>thevariantremainshidden. ::=revealvariant{component<br />
usually)generatedautomaticallyasaresultofacoercionwhichdropsthe caseattribute. Thehideoperationisacoercion.Itcanbeexplicitlycoded,or(more Hide<br />
Itmustbeinitialized.Afterexecutingthestatement,thevariantwillbe hidden. Thesingleoper<strong>and</strong>ofahidestatementisavariableofvarianttype. simple{statement ::=hidevariant{variable<br />
Thecaseofoperatortakesavariantasoper<strong>and</strong><strong>and</strong>returnsthecaseof Case thevariant.Theresultisavalueofthevariant'scasetype. secondary::=caseofsecondary
InputPort,OutputPort,CallmessageTypeFamilies 11811.7.VariantOperations 11.8ProcessCreation<strong>and</strong>Communication type{construction<br />
::=callmessage(<br />
::=inportofcallmessage{typeentry{typestate ...] )[constant{parameters] exitexit{typestate [user{exception]... [minimum] [component{declaration[,component{declaration]<br />
constant{parameters ::=constant([component{name[,component{name]... ::=outportofinport{type<br />
Thetypefamiliesinputport,outputport,<strong>and</strong>callmessageareusedin \programming-in-the-large"|thatis,thedivisionofsystemsintoprocesses, minimum::=minimumminimum{typestate user{exception ::=exceptionuser{exception{nameexception{typestate ])<br />
thecreationofprocesses,thecreationofbindingsbetweenprocesses,<strong>and</strong><br />
type,<strong>and</strong>(2)aformaltypestate,calledtheentrytypestate. portsorentriesarenotvaluesofvariables. inportvaluesarestoredininportvariablesjustasintegerorstringvalues made.Itshouldbeemphasizedthatin<strong>Hermes</strong>inportsarevalues,<strong>and</strong>that arestoredinintegerorstringvariables.Thisiscompletelyconsistentwith therestof<strong>Hermes</strong>,butmightappear\dierent"becauseinmanylanguages thecommunicationbetweenprocesses.<br />
Usuallythemessagetypewillbeacallmessagetype.However,themessagetypecanbeanytype,sincesendcanbeusetotransmitanyvalueto<br />
aninport. callmessage,sinceallcallstatementswillgenerateinitializedcallmessages, willhavewhensent.Youmayomitinit(*)fromtheformaltypestateofa <strong>and</strong>usingsendtodeliveranuninitializedcallmessageispointless. Aninporttypedenitionspecies(1)atypename,calledthemessage Aninputportorinportisamessagequeuetowhichconnectionscanbe<br />
Theentrytypestateisthetypestatethatvaluesofthemessagetype
Itistheabilityforprogramstosend<strong>and</strong>receiveoutputportsthatgives other<strong>Hermes</strong>value,<strong>and</strong>canbestoredinvariables<strong>and</strong>passedinmessages. ports,itshouldbere-emphasizedthatoutputportsaretreatedlikeany copiesofthesameinport.comparisonof Twoinportscompareequalonlyiftheyarethesameinportorconstant Anoutputportoroutportisaconnectiontoaninputport.Aswithinput 11.<strong>Hermes</strong>Operations119<br />
<strong>Hermes</strong>thepowerofcapability-basedsystems. messagetype<strong>and</strong>typestateofthismatchinginputporttype. port.Eachinputportcreatedwiththenewoperationisconsideredadifferentinputport.Aconstantcopyofaninputportisconsideredthesame<br />
thetypeoftheinputporttowhichtheoutputportcanbeconnected.The type<strong>and</strong>typestateofdatasentonanoutputportisdeterminedbythe Acallmessagetypedenitionconsistsof Anoutporttypedenitionspeciesamatchinginputporttype.Thisis Twooutportsareequalwhentheyareconnectionstothesameinput<br />
asetofcomponentdeclarations,<br />
thesedeclarationsisimportant,becausethecallargumentsarematched Thecomponentdeclarationsdenethecallparameters.Theorderof anoptionalsetofcallmessageexceptions. anoptionalminimumformaltypestate,<strong>and</strong> anexitformaltypestate, anoptionalsetofconstantparameters,<br />
totheseparametersinthesameorder.Theconstantparametersstatewhich componentsarenotmodiablebythecalledprocess.Theexitformaltypestatespeciesthetypestateofthecallmessagewhenitisreturnedtothe<br />
callerinanormaloutcome.Theminimumformaltypestatespeciesthe lowesttypestatethatthecomponentsofacallmessagemaybeloweredto. callmessageisdiscarded. Thisisthetypestatetowhichthecomponentswillbeloweredwhenthe typestate.Theformaltypestatespeciesthetypestatethatthecallmessagewillhavewhenitisreturnedwiththatexception.Donotincludethclared<strong>and</strong>thetypestateforthisexceptionisthesameastheminimum<br />
Thecallmessageexceptionsconsistofanexceptionname<strong>and</strong>aformal oneinwhichallconstantsarefullyinitialized,<strong>and</strong>allotherparametersare uninitialized.<br />
Discardedexceptioninthislist|thisexceptionisalwaysimplicitlyde-<br />
Thefollowingisanexampleofacallmessage<strong>and</strong>theassociatedports. sampleinterface:callmessage( Ifthereisnoexplicitminimumformaltypestate,thenitistakentobe
12011.8.ProcessCreation<strong>and</strong>CommunicationOperations first:integer, second:integer,<br />
sampleinport:inportofsampleinterface )constant(first) exitfinit(first),init(second),init(fourth)g minimumfinit(first),init(second)g exceptionFailurefinit(first),init(second),init(third),negative(first)g; third:integer,<br />
finit(first),init(second),init(third)g; fourth:integer<br />
dierent|parametersfirst,second,<strong>and</strong>thirdwillbeinitialized,<strong>and</strong> <strong>and</strong>returneduninitialized.ThetypestatesfortheexceptionFailureare initializedonnormalexit.Parameterthirdisatransferredparameter| entry<strong>and</strong>exit,<strong>and</strong>guaranteedconstant.Parametersecondisaninout ownedbythecallerbeforethecall,butretainedbythecalledprocess rameterfourthisanoutparameter|uninitializedonentry,butreturned parameter|initializedonentry<strong>and</strong>exit,butnotguaranteedconstant.Pa-<br />
Inthisexample,parameterfirstisaninparameter|initializedon sampleoutport:outportofsampleinport;<br />
acallmessagetospecifyatypestatewhichisnothigherthanorequalto parameterfirstwillbeknowntobenegative. theminimumtypestate.Similarlyallexit<strong>and</strong>exceptiontypestatemustbe higherthanorequaltotheminimumtypestate. Newsimple{statement Itisillegalfortheentrytypestateofaninportwhosemessagetypeis<br />
Thenewoperationinitializesaninputportvariabletoanemptyqueuewith noconnections.Thepreviousvalueoftheinputportvariableisdiscarded. Empty secondary::=emptyofsecondary ::=newvariable{name<br />
Theemptyofoperationreturnsatruebooleanvalueifthequeueisempty, ofoperationonlytondtheinportnolongerempty.However,sinceonly otherwiseitreturnsfalse.Theoper<strong>and</strong>mustbeaninitializedinport. emptyisnotastableproperty;aprocessmayrepeatasuccessfulempty theprocessowninganinputportcanreceivemessages,beingnon-emptyis astableproperty. Sinceotherprocessesmayenqueuemessagesatarbitrarytimes,being
Connect Theconnectstatementhastwooper<strong>and</strong>s.Therstoper<strong>and</strong>(beforethe keywordto)isanoutportvariable.Thesecondisaninportvariable.The simple{statement ::=connectoutport{variabletoinport{variable 11.<strong>Hermes</strong>Operations121<br />
inportvariablemustbeofthematchinginporttypeoftheoutportvariable outportvariableisassignedtoaconnectiontotheinportwhichisthe type,<strong>and</strong>mustbeinitialized. currentvalueoftheinportvariable. Call Thepreviousvalueoftheoutportvariable,ifany,isdiscarded.The simple{statement function{reference ::=calloutport{variablecall{arguments ::=call(outport{expression)call{arguments<br />
arguments.Theoutportmustbeinitialized.Thematchinginporttypemust haveanelementtypewhichisacallmessage.Theargumentsarematched guages.Theoper<strong>and</strong>softhecallstatementareanoutport<strong>and</strong>alistof Thecallstatementcorrespondstoaprocedurecallinconventionallan-<br />
association associated{pair ::=outport{primarycall{arguments<br />
used,thenthereshouldbeonefewerargumentthanparameter,themissingparameterbeingtheresult,whichispassedasanunnamedvariable.If<br />
uptothecallmessagecomponentseitherbyposition,ifpositionalnotation isused,orbyname,ifassociationnotationisused.Iffunctionnotationis positionalnotationisusedwithafunctioncall,thenthelastcallmessage componentistheresult.Ifassociationnotationisused,thentheomitted constantparameterswillbeloweredtoexactlymatchtheentrytypestate Eachargumentmusthaveatypestateatleastashighastheentrytypestate ofthecorrespondingparameter.Thetypestatesofargumentsmatching constantparameterswillremainunchanged. ofthecorrespondingparameter.Thetypestateofargumentsmatchingnon-<br />
call.Twovariablesoverlapifoneoftheirnamesisaprexoftheotheror theyarethesame. Eachargumentmusthaveatypematchingitscorrespondingparameter. Overlappingvariablescannotbepassedastwoormoreargumentsofa
12211.8.ProcessCreation<strong>and</strong>CommunicationOperations<br />
ingtheargumentsintothecallmessage,(3)sendingthecallmessageto theinputporttowhichtheoutputportisconnected,(4)waitingforthe nofunctioncallcanhaveanymodiableparameterexceptitsresult. arepartsofexpressions,<strong>and</strong>expressionsmaynotmodifytheiroper<strong>and</strong>s, procedurereturns4,youwillnotchangethevalueof3.)Sincefunctioncalls ables.Ifthesevariablesarepassedtomodiableparameters,themodica-<br />
tionsarelost.(Forexample,ifyoupass3toaninoutparameter,<strong>and</strong>the Thecallisexecutedby:(1)creatinganewcallmessagevalue;(2)mov-<br />
Itshouldbenotedthatexpressionsareevaluatedintotemporaryvari-<br />
callmessagetobereturned,(5)movingthecallmessagecomponentsback theneventuallythemessagewillbereceived. ismade,<strong>and</strong>thereceivingprocessrepeatedlyissuesreceivestatements, arereturnedinthesametypestatetheyweresent. ontheseoutputportsaremergedfairly.Thismeansthatifacallorsend intotheargumentvariables,(6)throwingawaythecallmessage. aportconnection,theDisconnectedexceptionisraised.Thearguments riedoutasinaregularcall,butadditionally,theexceptionisraisedinthe Ifthecallisreturnedwithanexception,thenalltheabovestepsarecar-<br />
Ifseveraloutputportsareconnectedtothesameinputport,thencalls<br />
caller.Thiscanonlyhappenifthereexistsadeclarationofthatexceptionin thecallmessagetypedenition.Thefullnamefortheexceptionincludesthe callmessagetype<strong>and</strong>theexceptionname|.. Iftheinputporthasbeenthrownaway,leavingtheoutputportwithout<br />
parametersareadded<strong>and</strong>dropped.Theseadds<strong>and</strong>dropsareappliedto betweentheentry<strong>and</strong>returntypestatesdeneswhichattributesofthe .Discardedisraisedinthecaller.Thecallmessageisreturned withtheparametersintheminimumtypestateasdenedinthecallmessage tatejustpriortothecall,fromtheentrytypestate,<strong>and</strong>fromthetypestate<br />
denedforthenormalorexceptionalreturnbeingmade.Thedierence Thetypestateafterexecutingacallstatementisderivedfromthetypes-<br />
Iftheprocessowningthecallmessagediscardsit,thentheexception<br />
theargumentsmatchingtheparameters. Forexample<br />
tionsampleinterface.Failure,thetypestatewillbefinit(p),init(a), constantparametersecond,itcannotretainitsattributeeven(b),which even(b),init(c)g.Sinceamatchestheconstantparameterfirst,it mayretainitsadditionalattributeeven(a).Sincebmatchesthenon-<br />
isdroppedpriortothecall.Onnormalreturnfromthecall,thetypestate willbefinit(p),init(a),even(a),init(b),init(d)g.Onexcep-<br />
typestatepriortothecallis:finit(p),init(a),even(a),init(b), callp(a,b,c,d);<br />
even(a),negative(a),init(b),init(c)g. Supposethetypeofpissampleoutport,denedabove.Supposethe
possible,<strong>and</strong>storesitinadestinationvariable.Theinputportmustbe Receive Thereceivestatementdequeuesamessagefromaninputport,ifthisis simple{statement ::=receivecallmessage{variablefrominport{variable 11.<strong>Hermes</strong>Operations123<br />
initialized.<br />
thenthereceivestatementwillblockindenitely. beraised. toreceiveisnon-deterministic. Themessageismovedintothedestinationvariable.Thisvariablewillbein theentrytypestateassociatedwiththeinport.Thechoiceofwhichmessage port.Thepreviouscontentsofthedestinationvariable,ifany,arediscarded. Iftheinporthasconnections,butnomessageiseversenttotheinport, Iftheinporthasnoconnections,thentheDisconnectedexceptionwill Onnormalcompletionofreceive,amessageisdequeuedfromthein-<br />
Return Thereturnstatementreturnsacallmessagetoitscaller<strong>and</strong>resumesexecutionofthecaller.Optionally,anexceptioncanbereturnedtothecaller.<br />
simple{statement<br />
qualier. inthedenition.Theexceptionnameiswrittenwithoutanytypename ceptionforthatcallmessagetype|eitherDiscarded,oranexceptionlisted Thereturnstatementmustspecifyeithernoexception,oralegalex-<br />
::=returncallmessage{variable<br />
Thecallmessagemusthavethetypestateattributesassociatedwiththe [exceptionuser{exception{name]<br />
whichisexpectedbythecaller. appropriateexceptiontypestateforareturnwithanexception.Ifthetypestateishigher,coercionsareinsertedtolowerthetypestatetoexactlythat<br />
kindofreturn|theexittypestateforareturnwithoutexceptions,orthe<br />
theequivalenteectofprocedures,codethereturnstatementasthelast executablestatementoftheprocess,orfollowthereturnstatementwith anexitstatementjumpingtotheendoftheprocess. ment,aswouldbethecaseifprocesseswerepassiveprocedures.Toproduce continuesexecuting. execution.Ifanexceptionisspecied,thatexceptionisraisedinthecaller, notintheprocessissuingthereturnstatement.Theprocessissuingreturn Thereisnoautomaticterminationofaprocessexecutingareturnstate-<br />
Afterthereturn,thecallmessageisuninitialized.Thecallerresumes
12411.8.ProcessCreation<strong>and</strong>CommunicationOperations Send<br />
terminedfromthematchinginporttypeoftheoutport.Ifthetypestateis musthavetheentrytypestateorhigher.Thetype<strong>and</strong>typestatearede-<br />
higherthantheentrytypestate,itiscoerceddowntotheentrytypestate. inputport.Itsoper<strong>and</strong>sareasourcevariable<strong>and</strong>anoutport. Thesendstatementmovesavalueoutofavariable<strong>and</strong>enqueuesitonan Thevariablewhosevalueistobesentmusthavethecorrecttype,<strong>and</strong> simple{statement<br />
Theoutputportmustbeinitialized. ::=sendsource{expressiontooutport{expression<br />
carded,thentheDisconnectedexceptionisraised. Create Iftheinputporttowhichtheoutputportwasconnectedhasbeendis-<br />
compiledwithinthemainprogramorwithinotherprocessliterals.Amain setofprocesses.Oneisthemainprogram.Theothersareprocessliterals isavariableoftypepredefined!program.Theresultisanoutport. Thecreateofoperationinstantiatesanewprocess.Theoper<strong>and</strong>ofcreate Theprogrammusthavethetypestatechecked. Theprogramvalueisdenedinthepredefinedmodule.Itconsistsofa secondary::=createofsecondary programistheresultofconvertingtheprocessmoduleproductionofa process.Thismustbeaninputporttype.Whencreateisexecuted,itis sourcemodule. outporttypewhichistheresultofthecreatestatement.Ifitisnot,the checkedthatthisinputporttypeisthematchinginputporttypeofthe exceptionInterfaceMismatchisraised. Theinitializationportisthevariabledeclaredfollowingthekeyword<br />
Procedure initializationportwillbeinitialized.Aconnectiontotheinitializationport isreturnedasthevalueofcreate. willexecutetheprogramdenedbythemainprogramintheprogramvalue, beginningatthestatementfollowingthekeywordbegin.Initiallyonlythe Ifthereisnointerfacemismatch,anewprocessiscreated.Thisprocess<br />
isacheckedprogram,<strong>and</strong>theresultisanoutputport.Aswithcreate, anInterfaceMismatchexceptionisreturnediftheoutputporttypeis Theprocedureofoperationinstantiatesaprocessgenerator.Theoper<strong>and</strong> secondary::=procedureofsecondary
incompatiblewiththeinputporttypeoftheinitializationportofthenew<br />
iscreatedisnotaprocessrunningthedesignatedprogram,butinsteadis ageneratorprocess. Theeectofprocedureisidenticaltothatofcreateexceptthatwhat Eachtimethegeneratorprocessiscalled,itconstructsanewinstanceof 11.<strong>Hermes</strong>Operations125<br />
exactlylikethesemanticsofproceduresinAlgol-likelanguages. iscalledprocedureofbecausethesemanticsofgeneratorprocessesis aprocessrunningthedesignatedprogram.Itthensendsthecallmessageit receivedtotheinitializationportofthenewprocess. ofthedesignatedprogram.Theoperationtocreateageneratorprocess callaninputportinthesameprocesswillproduceadeadlock.Acalltoa generatorprocesswillnotdeadlocksinceeachcallgeneratesanewinstance Ordinaryprocessesarenotrecursive,sinceanattemptbyaprocessto<br />
11.9PolymorphOperations Apolymorphisavalueconsistingoftwoparts:(1)awrappedvalue,which PolymorphTypeFamily formaltypestateofthewrappedvalue. thepurposesofassignment<strong>and</strong>comparison.Forexample: canbeofanytype<strong>and</strong>typestate,(2)awrapperdescribingthetype<strong>and</strong> Resource:polymorph; Apolymorphtypedenitiondenesadistinctdomainofpolymorphsfor type{construction<br />
MailItem:polymorph; ::=polymorph<br />
wrappedvaluesofanytype;however,avariableoftypeResourcecannot if<strong>and</strong>onlyifbothwrappers<strong>and</strong>bothwrappedvaluesareequal. Wrap beassignedwithorcomparedtoavariableoftypeMailItem. VariablesoftypeResource<strong>and</strong>variablesoftypeMailItemcancontain Twopolymorphscanbecomparedforequality.Thepolymorphsareequal<br />
containingthesourcevariable'stype<strong>and</strong>formaltypestate,<strong>and</strong>movesthe resultantpolymorphvalueintothepolymorphvariable.Thepolymorph ofthetypestateofthewrappedvalue.Thesourcevariable'stypestatewill Thewrapstatementremovesavaluefromasourcevariable,addsawrapper variableitselfwillhaveatypestateofinitaftertheoperation,regardless simple{statement ::=wrapsource{expressionaspolymorph{variable
12611.9.PolymorphOperations<br />
positive(x.id),gt(x.id,y)g.Thenafterexecutingthestatement tateattributesincludingxare:finit(x),init(x.name),init(x.id), <strong>and</strong>avariablethatdoesnot. constraintwhichincludebothavariablethatoverlapsthesourcevariable thedestinationvariablewillbedropped. beuninitialized.Beforethewrapstatementtypestateanalysiswilldropany nordestinationcanbeconstant,<strong>and</strong>attributesotherthaninitinvolving Othertypestaterestrictionsapplyasforamovestatement:neithersource<br />
inalvalueofx,<strong>and</strong>whosewrappercontainsatypeofperson<strong>and</strong>a formaltypestateoffinit(*),init(name),init(id),positive(id)g. Theconstraintfgt(x.id,y)gwillbedropped. wrapxasy; thevalueofywillbeapolymorphwhosewrappedvalueistheorig-<br />
Forexample,supposethatvariablexisoftypeperson,<strong>and</strong>thetypes-<br />
Unwrap Thenewtypestateforywillbesimplyfinit(y)g.<br />
expectedbythedestinationvariable.Thesource(polymorph)variablemust thatthetype<strong>and</strong>typestateonthewrappermatchthetype<strong>and</strong>typestate <strong>and</strong>movesthevalueintoadestinationvariable.Aruntimecheckinsures Theunwrapstatementremovesawrappedvaluefromapolymorphvariable simple{statement ::=unwrapresult{variable<br />
expectedtypestateisspeciedbycodingaformaltypestatewithinthe beinitialized. Theexpectedtypeissimplythetypeofthedestinationvariable.The frompolymorph{expressionunwrapped{typestate<br />
unwrapstatement. type,orifthetypestateonthewrapperisnotatleastashighastheformal typestatespeciedontheunwrapstatement,thenaPolymorphMismatch exceptionisraised. Ifthetypeonthewrapperdoesnotmatchthedestinationvariable's<br />
attributesofthedestinationvariableotherthanthosedenedbytheformal typestatearedropped. above,wecodethestatement: nordestinationcanbeconstant,thesourcevariablebecomesuninitialized, movingthevalue.Thismayentaildiscardingsomeofthewrappedvalue. theunwrapstatement,thentheappropriateattributesaredroppedbefore Othertypestaterestrictionsapplyasforamovestatement:neithersource Forexample,assumethatimmediatelyafterthewrapstatementshown Ifthetypestateonthewrapperishigherthanthetypestatespeciedon<br />
unwrapxfromyfinit(*),init(id),positive(id)g;
Inspect-polymorph willincludefinit(name)g.Componentnamewillbediscardedbeforemovingthewrappedvalueintox.Theresultingtypestatewillbefinit(x),<br />
Thetypeswillmatch,buttheformaltypestateinthewrapperofy 11.<strong>Hermes</strong>Operations127 init(x.id),positive(x.id)g. compound{statement ::=inspectdeclaration<br />
morphisconstant. ceptthatinsteadofmovingthewrappedvalue,aconstantcopyismade. Theinspect-polymorphstatementbehaveslikeanunwrapstatementex-<br />
Thisallowsthevalueofapolymorphtobeexamined,evenifthepoly-<br />
endinspect begin [statement;]... frompolymorph{expressioninspect{typestate<br />
whichwouldbelegalevenifthepolymorphywereconstant: Hereisanalternativeversionoftheunwrapstatementshownabove,<br />
wouldnotbeaccessible,sincethetypestateinsidethestatementwouldbe thatcomponentwouldnotbediscardedintheconstantcopyx,butit inspectx:personfromyfinit(*),init(id),positive(id)g<br />
operation. simplyfinit(y)init(x),init(x.id),positive(x.id)g. Assumingthatthewrappedvaluehadaninitializedcomponentname, TheexceptionPolymorphMismatchisraisedexactlyasforanunwrap endinspect; begin .../*statementsreferringtox*/<br />
Type morphwrapper.Thisisaninitializedvalueoftypepredefined!typeofvalue. Thetypeofoperationevaluatestothetypeinformationstoredinthepoly-<br />
Thevalueincludesthetypename,thedenitionsmoduledeningthetype name,<strong>and</strong>alltheimporteddenitionsmodules. Theoper<strong>and</strong>mustbeaninitializedpolymorph. secondary::=typeofsecondary Typestate secondary::=typestateofsecondary
12811.9.PolymorphOperations Thevalueincludesthetypestate,thedenitionsmoduledeningthetypestate,<strong>and</strong>alltheimporteddenitionsmodules.<br />
Thetypestateofoperationevaluatestothetypestateinformationstored inthepolymorphwrapper.Thisisaninitializedvalueoftypepredefined!typestateofvalue.<br />
intocheckedprogramvalues.Alternatively,youcancreateprogramvalues, linearsourceform<strong>and</strong>passthemtothe<strong>Hermes</strong>compilerforconversion 11.10ProgramOperations In<strong>Hermes</strong>,youcancreateprogramsintwoways:Youcanwritethemin Theoper<strong>and</strong>mustbeaninitializedpolymorph.<br />
either\fromscratch",orbycomposingormodifyingotherprogramvalues.<br />
pilingitintomachinecodeforthemachineormachinesonwhichthepro-<br />
statement ingacheckedprogramwillbemissingthepredefined!checkedattribute. Tocheckafullyinitializedinstanceofprogramvariablepgm,executethe tributepredefined!checked.Aprogrambuiltfromscratchorbymodify-<br />
assertchecked(pgm); Inmostimplementationsof<strong>Hermes</strong>,checkingaprogramalsoentailscom-<br />
Aprogramvalueobtainedfromthecompilerwillhavethetypestateat-<br />
instantiateaprogramwhichisnotchecked. predefined!program. ProgramLiteral gramwillbeinstantiated.Thisisanoptional<strong>and</strong>machine-dependentop-<br />
timization;theprogrammercannotdirectlymanipulatethemachinecode. Thechecking,however,isnotoptional.Itisatypestateerrortotryto Theoperationsinthissectionareusedtoconstructobjectsoftype Thepredefined!programdenitionisshownintheappendix. program{literal ::=process(declaration) begin [declaration{section] [pragma]<br />
Thecompilerwillchecktheprogramliteralatthesametimethatitchecks Aprogramliteraloperationiscodedasaself-deningvalue.Thevalueof theliteralisthevalueoftheprogramaftertranslationbythecompiler. ::=processlink{name endprocess [h<strong>and</strong>ler]... [statement;]...
theprogramwhichembedsit.Thereforetheprogramliteralvaluewillhave thetypestateattributechecked. Example: doubler
13011.10.ProgramOperations where(parm.input=0) where(parm.input>0) parm.result
type).Ifthecheckfails,theexceptionDefinitionErrorisraised. ischeckedforresolutionerrors<strong>and</strong>otherrestrictions(e.g.eachvariant denitionincludesacaseidforeachpossiblevalueoftheenumeration oper<strong>and</strong>isafullyinitializeddenitionsmodule.Thedenitionsmodule Thisoperationcompletestheinitializationofadenitionsmodule.The Ifthechecksucceeds,theidcomponentofthedenitionsmoduleisre-<br />
11.<strong>Hermes</strong>Operations131<br />
attributebehaveslikeaconstraint:anyattempttomodifythedenitions initionsmodulearereplacedbytheuniqueidentier.Thedenitionsmod-<br />
uleacquirestheattributecheckeddefinitions.Thecheckeddefinitions placedbyauniqueidentier.Allreferencestothatidentierwithinthedef-<br />
modulewilldiscardtheattributecheckeddefinitions.Unlikeaconstraint attribute,checkeddefinitionscannotbeusedinanassertstatement; anteedthatwhentwotypenamesorattributenamesareequal,theyalways mescanenforce\nameequivalence"oftypes.Noothercheckeddenitions modulecanpossiblyhavethesamemoduleidentier.Thereforeitisguar-<br />
denotethesametypeorattributedenition. theattributecanonlybeassertedbyexecutingthecheckdefinitions statement.<br />
11.11Constraints Becausecheckeddenitionsaregivenauniquemoduleidentier,Her-<br />
attribute{construction<br />
argumentbenon-negative.Aprogramlibrarymightbedenedasatable ::=constraint(<br />
ofcheckedprograms. Forinstance,theinterfacetoasquare-rootfunctionmightrequirethatthe Constraintsareprogrammer-denedpredicatesonthevaluesofvariables.It isoftendesirabletoincludeconstraintsininterfacesorintypedenitions. )isconstraint{typestateconstraint{expression [declaration[,declaration]...]<br />
betrackedastypestateattributes.Currently,<strong>Hermes</strong>isnotsophisticated enoughtounderst<strong>and</strong>thesemanticsofconstraintpredicateswellenough totrackhowtheyarepreservedunderalloperations.Forexample,the compilerwillnotdeterminethataddingonetoanon-negativenumberwill yieldanothernon-negativenumber.Whatitwilldoisthefollowing: In<strong>Hermes</strong>,theprogrammercanspecifythatcertainconstraintsareto<br />
addthetypestateattributeNonNegative(a)iftheoperationassert associateanamewithapredicate{e.g.NonNegative(x)withthe whichwilltestwhethera>=0<strong>and</strong>raiseanexceptionifitisnot. predicatex>=0.ThisdenesanoperationassertNonNegative(a)
13211.11.Constraints<br />
ConstraintDenitions Thissimpletrackingofconstraintsisenoughformanypracticalpurposes. tracktheattributeNonNegative(a)throughsuccessorstatements NonNegative(a)isnotinthetypestate untileitheraismodied,orcontrolmergeswithapathinwhich NonNegative(a)succeeds.<br />
Aconstraintdenitionincludes:adeningoccurrenceofanattributename, asetofformalparameters,thetype<strong>and</strong>typestateoftheseformalparametersportedexactlyasaretypedenitions<br />
Example:<br />
Assert NonNegative:constraint(x:integer)is Interval:constraint(x:integer,y:integer)is Constraintattributedenitionsoccurindenitionsmodules<strong>and</strong>areim-<br />
finit(x)gx>=0;<br />
simple{statement finit(x),init(y)gx
isusuallygeneratedasacoercionwhenmergingtwopathsoneofwhich includesaconstraintattribute<strong>and</strong>theotherofwhichdoesnot.However, itcanbecodedexplicitlybytheprogrammertoindicatethataconstraint isabouttobebroken: Thedropstatementexplicitlydropsaconstraintattribute.Thisoperation<br />
11.<strong>Hermes</strong>Operations133<br />
while('true')repeat Rq
familiarBNF(Backus-NaurForm).Thefollowingnotationalconventions AppendixA <strong>Hermes</strong>ConcreteSyntax The<strong>Hermes</strong>syntaxispresentedinthisappendixinaformatsimilartothe apply: Namesofsyntacticcategories(nonterminalsymbols)arerenderedin Keywords<strong>and</strong>othernon-terminals(e.g.punctuation)arerenderedin Optionalsyntaxisenclosedinsquarebrackets.Theindicatedconstructmayappearonceornotatall.<br />
Example:compound{statement italic. caseisinsignicant)Ėxample:begin,,! boldface.Theyshouldappearinprogramsexactlyasshown(though Repeatingsyntaxisindicatedbyellipsis.Theimmediatelypreceding iftherepeatedconstructisnotshownasoptional,thenatleastone constructmayappearanynumberoftimesinsuccession.Notethat repetitionmustappear. Example:exit{name[,exit{name]... [declaration{section]
A.1LexicalRules Webeginwiththerulesthatdenethelexicaltokensofthelanguage, distinguishthemfromnormalidentiers.Additionallogicisrequiredto includingidentier<strong>and</strong>varioustypesofliteral.Notethatkeywords<strong>and</strong> reservedwordsarelexicallyequivalenttoidentiers.Atableisusedto AppendixA.<strong>Hermes</strong>ConcreteSyntax135<br />
arelistedinTableA.1. determinewhenakeywordisactuallyusedasakeyword<strong>and</strong>whenitis acter.Tokensmayneverspanlines,includingnamedliterals<strong>and</strong>string appearbetweentokens. tiontokens.PunctuationsequencesarelistedinTableA.2. usedasanormalidentier,sincemostkeywordsarenotreserved.Keywords literals.Arbitraryamountsofwhitespace(spaces,tabs,linebreaks)may named{literal<strong>and</strong>string{literal,wheretheytreatedlikeanyotherchar-<br />
Certaincharacters<strong>and</strong>two-charactercombinationsconstitutepunctua-<br />
Spaces<strong>and</strong>tabsarenotallowedwithintokens,exceptinthecaseof Therearetwocommentingstyles: Commenttextmaybeembeddedwithinalinebydelimitingitwith Twoconsecutivehyphens(--)beginacommentthatextendstothe endoftheline.<br />
integer{literal extendstotheendoftheline.Acommentistreatedasaspace. identier::=alpha[alphanum]... Acommentbeginswithtwoconsecutivehyphencharacters(--)<strong>and</strong> thecharacterpairs\/*"atthebeginning<strong>and</strong>\*/"attheend.<br />
integer{part::=integer{literal real{literal::=[sign]initeger{part.[fraction{part][exponent] fraction{part::=integer{literal ::=[sign]digit[digit]...<br />
exponent::=exponent{letter[sign]integer{literal named{literal otherthanthespacecharacterareimplicitlyexcludedinallcases. string{literal::="[string{literal{character]..." Characterclassesusedintheaboveareasfollows.Nonprintingcharacters ::='named{literal{character[named{literal{character]...'
136A.1.LexicalRules digitisanyofthedigits0through9. alphaisanyupperorlowercaseletter,ortheunderscorecharacter alphanumincludesallcharactersindigit<strong>and</strong>digit. exponent{letterincludestheupper<strong>and</strong>lowercaseletter'E'. signincludestheplus(+)<strong>and</strong>minus(-)signs. ().<br />
string{literal{characterincludesallcharactersexceptthedoublequote named{literal{characterincludesallprintingcharactersexceptthe singlequote(').Twoconsecutivesingle-quotecharacterswithina (").Twoconsecutivedouble-quotecharacterswithinastring{literal named{literalaretreatedasonesinglequotecharacterinthisclass. aretreatedasonedoublequotecharacterinthisclass.
accuracy against <strong>and</strong>y assert drop elsey AppendixA.<strong>Hermes</strong>ConcreteSyntax137<br />
attributename beginy empty endy enumerationminimumreveal is keys linking merge block evaluatey remove<br />
boolean eventy every moduleidsend new repeat<br />
nominal return<br />
callmessage case exception noty select<br />
checkdenitionsfalse connect exists exit of ony size<br />
constant extract table<br />
constraint ordered theny<br />
convert otherwiseytypestate to<br />
copy forall outport true<br />
create from hide if polymorphunite position pragmay print typename uniquey unwrap using<br />
TABLEA.1.<strong>Hermes</strong>keywords.Reservedwordsaremarkedwithadagger(y). Reservedwordscannotbeusedasidentiers. currentprogramyinport declare denitions discard dissolve insert inspect integer into procedurewherey processy real receive record variant while<br />
({varioususes {{typestatedelimiter}typestatedelimiter )varioususesothersy<br />
,{listseparator !{modulequalier .{componentselection{casedeclaration ={equal =greaterorequal *multiply -minus
follows. modules)otherprocessmodulestobestaticallylinked.Themodulebody allysupplieslistsofdenitionsmodulestobeimported<strong>and</strong>(forprocess 138A.1.LexicalRules Amoduleisintroducedbyaheaderwhichnamesthemodule<strong>and</strong>option-<br />
module::=module{name:[imports][linking] A.2SyntacticRules<br />
process{module{body<br />
whatthenfollowslooksalmostlikeablockbody:anoptionaldeclarations Aprocessmodulebodybeginswithadeclarationfortheinitport,<strong>and</strong> linking::=linking([link{name[,link{name]...]) imports::=using([module{name[,module{name]...]) section,followedbythestatementsformingtheprocessbody,optionally denitions{module{body<br />
process{module{body followedbyoneormoreexceptionh<strong>and</strong>lerspecications ::=process(declaration)<br />
nameofitstype.Apragmaisoptionalpriortothetypename. Adeclarationcontainsanidentier(thevariablebeingdeclared)<strong>and</strong>the endprocess [h<strong>and</strong>ler]... begin [declaration{section] [pragma]<br />
declaration{section ::=declare[declaration;]... [statement;]...<br />
optionallybeprecededbyapragma. Statementscomeintwobasicvarieties:simple<strong>and</strong>compound.Eithermay statement::=[pragma]simple{statement declaration::=base{variable:[pragma]type{name ::=[pragma]compound{statement
Thesimplestatements: simple{statement ::=result{variable:=source{expression<br />
AppendixA.<strong>Hermes</strong>ConcreteSyntax139<br />
::=assertattribute ::=calloutport{variablecall{arguments ::=call(outport{expression)call{arguments ::=checkdenitionsdenitions{module{variable againstdenitions{library{variable source{expression<br />
::=connectoutport{variabletoinport{variable ::=dropattribute ::=discardvariable{name ::=exitexit{name ::=dissolvevariant{componentintoresult{variable ::=extracttable{variablefromselector ::=insertelement{expressionintotable{variable ::=hidevariant{variable ::=mergetable{expressionintotable{variable ::=newvariable{name ::=printexpression ::=receivecallmessage{variablefrominport{variable ::=removeelement{variablefromselector<br />
::=returncallmessage{variable [atposition{expression]<br />
::=revealvariant{component ::=sendsource{expressiontooutport{expression ::=unitevariant{componentfromsource{expression ::=unwrapresult{variable [exceptionuser{exception{name]<br />
Thecompoundstatements: ::=wrapsource{expressionaspolymorph{variable frompolymorph{expressionunwrapped{typestate
140A.2.SyntacticRules compound{statement ::=block begin [declaration{section] [constant{section]<br />
::=forenumeration{variable:enumeration{typerepeat ::=forselectorinspect endfor<br />
endblock [h<strong>and</strong>ler]...<br />
[statement;]...<br />
::=inspectdeclaration ::=inspectselectorbegin ::=iftest{expression<br />
endif frompolymorph{expressioninspect{typestate<br />
[else[statement;]...] then[statement;]...<br />
::=select[select{expression] endinspect [statement;]...<br />
Varioussyntacticelementsappearingincompoundstatements: ::=whiletest{expressionrepeat endselect [select{clause]...<br />
constant{sectionendwhile<br />
[statement;]... otherwise{clause<br />
select{clause::=boolean{guard[statement;]... h<strong>and</strong>ler::=on([exception{name[,exception{name]...]) ::=constant([base{variable[,base{variable]...]) ::=onexit([exit{name[,exit{name]...])
oolean{guard event{guard::=eventinport{variable ::=event{guard<strong>and</strong>boolean{guard[statement;]... ::=event{guard[statement;]... AppendixA.<strong>Hermes</strong>ConcreteSyntax141<br />
[...]). Threesyntaxesareavailableforselectors(usedintableoperations):along form(usingwhere),<strong>and</strong>twoshorth<strong>and</strong>forms(usingsquarebrackets{ otherwise{clause ::=where(test{expression)<br />
selector::=base{variableintable{variable ::=otherwise[statement;]...<br />
The<strong>Hermes</strong>expressionsyntaxfollows.Allthe<strong>Hermes</strong>binaryoperators ::=table{variable[[expression[,expression]...]]<br />
where(selector{expression)<br />
expression::=disjunction representthis. areleft-associative,thoughthegrammarshownheredoesnotexplicitly<br />
disjunction::=conjunction relation::=concat conjunction::=relation ::=disjunctionorconjunction<br />
::=concatconcat ::=concat=concat
142A.2.SyntacticRules term factor::=secondary ::=factor ::={factor ::=term+factor ::=term{factor<br />
secondary::=primary ::=factorremsecondary ::=factormodsecondary ::=factor/secondary ::=factor*secondary ::=the{element ::=caseofsecondary ::=createofsecondary ::=convertofsecondary ::=copyofsecondary ::=emptyofsecondary ::=evaluatedeclarationfrom[statement;]...end ::=everyofselector ::=existsofselector ::=forallofselector ::=notsecondary<br />
primary::=type{speciertyped{primary ::=positionofelement{variable ::=positionofselector ::=procedureofsecondary ::=sizeofsecondary ::=typeofsecondary ::=typestateofsecondary<br />
typed{primary type{specier::=type{name# ::=variable{name ::=function{reference ::=typed{primary ::=literal
::=(expression)AppendixA.<strong>Hermes</strong>ConcreteSyntax143 ::=currentprogram<br />
Literalsofvarioustypes: the{element::=selector function{reference ::=unique<br />
literal::=integer{literal ::=real{literal ::=named{literal ::=string{literal ::=outport{primarycall{arguments<br />
program{literal ::=program{literal ::=attributename{literal ::=typename{literal ::=process(declaration)<br />
attributename{literal ::=processlink{name endprocess [h<strong>and</strong>ler]... begin [declaration{section] [pragma]<br />
typename{literal ::=nattributenameattribute{namen [statement;]...<br />
Adenitionsmodulecomprisesacollectionoftype<strong>and</strong>constraintdenitions.Atypedenitionassociatesanamewithatypeconstruction,while<br />
aconstraintdeninitionassociatesanamewithanattributeconstruction. Apragmamayoptionallyappearwitheithertypeofdenition. ::=denitions ::=ntypenametype{namen denitions{module{body enddenitions [denition;]...
144A.2.SyntacticRules Typeconstructions: type{construction denition::=denition{name:[pragma]construction construction::=type{construction ::=callmessage( ::=boolean(boolean{association) ::=attribute{construction<br />
::=[ordered]enumeration( ...] )[constant{parameters] exitexit{typestate [user{exception]... [minimum] [component{declaration[,component{declaration]<br />
::=inportofcallmessage{typeentry{typestate ::=polymorph ::=nominal ::=outportofinport{type ::=integer<br />
[named{literal[,named{literal]...]<br />
::=realofaccuracyinteger{literal/integer{literal ::=[ordered]tableofelement{typeelement{typestate ::=record(<br />
[component{declaration[,component{declaration]<br />
Varioussyntacticelementsusedintypedenitions: boolean{association ::=true:named{literal,false:named{literal ::=variantofenumeration{type( )[case{declaration[,case{declaration]...]<br />
[keys[key]...]<br />
::=false:named{literal,true:named{literal
user{exception constant{parameters minimum::=minimumminimum{typestate ::=constant([component{name[,component{name]... ]) AppendixA.<strong>Hermes</strong>ConcreteSyntax145<br />
key ::=exceptionuser{exception{nameexception{typestate<br />
Attributeconstructions: case{declaration ::=([formal{variable[,formal{variable]...])<br />
attribute{construction component{declaration ::=constraint( ::=named{literal!component{declaration ::=declaration component{typestate<br />
(e.g.variants,tables,inports).Inaformaltypestatespecication,eachattributeargumentistakentobeacomponentofanassumedbasevariable<br />
attribute::=attribute{nameattribute{arguments formal{typestate formal{attribute typestate::=f[attribute[,attribute]...]g specicationconsistsofacollectionofattributes,eachofwhichincludesan attributename<strong>and</strong>alistofarguments.Formaltypestatesappearinthe unwrap<strong>and</strong>for...inspectstatements,<strong>and</strong>inseveraltypeconstructions Typestatespecicationsappearinattributeconstructions.Atypestate )isconstraint{typestateconstraint{expression [declaration[,declaration]...]<br />
whichdependsonthecontext.<br />
Argumentlistsappearinvariouscontexts,includingcallstatements<strong>and</strong> typestateattributes.Theymatchactualargumentstoparameters.Positionalmatchingisachievedwithacomma-separatedlistofarguments.A<br />
keyword-basedargumentslistexplicitlyincludestheparameternamesso ::=f[formal{attribute[,formal{attribute]...]g<br />
thatpositionisunimportant. allowedasanargument. Thevarioustypesofargumentlistsaredistinguishedonlybywhatis ::=attribute{nameformal{attribute{arguments
146A.2.SyntacticRules call{arguments labeled{expression attribute{arguments ::=([expression[,expression]...]) ::=(labeled{expression[,labeled{expression]...)<br />
labeled{variable{name ::=identier:expression<br />
formal{attribute{arguments ::=([variable{name[,variable{name]...]) ::=identier:variable{name ::=empty ::=([formal{variable[,formal{variable]...]) ::=(labeled{variable{name[,labeled{variable{name]...)<br />
Names: attribute{name labeled{formal{variable ::=(labeled{formal{variable[,labeled{formal{variable]...<br />
::=denition{name ::=identier:formal{variable )<br />
component{name builtin{exception{name base{variable::=identier ::=module{name!denition{name<br />
exception{name denition{name<br />
::=type{name.user{exception{name<br />
exit{name::=identier ::=builtin{exception{name
formal{variable module{name::=identier link{name::=identier ::=* ::=component{name[.component{name]... AppendixA.<strong>Hermes</strong>ConcreteSyntax147<br />
type{name::=denition{name<br />
Variablenamesappearinginparticularcontexts variable{name user{exception{name ::=module{name!denition{name<br />
callmessage{variable<br />
::=base{variable[.component{name]...<br />
denitions{library{variable<br />
enumeration{variable denitions{module{variable element{variable<br />
inport{variable ::=base{variable<br />
result{variable polymorph{variable outport{variable<br />
table{variable ::=variable{name
148A.2.SyntacticRules variant{component variant{variable<br />
element{expression Expressionsappearinginparticularcontexts: constraint{expression<br />
::=variable{name<br />
position{expression polymorph{expression outport{primary outport{expression<br />
::=primary ::=expression<br />
select{expression table{expression selector{expression source{expression<br />
test{expression ::=expression<br />
::=expression<br />
Typesappearinginparticularcontexts:<br />
inport{type::=type{name enumeration{type element{type::=type{name callmessage{type
Typestatesappearinginparticularcontexts: component{typestate constraint{typestate<br />
AppendixA.<strong>Hermes</strong>ConcreteSyntax149<br />
element{typestate entry{typestate exception{typestate<br />
::=typestate<br />
exit{typestate::=formal{typestate inspect{typestate<br />
minimum{typestate<br />
unwrapped{typestate<br />
empty::= open-ended.Itmaybecomemorestructuredinthefuture. Variousodds<strong>and</strong>ends.Notethatthepragmasyntaxiscurrentlyvery pragma::=pragmastring{literal ::=formal{typestate
AppendixB <strong>Hermes</strong>Operations Thischapterlistsallthehermesoperations<strong>and</strong>providespreciserulesfor typechecking,typeinferencing,<strong>and</strong>typestatecheckingeachoperation. AtypicaloperationdescriptionappearsinFigureB.1.Theexamplewillbe usedthroughoutthissection. B.1OperationDescriptions merge{at(destination,source,position)Exceptions:Depletion, TypeRules: Preconditions:<br />
destination2orderedtable source2table destinationsource predefined!integer RangeError,<br />
init(source) (DuplicateKey)<br />
Description:Removealltableelementsfromsource<strong>and</strong>insertthem duplicatekey(destination) var(destination) init(destination) init(position) var(source) Postconditions:<br />
intodestinationsothattheresultingpositionofthersttransferred makeuninit(source)<br />
element,ifany,willbeequaltoposition.Allothertransferredelements killconstraints(destination)<br />
Qualier:absent <strong>and</strong>followingthelasttransferredelement. Allelementsofdestinationthatformerlyoccupiedpositionsatposition willfollowconsecutively,inthesameorderastheyappearedinsource. orbeyondareshiftedsothattheyappearinthesamerelativeorder, FIGUREB.1.SampleoperationdescriptionSeex11.6,p.112
destination,source,<strong>and</strong>position.Someoperationstakeavariablenumber ofoper<strong>and</strong>s.Inthesecases,theoper<strong>and</strong>listwillappearasanellipsis. B.1.1DescriptionHeader Theoperationnameappearsrst,inbold-face,followedbyanoper<strong>and</strong>list. Ourexampledescribesthemergeatoperation,whichtakesthreeoper<strong>and</strong>s: Onthefarrightoftheheaderlineisalistoftheexceptionsthatcan AppendixB.<strong>Hermes</strong>Operations151<br />
beraisedbytheoperation.OurexampleshowsthatDepletion,RangeError,<strong>and</strong>DuplicateKeymayallberaisedbythemergeatoperation.The<br />
B.1.2TypeRules terminingthisarespeciedlaterintheoperationdescription.Inthiscase, DuplicateKeycanberaisedonlyifthedestinationisakeyedtable. Belowthedescriptionheaderarethetyperules,whichformthebasisfor parenthesessurroundingDuplicateKeyindicatethatinsomecasesitcan<br />
bothtypechecking(ensuringthatoper<strong>and</strong>sareofthecorrecttype),<strong>and</strong> bestaticallydetermined,basedonthetypesoftheoper<strong>and</strong>s,thatthe<br />
typeinferencing(deducingthetypeofundeclaredoper<strong>and</strong>sfromtheircontext).Thetyperulescomeintwoforms:classrules<strong>and</strong>inferencerules.<br />
classcontainsmanytypes.Thefollowingclassruleappearsinthemergeat Aclassrulespeciesthatanoper<strong>and</strong>mustbeofatypethatfallsina<br />
mergeatoperationcannotraiseDuplicateKey.Theexactconditionsde-<br />
description: speciedclass.Aclassrulecanneverbeusedtoinferatype,sinceatype<br />
ation.Anexampleinwhichnootheroper<strong>and</strong>appearscanbefoundinthe mergeatoperation:position typemayormaynotdependonthetypeofanotheroper<strong>and</strong>intheoper-<br />
Alistofthetypeclasses<strong>and</strong>theirmeaningsappearsinsectionB.2. Aninferenceruleconstrainsanoper<strong>and</strong>tobeofaparticulartype.That destination2orderedtable<br />
insertinstruction:element \assignmentrule."Thesecondrulerequiresthatelementbeofthetype predefined!integer.Thistypeofinferenceruleissometimescalledan Therstrulerequiresthatthepositionoper<strong>and</strong>beofthespecictype, Foranexampleinvolvingtwooper<strong>and</strong>s,wehavethefollowingfromthe elementtypeof(table) predefined!integer<br />
function"tothetypeofthetableoper<strong>and</strong>.Allinferencefunctions<strong>and</strong> theirmeaningsarelistedinsectionB.3. thatisuniquelydeterminedbyapplyingtheelementtypeof\inference
152B.1.OperationDescriptions inferthetypeoftheleft-h<strong>and</strong>oper<strong>and</strong>,ifeithertheruleisoftheassignment variety,orifthetypeoftheright-h<strong>and</strong>oper<strong>and</strong>isalreadyknown. Aninferencerulecanbeusedfortypechecking.Itcanalsobeusedto<br />
ofeitheroper<strong>and</strong>canbeinferredfromthetypeoftheother. fromthemergeatoperation: tion,whichidentiestwooper<strong>and</strong>sthatmusthavethesametype.Allsuch rulesinanoperationdescriptionaredisplayedasinthefollowingexample Inthiscase,thenormalasymmetryofinferencerulesvanishes:thetype Aspecialnotationisusedforrulesinvolvingthesameasinferencefunc-<br />
B.1.3Preconditions Precondition<strong>and</strong>postconditionrulesappearinside-by-sideboxesbelow thetyperules. destinationsource<br />
timetheoperationistobeexecuted.Allpreconditionsmustbestatically veriablebythecompiler. Thepreconditionrulesspecifyvariousconditionsthatmustholdatthe<br />
deneconditionsunderwhichanexceptionisknowntobepossible.Forexample,thefollowingpreconditionindicatesthatifthedestinationoper<strong>and</strong><br />
isakeyedtable,thentheoperationcanraiseDuplicateKey: init(source) operationcantakeplace. listofoper<strong>and</strong>s.Anexamplefromthemergeatoperationis: Some\preconditions"donotcheckforanytypestateattributes.They Thisstatesthatthesourceoper<strong>and</strong>mustbeinitializedbeforethemergeat Apreconditiontakestheformofapreconditionfunctionfollowedbya<br />
B.4. B.1.4Postconditions Thepostconditionrulescharacterizetheeectsofanormal(non-exception) executionoftheoperation.Eachruleisspeciedviaapostconditionfunctionfollowedbyalistofoper<strong>and</strong>s.Anexamplefromthemergeatoperation<br />
is: Allthepreconditionfunctions<strong>and</strong>theirmeaningsarelistedinsection duplicatekey(destination)<br />
makeuninit(source)
oper<strong>and</strong>willnolongerbeinitialized. B.1.5SpecialRules Thisindicatesthatfollowingasuccessfulmergeatoperation,thesource Thepostconditionfunctions<strong>and</strong>theirmeaningsarelistedinsectionB.5. AppendixB.<strong>Hermes</strong>Operations153<br />
theoper<strong>and</strong>stoanoperationwithoutaxedoper<strong>and</strong>list(likecallor assert)arespeciedinthismanner. treatmentismostlyrequiredwhenarulecannotbeexpressedsolelyin type<strong>and</strong>typestaterulesthatcouldnotbeencodedintheruletables.This termsofnamedoper<strong>and</strong>s.Thus,rulesregardingdataencodedinthestatementqualier(describedbelow)appearasspecialrules.Also,rulesaboumediatelyfollowingthetypestatepre-<strong>and</strong>post-conditionboxes,<strong>and</strong>listtionsisaboxlabeled\SpecialRules".Thisfull-widthboxappearsim-<br />
Absentfromthemergeatexamplebutpresentinsomeoperatordescrip-<br />
Followingthepost-<strong>and</strong>pre-conditionboxesisabriefdescriptionofthe B.1.6OperationSemantics<br />
operatororusingamechanismsuchasqualiers.In<strong>Hermes</strong>,thisparticular semanticmeaningoftheoperation.Belowthis,attheverybottomofthe<br />
situationish<strong>and</strong>ledbytheintegerliteraloperation,whichrequiresthat anintegervariabletothevalue\1"withouthavingaspecial\set-to-one" panel,aretwoboxesshowingthestatementqualiertypeforthisoperation, uninitialized(exceptitsinitializationport),itwouldbeimpossibletoset itsoper<strong>and</strong>s.Forexample,sinceaprocessbeginswithallitsvariables <strong>and</strong>apointertothesection<strong>and</strong>pageinthereferencemanualthatdescribes theoperationindetail.<br />
ment,sothequalieritselfisavariant.Itstypeispredefined!qualifier, anintegervaluebeencodedinthequalier. Theinformationthatappearsinqualiersvariesfromstatementtostate-<br />
Astatementqualiercontainsallparametersofanoperationotherthan<br />
theoperationdescriptionpanelidentieswhichcomponentofthisvariant <strong>and</strong>youcannditsdenitioninappendixC.Thequaliertypeidentiedin typeappliestothisparticularoperation. B.2TypeClasses Followingarethetypeclassesappearinginclassrules: integer real
154B.2.TypeClasses boolean nominal enumeration variant table polymorph<br />
orderedscalar:includesinteger,real,<strong>and</strong>anyenumerationde- inport outport callmessage numeric:includesinteger<strong>and</strong>real. variantcomponent:Thisisnot,strictlyspeaking,atypeclass.Itis enumerationorboolean:includesenumeration<strong>and</strong>boolean. reallyavariableclass,comprisingvariablesthatarecomponentsof isinclassvariant. variableswhosetypesareinthevarianttypeclass.Thus,x.visin theclassvariantcomponentif<strong>and</strong>onlyifxisavariablewhosetype nedwiththeorderedkeywordpresent.<br />
orderedtable:Allorderedtablestypes,i.e.,alltypesdenedwith<br />
copyable:Alltypesotherthaninputports,callmessages,<strong>and</strong>types newable:Allinputport,table,<strong>and</strong>recordtypes,i.e.,alltypesdened string:Allorderedtabletypeswhoseelementtypesareenumerations.Thatis,atypetisinclassstringif<strong>and</strong>onlyif:(1)tisinclass<br />
thetabletypeconstructor<strong>and</strong>withtheorderedkeywordpresent. witheithertheinport,table,orrecordtypeconstructor. orderedtable;<strong>and</strong>(2)theelementtypeoftisinclassenumeration. thatcancontainsuchobjects.Thisclassincludestheclassesinteger, real,nominal,enumeration,boolean,<strong>and</strong>outport.Italsoincludes copyable. theclasspolymorphalthoughapolymorphobjectmaywrapanuncopyableobject(anyattempttocopysuchapolymorphwouldraise<br />
tableisincopyableif<strong>and</strong>onlyiftheassociatedelementtypeisin typesofallthedenedcomponentsareincopyable.Atypeinclass therecordtypeconstructor)isinclasscopyableif<strong>and</strong>onlyifthe Uncopyable).Atypeinclassvariant,orarecordtype(denedwith
Followingaretheinferencefunctionsappearingininferencerules.Each B.3InferenceFunctionsAppendixB.<strong>Hermes</strong>Operations155 typemustbethetypeinferredbythegiveninferencefunctionfromthe inferencefunctioninfersatypefromitsoper<strong>and</strong>.Aninferencerulerelates twooper<strong>and</strong>s,asource<strong>and</strong>atarget,byspecifyingthattargetoper<strong>and</strong>'s sourceoper<strong>and</strong>'stype. casetypeof(oper<strong>and</strong>):Thesourcetypeisinclassvariant.Thetar-<br />
sameas(oper<strong>and</strong>):Thetarget<strong>and</strong>sourceoper<strong>and</strong>smusthavethe matchinginportof(oper<strong>and</strong>):Thesourcetypeisinclassoutport. gettypeistheenumerationtypeappearinginthesourcetype'sde-<br />
sametype.1<br />
messagetypeof(oper<strong>and</strong>):Thesourcetypeiseitherinclassinport<br />
Thetargettypeistheinputporttypeappearinginthesourcetype's denition.<br />
elementtypeof(oper<strong>and</strong>):Thesourcetypeisinclasstable.The orinclassoutport.Intheformercase,thetargettypeisthecallmessagetypeappearinginthesourcetype'sdenition;inthelattercase,<br />
iftypeipistheinputporttypeappearinginthesourcetype'sde-<br />
type'sdenition. targettypeistheassociatedelementtypeappearinginthesource denitionofip. nition,thenthetargettypeisthecallmessagetypeappearinginthe<br />
B.4.1TypestatePreconditions B.4PreconditionFunctions<br />
(2)inserttheoperationoper<strong>and</strong>,<strong>and</strong>adot(`.')beforeallotherattribute toanyattributeintheformaltypestatewiththeoperationoper<strong>and</strong>;<strong>and</strong> tion.Thissubstitutionconsistsofthefollowing:(1)replaceany`*'oper<strong>and</strong> oper<strong>and</strong>intoaformaltypestatethatissomehowassociatedwiththeopera-<br />
mustnotbepresent. programtypestatebeforeinvokingtheoperation,aswellasattributesthat Thefollowingpreconditionsensurepropertypestatepriortoanoperation. Eachpreconditioncanspecifytypestateattributesthatarerequiredinthe<br />
op1op2...opntodenoteallrulesopi Inseveralcases,requiredattributesaredeterminedbysubstitutingan 1Intheoperatordescriptionpanels,weusethespecialnotation sameas(opj)fori6=j.
156B.4.PreconditionFunctions oper<strong>and</strong>s,derivingcomponentsoftheoperationoper<strong>and</strong>.Forstep(1),recallthatanyattributewithoutoper<strong>and</strong>sistreatedasanattributeapplied<br />
toasingle`*'oper<strong>and</strong>. Asanexample,wesubstitutexintotheformaltypestate: Theresultingtypestateis: full(oper<strong>and</strong>):Theattributeinit(oper<strong>and</strong>)isrequired.Inaddition, init(oper<strong>and</strong>):Theattributeinit(oper<strong>and</strong>)mustbepresent. ifoper<strong>and</strong>isavariant,record,orcallmessage,thentheprecondition full(oper<strong>and</strong>.x)mustbe(recursively)satisedforeverycomponent finit(x),case(x,x.a)g finit,case(*,*.a)g<br />
initwithoutcase(varcomp):Theattributeinit(variant)isrequired, casets(oper<strong>and</strong>,varcomp):Therequiredattributesarefoundbysubstitutingoper<strong>and</strong>intothecasetypestateofthevariantcomponenbiddenattributesareallotherattributesinvolvingoper<strong>and</strong>orits<br />
varcomp(asgivenintherelevantvarianttypedenition).Thefor-<br />
subcomponents. xcontainedinoper<strong>and</strong>.<br />
checked(oper<strong>and</strong>):Theattributesinit(oper<strong>and</strong>)<strong>and</strong>checked(oper<strong>and</strong>) subcomponentsareforbidden. nent.Allotherattributes(notably,casets)involvingvariantorits wherevariantisthevariantvariableofwhichvarcompisacompo-<br />
callpreconditions():Thispreconditionappearsonlywiththecall lowestelementstate(element,table):Therequiredattributesare arerequired.Therearenoforbiddenattributes.<br />
Thetypedenitionforipincludesaformaltypestateinwhichthe ingcalled,<strong>and</strong>letcmbethecallmessagetypeassociatedwithip. operation.Thefollowingnonst<strong>and</strong>ardsubstitutionprocedureisused: Letipbetheinputporttypeassociatedwiththeoutputportbe-<br />
attributesinvolvingelementoritssubcomponents. thedenitionoftable'stype.Theforbiddenattributesareallother foundbysubstitutingelementintotheelementtypestateprovidedin<br />
componentsofcmappearasarguments.Substitute,foreachsuch argumentinthecalloperation.Theresultingtypestatecomprisesthe attributesrequiredbythisprecondition.Iftherearenon-constantparameters,thenallattributesinvolvinganyofthecorrespondingactual<br />
parametersortheirsubcomponents,exceptrequiredcomponentsas componentnameinthisformaltypestate,thecorrespondingactual determinedabove,areforbidden.
lowestentrycondition(message,port):Thispreconditionappears intotheformaltypestateappearinginip'stypedenitiontoyield therequiredattributes.Allotherattributesinvolvingmessageorits subcomponents. onlyinthesendoperation.Letipbetheinputporttypeassociated withtheportoper<strong>and</strong>,whichisanoutputport.Substitutemessage AppendixB.<strong>Hermes</strong>Operations157<br />
lowestpostcondition(message):Thispreconditionappearsonlywith<br />
polymorphprecondition(oper<strong>and</strong>):Thispreconditionappearsonly maltypestateintoyieldtherequiredattributes.Allotherattributes involvingmessageoritscomponentsareforbidden. tionformessagedeterminesthepreconditions;inthelattercase,the typestateassociatedwiththeexceptionbeingreturneddetermines thepreconditions.Ineithercase,messageissubstitutedintothefor-<br />
thereturn<strong>and</strong>return-exceptionoperations.Intheformercase,<br />
withthewrapoperation.Ifaformaltypestateisspeciedinthe thenormalexittypestateappearinginthecallmessagetypedeni-<br />
assertable():Thispreconditionappearsonlywiththeassertoperation.Iftheconstraintbeingassertedisalreadypresent,thenthis<br />
substitutingoper<strong>and</strong>intotheformaltypestate<strong>and</strong>forbidallother operation,thenthepreconditionrequiretheattributesobtainedby stateisgiven,thispreconditionhasnoeect.2 attributesinvolvingoper<strong>and</strong>oritssubcomponents.Ifnoformaltype-<br />
B.4.2ContextPreconditions variablesotherthantypestate. Thefollowingpreconditionfunctionstestcontext-dependentpropertiesof preconditionhasnoeect.Otherwise,substituteactualarguments forformalparametersinthetypestateappearingwiththeconstraint<br />
var(oper<strong>and</strong>):Thevalueofoper<strong>and</strong>valuemaychangeasaresultof denitiontoyieldtherequiredattributes.Therearenoforbidden<br />
theoperation.Itmustnotbeconstantinthecurrentscope(e.g.via<br />
stateinawrapstatement,sothispreconditionneverhasanyeect. 2Notethatitisimpossible,withthecurrentsyntax,tospecifyaformaltype-<br />
pos(oper<strong>and</strong>):oper<strong>and</strong>mustbetheselectorvariableinan\active" scopeincludesthecurrentoperation,orisassociatedwithaninspect inspectorfor...inspectstatement). theconstantlistinacallmessagedenition,orinthebodyofan selectorinvolvinganorderedtable.Anactiveselectorisonewhose
158B.4.PreconditionFunctions B.4.3ConditionalExceptions Thefollowingpreconditionstestwhethertheoperationiscapableofraising certainexceptionsinadditiontoitsst<strong>and</strong>ardset. rangeerror(source,result):Thispreconditionappearsonlywith orfor...inspectstatementwhosebodyincludesthecurrentoperation.<br />
uncopyable(oper<strong>and</strong>):Atypeispotentiallyuncopyableifitisan duplicatekey(table):Ifthetablehaskeys,thenaDuplicateKey inputportorcallmessagetype(whichareactuallyuncopyable),a exceptionispossible. conversionofeveryvalueinthedomainofsource,thenaRangeError<br />
theconvertoperation.Ifthedomainofresultdoesnotincludethe<br />
B.5PostconditionFunctions ablecomponenttypes,oratabletypewithapotentiallyuncopyable elementtype.Ifoper<strong>and</strong>isofapotentiallyuncopyabletype,thenthe polymorphtype,arecordorvarianttypewithpotentiallyuncopy-<br />
completionofanoperation.Eachfunctioncancauseattributestobeadded <strong>and</strong>/ordropped. Thefollowingfunctionsdeterminehowthetypestatechangesonnormal Uncopyableexceptionispossible.<br />
makeinit(oper<strong>and</strong>):Addtheattributeinit(oper<strong>and</strong>). makeuninit(oper<strong>and</strong>):Dropallattributesinvolvingoper<strong>and</strong>orits makefull(oper<strong>and</strong>):Addtheattributeinit(oper<strong>and</strong>).Inaddition, movets(source,destination):Foreachattributeinvolvingsourceora ifoper<strong>and</strong>isarecordorcallmessage,makeallitscomponentsrecursivelyfull.<br />
subcomponents. allotherattributesinvolvingdestinationvariableorasubcomponent. subcomponent. source,<strong>and</strong>addthesubstitutedattributeifnotalreadypresent.Drop subcomponent:(1)droptheattribute,(2)substitutedestinationfor Dropallconstraintattributesofvariablesofwhichdestinationisa
copy(source,destination):Foreachattributeinvolvingsourceora makecase(varcomp):Addtheattributecase(variant,varcomp),where subcomponent,substitutedestinationforsource<strong>and</strong>addtheresultingattribute.Dropanyotherattributeinvolvingdestinationorits<br />
subcomponents.Dropallconstraintattributesofvariablesofwhich AppendixB.<strong>Hermes</strong>Operations159 destinationisasubcomponent.<br />
makechecked(oper<strong>and</strong>):Ifoper<strong>and</strong>'stypeispredefined!program, killvariant(varcomp):Dropallattributesinvolvingthevariantof dropcomponents(variant):Dropanycaseattributeinvolvingvariant,<strong>and</strong>allattributesinvolvingacomponentofvariant.<br />
whichvarcompisacomponent,aswellasallattributesinvolvingits subcomponents. variantisthevariableofwhichvarcompisacomponent.<br />
moveelementts(table,element):Substituteelementintotheelement whichelementisasubcomponent. subcomponents.Dropallconstraintattributesinvolvingvariablesof sultingattributes.Dropallotherattributesinvolvingelementorits formaltypestateassociatedwiththetable'stype,<strong>and</strong>addthere-<br />
addtheattributecheckeddefinitions(oper<strong>and</strong>). addtheattributechecked(oper<strong>and</strong>);ifoper<strong>and</strong>'stypeispredefined!definitionsmodule,<br />
polymorphts(oper<strong>and</strong>):Thispostconditionappearsonlywiththe moveentryts(port,message):Substitutemessageintotheentryformaltypestateassociatedwithport's(inputport)type,<strong>and</strong>addthe<br />
unwrapoperation.Substituteoper<strong>and</strong>intotheformaltypestateap-<br />
itssubcomponents.Dropallconstraintattributesinvolvingvariables pearingintheunwrapstatement,<strong>and</strong>addtheresultingattributes. resultingattributes.Dropallotherattributesinvolvingmessageor ofwhichmessageisasubcomponent.<br />
killconstraints(oper<strong>and</strong>):Dropallconstraintattributesinvolving asserted():Thispostconditionappearsonlywiththeassertoperation.Addtheattributenamedintheassertstatement.<br />
Dropallotherattributesinvolvingoper<strong>and</strong>oritssubcomponents. asubcomponent. oper<strong>and</strong>oranyvariablesofwhichoper<strong>and</strong>isasubcomponent. Dropallconstraintattributesinvolvingvariablesofwhichoper<strong>and</strong>is
Followingarethedetaileddescriptionsofallthe<strong>Hermes</strong>operations: 160B.5.PostconditionFunctions B.6OperationDescriptions add(result,source1,source2) TypeRules: Preconditions: source12numeric init(source2) init(source1) result2numeric resultsource1source2 source22numeric Exceptions:Depletion<br />
Description:Storethesumofsource1<strong>and</strong>source2inresult. Qualier:absent var(result) Postconditions:<br />
<strong>and</strong>(result,source1,source2) makeinit(result)<br />
TypeRules: Preconditions: source12boolean result2boolean resultsource1source2 source22boolean Exceptions:Depletion Seex11.4,p.104<br />
Description:Ifbothsource1<strong>and</strong>source2aretrue,thensetresultto Qualier:absent var(result) true.Otherwisesetresulttofalse. init(source2) init(source1) Postconditions: makeinit(result)<br />
assert(...)Exceptions:Depletion,ConstraintError,ConstraintFailure TypeRules:SeeSpecialRules Preconditions: assertable() Postconditions: asserted() Seex11.4,p.105<br />
SpecialRules:Thenumberofoper<strong>and</strong>smustequalthenumberofparametersdeclaredinthedenitionoftheattributenamedinthestatement<br />
attributeparameter. qualier.Eachoper<strong>and</strong>mustalsomatchthetypeofthecorresponding
assert(continued) Description:Evaluatetheconstraintidentiedintheinstructionqualier Qualier:constraintname withthegivenoper<strong>and</strong>s.Iftheconstraintfails,raiseConstraintError. Ifitraisesanexception,raiseConstraintFailure. AppendixB.<strong>Hermes</strong>Operations161<br />
attributename(result) TypeRules: Preconditions: result var(result) predefined!attribute--name Postconditions: makeinit(result) Exceptions:Depletion Seex11.11,p.132<br />
Description:Copytheattributenameobject(oftypepredefined!attributename) Qualier:attributename block() TypeRules:None Preconditions:None fromtheinstructionqualierintoresult.<br />
SpecialRules:Theentrytypestatetothemainclauseisidenticalto Postconditions:SeeSpecialRules Exceptions:Depletion Seex11.10,p.130<br />
theentrytypestateoftheblockstatement.Theentrytypestatefora<br />
Description:Executetheinstructionsinthescopeidentiedbytheinstructionqualier.Ifanexceptionorexitoccursthatisnoth<strong>and</strong>ledby<br />
acontainedblock,<strong>and</strong>ifthereisanapplicableh<strong>and</strong>lerlistedinthis block'squalier,executetheh<strong>and</strong>ler.Notethatexceptions<strong>and</strong>exits involvingvariablesdeclaredintheblockstatement. themeetofthenormalexittypestatesofallclauses(includingthemain clause<strong>and</strong>allh<strong>and</strong>lers)thatcanexitnormally,minusanyattributes exception.Thetypestateonnormalterminationofablockstatementis thatbranchtotheh<strong>and</strong>ler,alongwiththeappropriateexceptionexit typestatesofanystatementsthatcanbranchtotheh<strong>and</strong>lerduetoan h<strong>and</strong>lerclauseisthemeetoftheentrytypestatesofallexitstatements<br />
Qualier:block areonlyh<strong>and</strong>ledwhentheyoccurintheblock'smainclause(orcontainedsubclauses);exceptionsorexitsoccuringwithinah<strong>and</strong>lerare<br />
passedontotheoutercontainingblock. Seex11.3,p.96
162B.6.OperationDescriptions call(...) TypeRules:SeeSpecialRules Preconditions: SpecialRules:Therstoper<strong>and</strong>mustbeinclassoutport,<strong>and</strong>itsassociatedinporttypemusthaveamessagetypeinclasscallmessage.The<br />
SeealsoSpecialRules callpreconditions() Exceptions:Depletion,Disconnected<br />
remainingoper<strong>and</strong>sarethecallarguments.Thenumberofarguments mustequalthenumberofcomponentsinthedenitionofthemessage type,<strong>and</strong>eachargumenttypemustbethesameasthecorresponding Postconditions:SeeSpecialRules<br />
intheinterface.Theexittypestatefornormalorexceptionalreturn rameterswillbecoerceddowniftheirtypestateishigherthanspecied includesinitoftherstoper<strong>and</strong>,plustypestatesforargumentsas inporttypedenition;argumentscorrespondingtonon-constantpa-<br />
typestatespeciedforthecorrespondingparameterintheassociated (e.g.arecordmaynotappearinthesameargumentlistasoneofits components).Therstoper<strong>and</strong>musthavetheinitattributeonentry.Eachargumentmusthaveatypestateatleastashighastheentry<br />
messagecomponenttype.Theargumentsmustnotoverlapinstorage<br />
Description:Therstoper<strong>and</strong>mustbeanoutputport.Formacallmessagebymovingallbuttherstoper<strong>and</strong>intosuccessivecallmessagtained,eveniftheydonotappearintheappropriateexittypestate.<br />
involvingonlyargumentscorrespondingtoconstantparametersarere-<br />
speciedinthecallmessagetypedenition.Additionally,attributes<br />
Qualier:absent ponentsbackintotheoper<strong>and</strong>variablesfromwhichtheyweretaken. returnofthecallmessage(includingexceptionreturns),moveitscom-<br />
case(result,variant) components,<strong>and</strong>thensendthecallmessageontheoutputport.On<br />
TypeRules: Preconditions: variant2variant<br />
casetypeof(variant) Exceptions:Depletion Seex11.8,p.121<br />
var(result) init(variant) Postconditions: makeinit(result)
case(continued) Description:Copytheenumerationvaluecorrespondingtothecurrent Qualier:absent caseofvariantintoresult. AppendixB.<strong>Hermes</strong>Operations163<br />
checkdenitions(module,library) TypeRules:<br />
predefined!definitions--modules<br />
Exceptions:Depletion, DenitionError Seex11.7,p.117<br />
Preconditions: Description:Checkthatthedenitionscontainedinmodulearecorrect Qualier:absent var(module) init(library) full(module) <strong>and</strong>consistent,bothinternally<strong>and</strong>withrespecttoallthedenitions modulesinlibrary. Postconditions: makechecked(module)<br />
concatenate(result,source1,source2)Exceptions:Depletion, TypeRules: source12orderedtable source22orderedtable source12copyable source22copyable (DuplicateKey) (Uncopyable), Seex11.10,p.130<br />
Preconditions: duplicatekey(result) uncopyable(source2) uncopyable(source1) var(result) init(source2) init(source1) result2orderedtable resultsource1source2 Postconditions: makeinit(result)
164B.6.OperationDescriptions concatenate(continued) Description:Createanewtableinresultthatcontainscopiesofallthe Qualier:absent connect(outport,inport) TypeRules: wereinthesourcetable. alltheelementsfromeithersourcetableareorderedinresultasthey elementsofsource1followedbyalltheelementsofsource2,suchthat<br />
Preconditions: inport2inport matchinginportof(outport) outport2outport Exceptions:Depletion Seex11.6,p.109<br />
Description:Createanoutputportconnectedtoinport,<strong>and</strong>storeitin Qualier:absent init(inport) var(outport) outport. Postconditions:<br />
convert(result,source) makeinit(outport)<br />
TypeRules: Preconditions: source2orderedscalar init(source) Exceptions:Depletion,(RangeError) result2orderedscalar Seex11.8,p.121<br />
Description:Convertthevalueofsourcetotheappropriatecorrespondingvalueinthedomainofresult,<strong>and</strong>storetheconvertedvalueinresult<br />
rangeerror(source,result) var(result) Postconditions: makeinit(result) Qualier:absent copy(result,source) TypeRules: source2copyable resultsource Exceptions:Depletion,(Uncopyable) result2copyableSeex11.4,p.106
copy(continued) Preconditions: uncopyable(source) var(result) init(source) AppendixB.<strong>Hermes</strong>Operations165<br />
Description:Makeacopyoftheobjectstoredinsource,<strong>and</strong>storethe Qualier:absent copyinresult. Postconditions: copy(source,result)<br />
create(result,program)Exceptions:Depletion,InterfaceMismatch TypeRules: Preconditions:<br />
result2outport predefined!program Seex11.1,p.94<br />
Description:Instantiateprogramasaprocess,<strong>and</strong>storeanoutputport Qualier:absent var(result) checked(program) connectedtotheprocess'initializationportinresult. Postconditions:<br />
currentprogram(result) makeinit(result)<br />
TypeRules: Preconditions: result var(result) predefined!programPostconditions:<br />
makechecked(result) Exceptions:Depletion Seex11.8,p.124<br />
Description:Storeacopyoftheprogramobjectfromwhichtheexecuting Qualier:absent discard(variable) TypeRules:None Preconditions: processwasinstantiated,intoresult.<br />
var(variable) Postconditions: makeuninit(variable) Seex11.10,p.129 Exceptions:|
166B.6.OperationDescriptions discard(continued) Description:Discardtheobjectstoredinvariable,leavingvariableuninitialized.<br />
Qualier:absent dissolve(result,varcomp) TypeRules: Preconditions: resultvarcomp varcomp2variantcomponent Exceptions:Depletion Seex11.1,p.95<br />
Description:Movetheobjectstoredinvariantcomponentvarcompinto Qualier:absent casets(varcomp,varcomp) result,leavingthevariantofwhichvarcompisacomponentuninitialized.<br />
Postconditions: movets(varcomp,result) killvariant(varcomp) var(varcomp) var(result)<br />
divide(result,source1,source2)Exceptions:Depletion,DivideByZero TypeRules: Preconditions: source12numeric result2numeric resultsource1source2 source22numericSeex11.7,p.116<br />
Description:Storethequotientofsource1dividedbysource2inresult. Qualier:absent var(result) init(source2) init(source1) Postconditions:<br />
drop(...) makeinit(result)<br />
TypeRules:SeeSpecialRules Preconditions:None Postconditions:None Seex11.4,p.104 Exceptions:|
drop(continued) SpecialRules:Thenumberofoper<strong>and</strong>smustequalthenumberofparametersdeclaredinthedenitionoftheattributenamedinthestatement<br />
AppendixB.<strong>Hermes</strong>Operations167 attributeparameter. qualier.Eachoper<strong>and</strong>mustalsomatchthetypeofthecorresponding Description:Removetheconstraintidentiedbytheinstructionquali- Qualier:constraintname empty(result,inport) TypeRules: er,appliedtothegivenoper<strong>and</strong>s,fromthecurrentprogramtypestate.<br />
Preconditions: result2boolean init(inport) inport2inport Exceptions:Depletion Seex11.11,p.132<br />
Description:Iftherearemessagesqueuedforreceiptoninport,setresult Qualier:absent var(result) tofalse.Otherwisesetresulttotrue. Postconditions:<br />
equal(result,source1,source2) makeinit(result)<br />
TypeRules: Preconditions: result2boolean init(source1) source1source2 Exceptions:Depletion Seex11.8,p.120<br />
Description:Ifsource1<strong>and</strong>source2areindistinguishableobjects,set Qualier:absent var(result) resulttotrue.Otherwisesetresulttofalse. init(source2) Postconditions: makeinit(result)<br />
every(result,table) TypeRules: result2table table2copyable SeealsoSpecialRules Exceptions:Depletion,(Uncopyable) table2table resulttableSeex11.1,p.94
168B.6.OperationDescriptions every(continued) Preconditions: SpecialRules:Thestatementqualierisaselector.Theresultvariable init(table) uncopyable(table) var(result) SeealsoSpecialRules Postconditions:<br />
typeoftheelementvariableidentiedintheselectormustbetheelementtypeoftable.Theentrytypestatefortheselectoristheentry<br />
theeverystatementiscomputedbyapplyingthepostconditionrules listedabovetothenormalexittypestateoftheselector,minusanyattributesinvolvingtheresultorelementvariable.SeeSectionfora<br />
typestateoftheeverystatement.Thetypestateonnormalexitfrom identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> musthavetheinitattributeonnormalexitfromtheselector.The SeealsoSpecialRules makeinit(result)<br />
Description:Createanewtablecontainingacopyofeveryelementof Qualier:selector <strong>and</strong>storethenewtableinresult.Iftableisordered,theelementsin tablethatsatisestheselectoridentiedintheinstructionqualier, resultappearinthesamerelativeorderastheydointable. discussionofhowtypestatesarecomputedforselectors.<br />
exists(result,table) TypeRules: Preconditions: result2boolean table2table Exceptions:Depletion Seex11.6,p.110<br />
init(table) SeealsoSpecialRules var(result) Postconditions: SeealsoSpecialRules makeinit(result)
exists(continued) SpecialRules:Thestatementqualierisaselector.Theresultvariable typeoftheelementvariableidentiedintheselectormustbetheelementtypeoftable.Theentrytypestatefortheselectoristheentry<br />
typestateoftheforallstatement.Thetypestateonnormalexitfrom identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> musthavetheinitattributeonnormalexitfromtheselector.The AppendixB.<strong>Hermes</strong>Operations169<br />
Description:Ifanyelementoftablesatisestheselectoridentiedin Qualier:selector false.Inparticular,iftableisempty,setresulttofalse. theinstructionqualier,thensetresulttotrue.Otherwisesetresultto theforallstatementiscomputedbyapplyingthepostconditionrules listedabovetothenormalexittypestateoftheselector,minusanyattributesinvolvingtheresultorelementvariable.SeeSectionfora<br />
exit() discussionofhowtypestatesarecomputedforselectors.<br />
TypeRules:None Preconditions:None SpecialRules:Theexitstatementcannotterminatenormally<strong>and</strong>thereforehasnonormalterminationtypestate.<br />
Exceptions:| Postconditions:SeeSpecialRules Seex11.6,p.110<br />
Description:Raiseanexitconditionfortheexitidentiedintheinstructionqualier.Controltransferstoappropriateh<strong>and</strong>lerintheinnermost<br />
Qualier:exit expression{block() TypeRules:None Preconditions:SeeSpecialRulesPostconditions:SeeSpecialRules containingblockthath<strong>and</strong>lesthisexitcondition.<br />
SpecialRules:Thetypestateonentrytotheexpressionclauseisidentical toentrytypestatefortheexpressionblockstatement.Theresultvariablemusthavetheinitattributeonexitfromtheexpressionclause.<br />
thenormalexittypestateoftheexpressionclause,minusanyattributes<br />
Exceptions:Depletion Seex11.3,p.101<br />
Thetypestateonnormalexitfromtheexpressionblockstatementis involvingvariablesdeclaredintheexpressionblockstatement.
170B.6.OperationDescriptions expression{block(continued) Description:Executetheinstructionscontainedinthescopeidentied Qualier:expressionblock extract(result,table) TypeRules: result2table computeavalueforaresultvariablealsoidentiedinthequalier. bytheinstructionqualier.Moduloexceptions,theeectwillbeto<br />
resulttable<br />
table2table Exceptions:Depletion Seex11.3,p.100<br />
Preconditions: SpecialRules:Thestatementqualierisaselector.Theresultvariable SeealsoSpecialRules init(table) var(result) var(table) Postconditions:<br />
typeoftheelementvariableidentiedintheselectormustbetheelementtypeoftable.Theentrytypestatefortheselectoristheentry<br />
typestateoftheextractstatement.Thetypestateonnormalexitfrom listedabovetothenormalexittypestateoftheselector,minusanyat-<br />
theextractstatementiscomputedbyapplyingthepostconditionrules identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> musthavetheinitattributeonnormalexitfromtheselector.The SeealsoSpecialRules killconstraints(table) makeinit(result)<br />
Description:Removealltheelementsfromtablethatsatisfytheselector Qualier:selector identiedintheinstructionqualier,assemblethemintoanewtable, resultwillappearinthesamerelativeorderasthedidintable. <strong>and</strong>storethenewtableinresult.Iftableisordered,theelementsof tributesinvolvingtheresultorelementvariable.SeeSectionfora discussionofhowtypestatesarecomputedforselectors.<br />
forall(result,table) TypeRules: Preconditions: result2boolean init(table) table2table Exceptions:Depletion Seex11.6,p.111<br />
var(result) Postconditions: makeinit(result)
forall(continued) Description:Ifeveryelementoftablesatisestheselectoridentiedin Qualier:selector empty.Inparticular,iftableisempty,setresulttotrue. theinstructionqualier,thensetresulttotrue.Otherwisesetresultto AppendixB.<strong>Hermes</strong>Operations171<br />
for{enumerate() TypeRules:SeeSpecialRules Preconditions:SeeSpecialRulesPostconditions:SeeSpecialRules SpecialRules:Theenumeratorvariableidentiedinthestatementqualiermustbeinclassenumeration.Theentrytypestateforthebody<br />
Exceptions:Depletion Seex11.6,p.110<br />
clausecontainsalltheattributesinthemeetoftheentrytypestate<br />
Description:Executethestatementscontainedinthescopeidentiedin onnormalterminationoftheforenumeratestatementcontainsallthe inthebody. bodyclause,aswellasinitoftheenumeratorvariable(aninterative attributesinthenormalexittypestateofthebodyclause,minusany solutionisrequiredforthis,asdescribedinSection).Thetypestate attributesinvolvingtheenumeratorvariableoranyvariablesdeclared fortheforenumeratestatement<strong>and</strong>thenormalexittypestateofthe<br />
Qualier:forenumerate itsvaluesareiteratedoverinascendingorder. spondingtothecurrentiteration.Iftheenumerationtypeisordered, foreachenumerationvalueintheenumerationtypecorrespondingto cution,theenumeratorvariableissettotheenumerationvaluecorre-<br />
enumeratorvariablealsoidentiedinthequalier.Duringeachexe-<br />
theinstructionqualierrepeatedly.Thestatementsareexecutedonce<br />
for{inspect(table) TypeRules: Preconditions: table2table<br />
Exceptions:Depletion Seex11.4,p.106<br />
init(table) SeealsoSpecialRules Postconditions:SeeSpecialRules
172B.6.OperationDescriptions for{inspect(continued) SpecialRules:Thestatementqualiercontainsaselector.Theresult <strong>and</strong>musthavetheinitattributeonnormalexitfromtheselector.The oftheforinspectstatement.Theentrytypestateofthebodyclause typeoftheelementvariableidentiedintheselector,<strong>and</strong>thatofthe typeoftable.Theentrytypestatefortheselectoristheentrytypestate elementvariableidentieddirecltyinthequalier,mustbetheelement variableidentiedinthatselectormustbeoftypepredefined!boolean identiedinthequalierincludesinitoftheelementvariableidentied inthequalier,plusallattributesinthemeetof(1)theexittypestate oftheselector,minusanyattributesinvolvingtheselector'sresultor<br />
Description:Executethestatementscontainedinthescopeidentiedby typestateonnormalterminationoftheforinspectstatementcontains elementvariable;<strong>and</strong>(2)theexittypestateofthebodyclause(an iterativesolutionisrequiredforthis,asdescribedinSection).The<br />
ier.Duringexecutionofthebody,theinspectvariable(alsoidentied foreachelementoftablethatsatisestheselectoridentiedinthequal-<br />
theinstructionqualierrepeatedly.Thestatementsareexecutedonce oranyvariabledeclaredinthebody.SeeSectionforadiscussionof howtypestatesarecomputedforselectors. alltheattributesinthenormalexittypestateofthebodyclause,minus<br />
inthequalier)issettoaconstantcopyofthecurrentmatchingtableelement.Iftableisordered,matchingelementswillbeinspectedin<br />
theordertheyappearintable.tableitselfisnotheldconstantduring executionsofthebody.<br />
anyattributesinvolvingtheelementvariableidentiedinthequalier<br />
Qualier:inspecttable greater(result,source1,source2) TypeRules: Preconditions: source12orderedscalar result2boolean source1source2 source22orderedscalar Exceptions:Depletion Seex11.6,p.113<br />
var(result) init(source2) init(source1) Postconditions: makeinit(result)
greater(continued) Description:Ifsource1comparesgreaterthansource2(numericallyor Qualier:absent resulttofalse. viaanenumerationordering),thensetresulttotrue.Otherwiseset AppendixB.<strong>Hermes</strong>Operations173<br />
greater{equal(result,source1,source2) TypeRules: Preconditions: source12orderedscalar result2boolean source1source2 source22orderedscalar Exceptions:Depletion Seex11.4,p.105<br />
Description:Ifsource1comparesgreaterthanorequaltosource2(nu-<br />
Qualier:absent mericallyorviaanenumerationordering),thensetresulttotrue.Oth-<br />
erwisesetresulttofalse. init(source2) init(source1) Postconditions: makeinit(result) var(result) hide(variant) TypeRules: Preconditions: variant2variant Seex11.4,p.105<br />
Description:Removetypestateattributesasrequiredbythepostconditions.Runtimecoercionsmayresult,butotherwisethereisnoruntime<br />
init(variant) Postconditions: dropcomponents(variant) Exceptions:|<br />
Qualier:absent if() TypeRules:SeeSpecialRules Preconditions:SeeSpecialRulesPostconditions:SeeSpecialRules eect. Seex11.7,p.117 Exceptions:|
174B.6.OperationDescriptions if(continued) SpecialRules:Thetestvariableidentiedinthestatementqualiermust<br />
Description:Executethestatementsinthetestclauseidentiedinthe onnormalexitfromtheifstatementisthemeetofthenormalexit isidenticaltotheexittypestatefromthetestclause.Thetypestate typestatesofthethen<strong>and</strong>elseclauses. beoftypepredefined!boolean<strong>and</strong>musthavetypestateinitonnormalexitfromthetestclauseidentiedinthequalier.Thetypestateon<br />
typestateonentrytothethenclause<strong>and</strong>(ifpresent)theelseclause identiedinthequalier)istrue,thenexecutethestatementsinthe instructionqualier.Iftheresultingvalueinthetestvariable(also entrytothetestclauseistheentrytypestatefortheifstatement.The<br />
Qualier:if insert(table,element) TypeRules: clauseisidentiedinthequalier,executethestatementsinthatclause. \then"clause(alsoidentiedinthequalier).Otherwise,ifan\else"<br />
Preconditions: table2table<br />
elementtypeof(table) Exceptions:Depletion,(DuplicateKey) Seex11.3,p.97<br />
Description:Inserttheobjectstoredinelementintotable,leavingelementuninitialized.Iftableisordered,thenewelementwillfollowall<br />
killconstraints(table) makeuninit(element) duplicatekey(table) var(element) var(table) init(table) lowestelementstate(element,table) Postconditions:<br />
previouslyexistingelements. Qualier:absent Seex11.6,p.110
insert{at(table,element,position) TypeRules: AppendixB.<strong>Hermes</strong>Operations175<br />
Preconditions: table2orderedtable<br />
element predefined!integer Exceptions:Depletion,<br />
init(table) elementtypeof(table) RangeError,<br />
lowestelementstate(element,table) (DuplicateKey)<br />
Description:Inserttheobjectstoredinelementintotable,soastomake duplicatekey(table) var(element) init(position) var(table) Postconditions:<br />
thepositionofthenewlyinsertedelementintheresultingtableequal killconstraints(table) makeuninit(element)<br />
Qualier:absent inspect{polymorph(polymorph) positionhigherinthetable. ouslyoccupiedelementpositionsatorbeyondpositionareshiftedone toposition,<strong>and</strong>leavingelementuninitialized.Allelementsthatprevi-<br />
TypeRules: Preconditions: polymorph2polymorph Exceptions:Depletion, PolymorphMismatch Seex11.6,p.110<br />
SpecialRules:Theentrytypestateforthebodyclauseidentiedinthe istheexittypestateofthebodyclause,minusanyattributesinvolving statementqualieristheentrytypestatefortheinspectpolymorph variableidentiedinthequalierintotheformaltypestateappearingin init(polymorph) statement,plusallattributesresultingfromsubsitutionoftheelement thequalier.Theexittypestatefortheinspectpolymorphstatement Postconditions:SeeSpecialRules<br />
theelementvariableoranyvariablesdeclaredinthebody.
176B.6.OperationDescriptions inspect{polymorph(continued) Description:Executethestatementscontainedinthescopeidentiedin Qualier:inspectpolymorph inspect{table(table) TypeRules: theinstructionqualier.Duringexecution,theinspectvariable(also identiedinthequalier)issettothevaluewrappedinpolymorph<strong>and</strong> isheldconstant.polymorphitselfisnotheldconstant.<br />
Preconditions: table2table<br />
Exceptions:Depletion,NotFound Seex11.9,p.127<br />
SpecialRules:Thestatementqualiercontainsaselector.Theresult <strong>and</strong>musthavetheinitattributeonnomralexitfromtheselector.The typeoftheelementvariableidentiedintheselector,<strong>and</strong>thatofthe elementvariableidentieddirectlyinthequalier,mustbetheelement variableidentiedinthatselectormustbeoftypepredefined!boolean init(table) SeealsoSpecialRules Postconditions:SeeSpecialRules<br />
oftheinspecttablestatement.Theentrytypestateofthebodyclause typeoftable.Theentrytypestatefortheselectoristheentrytypestate identiedinthequalieristheexittypestateoftheselector,minusany<br />
Description:Executethestatementscontainedinthescopeidentied attributesinthenormalexittypestateofthebodyclause,minusany attributesinvolvingtheelementvariableidentiedinthequalieror onnormalterminationoftheinspecttablestatementcontainsallthe attributeinvolvingtheselector'sresultorelementvariable,plusinit<br />
bytheinstructionqualier.Duringexecutionofthebody,theinspect howtypestatesarecomputedforselectors. anyvariablesdeclaredinthebody.SeeSectionforadiscussionof oftheelementvariableidentieddirectlyinthequalier.Thetypestate<br />
Qualier:inspecttable atableelementthatsatisestheselectoridentiedinthequalier.If variable(alsoidentiedinthequalier)issettoacontstantcopyof tableisordered,thersttableelementthatsatisestheselectorwill body. beinspected.tableitselfisnotheldconstantduringexecutionofthe Seex11.6,p.112
integer{literal(result) TypeRules: Preconditions: result2integer AppendixB.<strong>Hermes</strong>Operations177<br />
Description:Interpretthedigitstringstoredintheinstructionqualier asadecimalinteger,<strong>and</strong>storevalueinresult. var(result) Postconditions: makeinit(result) Exceptions:Depletion<br />
Qualier:literal less(result,source1,source2) TypeRules: Preconditions: source12orderedscalar result2boolean source1source2 source22orderedscalar Exceptions:Depletion Seex11.4,p.104<br />
Description:Ifsource1compareslessthansource2(numericallyorvia Qualier:absent var(result) init(source2) init(source1) anenumerationordering),thensetresulttotrue.Otherwisesetresult tofalse. Postconditions: makeinit(result)<br />
less{equal(result,source1,source2) TypeRules: Preconditions: source12orderedscalar result2boolean source1source2 source22orderedscalar Exceptions:Depletion Seex11.4,p.105<br />
Description:Ifsource1compareslessthanorequaltosource2(numericallyorviaanenumerationordering),thensetresulttotrue.Otherwise<br />
setresulttofalse. Postconditions: makeinit(result) Qualier:absent var(result) init(source2) init(source1) Seex11.4,p.105
178B.6.OperationDescriptions merge(destination,source)Exceptions:Depletion,(DuplicateKey) TypeRules: Preconditions: destinationsource duplicatekey(destination) var(destination) destination2table init(destination) var(source) init(source) source2table<br />
Description:Removeallthetableelementsfromsource<strong>and</strong>insertthem Postconditions: makeuninit(source)<br />
relativeorderastheyappearedinsource,<strong>and</strong>followingallpreviously thenthetransferredelementswillappearindestinationinthesame intodestination,leavingsourceuninitialized.Ifthetablesareordered, killconstraints(destination)<br />
Qualier:absent merge{at(destination,source,position)Exceptions:Depletion, TypeRules: existingelementsofdestination.<br />
destination2orderedtable source2table RangeError, (DuplicateKey) Seex11.6,p.112<br />
Preconditions:<br />
var(destination) destinationsource init(destination) init(position) var(source) init(source) predefined!integer<br />
duplicatekey(destination) Postconditions: makeuninit(source) killconstraints(destination)
merge{at(continued) Description:Removealltableelementsfromsource<strong>and</strong>insertthem willfollowconsecutively,inthesameorderastheyappearedinsource. intodestinationsothattheresultingpositionofthersttransferred element,ifany,willbeequaltoposition.Allothertransferredelements AppendixB.<strong>Hermes</strong>Operations179<br />
Qualier:absent mod(result,source1,source2)Exceptions:Depletion,DivideByZero TypeRules: <strong>and</strong>followingthelasttransferredelement. Allelementsofdestinationthatformerlyoccupiedpositionsatposition orbeyondareshiftedsothattheyappearinthesamerelativeorder,<br />
Preconditions: source12numeric result2numeric resultsource1source2 source22numericSeex11.6,p.112<br />
Description:Letabethevalueofsource1,<strong>and</strong>bbethevalueofsource2. var(result) init(source2) init(source1) Postconditions:<br />
Qualier:absent Thevaluechavingthesamesignasb,withabsolutevaluelessthan thatofb,<strong>and</strong>satisfyingtheequationa=nb+cforsomeintegern, isstoredinresult. makeinit(result)<br />
move(result,source) TypeRules: Preconditions: resultsource init(source) Exceptions:Depletion Seex11.4,p.104<br />
Description:Movetheobjectstoredinsourcetoresult,leavingsource Qualier:absent var(result) uninitialized. var(source) Postconditions: movets(source,result) Seex11.1,p.93
180B.6.OperationDescriptions multiply(result,source1,source2) TypeRules: Preconditions: source12numeric init(source2) init(source1) result2numeric resultsource1source2 source22numeric Exceptions:Depletion<br />
Description:Storetheproductofsource1<strong>and</strong>source2inresult. Qualier:absent var(result) Postconditions:<br />
named{literal(result) makeinit(result)<br />
TypeRules: Preconditions: SeealsoSpecialRules result2enumerationorboolean Exceptions:Depletion Seex11.4,p.104<br />
SpecialRules:Thecharacterstringappearinginthestatementqualier Description:Setresulttotheenumerationvaluebelongingtoitsenumerationtype<strong>and</strong>namedbytheinstructionqualier.<br />
makeinit(result) mustequaloneofthenamesappearinginthedenitionofthetypeof result. var(result) Postconditions:<br />
Qualier:literal new(result) TypeRules: Preconditions: result2newable var(result) Postconditions: makeinit(result) Exceptions:Depletion Seex11.4,p.104<br />
Description:Createanewobjectoftheappropriatetype<strong>and</strong>storeit Qualier:absentSeex11.5,p.107;x11.6,p.108;<strong>and</strong>x11.8,p.120 inresult.Allcomponentsofanewlycreatedrecordareuninitialized. Anewlycreatedtableisempty.Anewlycreatedinputportisnot connectedtoanyoutputport<strong>and</strong>hasnoqueuedmessages.
not(result,source) TypeRules: AppendixB.<strong>Hermes</strong>Operations181<br />
Preconditions: source2boolean var(result) init(source) resultsource result2boolean Postconditions: makeinit(result) Exceptions:Depletion<br />
Description:Ifsourceistrue,setresulttofalse.Otherwisesetresultto Qualier:absent not{equal(result,source1,source2) TypeRules: true.<br />
Preconditions: result2boolean init(source1) source1source2 Exceptions:Depletion Seex11.4,p.105<br />
Description:Ifsource1<strong>and</strong>source2areindistinguishableobjects,then Qualier:absent setresulttofalse.Otherwisesetresulttotrue. var(result) init(source2) Postconditions: makeinit(result)<br />
or(result,source1,source2) TypeRules: Preconditions: source12boolean result2boolean resultsource1source2 source22boolean Exceptions:Depletion Seex11.1,p.94<br />
Description:Ifeithersource1istrueorsource2istrue(orbotharetrue), Qualier:absent var(result) thensetresulttotrue.Otherwisesetresulttofalse. init(source2) init(source1) Postconditions: makeinit(result) Seex11.4,p.105
182B.6.OperationDescriptions position{of{element(result,element) TypeRules: Preconditions: Description:Setresulttothepositionoccupiedbyelementinthetableonwhichthecorrespondingselectorisoperating.Ifthetablehas<br />
var(result) pos(element) predefined!integerPostconditions:<br />
makeinit(result) Exceptions:Depletion<br />
Qualier:absent position{of{selector(result,table)Exceptions:Depletion,NotFound changedsincetheselectoroperationcommenced,thenthepositionof itscurrentposition. elementatthetimetheselectoroperationbeganisused,ratherthan TypeRules:<br />
table2orderedtable result predefined!integer Seex11.6,p.114<br />
Preconditions: SpecialRules:Thestatementqualierisaselector.Theresultvariable init(table) SeealsoSpecialRules var(result) Postconditions:<br />
typeoftable.Theentrytypestatefortheselectoristheentrytypestate identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> oftheelementvariableidentiedintheselectormustbetheelement musthavetheinitattributeonnormalexitfromtheselector.Thetype SeealsoSpecialRules makeinit(result)<br />
Description:Setresulttothepositionofanelementfromtablethat selector,minusanyattributesinvolvingtheresultorelementvariable. SeeSectionforadiscussionofhowtypestatesarecomputedfor ofthepositionofselectorstatement.Thetypestateonnormalexit<br />
ordered,usethepositionoftherstsuchelement. selectors. satisestheselectoridentiedintheinstructionqualier.Iftableis thepostconditionruleslistedabovetothenormalexittypestateofthe fromthepositionofselectorstatementiscomputedbyapplying<br />
Qualier:selector Seex11.6,p.114
print(variable) TypeRules:None Preconditions:None Description:Produceaprintedrepresentationoftheobjectstoredin AppendixB.<strong>Hermes</strong>Operations183<br />
variable.Thisoperation,<strong>and</strong>thecorrespondingprintstatementin theconcretesyntax,areprovidedonlyforpurposesof<strong>Hermes</strong>compiler debugging,<strong>and</strong>arenotmeantforusebyapplicationprograms.They Postconditions:None Exceptions:|<br />
Qualier:absent procedure(outport,program) TypeRules: outport2outport maybecomeunavailablewithoutnotice.<br />
predefined!program Exceptions:Depletion, InterfaceMismatch|<br />
Preconditions: Description:Createaprocedurethatwillrepeatedlyinstantiateprogram var(outport) checked(program) Postconditions:<br />
Qualier:absent intoprocesses,<strong>and</strong>storeanoutputportmatchingthetypeofprogram's initializationportinoutport.Wheneveramessageissentonthisoutput port,anewprocesswillbeinstantiated<strong>and</strong>themessageforwardedto thenewprocess'initializationport. makeinit(outport)<br />
program{literal(program) TypeRules: Preconditions:<br />
var(program) predefined!programPostconditions:<br />
makechecked(program) Exceptions:Depletion Seex11.8,p.124<br />
Description:Makeacopyoftheprogramobjectidentiedintheinstructionqualier<strong>and</strong>storeitinprogram.<br />
Qualier:programliteral Seex11.10,p.128
184B.6.OperationDescriptions real{literal(result) TypeRules: Preconditions: Description:Interpretthecharacterstringstoredintheinstructionqualierasarealnumber,<strong>and</strong>storethevalueinresult.<br />
result2integer var(result) Postconditions: makeinit(result) Exceptions:Depletion<br />
Qualier:literal rem(result,source1,source2)Exceptions:Depletion,DivideByZero TypeRules: Preconditions: source12numeric result2numeric resultsource1source2 source22numericSeex11.4,p.104<br />
Description:Letabethevalueofsource1,<strong>and</strong>bbethevalueofsource2. var(result) init(source2) init(source1) Postconditions:<br />
Qualier:absent thatofb,<strong>and</strong>satisfyingtheequationa=nb+cforsomeintegern, Thevaluechavingthesamesignasa,withabsolutevaluelessthan isstoredinresult. makeinit(result)<br />
receive(message,inport) TypeRules: Preconditions: inport2inport<br />
messagetypeof(inport) Exceptions:Depletion,Disconnected Seex11.4,p.104<br />
Description:Dequeuetherstavailablemessagefrominport<strong>and</strong>store Qualier:absent var(message) init(inport) itinmessage.Ifnomessageisavailable,waitforonetoarrive. var(inport) Postconditions: moveentryts(inport,message) Seex11.8,p.123
emove(element,table) TypeRules: AppendixB.<strong>Hermes</strong>Operations185<br />
Preconditions: table2table<br />
init(table)<br />
elementtypeof(table) Exceptions:Depletion,NotFound<br />
SpecialRules:Thestatementqualierisaselector.Theresultvariable SeealsoSpecialRules var(element) var(table) Postconditions:<br />
typeoftheelementvariableidentiedintheselectormustbetheelementtypeoftable.Theentrytypestatefortheselectoristheentry<br />
typestateoftheremovestatement.Thetypestateonnormalexitfrom identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> musthavetheinitattributeonnormalexitfromtheselector.The SeealsoSpecialRules killconstraints(table) moveelementts(table,element)<br />
Description:Removeanelementfromtablethatsatisestheselector Qualier:selector identiedintheinstructionqualier,<strong>and</strong>storeitinelement.Iftableis ordered,removetherstsuchelement. theremovestatementiscomputedbyapplyingthepostconditionrules listedabovetothenormalexittypestateoftheselector,minusanyattributesinvolvingtheresultorelementvariable.SeeSectionfora<br />
return(callmessage) discussionofhowtypestatesarecomputedforselectors.<br />
TypeRules: Preconditions: callmessage2callmessage lowestpostcondition(callmessage) Exceptions:Depletion Seex11.6,p.111<br />
Description:Returncallmessagetotheprocessthatoriginallysentit, Qualier:absent withoutraisingauserexception. var(callmessage) Postconditions: makeuninit(callmessage) Seex11.8,p.123
186B.6.OperationDescriptions return{exception(callmessage) TypeRules: Preconditions: Description:Returncallmessagetotheprocessthatoriginallysentit, callmessage2callmessage var(callmessage) lowestpostcondition(callmessage) Postconditions: makeuninit(callmessage) Exceptions:Depletion<br />
Qualier:returnexception reveal(varcomp) TypeRules: raisingtheuserexceptionidentiedbytheinstructionqualierinthat process.<br />
Preconditions: varcomp2variantcomponent initwithoutcase(varcomp) Postconditions: Exceptions:Depletion,CaseError makecase(varcomp) Seex11.8,p.123<br />
Description:Addtypestateattributesasrequiredbythepostconditions. Qualier:absent select() TypeRules:SeeSpecialRules Preconditions:None Thereisnoruntimeeect. Exceptions:Depletion,Disconnected Postconditions:None Seex11.7,p.117
select(continued) SpecialRules:Allthevariablesidentiedintheeventguardsassociatedwiththeclauseslistedinthestatementqualiermustbeinclass<br />
AppendixB.<strong>Hermes</strong>Operations187 resultvariableidentiedineachbooleanguardassociatedwithaclause inport.Ifthereisanoper<strong>and</strong>,itstypemustbethesameasthatofthe onnormalexitfromtheirassociatedtestclauses.Theentrytypestate foreachbooleanguardclauseisidenticaltotheentrytypestateforthe ment.Allbooleanguardresultvariablesmusthavetheinitattribute theotherwiseclause,isthemeetofthenormalexittypestatefromall thebooleanguardtestclauses(ortheselectstatemententrytypestateiftherearenobooleanguards).Thenormalexittypestatefrom<br />
mustbeoftypepredefined!boolean.Allvariablesassociatedwith selectstatement.Theentrytypestateforeachselectclause,including eventguardsmusthavetheinitattributeonentrytotheselectstate-<br />
listedinthequalier.Otherwise,eachbooleanguardresultvariable<br />
Description:Theinstructionqualiercontainsatableofselectclauses, eachofwhichspeciesoneorbothofaneventguard<strong>and</strong>aboolean astatementclause.Theselectoperationrstexecutesallthestatementsinclausesidentiedbybooleanguards,yieldingvaluesforallthe<br />
guard,aswellasanassociatedstatementclause.Aneventguardis theselectstatementisthemeetofthenormalexittypestatesofall theselectclauses,includingtheotherwiseclause. aninputportvariable,whileabooleanguardidentiesavariable<strong>and</strong><br />
eventguardwhoseassociatedinputportisnonempty,isselected.The booleanguardvariables.Iftheselectoperationhasanoper<strong>and</strong>,itis statementsinthestatementclauseassociatedwiththeselectedclause arethenexecuted.Iftherearenoenabledselectclauses,thenthestatementsinthe\otherwise"clause(identiedintheinstructionqualier)<br />
outport2outport<br />
messagetypeof(outport) Exceptions:Depletion,Disconnected<br />
selectclauseswithtruebooleanguardvaluesareenabled.Inaddition, selectclauseswithoutbooleanguardsareenabled.Ifanyselectclause erationhasnooper<strong>and</strong>s,thebooleanguardvaluesmustbeboolean,<strong>and</strong> isenabled,oneenabledclausewitheithernoeventguard,orwithan clauseforwhichthetestsucceedsbecomes\enabled."Iftheselectop-<br />
testedforequalitywitheachbooleanguardvariable,<strong>and</strong>eachselect<br />
Qualier:select send(outport,message) TypeRules: areexecuted. Seex11.3,p.98
188B.6.OperationDescriptions send(continued) Preconditions: Description:Addmessagetothequeueassociatedwiththeinputport Qualier:absent var(message) init(outport) lowestentrycondition(message,outport) connectedtooutport,leavingmessageuninitialized. Postconditions: makeuninit(message)<br />
size(result,table) TypeRules: Preconditions: table2table<br />
predefined!integer Exceptions:Depletion Seex11.8,p.124<br />
Description:Setresultequaltothenumberofelementsintable. Qualier:absent string{literal(result) init(table) var(result) Postconditions: makeinit(result)<br />
TypeRules: Preconditions: SeealsoSpecialRules result2string Exceptions:Depletion,(DuplicateKey) Seex11.6,p.114<br />
SpecialRules:Eachelementofthetableappearinginthestatement Description:Copythestringstoredintheinstructionqualier<strong>and</strong>store duplicatekey(result) var(result) qualiermustcorrespondtooneoftheenumerationvaluesappearing inthedenitionoftheelementtypeofresult.Thatis,asingletontable containingtheelementmustequaloneoftheenumerationvalues. Postconditions:<br />
thecopyinresult. makeinit(result)<br />
Qualier:literal Seex11.6,p.109
subtract(result,source1,source2) TypeRules: AppendixB.<strong>Hermes</strong>Operations189<br />
Preconditions: source12numeric init(source2) init(source1) result2numeric resultsource1source2 source22numeric Exceptions:Depletion<br />
Description:Subtractsource2fromsource1<strong>and</strong>storetheresultinresult. Qualier:absent var(result) Postconditions: makeinit(result)<br />
the{element(result,table) TypeRules:<br />
table2table elementtypeof(table) table2copyable Exceptions:Depletion, NotFound,(Uncopyable) Seex11.4,p.104<br />
Preconditions: SpecialRules:Thestatementqualierisaselector.Theresultvariable init(table) uncopyable(table) var(result) SeealsoSpecialRules Postconditions:<br />
typeoftheelementvariableidentiedintheselectormustbetheelementtypeoftable.Theentrytypestatefortheselectoristheentry<br />
identiedinthatselectormustbeoftypepredefined!boolean<strong>and</strong> musthavetheinitattributeonnormalexitfromtheselector.The SeealsoSpecialRules moveelementts(table,result)<br />
Description:Copyanelementfromtablethatsatisestheselectoridentiedintheinstructionqualier,<strong>and</strong>storethecopyinresult.<br />
typestateofthetheelementstatement.Thetypestateonnormalexit tionforadiscussionofhowtypestatesarecomputedforselectors. minusanyattributesinvolvingtheresult<strong>and</strong>elementvariable.SeeSec-<br />
fromthetheelementstatementiscomputedbyapplyingthepostconditionruleslistedabovetothenormalexittypestateoftheselector,<br />
Qualier:selector Seex11.6,p.109
190B.6.OperationDescriptions type(result,polymorph) TypeRules: Preconditions: polymorph2polymorph<br />
init(polymorph) var(result) predefined!typeof--value Postconditions: makefull(result) Exceptions:Depletion<br />
Description:Storethetypeoftheobjectwrappedinsidepolymorphin Qualier:absent typename(result) TypeRules: result,alongwithanydenitionmodulesnecessarytoresolvethetype.<br />
Preconditions:<br />
var(result) predefined!typenamePostconditions:<br />
makefull(result) Exceptions:Depletion Seex11.9,p.127<br />
Description:Makeacopyofthetypenamefoundintheinstructionqualier,<strong>and</strong>storeitinresult.<br />
Qualier:typename typestate(result,polymorph) TypeRules: Preconditions: polymorph2polymorph<br />
predefined!typestateof--valueExceptions:Depletion<br />
Seex11.10,p.130<br />
Description:Storethetypestateoftheobjectwrappedinsidepolymorph Qualier:absent init(polymorph) var(result) straintattributes. inresult,alongwithanydenitionmodulesnecessarytoresolvecon-<br />
Postconditions: makeinit(result) Seex11.9,p.127
unary{minus(result,source) TypeRules: AppendixB.<strong>Hermes</strong>Operations191<br />
Preconditions: result2numeric var(result) init(source) resultsource source2numeric Postconditions: makeinit(result) Exceptions:Depletion<br />
Description:Negatesource<strong>and</strong>storetheresultinresult. Qualier:absent unique(result) TypeRules: Preconditions: result2nominal var(result) Postconditions: makeinit(result) Exceptions:Depletion Seex11.4,p.104<br />
Description:Createanewnominalvalue,distinguishablefromallother Qualier:absent unite(varcomp,source) TypeRules: nominalvaluesthathaveeverbeencreated,<strong>and</strong>storeitinresult.<br />
Preconditions: varcompsource varcomp2variantcomponent Exceptions:Depletion Seex11.4,p.105<br />
Description:Putthevariantofwhichvarcompisacomponentintowhateverstatecorrespondstovarcomp,<strong>and</strong>thenmovethevaluestoredin<br />
casets(source,varcomp) var(source) var(varcomp) Postconditions: movets(source,varcomp) makecase(varcomp) Qualier:absent sourcetovarcomp,leavingsourceuninitialized. Seex11.7,p.116
192B.6.OperationDescriptions unwrap(result,polymorph) TypeRules: Preconditions: polymorph2polymorph Exceptions:Depletion,<br />
Description:Movethevaluewrappedinsidepolymorphtoresult,leaving init(polymorph) var(result) Postconditions: polymorphts(result) makeuninit(polymorph) PolymorphMismatch<br />
Qualier:wrap while() TypeRules:None typestatetothatgivenbytheinstructionqualier. polymorphuninitialized<strong>and</strong>coercingresultasrequiredtolowerits<br />
Preconditions:None SpecialRules:Theresultvariableidentiedinthestatementqualier Postconditions:SeeSpecialRules Seex11.9,p.126<br />
stateonentrytothetestclauseisthemeetoftheentrytypestateof onnormalexitfromthetestclauseidentiedinthequalier.Thetype-<br />
mustbeoftypepredefined!boolean<strong>and</strong>musthavetheinitattribute Exceptions:|<br />
Description:Repeatedlyexecutethestatementsintheclauseidentied malexittypestateofthetestclause(aniterativesolutionisrequired forthis,asdescribedinSection). normalexittypestateforthewhilestatement,areidenticaltothenor-<br />
repeatedclause.Thetypestateonentrytotherepeatedclause,<strong>and</strong>the thewhilestatement<strong>and</strong>thetypestateonnormalterminationofthe<br />
Qualier:while iseverfalse,terminateexecutionofthewhileoperationimmediately (withoutperformingthecurrentiteration). forthetestresultvariable(identiedinthequalier).Ifthetestresult mentsinthetestclause(alsoidentiedinthequalier)toyieldavalue intheinstructionqualier.Priortoeachiteration,executethestate-<br />
wrap(polymorph,source) TypeRules: polymorph2polymorph Exceptions:Depletion Seex11.3,p.97
wrap(continued) Preconditions: var(source) var(polymorph) polymorphprecondition(source) AppendixB.<strong>Hermes</strong>Operations193<br />
Description:Coercesourceasnecessarytoloweritstypestatetothat Postconditions:<br />
Qualier:wrap typestate<strong>and</strong>storetheresultinpolymorph,leavingsourceuninitialized. givenintheinstructionqualier.Thenwrapitupwithitstype<strong>and</strong> makeuninit(source) makeinit(polymorph) Seex11.9,p.125
AppendixC PredenedModule Thisappendixprovidesacompletelistingofthepredefined.ddenitions module.Thepredefinedmoduleisimplicitlyimportedbyall<strong>Hermes</strong> enforceassignment-styletyperules.Forexample,theoperationdescription modules.Itcontainsallthetypedenitionsrequiredbythecompilerto<br />
forthelatterisalsoincluded. thedenitionofprogrammakesuseofpredefined!processid,adenition causeitisreferencedinthetyperulesforcreate<strong>and</strong>procedure.Since function.Manytypesaredenedinpredefinedbecausethemodulemust predefined!integer.Thustheremustbeatypenamedintegerdened becompletelyself-contained.Forexample,typeprogramisincludedbe-<br />
inadenitionsmodulenamedpredefinedinorderforthecompilerto fortheinsert-atoperationrequiresthatthepositionargumentbeoftype<br />
predefined. writea<strong>Hermes</strong>applicationthatmakesnoexplicituseofanythingfrom chosenforinclusionistheonepresentedabove.Itisnotuncommonto provideacollectionoftypedenitionsthatpeoplewillndgenerallyuseful intheirprogramming.Theonlycriterionbywhichatypedenitionis whichisusedtorepresentabstract<strong>Hermes</strong>programs.Anyprogramthat intendstomanipulate<strong>Hermes</strong>programobjectsasdatawillnecessarilydependheavilyonthedenitionsinpredefined.<br />
Thevastmajorityofthemodulecentersaroundthetypepredefined!program, Itshouldbestressedthatthepredefinedmoduleisnotintendedto
definitions predefined:using() AppendixC.PredenedModule195<br />
option:enumeration('present','absent'); empty:enumeration(); FundamentalTypes<br />
boolean:boolean(true:'true',false:'false'); integer:integer; char:orderedenumeration( '(',')','*','+',',','-','.','/', '8','9',':',';','','', '0','1','2','3','4','5','6','7', '','!','"','#','$','%','&','''', 'DLE','DC1','DC2','DC3','DC4','NAK','SYN','ETB', 'CAN','EM','SUB','ESC','FS','GS','RS','US', 'NUL','SOH','STX','ETX','EOT','ENQ','ACK','BEL', 'BS','HT','NL','VT','NP','CR','SO','SI',<br />
);'x','y','z','f','|','g','~','DEL' '@','A','B','C','D','E','F','G', 'H','I','J','K','L','M','N','O',<br />
charstring:orderedtableofcharfinitg; '','a','b','c','d','e','f','g', 'h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w', 'P','Q','R','S','T','U','V','W', 'X','Y','Z','[','n',']','^','',<br />
TheAbstractProgramObject
196AppendixC.PredenedModule program:pragma"program"record( definitionsmodules:definitionsmodules,{{importedmodules<br />
definitionsmodule:record( );{{therecanbemultipleprogramsbecauseofprogramliterals definitionsmodules:tableofdefinitionsmodule programs:processes mainprogram:processid, ffull/*,checkeddefinitions*/gkeys(id); {{oneormoreprograms {{themainprogram<br />
); typedefinitions:typedefinitions,{{typedenitions id:moduleid, attrdefinitions:attrdefinitions{{attributedenitions Names<strong>and</strong>IDs{{uniqueidofmodule<br />
processid:nominal; clauseid:nominal; rootid:nominal; typeid:nominal; exceptionid:nominal; statementid:nominal; {{identiesaprocessobject<br />
attributeid:nominal; moduleid:nominal; scopeid:nominal; {{clauseidentiers<br />
exitid:nominal; componentid:nominal; {{rootnameidentiers {{exceptionid {{typeidentiers<br />
{{Thefollowingistoallow,inabsprog,variableswithundeclared {{statementidentier {{attributeidentier {{scopeidentier {{moduleid<br />
{{types.Forexample,temporariesthatgetintroducedwhenexp<strong>and</strong>ing {{expressionstoassignmentstatements.Theirtypesarenotknown {{idofexith<strong>and</strong>ler {{componentidentier<br />
optionaltypename:variantoftypenameoption( typenameoption:enumeration('named','unnamed'); {{untilthetypecheckingphasewhichcomesafterresolution. 'unnamed'->noname:emptyfg,
);'named'->typename:typenameffullg typename:record(<br />
AppendixC.PredenedModule197<br />
);attributeid:attributeid );typeid:typeid constraintname:record( moduleid:moduleid, {{timestampofmodule<br />
{{anobject(variable)gives(i)thescopewhereitisdeclared,(ii) {{attributeidwithinmodule {{typeidwithinmodule<br />
{{itsrootid,<strong>and</strong>(iii)ifitisacomponent,itscompoenentid. {{e.g.,ifinscopesthereisthedeclarationr:Q,whereQisa {{recordhavingacomponentz,thentheobjectr.zgetswouldhave {{theobjectname(s,r,z). rootname:record(<br />
);components:componentlist objectname:record( scope:scopeid, root:rootid root:rootname, {{identiersofcomponents {{scopeofrootdeclaration {{rootidentierusedto {{rootobject {{refertothisobject<br />
componentlist:orderedtableofcomponentidffullg;<br />
typedefinitions:tableoftypedefinitionffullgkeys(id); objectnames:orderedtableofobjectnameffullg;<br />
{{Eachtypehasaunique(withinitsdenitionsmodule)typeid,a TypeDenitions
typedefinition:record( {{callmessages),aspecicationconsistingofaprimitivetype<strong>and</strong> {{associatedinformation,<strong>and</strong>apragmastring 198AppendixC.PredenedModule<br />
);prag:charstring {{setoftypedcomponents(emptyexceptforrecords,variants<strong>and</strong><br />
componentdeclarations:orderedtableofcomponentdeclarationffullg specification:specificationtype, id:typeid,<br />
componentdeclaration:record( keys(id); componentdeclarations:componentdeclarations,<br />
);type:typename primitivetypes:orderedenumeration( 'recordtype','varianttype','tabletype', 'inporttype','outporttype','callmessagetype', 'polymorphtype'); 'nominaltype','integertype','booleantype','enumerationtype','realtype', id:componentid, {{declaredtype {{uniquenameofcomponent<br />
specificationtype:variantofprimitivetypes( 'booleantype'->boolean:booleaninfoffullg, 'varianttype'->variantinfo:variantinfoffullg, 'nominaltype'->nominalinfo:emptyfg, 'realtype'->accuracyinfo:accuracyinfoffullg, 'enumerationtype'->enumeration:enumerationinfoffullg, 'recordtype'->recordinfo:emptyfg, 'tabletype'->tableinfo:tableinfoffullg, 'integertype'->integerinfo:emptyfg,<br />
);'polymorphtype'->polymorphinfo:emptyfg 'outporttype'->outportinfo:typenameffullg, 'callmessagetype'->callmessageinfo:callmessageinfoffullg, 'inporttype'->inportinfo:inportinfoffullg,
{{Specicinformationneededtocompletelyspecifyatypefallingin {{eachofthevariousprimitivetypecategories booleaninfo:record( AppendixC.PredenedModule199<br />
);falsename:charstring enumerationinfo:record( truename:charstring,<br />
);accuracydenominator:integer accuracyinfo:record( );values:enumerationvalues enumerationvalues:orderedtableofcharstringfinitgkeys(*); ordered:boolean, accuracynumerator:integer, {{isitanorderedenumeration {{components<br />
variantinfo:record( casetype:typename, casemapping:partitionset {{theenumerationtaggingthevariant {{mapscasetags(fromcase-type {{enumeration)tocomponents {{forrealtypes<br />
partitionset:tableofpartitioninfoffullgkeys(componentid); partitioninfo:record( );casetypestate:formaltypestate{{typestateofcomponent tableinfo:record( caseid:integer, orderedtable:boolean, componentid:componentid, {{componentofvariant<br />
elementtype:typename, keys:keyset, {{allthekeys {{typeofeachtableelement {{isthetableordered {{correspondingenumerationvalue<br />
);elementtypestate:formaltypestate{{typestateofeachtableelement
{{Anemptysetindicatestheentireelementobject {{Eachkeyconsistsofasetof(sub-)componentsoftheelementtype. 200AppendixC.PredenedModule<br />
formalobjects:orderedtableofcomponentlistffullg; keyset:orderedtableofformalobjectsffullgkeys(*);<br />
);messagetypestate:formaltypestate{{typestateofeachqueuedmessage callmessageinfo:record( inportinfo:record( constants:componentset, messagetype:typename, {{typeofeachqueuedmessage<br />
);exceptionspecifications:exceptionspecifications {{typestateforthecallmessagetype. {{followingassociatesexittypestateswithexceptions minimum:exceptionid, {{callmessage.Theassociatedexittypestateistheminimum normal:formaltypestate, {{followingidentiestheDiscardedexceptionforthis {{exittypestatefornormalreturn {{whichcomponentsareheldconstant<br />
componentset:tableofcomponentidfinitgkeys(*); exceptionspecifications:tableofexceptionffullgkeys(exceptionid); exception:record( posttypestate:formaltypestate{{typestateonthatoutcome exceptionid:exceptionid, AttributeDenitions {{uniquenameofexception<br />
{{module)identier,thecodethatevaluatestheattribute, attrdefinitions:tableofattrdefinitionffullgkeys(attributeid); {{Anattributedenitionincludesaunique(withinadenitions {{parameters,<strong>and</strong>therequiredentrytypestateoftheparameters. {{Theparametersexistintheouterscopeofthecode.
attrdefinition:record( attributeid:attributeid, AppendixC.PredenedModule201<br />
); rootids:orderedtableofrootidfinitg; pretypestate:typestate, prag:charstring parameters:rootids, returnvalue:objectname, executionenvironment:executionenvironment,{{expressiontoevaluate {{pragma {{typestateonentry {{declaredintheouterscope {{booleanobject {{uniqueidofattribute<br />
processes:tableofprocffullgkeys(id); {{typeexecutionenvironment,whichincludesthestatementsappearing {{Eachprocesshasauniqueidentier.Thecodeisanobjectof ProcessModules<br />
{{theoutermostscope. proc:record( {{inthecode,aswellasdeclarationsforalltherootobjects {{introducedbyincludedscopes.Theinitportisalwaysanobjectin<br />
{{acollectionofnestedscopes,withasinglemain,oroutermost {{moduleorfromanattributedenition.Thecodeisrepresentedas id:processid, executablepart:executionenvironment,{{dcls+statements<br />
{{<strong>and</strong>isassociatedwithaclause.Aclauseisalistofstatements, {{scope.Eachscopeintroducesnewdeclarationsforrootobjects, ); {{Followingrecordrepresentsapieceofcode,eitherfromaprocess initport:rootid, prag:charstring {{pragma {{nameofinitializationport<br />
{{alwaysbeginswiththeclauseassociatedwiththeoutermostscope. {{someofwhichintroducenestedscopes.Executionofthecode executionenvironment:record( scopes:scopes,
202AppendixC.PredenedModule );mainscope:scopeid scopes:tableofscopeffullgkeys(id); scope:record( clauses:clauses,<br />
{{optionallyassociatesatypewiththeobject.Ifnotypeis {{context. );clause:clauseid {{Eachdeclarationidentiesthedeclaredrootobject,<strong>and</strong> {{suppliedinadeclaration,thetypemustbeinferrablefrom declarations:declarations, id:scopeid, {{declarationsintroducedbyscope {{statementstoexecuteinscope {{scopeidentier<br />
declaration:record( declarations:tableofdeclarationffullgkeys(id);<br />
{{listofthestatementsthatmakeuptheclause clauses:tableofclauseffullgkeys(id); );prag:charstring {{Eachclausehasaunique(withinanexecutionenvironment)id<strong>and</strong>a id:rootid, typename:optionaltypename, {{idusedforreference {{typeofobject<br />
clause:record( {{pragma<br />
);statements:statements {{Eachstatementhasaunique(withinanexecutionenvironment) {{identier,anoperator<strong>and</strong>oper<strong>and</strong>s,<strong>and</strong>possiblyadditionaldata id:clauseid, {{identierofclause<br />
{{qualier.Theprecisecontentsofthequalierdependsonthe {{viaaccessibleprogramobjectsatruntime,mustbeprovidedinthe {{speciedinisqualier.Anyinformationthatisneededforthe {{properexecutionofthestatement<strong>and</strong>cannotnotbemadeavailable {{statementsofclause<br />
{{operator. statements:orderedtableofstatementffullgkeys(id);
statement:record( id:statementid, operator:operator, oper<strong>and</strong>s:objectnames, qualifier:qualifier, AppendixC.PredenedModule203<br />
);prag:charstring {{Hereareallthe<strong>Hermes</strong>operators operator:orderedenumeration( 'checkdefinitions','concatenate','connect','convert','copy', 'create','currentprogram','discard','dissolve','divide','drop', 'empty','equal','every','exists','exit','expressionblock', 'extract','forenumerate','forinspect','forall','greater', 'greaterequal','hide','if','insert','insertat', 'lessequal','merge','mergeat','mod','move','multiply', 'namedliteral','new','not','notequal','or', 'inspectpolymorph','inspecttable','integerliteral','less', 'add','<strong>and</strong>','assert','attributename','block','call','case',<br />
'positionofelement','positionofselector',<br />
); 'typename','typestate','unaryminus','unique','unite','unwrap', 'print', 'procedure','programliteral','realliteral','receive','rem', 'remove','return','returnexception','reveal','select','send', 'size','stringliteral','subtract','theelement','type', 'while','wrap' {{includedfordebuggingpurposesonly<br />
{{Namesofallthequaliertypes...commentsidentifywhich {{operatorsuseeachqualiertype qualifiertypes:orderedenumeration( 'absent', OperationQualiers<br />
'block', 'attributename', {{block {{attributenameliteral
204AppendixC.PredenedModule<br />
'inspecttable', 'if', 'constraintname', 'forenumerate', 'exit', 'expressionblock', {{assert,drop {{exit<br />
'returnexception', 'programliteral', 'literal', 'inspectpolymorph', {{forinspect,inspecttable {{programliteral {{if-then-else {{inspectpolymorph {{integerliteral, {{returnexception {{realliteral,namedliteral {{forenumerate {{expressionblock<br />
);'wrap' 'select', 'selector', {{select<br />
{{Followingisthevariantusedtorepresentallstatementqualiers 'typename', 'while', {{typenameliteral {{while {{wrap,unwrap {{every,exists,extract, {{forall,remove,<br />
qualifier:variantofqualifiertypes( {{theelement,positionofselector<br />
'attributename'->attributename:attributenameffullg, 'absent'->empty:emptyfg,{{noqualier 'exit'->exit:exitidffullg, 'forenumerate'->forenumerate:forenumeratequalifierffullg, 'if'->if:ifqualifierffullg, 'block'->block:blockqualifierffullg, 'expressionblock'->expression:expressionqualifierffullg, 'constraintname'->constraintname:constraintnameffullg, 'inspectpolymorph'-><br />
'while'->while:whilequalifierffullg, 'returnexception'->exceptionid:exceptionidffullg, 'typename'->typename:typenameffullg, 'literal'->literal:charstringffullg, 'selector'->selector:selectorffullg, 'programliteral'->programliteral:processidffullg, 'select'->select:selectqualifierffullg, 'inspecttable'->inspecttable:inspecttablequalifierffullg, inspectpolymorph:inspectpolymorphqualifierffullg,<br />
);'wrap'->formaltypestate:formaltypestateffullg
{{Ablockstatementqualieridentiesthescopeholdingthe {{constantwithintheblock,<strong>and</strong>alltheh<strong>and</strong>lersassociatedwiththe {{declarations<strong>and</strong>mainbodycodeoftheblock,therootobjectsheld {{block. AppendixC.PredenedModule205<br />
);h<strong>and</strong>lers:h<strong>and</strong>lers rootnames:tableofrootnameffullgkeys(*); {{Eachh<strong>and</strong>lernamestheexceptionsorexitconditionsthatit blockqualifier:record(<br />
{{h<strong>and</strong>les,<strong>and</strong>suppliesaclause(notascope)containingthebodyof constants:rootnames, scope:scopeid, {{exception<strong>and</strong>exith<strong>and</strong>lers {{newscopeintroducedbytheblock<br />
{{theh<strong>and</strong>ler. {{objectsnotchangedinthisscope<br />
h<strong>and</strong>lers:tableofh<strong>and</strong>lerffullgkeys(id); h<strong>and</strong>ler:record( );clause:clauseid {{H<strong>and</strong>lerscomeinfourvarieties... h<strong>and</strong>lertype:orderedenumeration( 'builtin', id:h<strong>and</strong>lername,<br />
);'others' {{Eachh<strong>and</strong>lertyperequirestype-specicadditionalinformationto {{fullyspecifytheconditionh<strong>and</strong>led 'user', 'exit', {{builtinexceptions {{userexceptions(dened<br />
h<strong>and</strong>lername:variantofh<strong>and</strong>lertype( {{withcallmessages) {{exitconditions<br />
'user'->user:userexceptionffullg, 'builtin'->builtin:builtinexceptionfinitg, {{exceptionsnototherwiseh<strong>and</strong>led<br />
'others'->others:emptyfg 'exit'->exit:exitidfinitg,
206AppendixC.PredenedModule ); {{Hereareallthebuiltinexceptions );'Uncopyable' {{Auserexceptionisspeciedbythecallmessagetype<strong>and</strong>oneof builtinexception:orderedenumeration( {{theexceptionsdenedwiththattype 'CaseError','ConstraintError','ConstraintFailure','Depletion',<br />
userexception:record( 'Disconnected','DivideByZero','DuplicateKey','InterfaceMismatch',<br />
type:typename, 'NotFound','PolymorphMismatch','DefinitionError','RangeError',<br />
{{executed<strong>and</strong>therootvariablethatwillholdtheexpression {{result.Therootvariableistheonlyvariableoutsidethe {{expressionblockscopethatisnotheldconstantwithinthescope. expressionqualifier:record( );exceptionid:exceptionid {{Thequalierforanexpressionblockidentiesthescopetobe<br />
{{scope. {{theenumeration.Theiterationvariableisdeclaredinthebody {{scope,aswellastherootvariablethatisusedtoiteratethrough );result:rootname {{Foraforenumeratestatement,thequalieridentiesthebody scope:scopeid,<br />
forenumeratequalifier:record( );enumerator:rootid {{Thequalierforanifstatementidentiestheclausethatwill {{evaluatethetestexpression,theobjectthatwillholdthe {{expressionresult,<strong>and</strong>theclausetobeexecutediftheexpression {{yieldsatrueresult.Inaddition,an'else'clausemayoptionally {{besupplied,identifyingtheclausetobeexecutedwhenthetest scope:scopeid,
{{expressionisfalse. ifqualifier:record( testclause:clauseid, testresult:objectname, thenclause:clauseid, AppendixC.PredenedModule207<br />
);optelseclause:optionalclauseid<br />
{{throughoutthebodyscope,<strong>and</strong>thetypestaterequiredforthe {{thebodyscope)thatwillholdtheunwrappedpolymorphvalue {{scopeformingthestatementbody,therootvariable(declaredin );'absent'->empty:emptyfg {{Thequalierforaninspectpolymorphstatementidentiesthe optionalclauseid:variantofoption(<br />
{{unwrappedvalue. 'present'->clauseid:clauseidfinitg,<br />
inspectpolymorphqualifier:record( );typestate:formaltypestate {{Followingqualierisusedforinspecttable<strong>and</strong>forinspect {{statements.Inadditiontothesamesortofselectorasthatused scope:scopeid,<br />
{{throughoutthebodyscope.Theinspectingrootobjectiscontained {{theidoftherootobjectthatholdstheinspectedtableelement {{forothertableoperations,abodyscopeisincluded,aswellas element:rootid,<br />
{{inthebodyscope.NotethatitISNOTthesameobjectasthe {{elementobjectintheselectoritself,astheydeclaredindisjoint );selector:selector {{Aselectstatementqualierincludesa"selectclause"foreach {{scopes.<br />
{{guardedarmoftheselectstatement,identifyingtheguard inspecttablequalifier:record( {{conditionforthearm<strong>and</strong>theclausetobeexecutedwhenthearm scope:scopeid, element:rootid, {{scopeofstatementbody {{inspectionvariable {{tableselector
selectqualifier:record( {{guardsaredisabledisspecied. 208AppendixC.PredenedModule<br />
);otherwiseclause:clauseid {{isselected.Inaddition,aclausetobeexecutedwhenall clauses:selectclauses,<br />
selectclauses:tableofselectclauseffullg; selectclause:record( clause:clauseid, info:clauseinfo {{otherwiseclauseism<strong>and</strong>atory<br />
{{giveninport,orboth. guardtype:enumeration('boolean','event','both'); {{Eacharmcanbeguardedbyabooleancondition,an"events"ona<br />
{{wheretheresultofthatexecutionwillbeplaced. clauseinfo:variantofguardtype( {{theclausetobeexecutedtoevaluatetheguard,<strong>and</strong>theobject );'both'->both:bothguardffullg {{Abooleanguard(orthebooleanpartofa"both"guard)identies 'boolean'->boolean:boolguardffullg,<br />
boolguard:record( 'event'->portname:objectnameffullg,<br />
);portname:objectname );result:objectname bothguard:record( clause:clauseid,<br />
{{Aselectorqualiesmanytable-relatedstatements,<strong>and</strong>encodesthe {{informationcontainedintheWHERE(...)clauseofsuchstatements. {{Theselectorintroducesascopewhichencodestheselector boolean:boolguard,
{{expression.The'element'rootvariableappearsinthatscope<strong>and</strong> {{'result'objectholdstheresultofevaluatingtheselectorfora {{holdsatableelementwhenevertheselectorisexecuted.The {{thetableelement. selector:record( AppendixC.PredenedModule209<br />
{{loopbody. {{willholdtheresultofthetest,<strong>and</strong>theclausecontainingthe );result:objectname {{Thequalierforawhilestatementidentiestheclausethat {{evaluatestheentrytestatthetopoftheloop,thevariablethat element:rootid, scope:scopeid, {{theelementbeingselected {{booleanvalueofselectorexpression {{scopeintroducedbytheselector<br />
whilequalifier:record( {{inpolymorphs );repeatedclause:clauseid {{Followingtypesdenitionsareforthevaluesresultingfrom {{TYPEOF<strong>and</strong>TYPESTATEOFexpressions,whichinspectvalueswrapped testclause:clauseid,<br />
typeofvalue:record( result:objectname,<br />
);definitions:definitionsmodules{{resolutionenvironmentforthattype typestateofvalue:record(<br />
typename:typename, typestate:formaltypestate, {{nameofthetype {{typestateofwrappedvalue<br />
Typestates<strong>and</strong>FormalTypestate {{attributesappearingintypestate<br />
{{Atypestateisasetofattributes,eachofwhichconstistofan
{{attribute. typestate:tableofattributeffullgkeys(*); 210AppendixC.PredenedModule {{attributename<strong>and</strong>alistofobjectsthataretheparametersofthe attribute:record( {{canalsonameauser-denedattribute,orconstraint.The'full' );objects:objectnames {{Therearethreebuilt-inattributes:init<strong>and</strong>case.Anattribute {{bedroppedfromthislistatsomefuturetime. {{attributeisanabbreviationforseveralinitattributes,<strong>and</strong>may name:attributename,<br />
attributetype:enumeration('initialized','case','constraint','full'); attributename:variantofattributetype(<br />
{{tosomevariable(notnecessarilyarootobject)dependingon );'full'->full:emptyfg {{Aformaltypestateislikeatypestate,butnorootvariableis {{mentioned.Instead,thecomponentlistsareinterpretedrelative 'case'->case:emptyfg, 'initialized'->init:emptyfg,<br />
{{itself,ratherthananyofits(sub-)components. {{context.Anemptycomponentlistindicatestheassociatedvariable 'constraint'->constraint:constraintnameffullg,<br />
);parameters:formalobjectlist formalobjectlist:orderedtableofcomponentlistffullg; formalattribute:record( formaltypestate:tableofformalattributeffullgkeys(*);<br />
enddefinitions attributename:attributename,
[ASU88]AlfredV.Aho,RaviSethi,<strong>and</strong>JereyD.Ullman.Compilers: C.1<strong>Reference</strong>s [Ada83]Ada.<strong>Reference</strong><strong>Manual</strong>fortheAdaProgrammingLanguage. Principles,Techniques<strong>and</strong>Tools.Addison-Wesley,1988. UnitedStatesDepartmentofDefense,1983. AppendixC.PredenedModule211<br />
[BS90]DavidF.Bacon<strong>and</strong>RobertE.Strom.Optimisticparallelization [AU77]AlfredV.Aho<strong>and</strong>JereyD.Ullman.PrinciplesofCompiler [BS89]DavidF.Bacon<strong>and</strong>RobertE.Strom.Implementingthehermes T.J.WatsonResearchCenter,1990. ofcommunicatingsequentialprocesses.ResearchNoteRC,<strong>IBM</strong> ResearchCenter,1989. processmodel.TechnicalReportRC14518,<strong>IBM</strong>T.J.Watson Design.Addison-Wesley,1977.<br />
[GJ87]ArthurP.Goldberg<strong>and</strong>DavidJeerson.Transparentprocess [FBSY87]KeithFeibusch,DavidF.Bacon,RobertE.Strom,<strong>and</strong> [Coo83]DougCooper.St<strong>and</strong>ardPascalUser<strong>Reference</strong><strong>Manual</strong>.W.W. T.J.WatsonResearchCenter,1987. face:Optimisticrecoveryfordiskstorage.Technicalreport,<strong>IBM</strong> Norton,1983.<br />
Processing,pages728{734,1987. cloning:Atoolforloadmanagementofdistributedprograms. InProceedingsofthe1987InternationalConferenceonParallel ShaulaAlex<strong>and</strong>erYemini.Checkpointmanagementdiskinter-<br />
[Jef85]DavidJeerson.Virtualtime.ACMTransactionsonProgrammingLanguages<strong>and</strong>Systems,7(3):404,July1985.<br />
[KP84]BrianW.Kernighan<strong>and</strong>RobPike.TheUNIXProgramming [KR78]BrianW.Kernighan<strong>and</strong>DennisM.Ritchie.TheCProgrammingLanguage.Prentice-HallSoftwareSeries,1978.<br />
232{247.ACM,August1988. glishLanguage.HoughtonMiinCompany,1980. [Mor80]WilliamMorris.TheAmericanHeritageDictionaryoftheEn-<br />
[NS88]VanL.Nguyen<strong>and</strong>RobertE.Strom.Processsemantics:global Environment.Prentice-HallSoftwareSeries,1984.<br />
ACMSymposiumonPrinciplesofDistributedComputing,pages axioms,compositionalrules,<strong>and</strong>applications.InProc.Seventh
212C.1.<strong>Reference</strong>s<br />
[SBY88]RobertE.Strom,DavidF.Bacon,<strong>and</strong>ShaulaAlex<strong>and</strong>erYem-<br />
[SBY87]RobertE.Strom,DavidF.Bacon,<strong>and</strong>ShaulaAlex<strong>and</strong>erYem-<br />
[PS83]FrancisN.Parr<strong>and</strong>RobertE.Strom.NIL:Ahigh-levellansearchNoteRC13373,<strong>IBM</strong>T.J.WatsonResearchCenter,1987ini.Volatilelogginginn-fault-tolerantdistributedsystems.Renal,22(1-2),1983guagefordistributedsystemsprogramming.<strong>IBM</strong>SystemsJour-<br />
[SY83]RobertE.Strom<strong>and</strong>ShaulaAlex<strong>and</strong>erYemini.NIL:Anintegratedlanguage<strong>and</strong>systemfordistributedprogramming.In<br />
[Str86]RobertE.Strom.Acomparisonoftheobject-oriented<strong>and</strong> process-orientedparadigms.In<strong>IBM</strong>/BrownWorkshopon 1986. TolerantComputing:DigestofPapers,pages44{49,June1988. Object-OrientedProgramming.ACM,SIGPLANNotices,June InTheEighteenthAnnualInternationalSymposiumonFault-<br />
[SY84]RobertE.Strom<strong>and</strong>ShaulaAlex<strong>and</strong>erYemini.Optimistic onFault-TolerantComputing.IEEEComputerSociety,1984. tributedsystems.InTheFourteenthInternationalSymposium recovery:Anasynchronousapproachtofault-toleranceindis-<br />
SoftwareSystems,June1983. SIGPLAN'83SymposiumonProgrammingLanguageIssuesin<br />
[SY86]RobertE.Strom<strong>and</strong>ShaulaAlex<strong>and</strong>erYemini.Typestate:A [SY85]RobertE.Strom<strong>and</strong>ShaulaAlex<strong>and</strong>erYemini.Optimisticrecoveryindistributedsystems.ACMTransactionsonComputer<br />
Systems,3(3):204{226,August1985. ity.IEEETransactionsonSoftwareEngineering,SE-12(1):157{ programminglanguageconceptforenhancingsoftwarereliabil-<br />
[SY89]RobertE.Strom<strong>and</strong>DanielM.Yellin.Computationally [SY87]RobertE.Strom<strong>and</strong>ShaulaAlex<strong>and</strong>erYemini.Synthesizing 171,January1986.<br />
tractablesemilatticesforglobaldataowanalysis.Technical puterSciencePress,1987. distributed<strong>and</strong>parallelprogramsthroughoptimistictransfor-<br />
ReportRC14936,<strong>IBM</strong>T.J.WatsonResearchCenter,August mations.InYechiamYemini,editor,CurrentAdvancesinDis-<br />
1989. tributedComputing<strong>and</strong>Communications,pages234{256.Com-
[SYB87a]RobertE.Strom,ShaulaAlex<strong>and</strong>erYemini,<strong>and</strong>DavidF.Ba-<br />
[SY90]RobertE.Strom<strong>and</strong>DanielM.Yellin.Extendingtypestate con.Alinguistictreatmentofprogramsastypedobjects.Re-<br />
searchNoteRC13325,<strong>IBM</strong>T.J.WatsonResearchCenter,1987. checkingusingconditionallivenessanalysis.TechnicalReport RC15398,<strong>IBM</strong>T.J.WatsonResearchCenter,January1990. AppendixC.PredenedModule213<br />
[SYB87b]RobertE.Strom,ShaulaAlex<strong>and</strong>erYemini,<strong>and</strong>DavidF.Ba-<br />
[SYB87d]RobertE.Strom,ShaulaAlex<strong>and</strong>erYemini,<strong>and</strong>DavidF.Bacon.Towardself-recoveringoperatingsystems.InHaroldLorincon.Towardself-recoveringoperatingsystems.InTheInternadivisionalTechnicalLiaison,<strong>IBM</strong>Corporation,February1987.<br />
[SYB87c]RobertE.Strom,ShaulaAlex<strong>and</strong>erYemini,<strong>and</strong>DavidF.Bacon.Programsasobjects.InH.N.Cooper,editor,<strong>IBM</strong>ProgrammingLanguageTechnologyITL,pages187{195.<strong>IBM</strong>Inter-<br />
editor,The<strong>IBM</strong>/SRISymposiumonOperatingSystems:Trends tionalConferenceonParallelProcessing.North-Holl<strong>and</strong>,1987.<br />
[SYW85]RobertE.Strom,ShaulaA.Yemini,<strong>and</strong>PeterWegner.Viewing [SYB88]RobertE.Strom,ShaulaAlex<strong>and</strong>erYemini,<strong>and</strong>DavidF.Ba-<br />
<strong>and</strong>IssuesinOperatingSystems,pages221{233.<strong>IBM</strong>Systems<br />
ingsoftheInternationalAdaConference,Paris,France,1985. ferenceonSystemSciences.IEEECS,1988. Adafromaprocessmodelperspective.InAdainUse:Proceedcon.Arecoverableobjectstore.InHawaiiInternationalCon-<br />
ResearchInstitute,<strong>IBM</strong>Corporation,1987.<br />
[YSB87]ShaulaAlex<strong>and</strong>erYemini,RobertE.Strom,<strong>and</strong>DavidF.Bacon.Improvingdistributedprotocolsbydecouplingrecovery<br />
WatsonResearchCenter,1987. fromconcurrencycontrol.ResearchNoteRC13326,<strong>IBM</strong>T.J.
Index<br />
--,73<br />
:=,94<br />
AppendixC.PredenedModule215<br />
coercion,88,89<br />
coercionoperations,57<br />
comment,73<br />
comparison,94,125<br />
ofrecords,107<br />
ofvariants,115<br />
componentname<br />
resolutionof,77<br />
components,107<br />
concatenate,109<br />
connect,14,121<br />
constant,88<br />
constant,22<br />
constantcopy,88,112,113,119,<br />
127<br />
constraint,131<br />
ConstraintErrorexception,132<br />
ConstraintFailureexception,132<br />
conversion<strong>and</strong>resolution,72<br />
convertoperator,106<br />
copyof,29<br />
copyingavalue,94<br />
create,124<br />
createof,15,16,24<br />
currentprogram,129<br />
deadcode,91<br />
declaration,18,19<br />
hidingnotallowed,20<br />
declarationslist,76<br />
denition,18<br />
denitionsmodule,21,77<br />
denitionsmodules,19<br />
Depletionexception,95<br />
discard,57,95,95<br />
Discardedexception,29,119,123<br />
discardedexceptions,78<br />
Disconnectedexception,29,99,<br />
122,123<br />
dissolve,116<br />
DivideByZeroexception,104<br />
DuplicateKeyexception,43,48,<br />
111,112<br />
element,107<br />
elementtype,107<br />
else,97<br />
empty,61,120<br />
enabledclause,99<br />
entrytypestate,118<br />
enumerationtypefamily,102<br />
evaluate,seeexpressionblock<br />
eventguard,26,98<br />
every,110<br />
everyof,42<br />
exception,11,119,122<br />
denition,22<br />
h<strong>and</strong>ler,11,96<br />
nameresolution,78<br />
return,123<br />
exists,110<br />
existsof,48<br />
exitnameresolution,79<br />
exit,79,88,123<br />
exit,101<br />
exitformaltypestate,119<br />
exittypestate,24<br />
expressionblock,59,88,100{101<br />
extract,42,111<br />
fairness<br />
inreceivestatement,122<br />
inselectstatement,99<br />
lterprogram,12<br />
forenumerate,106<br />
forstatement,46<br />
for-inspect,113<br />
forall,110<br />
formaltypestate,86<br />
full,23,78,85<br />
function<br />
call,121<br />
functioncall,122<br />
functionnotation,12<br />
generator<br />
process,125<br />
generatorprocess,125<br />
guard,98
216C.1.<strong>Reference</strong>s<br />
guardedselect,26<br />
h<strong>and</strong>lerclause,79,96<br />
<strong>Hermes</strong>,3{5<br />
researchdirections,67<br />
typesystem,55<br />
hide,117<br />
hidestatement,63<br />
Hoare,C.A.R.,55<br />
identiers,74<br />
if,97<br />
importslist,19,78<br />
inferencefunction<br />
elementtypeof,151<br />
sameas,152<br />
inferencerule,151<br />
inferencerules,21,80<br />
inferreddeclaration,81<br />
init,23,78,84{86<br />
init(),56<br />
initializationport,8,19<br />
inport,118<br />
inputport,8,22,94,118,119<br />
aseventguard,98<br />
denition,23,24<br />
enabled,26<br />
insert,29,111,111<br />
insert-at,111<br />
inspect,46,112<br />
inspectvariable,112<br />
integerliterals,50<br />
integertypefamily,103<br />
interface,11,22,60<br />
denition,22,24<br />
InterfaceMismatchexception,17,<br />
124,124<br />
key,108,110{112<br />
keys(),43<br />
keyword,74<br />
latebinding,5<br />
lexicalanalysis,71<br />
linkinglist,51,79<br />
literal<br />
named,73<br />
numeric,73<br />
real,73<br />
string,73<br />
literals,104<br />
long-livedsystems,55<br />
mainclause,96<br />
mainprogram,124<br />
meet,89<br />
merge,112<br />
merge-at,112<br />
messagetype,118<br />
minimumformaltypestate,119<br />
default,119<br />
minimumtypestate,87<br />
mod,104<br />
module,4<br />
move,93<br />
movingavalue,93<br />
movingversuscopying,29,93<br />
nameequivalenceoftypedenitions,24<br />
namespace,75,78<br />
ofbasevariables,76<br />
ofcomponentnames,77<br />
oftypeidentiers,77<br />
ofuser-denedexceptionnames,<br />
78<br />
namedliteral,73<br />
new,14,107,119,120<br />
nominaltypefamily,101,105<br />
normalexit,96<br />
not,105<br />
notation<br />
association,121<br />
function,121<br />
positional,121<br />
NotFoundexception,42,110{112<br />
numericliteral,73<br />
object-orientedlanguages,27<br />
occurrence<br />
applied,72
AppendixC.PredenedModule217<br />
dening,72<br />
on(others),50<br />
on(others),96<br />
operatingsystem,4<br />
or,105<br />
ordered<br />
tableoperations,29<br />
ordered,108<br />
orderedtable,28<br />
orderedtable,28<br />
others,96<br />
otherwise,27<br />
outcome,88<br />
outport,119<br />
outputport,8,22,119<br />
denition,24<br />
overlap,121<br />
parent,8<br />
passingparametersbyvalue-result,<br />
12<br />
pointers,prohibited,4<br />
polymorph,94<br />
polymorph,64<br />
polymorphtypefamily,125<br />
polymorphictypes,none,18<br />
PolymorphMismatchexception,66,<br />
126,127<br />
position,41<br />
positioninatable,28,110{112<br />
position-of-element,92<br />
position-of-element,113,114<br />
position-of-selector,114<br />
position-of-selector,42<br />
postcondition,89<br />
postconditionfunction,90<br />
precondition,88<br />
predened,19,75<br />
charactertype,102<br />
predefined,19,78<br />
predenedexceptions<br />
DivideByZero,104<br />
predefined!boolean,97<br />
predefined!program,51<br />
procedure,40<br />
procedure,125<br />
procedureof,40<br />
procedures,40<br />
process,4<br />
communication,12{17<br />
module,8<br />
name,79<br />
termination,29<br />
process,19<br />
block,96<br />
program,15<br />
checked,23<br />
program,15<br />
programliteral,50<br />
programvalue,71,80<br />
punctuation,73,74<br />
qualier,80,81<br />
RangeErrorexception,29,106,111,<br />
112<br />
realliteral,73<br />
typefamily,103<br />
realarithmetic,103<br />
receive,5,9,123<br />
record,107<br />
recorddenition,43<br />
rem,104<br />
remove,29,42,111<br />
repeatclause,97<br />
reservedwords,74<br />
resolution,75<br />
ofbasevariables,76<br />
ofcomponentnames,77<br />
oftypenames,77<br />
resultvariable,100<br />
return,5,9,24,123<br />
exception,78<br />
reveal,63,117<br />
safenumber,103<br />
safenumbers,103<br />
scalartypefamilies,101<br />
scope,76,80
218C.1.<strong>Reference</strong>s<br />
ofelementvariable,109<br />
ofinspectvariable,112<br />
security,55<br />
selectnofairchoice,99<br />
select,26<br />
abbreviation,40<br />
select,98{100<br />
selector,41,91,109<br />
expression,109<br />
long,109<br />
mapping,109<br />
semilattice,57,84<br />
meet,57<br />
send,118,124<br />
sendstatement,60<br />
server,9<br />
serverprocess,25<br />
shareddata,prohibited,4<br />
shell,9<br />
sizeof,26,114<br />
space,73<br />
stringliteral,50,73,109<br />
syntax<br />
analysis,71<br />
systemsprogramming,12<br />
table,28<br />
new,109<br />
comparison,108<br />
elementtypestate,108<br />
insert,29<br />
insertat,29<br />
operations,28<br />
representationindependent,28<br />
typefamily,107<br />
unordered,43<br />
table[expr],42<br />
table[key],43<br />
the-element,42,110<br />
tokens,73<br />
typechecking,8,9,17,18,72,80{<br />
82,150{153<br />
denition,22,77<br />
families,8<br />
inference,72,80{82<br />
inferencerules,55<br />
inferencing,150{153<br />
name,19<br />
specier,21<br />
type,127<br />
typename,77<br />
resolution,77<br />
typespecier,81,82,83<br />
o,104<br />
typestate,22<br />
caseattribute,62<br />
attributes,23,56,78,84{85<br />
checking,9,17,24,56,72,<br />
84{92,150{153<br />
checkingalgorithm,90<br />
checkingexample,89<br />
coercions,87<br />
constraintattributes,85<br />
entry,23,24<br />
errors,91{92<br />
exit,23<br />
exitformal,119<br />
formal,85{86<br />
initialization,23<br />
minimumformal,119<br />
postcondition,90<br />
postconditionrules,152<br />
preconditionfunction,89<br />
preconditionrules,152,155<br />
semilattice,84<br />
semilatticemeet,87<br />
syntax,84{85<br />
valid,86<br />
typestate,127<br />
Uncopyableexception,64,94<br />
unique,105<br />
unite,116<br />
unitestatement,62<br />
unwrap,66,126<br />
unwrapstatement,84<br />
usinglist,19
variablename discarded,29<br />
variant,61 overlap,121 temporary,122 nalized,29<br />
hidden,61 nameresolution,75{77<br />
revealed,61 basevariable,75 componentname,75 formal,86 typefamily,115<br />
windowsystem,31 while,97{98 while,10 where,109 whereexpression,41 where('true'),47 visibility,75 typestate,86<br />
wrappedvalue,125 wrapper,125 word,73,74 wrap,66,125<br />
AppendixC.PredenedModule219