BerkeleyPascalPXImplementationNotes Version2.0−−January,1979 WilliamN.Joy† M.KirkMcKusick‡ ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,California94720 ABSTRACT BerkeleyPascalisdesignedforinteractiveinstructionaluseandrunsonthe VAX11/780.TheinterpreterpxexecutesthePascalbinariesgeneratedbythePascaltranslatorpi. ThePXImplementationNotesdescribethegeneralorganizationofpx, detailthevariousoperationsoftheinterpreter,anddescribethefileinput/output structure.Conclusionsaregivenontheviabilityofaninterpreterbasedapproach tolanguageimplementationforaninstructionalenvironment. 9April1993 BerkeleyPascalPXImplementationNotes Version2.0−−January,1979 WilliamN.Joy† M.KirkMcKusick‡ ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,California94720 Introduction ThesePXImplementationNoteshavebeenupdatedfromtheoriginalPDP11/70implementationnotestoreflecttheinterpreterthatrunsontheVAX11/780.Thesenotesconsistoffour majorparts.Thefirstpartoutlinesthegeneralorganizationofpx.Section2describestheoperations(instructions)oftheinterpreterwhilesection3focusesoninput/outputrelatedactivity.A finalsectiongivesconclusionsabouttheviabilityofaninterpreterbasedapproachtolanguage implementationforinstruction. RelatedBerkeleyPascaldocuments ThePXPImplementationNotesgivedetailsoftheinternalsoftheexecutionprofilerpxp; partsoftheinterpreterrelatedtopxparediscussedinsection2.10.ApaperdescribingthesyntacticerrorrecoverymechanismusedinpiwaspresentedattheACMConferenceonCompiler ConstructioninBoulderColoradoinAugust,1979. Acknowledgements ThisversionofpxisaPDP11/70toVAX11/780opcodemappingoftheoriginalpxthatwas designedandimplementedbyKenThompson,withextensivemodificationsandadditionsby WilliamJoyandCharlesHaley.Withouttheirwork,thisBerkeleyPascalsystemwouldnever haveexisted.ThesenoteswerefirstwrittenbyWilliamJoyforthePDP11/70implementation. WewouldalsoliketothankourfacultyadvisorSusanL.Grahamforherencouragement,her helpfulcommentsandsuggestionsrelatingtoBerkeleyPascalandherexcellenteditorialassistance. †ThefinancialsupportoftheNationalScienceFoundationundergrantsMCS74-07644-A03and MCS78-07291andofanIBMGraduateFellowshiparegratefullyacknowledged. ‡ThefinancialsupportofaHowardHughesGraduateFellowshipisgratefullyacknowledged.

-2-1.Organization MostofpxiswrittenintheVAX11/780assemblylanguage,usingtheUNIX◯rassembleras. PortionsofpxarealsowrittenintheUNIXsystemsprogramminglanguageC.Pxconsistsofa mainprocedurethatreadsintheinterpretercode,amaininterpreterloopthattransferssuccessivelytovariouscodesegmentsimplementingtheabstractmachineoperations,built-inprocedures andfunctions,andseveralroutinesthatsupporttheimplementationofthePascalinput-output environment. TheinterpreterrunsatafractionofthespeedofequivalentcompiledCcode,withthisfractionvaryingfrom1/5to1/15.Theinterpreteroccupies18.5Kbytesofinstructionspace,shared amongallprocessesexecutingPascal,andhas4.6Kbytesofdataspace(constants,errormessages, etc.)acopyofwhichisallocatedtoeachexecutingprocess. 1.1.Formatoftheobjectfile PxnormallyinterpretsthecodeleftinanobjectfilebyarunofthePascaltranslatorpi. Thefilewherethetranslatorputstheobjectoriginally,andthemostcommonlyinterpretedfile,is calledobj.Inorderthatallpersonsusingpxshareacommontextimage,thisexecutablefileisa smallprocessthatcoordinateswiththeinterpretertostartexecution.Theinterpretercodeis placedattheendofaspecial‘‘header’’fileandthesizeoftheinitializeddataareaofthisheader fileisexpandedtoincludethiscode,sothatduringexecutionitislocatedataneasilydetermined addressinitsdataspace.Whenexecuted,theobjectprocesscreatesapipe,createsanotherprocessbydoingafork,andarrangesthattheresultingparentprocessbecomesaninstanceofpx. Thechildprocessthenwritestheinterpretercodethroughthepipethatithastotheinterpreter processparent.Whenthisprocessiscomplete,thechildexits. Therealadvantageofthisapproachisthatitdoesnotrequiremodificationstotheshell, andthattheresultantobjectsare‘‘trueobjects’’notrequiringspecialtreatment.Asimplermechanismwouldbetodeterminethenameofthefilethatwasexecutedandpassthistotheinterpreter.Howeveritisnotpossibletodeterminethisnameinallcases.‡ 1.2.Generalfeaturesofobjectcode Pascalobjectcodeisrelocatableasalladdressingreferencesforcontroltransferswithinthe codearerelative.Thecodeconsistsofinstructionsinterspersedwithinlinedata.Allinstructions havealengththatisanevennumberofbytes.Novariablesarekeptintheobjectcodearea. ThefirstbyteofaPascalinterpreterinstructioncontainsanoperationcode.Thisallowsa totalof256majoroperationcodes,and232oftheseareinuseinthecurrentpx.Thesecondbyte ofeachinterpreterinstructioniscalledthe‘‘sub-operationcode’’,ormorecommonlythesub-opcode.Itcontainsasmallintegerthatmay,forexample,beusedasablock-structurelevelfor theassociatedoperation.Iftheinstructioncantakealongwordconstant,thisconstantisoften packedintothesub-opcodeifitfitsinto8bitsandisnotzero.Asub-opcodevalueofzerospeci-fiesthattheconstantwouldnotfitandthereforefollowsinthenextword.Thisisaspaceopti-mization,thevalueofzeroforflaggingthelongercasebeingconvenientbecauseitiseasytotest. Otherinstructionformatsareused.Thebranchinginstructionstakeanoffsetinthefollowingword,operatorsthatloadconstantsontothestacktakearbitrarilylonginlineconstantvalues, andmanyoperationsdealexclusivelywithdataontheinterpreterstack,requiringnoinlinedata. ‡Forinstance,ifthepxrefprogramisplacedinthedirectory‘/usr/bin’thenwhentheusertypes ‘‘pxrefprogram.p’’thefirstargumenttotheprogram,nominallytheprogramsname,is‘‘pxref.’’ Whileitwouldbepossibletosearchinthestandardplace,i.e.thecurrentdirectory,andthesystem directories‘/bin’and‘/usr/bin’foracorrespondingobjectfile,thiswouldbeexpensiveandnotguaranteedtosucceed.Severalshellsexistthatallowotherdirectoriestobesearchedforcommands,and thereis,ingeneral,nowaytodeterminewhatthesedirectoriesare.

-3-1.3.Stackstructureoftheinterpreter Theinterpreteremulatesastack-structuredPascalmachine.The‘‘load’’instructionsput valuesontothestack,whereallarithmeticoperationstakeplace.The‘‘store’’instructionstake valuesoffthestackandplacetheminanaddressthatisalsocontainedonthestack.Theonly waytomovedataortocomputeinthemachineiswiththestack. Tomaketheinterpreteroperationsmorepowerfulandtotherebyincreasetheinterpreter speed,thearithmeticoperationsintheinterpreterare‘‘typed’’.Thatis,lengthconversionof arithmeticvaluesoccurswhentheyareusedinanoperation.Thiseliminatesinterpretercycles forlengthconversionandtheassociatedoverhead.Forexample,whenaddinganintegerthatfits inonebytetoonethatrequiresfourbytestostore,no‘‘conversion’’operatorsarerequired.The onebyteintegerisloadedontothestack,followedbythefourbyteinteger,andthenanadding operatorisusedthathas,implicitinitsdefinition,thesizesofthearguments. 1.4.Datatypesintheinterpreter Theinterpreterdealswithseveraldifferentfundamentaldatatypes.Inthememoryofthe machine,1,2,and4byteintegersaresupported,withonly2and4byteintegersbeingpresenton thestack.Theinterpreteralwaysconvertsto4byteintegerswhenthereisapossibilityofoverflowingtheshorterformats.ThiscorrespondstothePascallanguagedefinitionofoverflowin arithmeticoperationsthatrequiresthattheresultbecorrectifallpartialvaluesliewithinthe boundsofthebaseintegertype:4byteintegervalues. Characterconstantsaretreatedsimilarlyto1byteintegersformostpurposes,asare Booleanvalues.Allenumeratedtypesaretreatedasintegervaluesofanappropriatelength,usually1byte.Theinterpreteralsohasrealnumbers,occupying8bytesofstorage,andsetsand stringsofvaryinglength.Theappropriateoperationsareincludedforeachdatatype,suchasset unionandintersectionandanoperationtowriteastring. Nospecialpackeddataformatsaresupportedbytheinterpreter.Thesmallestunitofstorageoccupiedbyanyvariableisonebyte.Thebuilt-inspackandunpackthusdegeneratetosimple memorytomemorytransferswithnospecialprocessing. 1.5.Runtimeenvironment Theinterpreterruntimeenvironmentusesastackdataareaandaheapdataarea,thatare keptatoppositeendsofmemoryandgrowtowardseachother.Allglobalvariablesandvariables localtoproceduresandfunctionsarekeptinthestackarea.Dynamicallyallocatedvariablesand buffersforinput/outputareallocatedintheheap. Theaddressingofblockstructuredvariablesisdonebyusingafixeddisplaythatcontains theaddressofitsstackframeforeachstaticallyactiveblock.†Thisdisplayisreferencedby instructionsthatloadandstorevariablesandmaintainedbytheoperationsforblockentryand exit,andfornon-localgotostatements. 1.6.Dp,lc,loop Three‘‘global’’variablesintheinterpreter,inadditiontothe‘‘display’’,arethedp,lc,and theloop.Thedpisapointertothedisplayentryforthecurrentblock;thelcistheabstract machinelocationcounter;andtheloopisaregisterthatholdstheaddressofthemaininterpreter loopsothatreturningtothelooptofetchthenextinstructionisafastoperation. 1.7.Thestackframestructure Eachactiveblockhasastackframeconsistingofthreeparts:ablockmark,localvariables, andtemporarystorageforpartiallyevaluatedexpressions.Thestackintheinterpretergrows fromthehighaddressesinmemorytothelowaddresses,sothatthosepartsofthestackframe thatare‘‘onthetop’’ofthestackhavethemostnegativeoffsetsfromthedisplayentryforthe †Here‘‘block’’isbeingusedtomeananyprocedure,functionorthemainprogram.

-4-block.ThemajorpartsofthestackframearerepresentedinFigure1.1. Baseofstackframe BlockmarkPositiveoffsets ←Displayentrypointshere Local variables Negativeoffsets Temporary expression space Topofstackframe Figure1.1−Structureofstackframe Notethatthelocalvariablesofeachblockhavenegativeoffsetsfromthecorrespondingdisplay entry,the‘‘first’’localvariablehavingoffset‘−2’. 1.8.Theblockmark Theblockmarkcontainsthesavedinformationnecessarytorestoretheenvironmentwhen thecurrentblockexits.Itconsistsoftwoparts.Thefirstandtop-mostpartissavedbytheCALL instructionintheinterpreter.Thisinformationisnotpresentforthemainprogramasitisnever ‘‘called’’.ThesecondpartoftheblockmarkiscreatedbytheBEGbeginblockoperatorthatalso allocatesandclearsthelocalvariablestorage.TheformatoftheseblocksisrepresentedinFigure 1.2. ThedatasavedbytheCALLoperatorincludesthelinenumberlinoofthepointofcall,that isprintediftheprogramexecutionendsabnormally;thelocationcounterlcgivingthereturn address;andthecurrentdisplayentryaddressdpatthetimeofcall. TheBEGbeginoperatorsavesthepreviousdisplaycontentsatthelevelofthisblock,sothat thedisplaycanberestoredonblockexit.Apointertothebeginninglinenumberandthename ofthisblockisalsosaved.Thisinformationisstoredintheinterpreterobjectcodein-lineafter theBEGoperator.Itisusedinprintingapost-mortembacktrace.Thesavedfilenameandbuffer referencearenecessarybecauseoftheinput/outputstructure(thisisdiscussedindetailinsections3.3and3.4).Thetopofstackreferencegivesthevaluethestackpointershouldhavewhen therearenoexpressiontemporariesonthestack.ItisusedforaconsistencycheckintheLINO linenumberoperatorsintheinterpreter,thatoccursbeforeeachstatementexecuted.Thishelps tocatchbugsintheinterpreter,thatoftenmanifestthemselvesbyleavingthestacknon-empty betweenstatements. Notethatthereisnoexplicitstaticlinkhere.Thustosetupthedisplaycorrectlyaftera non-localgotostatementonemust‘‘unwind’’throughalltheblockmarksonthestacktorebuild thedisplay. 1.9.Argumentsandreturnvalues Afunctionreturnsitsvalueintoaspacereservedbythecallingblock.Argumentstoa functionareplacedontopofthisreturnarea.Forbothprocedureandfunctioncalls, -5-CreatedbyCALL Savedlino Savedlc Saveddp CreatedbyBEG Saveddpcontents Pointertocurrent entrylineand sectionname Currentfilename andbuffer Topofstackreference Figure1.2−Blockmarkstructure argumentsareplacedattheendoftheexpressionevaluationareaofthecaller.Whenafunction completes,expressionevaluationcancontinueafterpoppingtheargumentstothefunctionoff thestack,exactlyasifthefunctionvaluehadbeen‘‘loaded’’.Theargumentstoaprocedureare alsopoppedoffthestackbythecallerafteritsexecutionends. Asasimpleexampleconsiderthefollowingstackstructureforacalltoafunctionf,ofthe form‘‘f(a)’’. Spacefor valuereturned fromf Valueofa BlockMark Figure1.3−Stackstructureonfunctioncall‘f(a)’ Ifwesupposethatfreturnsarealandthataisaninteger,thecallingsequenceforthis functionwouldbe: PUSH−8 RV4:la CALL:lf POP4 HereweusetheoperatorPUSHtoclearspaceforthereturnvalue,loadaonthestackwitha ‘‘rightvalue’’operator,callthefunction,popofftheargumenta,andcanthencompleteevaluationofthecontainingexpression.Theoperationsusedherewillbeexplainedinsection2.

-6-Ifthefunctionfweregivenby 10functionf(i:integer):real; 11begin 12f:=i 13end; thenfwouldhavecodesequence: BEG:20 11

"f"

LV:l40 RV4:l32 AS48 END HeretheBEGoperatortakes9bytesofinlinedata.Thefirstbytespecifiesthelengthofthe functionname.Thesecondlongwordspecifiestheamountoflocalvariablestorage,herenone. Thesucceedingtwolinesgivethelinenumberofthebeginandthenameoftheblockforerror traceback.TheBEGoperatorplacesanamepointerintheblockmark.ThebodyofthefunctionfirsttakesanaddressofthefunctionresultvariablefusingtheaddressofoperatorLVa. Thenextoperationintheinterpretationofthisfunctionistheloadingofthevalueofi.Iisat thelevelofthefunctionf,heresymbolicallyl,andthefirstvariableinthelocalvariablearea. Thefunctioncompletesbyassigningthe4byteintegeronthestacktothe8bytereturnlocation,hencetheAS48assignmentoperator,andthenusestheENDoperatortoexitthecurrent block. 1.10.Themaininterpreterloop Themaininterpreterloopissimply: iloop: caseb(lc)+,$0,$255 <tableofopcodeinterpreteraddresses> Themainopcodeisextractedfromthefirstbyteoftheinstructionandusedtoindexinto thetableofopcodeinterpreteraddresses.Controlisthentransferredtothespecifiedlocation. Thesub-opcodemaybeusedtoindexthedisplay,asasmallconstant,ortospecifyoneofseveral relationaloperators.Inthecaseswhereaconstantisneeded,butitisnotsmallenoughtofitin thebytesub-operator,azeroisplacedthereandtheconstantfollowsinthenextword.Zerois easilytestedfor,astheinstructionthatfetchesthesub-opcodesetstheconditioncodeflags.A constructionlike: OPER: cvtbl(lc)+,r0 bneqL1 cvtwl(lc)+,r0 L1:... isallthatisneededtoeffectthispackingofdata.ThistechniquesavesspaceinthePascalobj objectcode. Theaddressoftheinstructionatiloopisalwayscontainedintheregistervariableloop. Thusareturntothemaininterpreterissimply: jmp(loop) thatisbothquickandoccupieslittlespace.

-7-1.11.Errors Errorsduringinterpretationfallintothreeclasses: 1)Interpreterdetectederrors. 2)Hardwaredetectederrors. 3)Externalevents. InterpreterdetectederrorsincludeI/Oerrorsandbuilt-infunctionerrors.Theseerrors causeasubroutinecalltoanerrorroutinewithasingleparameterindicatingthecauseofthe error.Hardwareerrorssuchasrangeerrorsandoverflowsarefieldedbyaspecialroutinethat determinestheopcodethatcausedtheerror.Itthencallstheerrorroutinewithanappropriate errorparameter.Externaleventsincludeinterruptsandsystemlimitssuchasavailablememory. Theygenerateacalltotheerrorroutinewithanappropriateerrorcode.Theerrorroutineprocessestheerrorcondition,printinganappropriateerrormessageandusuallyabacktracefromthe pointoftheerror. 2.Operations 2.1.Namingconventionsandoperationsummary Table2.1outlinestheopcodetypingconvention.Theexpression‘‘aaboveb’’meansthat‘a’ isontopofthestackwith‘b’belowit.Table2.3describeseachoftheopcodes.Thecharacter ‘∗’attheendofanamespecifiesthatalloperationswiththerootprefixbeforethe‘∗’aresummarizedbyoneentry.Table2.2givesthecodesusedtodescribethetypeinlinedataexpectedby eachinstruction.

-8-Table2.1−OperatorSuffixes Unaryoperatorsuffixes SuffixExampleArgumenttype 2NEG2Shortinteger(2bytes) 4SQR4Longinteger(4bytes) 8ABS8Real(8bytes) Binaryoperatorsuffixes SuffixExampleArgumenttype 2ADD2Twoshortintegers 24MUL24Shortabovelonginteger 42REL42Longaboveshortinteger 4DIV4Twolongintegers 28DVD28Shortintegerabovereal 48REL48Longintegerabovereal 82SUB82Realaboveshortinteger 84MUL84Realabovelonginteger 8ADD8Tworeals OtherSuffixes SuffixExampleArgumenttypes TADDTSets GRELGStrings Table2.2−Inlinedatatypecodes Code Description a Anaddressoffsetisgiveninthewordfollowingthe instruction. A Anaddressoffsetisgiveninthefourbytesfollowingtheinstruction. l Anindexintothedisplay isgiveninthesub-opcode. r Arelationaloperatorisencodedinthesub-opcode.(seesection2.3) s Asmallintegeris placedinthesub-opcode,orinthenextword ifitiszeroortoolarge. v Variablelengthinlinedata. w Awordvalueinthefollowingword. W Alongvalueinthefollowingfourbytes.

"

Aninlineconstantstring.

-9-Table2.3−Machineoperations MnemonicReferenceDescription ABS∗2.7Absolutevalue ADD∗2.7Addition AND2.4Booleanand ARGC2.14Returnsnumberofargumentstocurrentprocess ARGV2.14Copyspecifiedprocessargumentintochararray AS∗2.5Assignmentoperators ASRT2.12Asserttruetocontinue ATAN2.13Returnsarctangentofargument BEGs,W,w,"2.2,1.8Writesecondpartofblockmark,enterblock BUFF3.11Specifybufferingforfile"output" CALLl,A2.2,1.8Procedureorfunctioncall CARDs2.11Cardinalityofset CASEOP∗2.9Casestatements CHR∗2.15Returnsintegertoasciimappingofargument CLCK2.14Returnsusertimeofprogram CON∗v2.5Loadconstantoperators COS2.13Returnscosofargument COUNTw2.10Countastatementcountpoint CTTOTs,w,w2.11Constructset DATE2.14Copydateintochararray DEFNAME3.11Attachfilenameforprogramstatementfiles DISPOSE2.15Disposeofaheapallocation DIV∗2.7Fixeddivision DVD∗2.7Floatingdivision END2.2,1.8Endblockexecution EOF3.10Returnstrueifendoffile EOLN3.10Returnstrueifendoflineoninputtextfile EXP2.13Returnsexponentialofargument EXPO2.13Returnsmachinerepresentationofrealexponent FILE3.9Pushdescriptorforactivefile FLUSH3.11Flushafile FNIL3.7Checkfileinitialized,noteof,synced FOR∗a2.12Forstatements GET3.7Getnextrecordfromafile GOTOl,A2.2,1.8Non-localgotostatement HALT2.2Producecontrolflowbacktrace IFa2.3Conditionaltransfer INs,w,w2.11Setmembership INCT2.11Membershipinaconstructedset IND∗2.6Indirectionoperators INX∗s,w,w2.6Subscripting(indexing)operator ITOD2.12Convertintegertoreal ITOS2.12Convertintegertoshortinteger LINOs2.2Setlinenumber,countstatements LLIMIT2.14Setlinelimitforoutputtextfile LLVl,W2.6Addressofoperator LN2.13Returnsnaturallogofargument LRV∗l,A2.5Rightvalue(load)operators LVl,w2.6Addressofoperator MAXs,w3.8Maximumoftopofstackandw MESSAGE3.6Writetoterminal -10-Table2.3−Machineoperations MnemonicReferenceDescription MINs3.8Minimumoftopofstackands MOD∗2.7Modulus MUL∗2.7Multiplication NAMA3.8Convertenumeratedtypevaluetoprintformat NEG∗2.7Negation NEWs2.15Allocatearecordonheap,setpointertoit NIL2.6Assertnon-nilpointer NODUMPs,W,w,"2.2BEGmainprogram,suppressdump NOT2.4Booleannot ODD∗2.15Returnstrueifargumentisodd,falseifeven OFFs2.5Offsetaddress,typicallyusedforfieldreference OR2.4Booleanor PACKs,w,w,w2.15Convertandcopyfromunpackedtopacked PAGE3.8Outputaformfeedtoatextfile POPs2.2,1.9Pop(arguments)offstack PRED∗2.7Returnspredecessorofargument PUSHs2.2,1.9Clearspace(forfunctionresult) PUT3.8Outputarecordtoafile PXPBUFw2.10Initializepxpcountbuffer RANDOM2.13Returnsrandomnumber RANG∗v2.8Subrangechecking READ∗3.7Readarecordfromafile REL∗r2.3RelationaltestyieldingBooleanresult REMOVE3.11Removeafile RESET3.11Openfileforinput REWRITE3.11Openfileforoutput ROUND2.13ReturnsTRUNC(argument+0.5) RV∗l,a2.5Rightvalue(load)operators SCLCK2.14Returnssystemtimeofprogram SDUP2.2Duplicatetopstackword SEED2.13Setrandomseed,returnoldseed SIN2.13Returnssinofargument SQR∗2.7Squaring SQRT2.13Returnssquarerootofargument STLIM2.14Setprogramstatementlimit STOD2.12Convertshortintegertoreal STOI2.12Convertshorttolonginteger SUB∗2.7Subtraction SUCC∗2.7Returnssuccessorofargument TIME2.14Copytimeintochararray TRAa2.2Shortcontroltransfer(localbranching) TRA4A2.2Longcontroltransfer TRACNTw,A2.10Countaprocedureentry TRUNC2.13Returnsintegerpartofargument UNDEF2.15Returnsfalse UNIT∗3.10Setactivefile UNPACKs,w,w,w2.15Convertandcopyfrompackedtounpacked WCLCK2.14Returnscurrenttimestamp WRITEC3.8Characterunformattedwrite WRITEFl3.8Generalformattedwrite WRITESl3.8Stringunformattedwrite -11-Table2.3−Machineoperations MnemonicReferenceDescription WRITLN3.8Outputanewlinetoatextfile -12-2.2.Basiccontroloperations HALT CorrespondstothePascalprocedurehalt;causesexecutiontoendwithapost-mortemback-traceasifarun-timeerrorhadoccurred. BEGs,W,w," Causesthesecondpartoftheblockmarktobecreated,andWbytesoflocalvariablespace tobeallocatedandclearedtozero.Stackoverflowisdetectedhere.wisthefirstlineofthe bodyofthissectionforerrortraceback,andtheinlinestring(lengths)thecharacterrepresentationofitsname. NODUMPs,W,w," EquivalenttoBEG,andusedtobeginthemainprogramwhenthe‘‘p’’optionisdisabledso thatthepost-mortembacktracewillbeinhibited. END ComplementarytotheoperatorsCALLandBEG,exitsthecurrentblock,callingtheprocedurepclosetoflushbuffersforandreleaseanylocalfiles.Restorestheenvironmentofthe callerfromtheblockmark.Ifthisistheendforthemainprogram,allfilesareflushed,and theinterpreterisexited. CALLl,A Savesthecurrentlinenumber,returnaddress,andactivedisplayentrypointerdpinthe firstpartoftheblockmark,thentransferstotheentrypointgivenbytherelativeaddress A,thatisthebeginningofaprocedureorfunctionatlevell. PUSHs Clearssbytesonthestack.Usedtomakespaceforthereturnvalueofafunctionjust beforecallingit. POPs Popsbytesoffthestack.Usedafterafunctionorprocedurereturnstoremovetheargumentsfromthestack. TRAa Transfercontroltorelativeaddressaasalocalgotoorpartofastructuredstatement. TRA4A Transfercontroltoanabsoluteaddressaspartofanon-localgotoortobranchoverproce-durebodies. LINOs Setcurrentlinenumbertos.Forconsistency,checkthattheexpressionstackisemptyasit shouldbe(asthisisthestartofastatement.)Thisconsistencycheckwillfailonlyifthere isabugintheinterpreterortheinterpretercodehassomehowbeendamaged.Increment thestatementcountandifitexceedsthestatementlimit,generateafault. GOTOl,A TransfercontroltoaddressAthatisintheblockatlevellofthedisplay.Thisisanonlocalgoto.CauseseachblocktobeexitedasifwithEND,flushingandfreeingfileswith -13-pclose,untilthecurrentdisplayentryisatlevell. SDUP∗∗ Duplicatethewordorlongonthetopofthestack.Thisisusedmostlyforconstructing sets.Seesection2.11. 2.3.Ifandrelationaloperators IFa Theinterpreterconditionaltransfersalltakeplaceusingthisoperatorthatexaminesthe Booleanvalueonthetopofthestack.Ifthevalueistrue,thenextcodeisexecuted,otherwisecontroltransferstothespecifiedaddress. REL∗∗r Thesetaketwoargumentsonthestack,andthesub-operationcodespecifiestherelational operationtobedone,codedasfollowswith‘a’above‘b’onthestack: CodeOperation 0a=b 2a<>b 4a<b 6a>b 8a<=b 10a>=b Eachoperationdoesatesttosettheconditioncodeappropriatelyandthendoesanindexed branchbasedonthesub-operationcodetoatestoftheconditionherespecified,pushinga Booleanvalueonthestack. Considerthestatementfragment: ifa=bthen Ifaandbareintegersthisgeneratesthefollowingcode: RV4:la RV4:lb REL4= IFElsepartoffset ...Thenpartcode... 2.4.Booleanoperators TheBooleanoperatorsAND,OR,andNOTmanipulatevaluesonthetopofthestack.All Booleanvaluesarekeptinsinglebytesinmemory,orinsinglewordsonthestack.ZerorepresentsaBooleanfalse,andoneaBooleantrue. 2.5.Rightvalue,constant,andassignmentoperators LRV∗∗l,A RV∗∗l,a Therightvalueoperatorsloadvaluesonthestack.Theytakeablocknumberasasubopcodeandloadtheappropriatenumberofbytesfromthatblockattheoffsetspecifiedin -14-thefollowingwordontothestack.Asanexample,considerLRV4: LRV4: cvtbl(lc)+,r0#r0hasdisplayindex addl3display(r0),(lc)+,r1#r1hasvariableaddress pushl(r1) #putvalueonthestack jmp(loop) Heretheinterpreterplacesthedisplaylevelinr0.Itthenaddstheappropriatedisplay valuetotheinlineoffsetandpushesthevalueatthislocationontothestack.Controlthen returnstothemaininterpreterloop.TheRV∗operatorshaveshortinlinedatathatreduces thespacerequiredtoaddressthefirst32Kofstackspaceineachstackframe.TheoperatorsRV14andRV24provideexplicitconversiontolongasthedataispushed.Thissavesthe generationofSTOItoalignargumentstoCsubroutines. CON∗∗r Theconstantoperatorsloadavalueontothestackfrominlinecode.Smallintegervalues arecondensedandloadedbytheCON1operator,thatisgivenby CON1: cvtbw(lc)+,−(sp) jmp(loop) Herenotethatlittleworkwasrequiredastherequiredconstantwasavailableat(lc)+.For longerconstants,lcmustbeincrementedbeforemovingtheconstant.TheoperatorCON takesalengthspecificationinthesub-opcodeandcanbeusedtoloadstringsandother variablelengthdataontothestack.TheoperatorsCON14andCON24provideexplicitconversiontolongastheconstantispushed. AS∗∗ Theassignmentoperatorsaresimilartoarithmeticandrelationaloperatorsinthatthey taketwooperands,bothinthestack,butthelengthsgivenforthemspecifyfirstthelength ofthevalueonthestackandthenthelengthofthetargetinmemory.Thetargetaddress inmemoryisunderthevaluetobestored.Thusthestatement i:=1 whereiisafull-length,4byte,integer,willgeneratethecodesequence LV:li CON1:1 AS24 HereLVwillloadtheaddressofi,thatisreallygivenasablocknumberinthesub-opcode andanoffsetinthefollowingword,ontothestack,occupyingasingleword.CON1,thatisa singlewordinstruction,thenloadstheconstant1,thatisinitssub-opcode,ontothestack. Sincetherearenotonebyteconstantsonthestack,thisbecomesa2byte,singlewordinteger.Theinterpreterthenassignsalength2integertoalength4integerusingAS24.The codesequenceforAS24isgivenby: AS24: incllc cvtwl(sp)+,∗(sp)+ jmp(loop)

-15-Thustheinterpretergetsthesinglewordoffthestack,extendsittobea4byteintegergets thetargetaddressoffthestack,andfinallystoresthevalueinthetarget.Thisisatypical useoftheconstantandassignmentoperators. 2.6.Addressingoperations LLVl,W LVl,w Themostcommonoperationdonebytheinterpreteristhe‘‘leftvalue’’or‘‘addressof’’operation.Itisgivenby: LLV: cvtbl(lc)+,r0#r0hasdisplayindex addl3display(r0),(lc)+,−(sp)#pushaddressontothestack jmp(loop) Itcalculatesanaddressintheblockspecifiedinthesub-opcodebyaddingtheassociated displayentrytotheoffsetthatappearsinthefollowingword.TheLVoperatorhasashort inlinedatathatreducesthespacerequiredtoaddressthefirst32Kofstackspaceineach callframe. OFFs Theoffsetoperatorisusedinfieldnames.Thustogettheaddressof p↑.f1 piwouldgeneratethesequence RV:lp OFFf1 wheretheRVloadsthevalueofp,givenitsblockinthesub-opcodeandoffsetinthefollow-ingword,andtheinterpreterthenaddstheoffsetofthefieldf1initsrecordtogetthecor-rectaddress.OFFtakesitsargumentinthesub-opcodeifitissmallenough. NIL Theexampleaboveisincomplete,lackingacheckforanilpointer.Thecodegenerated wouldbe RV:lp NIL OFFf1 wheretheNILoperationchecksforanilpointerandgeneratestheappropriateruntimeerror ifitis. LVCONs," Apointertothespecifiedlengthinlinedataispushedontothestack.Thisisprimarilyused forprintftypestringsusedbyWRITEF.(seesections3.6and3.8) INX∗∗s,w,w TheoperatorsINX2andINX4areusedforsubscripting.Forexample,thestatement -16-a[i]:=2.0 withianintegerandaan‘‘array[1..1000]ofreal’’wouldgenerate LV:la RV4:li INX4:81,999 CON82.0 AS8 HeretheLVoperationtakestheaddressofaandplacesitonthestack.Thevalueofiis thenplacedontopofthisonthestack.Thearrayaddressisindexedbythelength4index (alength2indexwoulduseINX2)wheretheindividualelementshaveasizeof8bytes.The codeforINX4is: INX4: cvtbl(lc)+,r0 bneqL1 cvtwl(lc)+,r0#r0hassizeofrecords L1: cvtwl(lc)+,r1#r1haslowerbound movzwl(lc)+,r2#r2hasupper-lowerbound subl3r1,(sp)+,r3#r3hasbasesubscript cmplr3,r2#checkforoutofbounds bgtruesubscr mull2r0,r3#calculatebyteoffset addl2r3,(sp)#calculateactualaddress jmp(loop) esubscr: movw$ESUBSCR,perrno jbrerror Herethelowerboundissubtracted,andrangecheckedagainsttheupperminuslower bound.Theoffsetisthenscaledtoabyteoffsetintothearrayandaddedtothebase addressonthestack.Multi-dimensionsubscriptsaretranslatedasasequenceofsinglesub-scriptings. IND∗∗ Forindirectreferencesthroughvarparametersandpointers,theinterpreterhasasetof indirectionoperatorsthatconvertapointeronthestackintoavalueonthestackfromthat address.differentINDoperatorsarenecessarybecauseofthepossibilityofdifferentlength operands.TheIND14andIND24operatorsdoconversionstolongastheypushtheirdata. 2.7.Arithmeticoperators Theinterpreterhasmanyarithmeticoperators.Alloperatorsproduceresultslongenough topreventoverflowunlesstheboundsofthebasetypeareexceeded.Thebasicoperatorsavailableare Addition:ADD∗,SUCC∗ Subtraction:SUB∗,PRED∗ Multiplication:MUL∗,SQR∗ Division:DIV∗,DVD∗,MOD∗ Unary:NEG∗,ABS∗ -17-2.8.Rangechecking Theinterpreterhasseveralrangecheckingoperators.Theimportantdistinctionamong theseoperatorsisbetweenvalueswhoselegalrangebeginsatzeroandthosethatdonotbeginat zero,forexampleasubrangevariablewhosevaluesrangefrom45to70.Forthosethatbeginat zero,asimpler‘‘logical’’comparisonagainsttheupperboundsuffices.Forothers,boththelow andupperboundsmustbecheckedindependently,requiringtwocomparisons.OntheVAX11/780 bothchecksaredoneusingasingleindexinstructionsotheonlygainisinreducingtheinline data. 2.9.Caseoperators Theinterpreterincludesthreeoperatorsforcasestatementsthatareuseddependingonthe widthofthecaselabeltype.Foreachwidth,thestructureofthecasedataisthesame,andis representedinfigure2.4. CASEOP No.ofcases Case transfer table Arrayofcase labelvalues Figure2.4−Casedatastructure TheCASEOPcasestatementoperatorsdoasequentialsearchthroughthecaselabelvalues. Iftheyfindthelabelvalue,theytakethecorrespondingentryfromthetransfertableandcause theinterpretertobranchtothespecifiedstatement.Ifthespecifiedlabelisnotfound,anerror results. TheCASEoperatorstakethenumberofcasesasasub-opcodeifpossible.Threedifferent operatorsareneededtohandlesinglebyte,word,andlongcasetransfertablevalues.Forexample,theCASEOP1operatorhasthefollowingcodesequence:

-18-CASEOP1: cvtbl(lc)+,r0 bneqL1 cvtwl(lc)+,r0#r0haslengthofcasetable L1: movaw(lc)[r0],r2#r2haspointertocaselabels movzwl(sp)+,r3#r3hastheelementtofind loccr3,r0,(r2)#r0hasindexoflocatedelement beqlcaserr#elementnotfound mneglr0,r0#calculatenewlc cvtwl(r2)[r0],r1#r1haslcoffset addl2r1,lc jmp(loop) caserr: movw$ECASE,perrno jbrerror Heretheinterpreterfirstcomputestheaddressofthebeginningofthecaselabelvaluearea byaddingtwicethenumberofcaselabelvaluestotheaddressofthetransfertable,sincethe transfertableentriesare2byteaddressoffsets.Itthensearchesthroughthelabelvalues,and generatesanECASEerrorifthelabelisnotfound.Ifthelabelisfound,theindexofthecorrespondingentryinthetransfertableisextractedandthatoffsetisaddedtotheinterpreterlocationcounter. 2.10.Operationssupportingpxp Thefollowingoperationsaredefinedtodoexecutionprofiling. PXPBUFw Causestheinterpretertoallocateacountbufferwithwfourbytecountersandtoclearthem tozero.Thecountbufferisplacedwithinanimageofthepmon.outfileasdescribedinthe PXPImplementationNotes.Thecontentsofthisbufferarewrittentothefilepmon.out whentheprogramends. COUNTw Incrementsthecounterspecifiedbyw. TRACNTw,A Usedattheentrypointtoproceduresandfunctions,combiningatransfertotheentrypoint oftheblockwithanincrementingofitsentrycount. 2.11.Setoperations Thesetoperations:unionADDT,intersectionMULT,elementremovalSUBT,andthesetrelationalsRELTarestraightforward.Thefollowingoperationsaremoreinteresting. CARDs Takesthecardinalityofasetofsizesbytesontopofthestack,leavinga2byteinteger count.CARDusestheffsopcodetosuccessivelycountthenumberofsetbitsintheset. CTTOTs,w,w Constructsaset.Thisoperationrequiresanon-trivialamountofwork,checkingbounds andsettingindividualbitsorrangesofbits.Thisoperationsequenceisslow,andmotivates thepresenceoftheoperatorINCTbelow.TheargumentstoCTTOTincludethenumberof elementssintheconstructedset,thelowerandupperboundsoftheset,thetwowvalues, -19-andapairofvaluesonthestackforeachrangeintheset,singleelementsinconstructed setsbeingduplicatedwithSDUPtoformdegenerateranges. INs,w,w Theoperatorinforsets.Thevaluesspecifiesthesizeoftheset,thetwowvaluesthelower andupperboundsoftheset.Thevalueonthestackischeckedtobeinthesetonthe stack,andaBooleanvalueoftrueorfalsereplacestheoperands. INCT Theoperatorinonaconstructedsetwithoutconstructingit.Theleftoperandofinison topofthestackfollowedbythenumberofpairsintheconstructedset,andthenthepairs themselves,allassinglewordintegers.Pairsdesignaterunsofvaluesandsinglevaluesare representedbyadegeneratepairwithbothvalueequal.Thisoperatorisgeneratedingrammaticalconstructssuchas ifcharacterin[` +´ ,´ −´ ,` ∗´ ,` /´ ] or ifcharacterin[` a´ ..` z´ ,` $´ ,` ´ ] TheseconstructsarecommoninPascal,andINCTmakesthemrunmuchfasterintheinterpreter,asiftheywerewrittenasanefficientseriesofifstatements. 2.12.Miscellaneous OthermiscellaneousoperatorsthatarepresentintheinterpreterareASRTthatcausesthe programtoendiftheBooleanvalueonthestackisnottrue,andSTOI,STOD,ITOD,andITOSthat convertbetweendifferentlengtharithmeticoperandsforuseinaligningtheargumentsinprocedureandfunctioncalls,andwithsomeuntypedbuilt-ins,suchasSINandCOS. Finally,iftheprogramisrunwiththerun-timetestingdisabled,therearespecialoperators forforstatementsandspecialindexingoperatorsforarraysthathaveindividualelementsizethat isapowerof2.Thecodecanrunsignificantlyfasterusingtheseoperators. 2.13.MathematicalFunctions ThetranscendentalfunctionsSIN,COS,ATAN,EXP,LN,SQRT,SEED,andRANDOMaretaken fromthestandardUNIXmathematicalpackage.Thesefunctionstakedoubleprecisionfloating pointvaluesandreturnthesame. ThefunctionsEXPO,TRUNC,andROUNDtakeadoubleprecisionfloatingpointnumber. EXPOreturnsanintegerrepresentingthemachinerepresentationofitsargument’sexponent, TRUNCreturnstheintegerpartofitsargument,andROUNDreturnstheroundedintegerpartofits argument. 2.14.Systemfunctionsandprocedures LLIMIT Alinelimitandafilepointerarepassedonthestack.Ifthelimitisnon-negativetheline limitissettothespecifiedvalue,otherwiseitissettounlimited.Thedefaultisunlimited. STLIM Astatementlimitispassedonthestack.Thestatementlimitissetasspecified.The defaultis500,000.Nolimitisenforcedwhenthe‘‘p’’optionisdisabled.

-20-CLCK SCLCK CLCKreturnsthenumberofmillisecondsofusertimeusedbytheprogram;SCLCKreturns thenumberofmillisecondsofsystemtimeusedbytheprogram. WCLCK Thenumberofsecondssincesomepredefinedtimeisreturned.Itsprimaryusefulnessisin determiningelapsedtimeandinprovidingauniquetimestamp. TheothersystemtimeproceduresareDATEandTIMEthatcopyanappropriatetextstringintoa pascalstringarray.ThefunctionARGCreturnsthenumberofcommandlineargumentspassedto theprogram.TheprocedureARGVtakesanindexonthestackandcopiesthespecifiedcommand lineargumentintoapascalstringarray. 2.15.Pascalproceduresandfunctions PACKs,w,w,w UNPACKs,w,w,w Theyfunctionasamemorytomemorymovewithseveralsemanticchecks.Theydono ‘‘unpacking’’or‘‘packing’’inthetruesenseastheinterpretersupportsnopackeddatatypes. NEWs DISPOSEs AnLVofapointerispassed.NEWallocatesarecordofaspecifiedsizeandputsapointerto itintothepointervariable.DISPOSEdeallocatestherecordpointedtobythepointerand setsthepointertoNIL. ThefunctionCHR∗convertsasuitablysmallintegerintoanasciicharacter.Itsprimarypurposeis todoarangecheck.ThefunctionODD∗returnstrueifitsargumentisoddandreturnsfalseifits argumentiseven.ThefunctionUNDEFalwaysreturnsthevaluefalse. 3.Input/output 3.1.Thefilesstructure EachfileinthePascalenvironmentisrepresentedbyapointertoafilesstructureinthe heap.Atthelocationaddressedbythepointeristheelementinthefile’swindowvariable. Behindthiswindowvariableisinformationaboutthefile,atthefollowingoffsets: −108FNAMETextnameofassociatedUNIXfile −30LCOUNTCurrentcountoflinesoutput −26LLIMITMaximumnumberoflinespermitted −22FBUFUNIXFILEpointer −18FCHAINChaintonextfile −14FLEVPointertoassociatedfilevariable −10PFNAMEPointertonameoffileforerrormessages −6FUNITFilestatusflags −4FSIZESizeofelementsinthefile 0Filewindowelement HereFBUFisapointertothesystemFILEblockforthefile.ThestandardsystemI/O libraryisusedthatprovidesblockbufferedinput/output,with1024charactersnormallytransferredateachreadorwrite.

-21-ThefilesinthePascalenvironment,arealllinkedtogetheronasinglefilechainthroughthe FCHAINlinks.ForeachfiletheFLEVpointergivesitsassociatedfilevariable.Theseareusedto freefilesatblockexitasdescribedinsection3.3below. TheFNAMEandPFNAMEgivetheassociatedfilenameforthefileandthenametobe usedwhenprintingerrordiagnosticsrespectively.Althoughthesenamesareusuallythesame, inputandoutputusuallyhavenoassociatedfilenamesothedistinctionisnecessary. TheFUNITwordcontainsasetofflags.whoserepresentationsare: EOF0x0100Atend-of-file EOLN0x0200Atend-of-line(textfilesonly) SYNC0x0400Filewindowisoutofsync TEMP0x0800Fileistemporary FREAD0x1000Fileisopenforreading FWRITE0x2000Fileisopenforwriting FTEXT0x4000Fileisatextfile;processEOLN FDEF0x8000Filestructurecreated,butfilenotopened TheEOFandEOLNbitsherereflecttheassociatedbuilt-infunctionvalues.TEMPspeci-fiesthatthefilehasageneratedtemporarynameandthatitshouldthereforeberemovedwhen itsblockexits.FREADandFWRITEspecifythatresetandrewriterespectivelyhavebeendone onthefilesothatinputoroutputoperationscanbedone.FTEXTspecifiesthefileisatextfile sothatEOLNprocessingshouldbedone,withnewlinecharactersturnedintoblanks,etc. TheSYNCbit,whentrue,specifiesthatthereisnousableimageinthefilebufferwindow. AsdiscussedintheBerkeleyPascalUser’sManual,theinteractiveenvironmentnecessitateshaving‘‘inputˆ ’’undefinedatthebeginningofexecutionsothataprogrammayprintaprompt beforetheuserisrequiredtotypeinput.TheSYNCbitimplementsthis.Whenitisset,itspecifiesthattheelementinthewindowmustbeupdatedbeforeitcanbeused.Thisisneverdone untilnecessary. 3.2.Initializationoffiles AllthevariablesinthePascalruntimeenvironmentareclearedtozeroonblockentry.This isnecessaryforsimpleprocessingoffiles.Ifafileisunused,itspointerwillbenil.Allreferences toaninactivefilearethusreferencesthroughanilpointer.IfthePascalsystemdidnotclear storagetozerobeforeexecutionitwouldnotbepossibletodetectinactivefilesinthissimpleway; itwouldprobablybenecessarytogenerate(possiblycomplicated)codetoinitializeeachfileon blockentry. Whenafileisfirstmentionedinaresetorrewritecall,abufferoftheformdescribedabove isassociatedwithit,andthenecessaryinformationaboutthefileisplacedinthisbuffer.Thefile isalsolinkedintotheactivefilechain.Thischainiskeptsortedbyblockmarkaddress,the FLEVentries. 3.3.Blockexit Whenblockexitoccurstheinterpretermustfreethefilesthatareinuseintheblockand theirassociatedbuffers.Thisissimpleandefficientbecausethefilesintheactivefilechainare sortedbyincreasingblockmarkaddress.Thismeansthatthefilesforthecurrentblockwillbeat thefrontofthechain.Foreachfilethatisnolongeraccessibletheinterpreterfirstflushesthe filesbufferifitisanoutputfile.Theinterpreterthenreturnsthefilebufferandthefilesstructure andwindowtothefreespaceintheheapandremovesthefilefromtheactivefilechain. 3.4.Flushing Flushingallthefilebuffersatabnormaltermination,oronacalltotheprocedureflushor messageisdonebyflushingeachfileonthefilechainthathastheFWRITEbitsetinitsflags word.

-22-3.5.Theactivefile Forinput-output,pxmaintainsanotionofanactivefile.Eachoperationthatreferencesa filemakesthefileitwillbeusingtheactivefileandthendoesitsoperation.Asubtlepointhere isthatonemaydoaprocedurecalltowritethatinvolvesacalltoafunctionthatreferences anotherfile,therebydestroyingtheactivefilesetupbeforethewrite.Thustheactivefileissaved atblockentryintheblockmarkandrestoredatblockexit.† 3.6.Fileoperations FilesinPascalcanbeusedintwodistinctways:astheobjectofread,write,get,andput calls,orindirectlyasthoughtheywerepointers.Theseconduseaspointersmustbecarefulnot todestroytheactivefileinareferencesuchas write(output,input↑) orthesystemwouldincorrectlywriteontheinputdevice. ThefundamentaloperatorrelatedtotheuseofafileisFNIL.Thistakesthefilevariable,as apointer,insuresthatthepointerisnotnil,andalsothatausableimageisinthefilewindow,by forcingtheSYNCbittobecleared. Asimpleexamplethatdemonstratestheuseofthefileoperatorsisgivenby writeln(f) thatproduces RV:lf UNIT WRITLN 3.7.Readoperations GET Advancetheactivefiletothenextinputelement. FNIL Afilepointerisonthestack.Insurethattheassociatedfileisactiveandthatthefileis syncedsothatthereisinputavailableinthewindow. READ∗∗ Ifthefileisatextfile,readablockoftextandconvertittotheinternaltypeofthespecifiedoperand.Ifthefileisnotatextfilethendoanunformattedreadofthenextrecord. TheprocedureREADLNreadsuptoandincludingthenextendoflinecharacter. READEA TheoperatorREADEreadsastringnameofanenumeratedtypeandconvertsittoitsinternalvalue.READEtakesapointertoadatastructureasshowninfigure3.2. †Itwouldprobablybebettertodispensewiththenotionofactivefileanduseanothermechanism thatdidnotinvolveextraoverheadoneachprocedureandfunctioncall.

-23-No.ofcases offsets ofelement names Arrayof nullterminated elementnames Figure3.2−Enumeratedtypeconversionstructure SeethedescriptionofNAMinthenextsectionforanexample. 3.8.Writeoperations PUT Outputtheelementintheactivefilewindow. WRITEFs Theargument(s)onthestackareoutputbythefprintfstandardI/Olibraryroutine.The sub-opcodesspecifiesthenumberoflongwordargumentsonthestack. WRITEC Thecharacteronthetopofthestackisoutputwithoutformatting.Formattedcharacters mustbeoutputwithWRITEF. WRITES Thestringspecifiedbythepointeronthetopofthestackisoutputbythefwritestandard I/Olibraryroutine.Allcharactersincludingnullsareprinted. WRITLN Alinefeedisoutputtotheactivefile.Theline-countforthefileisincrementedandchecked againstthelinelimit. PAGE Aformfeedisoutputtotheactivefile. NAMA Thevalueonthetopofthestackisconvertedtoapointertoanenumeratedtypestring name.TheaddressApointstoanenumeratedtypestructureidenticaltothatusedby READE.Anerrorisraisedifthevalueisoutofrange.Theformofthisstructureforthe predefinedtypebooleanisshowninfigure3.3.ThecodeforNAMis -24-bool:2 6 12 17 "false" "true" Figure3.3−Booleantypeconversionstructure NAM: incllc addl3(lc)+,ap,r6#r6pointstoscalarnamelist movl(sp)+,r3#r3hasdatavalue cmpwr3,(r6)+#checkvalueoutofbounds bgequenamrng movzwl(r6)[r3],r4#r4hasstringindex pushab(r6)[r4]#pushstringpointer jmp(loop) enamrng: movw$ENAMRNG,perrno jbrerror Theaddressofthetableiscalculatedbyaddingthebaseaddressoftheinterpretercode,ap totheoffsetpointedtobylc.Thefirstwordofthetablegivesthenumberofrecordsand providesarangecheckofthedatatobeoutput.Thepointeristhencalculatedas tblbase=ap+A; size=∗tblbase++; return(tblbase+tblbase[value]); MAXs,w Thesub-opcodesissubtractedfromtheintegeronthetopofthestack.Themaximumof theresultandthesecondargument,w,replacesthevalueonthetopofthestack.This functionverifiesthatvariablespecifiedwidthargumentsarenon-negative,andmeetcertain minimumwidthrequirements. MINs Theminimumofthevalueonthetopofthestackandthesub-opcodereplacesthevalueon thetopofthestack. Theusesoffilesandthefileoperationsaresummarizedinanexamplewhichoutputsarealvariable(r)withavariablewidthfield(i). writeln(´ r=´ ,r:i,´ ´ ,true); thatgeneratesthecode -25-UNITOUT FILE CON14:1 CON14:3 LVCON:4"r=" WRITES RV8:lr RV4:li MAX:81 RV4:li MAX:11 LVCON:8"%∗.∗E" FILE WRITEF:6 CONC4´ ´ WRITEC CON14:1 NAMbool LVCON:4"%s" FILE WRITEF:3 WRITLN HeretheoperatorUNITOUTisanabbreviatedformoftheoperatorUNITthatisusedwhen thefiletobemadeactiveisoutput.Afiledescriptor,recordcount,stringsize,andapointerto theconstantstring‘‘r=’’arepushedandthenoutputbyWRITES.Nextthevalueofrispushed onthestackandtheprecisionsizeiscalculatedbytakingsevenlessthanthewidth,butnotless thanone.Thisisfollowedbythewidththatisreducedbyonetoleavespacefortherequired leadingblank.Ifthewidthistoonarrow,itisexpandedbyfprintf.Apointertotheformat stringispushedfollowedbyafiledescriptorandtheoperatorWRITEFthatprintsoutr.The valueofsixonWRITEFcomesfromtwolongsforrandalongeachfortheprecision,width,format stringpointer,andfiledescriptor.TheoperatorCONC4pushestheblankcharacterontoalongon thestackthatisthenprintedoutbyWRITEC.Theinternalrepresentationfortrueispushedasa longontothestackandisthenreplacedbyapointertothestring‘‘true’’bytheoperatorNAM usingthetableboolforconversion.ThisstringisoutputbytheoperatorWRITEFusingtheformat string‘‘%s’’.FinallytheoperatorWRITLNappendsanewlinetothefile. 3.9.Fileactivationandstatusoperations UNIT∗∗ Thefilepointedtobythefilepointeronthetopofthestackisconvertedtobetheactive file.TheopcodesUNITINPandUNITOUTimplystandardinputandoutputrespectively insteadofexplicitlypushingtheirfilepointers. FILE ThestandardI/Olibraryfiledescriptorassociatedwiththeactivefileispushedontothe stack. EOF Thefilepointedtobythefilepointeronthetopofthestackischeckedforendoffile.A booleanisreturnedwithtrueindicatingtheendoffilecondition.

-26-EOLN Thefilepointedtobythefilepointeronthetopofthestackischeckedforendofline.A booleanisreturnedwithtrueindicatingtheendoflinecondition.Notethatonlytextfiles cancheckforendofline. 3.10.Filehousekeepingoperations DEFNAME Fourdataitemsarepassedonthestack;thesizeofthedatatypeassociatedwiththefile, themaximumsizeofthefilename,apointertothefilename,andapointertothefilevariable.Afilerecordiscreatedwiththespecifiedwindowsizeandthefilevariablesettopoint toit.Thefileismarkedasdefinedbutnotopened.ThisallowsprogramstatementassociationoffilenameswithfilevariablesbeforetheirusebyaRESEToraREWRITE. BUFFs Thesub-opcodeisplacedintheexternalvariablebufopttospecifytheamountofI/O bufferingthatisdesired.Thecurrentoptionsare: 0−characteratatimebuffering 1−lineatatimebuffering 2−blockbuffering Thedefaultvalueis1. RESET REWRITE Fourdataitemsarepassedonthestack;thesizeofthedatatypeassociatedwiththefile, themaximumsizeofthename(possiblyzero),apointertothefilename(possiblynull),and apointertothefilevariable.IfthefilehasneverexisteditiscreatedasinDEFNAME.Ifno filenameisspecifiedandnopreviousnameexists(forexampleonecreatedbyDEFNAME) thenasystemtemporarynameiscreated.RESETthenopensthefileforinput,while REWRITEopensthefileforoutput. ThethreeremainingfileoperationsareFLUSHthatflushestheactivefile,REMOVEthattakes thepointertoafilenameandremovesthespecifiedfile,andMESSAGEthatflushesalltheoutput filesandsetsthestandarderrorfiletobetheactivefile. 4.Conclusions Itisappropriatetoconsider,giventheamountoftimeinvestedinrewritingtheinterpreter, whetherthetimewaswellspent,orwhetheracode-generatorcouldhavebeenwrittenwithan equivalentamountofeffort.TheBerkeleyPascalsystemisbeingmodifiedtointerfacetothecode generatoroftheportableCcompilerwithnotmuchmoreworkthanwasinvolvedinrewrittingpx. Howeverthiscompilerwillprobablynotsupercedetheinterpreterinaninstructionalenvironment asthenecessaryloadingandassemblyprocesseswillslowthecompilationprocesstoanoticeable degree.Thiseffectwillbefurtherexaggeratedbecausestudentusersspendmoretimeincompilationthaninexecution.MeasurementsoverthecourseofaquarteratBerkeleywithamixtureof studentsfrombeginningprogrammingtoupperdivisioncompilerconstructionshowthatthe amountoftimeincompilationexceedstheamountoftimespentintheinterpreter,theratiobeing approximately60/40. Amorepromisingapproachmighthavebeenathrow-awaycodegeneratorsuchaswasdone fortheWATFIVsystem.Howevertheadditionofhigh-qualitypost-mortemandinteractivedebug-gingfacilitiesbecomemuchmoredifficulttoprovidethanintheinterpreterenvironment.