Compiler.mod 274 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404
  1. IMPLEMENTATION MODULE Compiler ;
  2. (* Turbo Pascal 3-style single-pass Pascal -> 8086 compiler in
  3. GNU Modula-2 (-fiso), following the structure of the original
  4. TPSRC6 'turbo' entry / TPSRC7-10:
  5. Inittur reset state, pre-defined types, scratch temporaries
  6. Skip lexer: blanks, comments { } and (* *), directives {$ }
  7. GetWord/WddTok/MatchKey word lexing with a keyword table (kName/kTk)
  8. PeekKw lookahead keyword check WITHOUT consuming (via saved
  9. srcPos) - needed because declarations and compound
  10. statements peek at END/ELSE/etc
  11. RdIntConst/RdConst integer, hex and char constants
  12. Search symbol table lookup filtered by lexical level
  13. ParseExpr -> ParseCmp -> ParseAdd -> ParseMul -> ParseNeg
  14. -> ParseAtom precedence climb (TPSRC9)
  15. Statmnt statements: if/while/repeat/for/case/goto/exit/begin
  16. assignment and calls (TPSRC8)
  17. ParseType/Decls ARRAY, STRING, scalar/subrange types; variable,
  18. constant, label and procedure/function definitions
  19. Compile driver: optional PROGRAM header, DefPart, progpart,
  20. final '.', header size patch, patch resolution.
  21. Ebyte/Eword/Ecall/Ejmp + patch list code emission (TPSRC10).
  22. The emitted image is a byte array (mode word, CS/DS, size words,
  23. CALL initmem, MOV BP,SP, then generated code). Forward labels and
  24. forward procedure calls resolve through a patch list (ptc records).
  25. Working subset (v0.4): integer/char/boolean/byte scalars, constants
  26. with folding, globals, locals, value parameters, procedures and
  27. scalar-result functions, ARRAY[const..const] with constant indexing,
  28. control flow, GOTO/EXIT, and the standard procedures WRITE, WRITELN,
  29. READ, READLN, HALT (DefBuiltins + IoCall).
  30. The standard procedures are dispatched per argument, as the original
  31. does (TPSRC8 pwriteln/pwrloop inspects each argument's class and emits
  32. a different call per type), so the runtime is handed a value and never
  33. a descriptor.
  34. Still not implemented: real/set/record/file and the string runtime
  35. raise Err (ENoLib) - the original's "not implemented" path. The
  36. runtime blob itself, the linker that rebases the TU_* entry offsets
  37. by the runtime's size, and CmdRun (the interpreter) are still pending,
  38. so a compiled image cannot be executed yet. *)
  39. FROM TextBuf IMPORT TextLimit, Length, CharAt, InsertStr, DeleteFromTo ;
  40. FROM SYSTEM IMPORT BYTE, ADR ;
  41. FROM Posix IMPORT open, read, close ;
  42. FROM Runtime IMPORT RT_Build, RT_Size, RT_Byte, RT_Entry, LoadBias ;
  43. (* The runtime is copied to the front of the code buffer and pc/dc start past
  44. it, so every emitted address is image-absolute and no relocation pass is
  45. needed. See Inittur.
  46. `LoadBias' comes from Runtime because it is the same constant on both
  47. sides of the image: Runtime adds it to every data address it bakes into its
  48. own code (FixUp, kind 2), and this module adds it to every ABSOLUTE address
  49. it bakes into the program's. It is deliberately ONE constant in ONE place
  50. rather than 0100h written out at six sites, because getting it wrong at one
  51. site is invisible - see the note on LoadBias in Runtime.mod. Relative
  52. encodings (the entry JMP, every CALL and JMP) must NOT get it: both
  53. operands shift together and the +0100h cancels. *)
  54. (* ---------------------------------------------------------------- *)
  55. (* constants *)
  56. (* ---------------------------------------------------------------- *)
  57. CONST
  58. MaxLine = 128 ;
  59. MaxName = 31 ;
  60. (* Size of the entry jump at image offset 0: E9 lo hi. The jump's
  61. displacement is relative to the END of the jump, so every offset in the
  62. image is EntSize further along than it was before the jump existed. *)
  63. EntSize = 3 ;
  64. MaxCode = 24000 ;
  65. (* Program layout, image offsets. The original puts the runtime and the
  66. program's code in CS and the globals in a SEPARATE DS segment, so the
  67. .COM contains no data and the code is not limited by a data gap. We
  68. have one flat segment (our boot loader), so the same property is
  69. obtained by putting the globals at a fixed high image offset: the .COM
  70. is code-only, hdrDS points at DataStart, and initmem zeroes it. The
  71. code must end below CodeMax, where the boot harness puts the stdin
  72. descriptor (memory 7000h). *)
  73. DataStart = 8000H ; (* image offset of the first global (memory 8100h) *)
  74. CodeMax = 6F00H ; (* code must end below memory 7000h *)
  75. MaxSym = 3000 ;
  76. MaxPatch = 2000 ;
  77. MaxPend = 400 ;
  78. MaxFields = 2000 ; (* record fields, in a table of their own: a
  79. field is scoped to its record, not global *)
  80. MaxArrs = 1000 ; (* array SHAPES, likewise: a symbol points at
  81. one, and 2-D indexing needs both ranges *)
  82. FileVarSize = 132 ; (* a file variable is our control block: the DOS
  83. handle (word), a mode word (0 closed, 1 read,
  84. 2 write), then a 128-byte NUL-terminated
  85. filename. TP3 keeps its own name buffer and
  86. a 128-byte data buffer here; we keep the name
  87. and do unbuffered INT 21h I/O, with the data
  88. buffer supplied by the caller. *)
  89. (* type codes (TP3 vartp) *)
  90. TNone = 0 ; TArray = 1 ; TRecord = 2 ; TSet = 3 ;
  91. TPtr = 4 ; TFile = 5 ; TText = 6 ; TUntyp = 7 ;
  92. TString = 8 ; TReal = 9 ; TScalar = 10 ; TBool = 11 ;
  93. (* CHAR needs a class of its own. It used to be registered as TScalar,
  94. which made a CHAR variable indistinguishable from an INTEGER one: the
  95. class is all IoCall has to dispatch on, so `write(c)` called wrint (the
  96. value 65 became the *address* 65 and it printed whatever lived at 0x41)
  97. and `readln(c)` called rdint (which stores a 16-bit result, so it wrote
  98. two bytes into a one-byte variable). TP3 TPSRC8 prdtyped/pwriteln
  99. dispatches on the type identifier for exactly this reason. BYTE stays
  100. TScalar: a BYTE is written as an integer, as in TP3 - but a READ of one
  101. is dispatched on the variable's size instead (TPSRC8 prdnum
  102. `CMP varsize,#$01 / JA -> rdint, else rdbyte'), so the one thing class
  103. alone cannot tell apart is told apart where the size is in hand. *)
  104. TChar = 12 ;
  105. TEnum = 13 ; (* an enumeration type: ordinal, size 1 (TP3 uses 1
  106. byte below 256 values), bounds in SymEntry.lo/hi *)
  107. (* symbol kinds *)
  108. KLabel = 100H ; KConst = 200H ; KType = 300H ;
  109. KVar = 400H ; KProc = 500H ; KFunc = 600H ;
  110. KBuiltin = 700H ; (* standard procedure, see BI_* below *)
  111. (* which standard procedure a KBuiltin symbol denotes *)
  112. BI_Write = 0 ; BI_WriteLn = 1 ; BI_Read = 2 ;
  113. BI_ReadLn = 3 ; BI_Halt = 4 ; BI_Length = 5 ;
  114. (* CRT identifiers. There is no unit system, so these are builtins. They
  115. are statements (except Length), dispatched in IoCall; each one that is
  116. not implemented yet is a loud ENoLib, never a silent no-op. *)
  117. BI_ClrScr = 6 ; BI_GotoXY = 7 ; BI_LowVideo = 8 ;
  118. BI_NormVideo = 9 ; BI_ClrEol = 10 ; BI_Delay = 11 ;
  119. BI_KeyPressed = 12 ; BI_UpCase = 13 ; BI_Succ = 14 ; BI_Pred = 15 ;
  120. (* File operations. TP3 has these as standard procedures/functions; our
  121. control block is Compiler.FileVarSize, so Assign stores the name for
  122. the later Reset/Rewrite. IOResult is an expression; EndOfFile is the
  123. next file increment. *)
  124. BI_Assign = 16 ; BI_Reset = 17 ; BI_Rewrite = 18 ;
  125. BI_Close = 19 ; BI_IoResult = 20 ; BI_Chr = 21 ;
  126. (* the sub-codes EmCrtSeq takes *)
  127. CrtClr = 0 ; CrtDl = 1 ; CrtDh = 2 ; CrtCaret = 3 ; CrtEol = 4 ;
  128. CrtLow = 5 ; CrtNorm = 6 ; CrtDelay = 7 ; CrtKey = 8 ;
  129. (* keyword tokens *)
  130. TkNone = 0 ; TkProgram = 1 ; TkBegin = 2 ; TkEnd = 3 ;
  131. TkIf = 4 ; TkThen = 5 ; TkElse = 6 ; TkWhile = 7 ;
  132. TkDo = 8 ; TkRepeat = 9 ; TkUntil = 10 ; TkFor = 11 ;
  133. TkTo = 12 ; TkDownto = 13 ; TkCase = 14 ; TkOf = 15 ;
  134. TkGoto = 16 ; TkExit = 17 ; TkWith = 18 ; TkVar = 19 ;
  135. TkConst= 20 ; TkType = 21 ; TkLabel = 22 ; TkProcedure = 23 ;
  136. TkFunction = 24 ; TkNil = 25 ; TkAnd = 26 ; TkOr = 27 ;
  137. TkNot = 28 ; TkDiv = 29 ; TkMod = 30 ; TkIn = 31 ;
  138. TkFile = 32 ; TkText = 33 ; TkRecord = 34 ; TkArray = 35 ;
  139. TkSet = 36 ; TkPacked = 37 ; TkForward = 38 ; TkExternal = 39 ;
  140. TkAbsolute = 40 ; TkOverlay = 41 ; TkString = 42 ;
  141. (* Codes for the SYMBOL operators, as BinOpEmit numbers them. The word
  142. operators carry their own Tk* token and need no code here.
  143. These are named, not bare numbers, because every precedence level's
  144. parser picks its own code out of the same set and BinOpEmit cannot see
  145. which level called it. ParseAdd chose 1 for '+' and ParseMul chose 1
  146. for '*', so every multiplication dispatched to EmAddAxCx and a * b
  147. compiled to a + b. Only the constant-folding path was right, which is
  148. why n * n with n a CONST was correct and a * b with a a variable was
  149. not. *)
  150. OpAdd = 1 ; OpSub = 2 ; OpMul = 3 ;
  151. (* TP3 error numbers *)
  152. ENoSemi = 1 ; EPointExp = 10 ; ESimpType = 30 ;
  153. EUnknown = 41 ; EConstRange = 45 ; EMemOvf = 98 ;
  154. ECompOvf = 99 ; ENoLib = 102 ; ETypeErr = 56 ;
  155. EIoHere = 66 ; (* I/O not allowed here - TPSRC8 prderrtp *)
  156. EFileNF = 90 ; (* File not found - TPSRC10 cdincl, errb *)
  157. EInclNest = 96 ; (* Illegal nesting of include files - TPSRC10 cdincl *)
  158. AposC = 39 ; (* ORD ("'") - avoids quote-in-quote *)
  159. (* ---------------------------------------------------------------- *)
  160. (* types *)
  161. (* ---------------------------------------------------------------- *)
  162. TYPE
  163. SymEntry =
  164. RECORD
  165. name : ARRAY [0..MaxName] OF CHAR ;
  166. tag : CARDINAL ;
  167. cls : CARDINAL ;
  168. size : CARDINAL ;
  169. elem : CARDINAL ;
  170. off : CARDINAL ;
  171. lval : LONGINT ;
  172. lo, hi : LONGINT ; (* an ORDINAL type's bounds: an enumeration
  173. (0..n-1) or a subrange. Needed so
  174. `set of T' can size its base. *)
  175. fldFirst, fldLast : CARDINAL ; (* a RECORD type's field range in the
  176. field table (0,0 when not a record) *)
  177. arrIdx : CARDINAL ; (* an ARRAY type's shape in ArrRec (0 = no) *)
  178. parmFirst, parmCount : CARDINAL ; (* a PROCEDURE/FUNCTION's parameters:
  179. symtab indices, in declaration order *)
  180. isKbd : BOOLEAN ; (* the predefined KBD file: reads are console *)
  181. isVar : BOOLEAN ; (* a VAR parameter: the slot holds an address *)
  182. level : CARDINAL ;
  183. local : BOOLEAN ;
  184. resvar : CARDINAL ;
  185. goPos : CARDINAL ;
  186. defnd : BOOLEAN ;
  187. fwd : BOOLEAN ;
  188. END ;
  189. PatchRec =
  190. RECORD
  191. place : CARDINAL ;
  192. target : CARDINAL ;
  193. filled : BOOLEAN ;
  194. END ;
  195. PendRec =
  196. RECORD
  197. kind : CARDINAL ; (* 0 goto, 1 call *)
  198. who : CARDINAL ;
  199. place : CARDINAL ; (* patch slot index *)
  200. END ;
  201. ERes =
  202. RECORD
  203. cls : CARDINAL ;
  204. kind : CARDINAL ; (* 0 const, 1 var, 2 value in AX,
  205. 3 string literal (cls = TString),
  206. 4 value on the stack (SaveLeft),
  207. 5 string element, address in DI,
  208. 7 set value (cls = TSet) *)
  209. imm : LONGINT ;
  210. idx : CARDINAL ;
  211. boff : CARDINAL ; (* constant fold-in for subscripts *)
  212. chr : BOOLEAN ; (* single-quoted literal, e.g. 'a' *)
  213. strx : CARDINAL ; (* string literal: index into strPool *)
  214. setoff : CARDINAL ; (* SET value: image offset of the bytes *)
  215. setbase : CARDINAL ; (* ... the first byte's first element,
  216. a multiple of 8 (TP3's hybrid origin) *)
  217. setsize : CARDINAL ; (* ... and how many bytes there are *)
  218. sz : CARDINAL ; (* width of a kind-1 value: an element or
  219. field's size, not its variable's *)
  220. END ;
  221. DirRec = RECORD rng, chk : BOOLEAN END ;
  222. FldRec =
  223. RECORD
  224. name : ARRAY [0..MaxName] OF CHAR ;
  225. cls : CARDINAL ;
  226. size : CARDINAL ;
  227. elem : CARDINAL ;
  228. off : CARDINAL ; (* byte offset within the record *)
  229. lo, hi : LONGINT ; (* bounds, for a subrange/enum field *)
  230. END ;
  231. ArrRec =
  232. RECORD
  233. n : CARDINAL ; (* number of ranges (1 for array[1..5]) *)
  234. lo, hi : ARRAY [0..3] OF LONGINT ;
  235. elem : CARDINAL ; (* element size in bytes *)
  236. ecls : CARDINAL ; (* element CLASS, for a subscripted value *)
  237. END ;
  238. (* ---------------------------------------------------------------- *)
  239. (* state *)
  240. (* ---------------------------------------------------------------- *)
  241. VAR
  242. srcPos, srcLen : CARDINAL ;
  243. (* Include state. srcName is the path the buffer was loaded from, set by
  244. SetSource; only its directory is used, because a {$I file} directive
  245. names the file relative to the INCLUDING file. Includes are expanded by
  246. ExpandIncludes BEFORE parsing, so inclEnd is the end of the include
  247. region currently being scanned and inclActive says one is open - a
  248. nested {$I} inside that region is error 96, since TP3 permits only one
  249. level. incBuf holds one whole include file while it is spliced. *)
  250. srcName : ARRAY [0..255] OF CHAR ; inclName : ARRAY [0..127] OF CHAR ;
  251. inclPath : ARRAY [0..383] OF CHAR ;
  252. inclEnd : CARDINAL ;
  253. inclActive : BOOLEAN ;
  254. incBuf : ARRAY [0..TextLimit] OF CHAR ;
  255. enumLo, enumHi : LONGINT ; (* bounds of the enumeration ParseType just read,
  256. handed to DefType which owns the type NAME *)
  257. fields : ARRAY [0..MaxFields - 1] OF FldRec ;
  258. fldTop : CARDINAL ; (* next free field-table slot *)
  259. recFldFirst, recFldLast : CARDINAL ; (* field range ParseType just built *)
  260. arrs : ARRAY [0..MaxArrs - 1] OF ArrRec ;
  261. arrTop : CARDINAL ; (* next free array-shape slot *)
  262. newArrIdx : CARDINAL ; (* ArrRec index+1 for the type just parsed *)
  263. constBlob : ARRAY [0..511] OF CHAR ; (* bytes of a set/array typed constant
  264. while it is being built *)
  265. wrd : ARRAY [0..MaxName] OF CHAR ;
  266. (* String-literal pool.
  267. TP3 does not put a literal in the data segment at all: it emits the
  268. literal *inline in the code stream* as <length byte><characters>, and
  269. the runtime entry "wrtinl" reads the length from the return address and
  270. returns to just past the last character (TPSRC4 xwrtinl, TPSRC10
  271. estring). So nothing here ends up in the image as data - the pool only
  272. has to survive from the moment the literal is scanned until IoCall
  273. decides to emit it, because by then the parser has moved on. *)
  274. strPool : ARRAY [0..4095] OF CHAR ;
  275. strOff : ARRAY [0..255] OF CARDINAL ;
  276. strLen : ARRAY [0..255] OF CARDINAL ;
  277. strTop : CARDINAL ; (* next free byte in strPool *)
  278. strCnt : CARDINAL ; (* literals collected so far *)
  279. rdStrX : CARDINAL ; (* pool index of the literal RdConst just read *)
  280. symtab : ARRAY [0..MaxSym - 1] OF SymEntry ;
  281. symTop : CARDINAL ;
  282. patches : ARRAY [0..MaxPatch - 1] OF PatchRec ;
  283. nPatch : CARDINAL ;
  284. pend : ARRAY [0..MaxPend - 1] OF PendRec ;
  285. nPend : CARDINAL ;
  286. exitPatch : ARRAY [0..63] OF CARDINAL ;
  287. exitCnt : CARDINAL ;
  288. brkSave : ARRAY [0..15] OF CARDINAL ;
  289. loopTy : ARRAY [0..15] OF CARDINAL ; (* 1 while/repeat, 2 for *)
  290. brkN : CARDINAL ;
  291. caseJmp : ARRAY [0..63] OF CARDINAL ;
  292. caseN : CARDINAL ;
  293. (* the active WITH scopes, innermost last. A DI-based base (an array
  294. element addressed at run time) is parked in a two-byte data slot: the
  295. body may clobber DI, so each field access reloads it. *)
  296. withN : CARDINAL ;
  297. withIsDI : ARRAY [0..3] OF BOOLEAN ;
  298. withIdx : ARRAY [0..3] OF CARDINAL ;
  299. withBoff : ARRAY [0..3] OF CARDINAL ;
  300. withSlot : ARRAY [0..3] OF CARDINAL ;
  301. withFF : ARRAY [0..3] OF CARDINAL ;
  302. withFL : ARRAY [0..3] OF CARDINAL ;
  303. lblLo, lblHi : ARRAY [0..31] OF LONGINT ; (* one arm's label list *)
  304. lblJmp : ARRAY [0..63] OF CARDINAL ; (* its body jumps: 1 or 2 per label *)
  305. pc, dc : CARDINAL ;
  306. varspc : CARDINAL ;
  307. cbuf : ARRAY [0..MaxCode - 1] OF BYTE ;
  308. codeSz, dataSz : CARDINAL ;
  309. (* Image layout, all image-absolute. rtSz is where the runtime ends and
  310. the program header begins; dataBase is the fixed high global area
  311. (DataStart = 8000H image, 8100H memory), which is NOT part of the .COM
  312. image: initmem zeroes it at startup, as the original's separate DS
  313. segment is zeroed. codeSz and dataSz are PROGRAM sizes - the runtime is
  314. excluded. *)
  315. rtSz, dataBase : CARDINAL ;
  316. (* TRUE once Compile has computed rtSz/dataBase, i.e. once the code window
  317. has been measured. Ebyte refuses to write past CodeMax/MaxCode and
  318. needs to know the window is real before it can: imgReady is FALSE until
  319. then, and a zero CodeMax would abort on the very first byte. *)
  320. imgReady : BOOLEAN ;
  321. (* Image offset of the entry jump's rel16 operand, patched at the end of
  322. Compile. The jump is at image offset 0, so its displacement is simply
  323. the program code's end - 3. *)
  324. entRel, prologAt : CARDINAL ;
  325. (* Runtime entry offsets as IMAGE-ABSOLUTE addresses, which is what
  326. EmCall and EmJmp want. They are derived from Runtime.RT_Entry in
  327. Inittur (after RT_Build, since RT_Entry only knows where the code
  328. landed once the blob is assembled) rather than written down, so a moved
  329. entry cannot leave the compiler calling the old address. Not a CONST
  330. block because RT_Entry is a function.
  331. Standard-procedure entries: TP3 does NOT pass a descriptor -
  332. TPSRC8 pwriteln/pwrloop inspects each argument's class in CL and emits
  333. a *different* call per type, so the type is fixed at compile time and
  334. the runtime needs only the value. Mirrored here. *)
  335. TU_InitMem : CARDINAL ;
  336. TU_ProgEnd : CARDINAL ;
  337. TU_StackChk : CARDINAL ;
  338. TU_WrInt : CARDINAL ; TU_WrIntW : CARDINAL ;
  339. TU_WrChar : CARDINAL ; TU_WrBool : CARDINAL ;
  340. TU_WrReal : CARDINAL ; TU_RealWrite : CARDINAL ; TU_WrLn : CARDINAL ;
  341. TU_RdInt : CARDINAL ; TU_RdChar : CARDINAL ; TU_RdBool : CARDINAL ;
  342. TU_RdLn : CARDINAL ; TU_Halt : CARDINAL ;
  343. TU_RdByte : CARDINAL ; (* one-byte variable reads; see IoCall *)
  344. TU_WrInl : CARDINAL ; (* inline string literal; NO stack argument *)
  345. TU_WrStr : CARDINAL ; (* string variable; address is the stack argument *)
  346. TU_RdStr : CARDINAL ; (* readln(s)/read(s); address on the stack, limit
  347. in CX *)
  348. TU_StrStore : CARDINAL ; (* s := t; dest and source addresses on the stack,
  349. limit in CX *)
  350. TU_SetOp : CARDINAL ; (* runtime set operations, entries 31..33 *)
  351. TU_SetCmp : CARDINAL ;
  352. TU_SetCopy : CARDINAL ;
  353. TU_FileAssign : CARDINAL ; (* file control block operations, entries 34..38 *)
  354. TU_FileReset : CARDINAL ;
  355. TU_FileRewrite : CARDINAL ;
  356. TU_FileClose : CARDINAL ;
  357. TU_IoResult : CARDINAL ;
  358. TU_IoStore : CARDINAL ; (* save AX as the last I/O status *)
  359. TU_CmpStr : CARDINAL ; (* string comparison; two addresses on the stack,
  360. signed -1/0/+1 in AX *)
  361. TU_StrCat : CARDINAL ; (* string concatenation; dest and source addresses
  362. on the stack, limit in CX; exit code 16 if the
  363. result would be too long *)
  364. abortFac : BOOLEAN ;
  365. errNum : CARDINAL ; (* NOT "errNo": Compile's formal of that
  366. name would shadow it, and the caller's
  367. errNo would never be filled in *)
  368. txerrPos : CARDINAL ;
  369. lexnest : CARDINAL ;
  370. curIsFunc : BOOLEAN ;
  371. resultVar : CARDINAL ;
  372. locFree : CARDINAL ; (* next local slot (BP-relative, 8-bit) *)
  373. locBytes : CARDINAL ; (* frame size for SUB SP *)
  374. parmOff : CARDINAL ; (* provisional parameter slot, in declaration
  375. order; remapped to TP3's BP+4 rule when the
  376. list has been read (see ProcFunc) *)
  377. dirs : DirRec ;
  378. tmpA, tmpB : CARDINAL ; (* global scratch word addresses *)
  379. crtAttrOff : CARDINAL ; (* image offset of the text attribute byte that
  380. LowVideo/NormVideo set and ClrScr/ClrEol use *)
  381. hdrFlag, hdrCS, hdrDS, hdrHeap, hdrMax : CARDINAL ;
  382. kName : ARRAY [0..42] OF ARRAY [0..15] OF CHAR ;
  383. kTk : ARRAY [0..42] OF CARDINAL ;
  384. (* ---------------------------------------------------------------- *)
  385. (* small char helpers *)
  386. (* ---------------------------------------------------------------- *)
  387. PROCEDURE CurCh () : CHAR ;
  388. BEGIN
  389. IF srcPos >= srcLen THEN
  390. RETURN 0C
  391. END ;
  392. RETURN CharAt (srcPos)
  393. END CurCh ;
  394. PROCEDURE GetCh () : CHAR ;
  395. VAR ch : CHAR ;
  396. BEGIN
  397. ch := CurCh () ;
  398. IF srcPos < srcLen THEN
  399. INC (srcPos)
  400. END ;
  401. RETURN ch
  402. END GetCh ;
  403. PROCEDURE PeekAhead (k : CARDINAL) : CHAR ;
  404. BEGIN
  405. IF srcPos + k >= srcLen THEN
  406. RETURN 0C
  407. END ;
  408. RETURN CharAt (srcPos + k)
  409. END PeekAhead ;
  410. PROCEDURE Digit (ch : CHAR) : BOOLEAN ;
  411. BEGIN
  412. RETURN (ch >= '0') AND (ch <= '9')
  413. END Digit ;
  414. PROCEDURE Alpha (ch : CHAR) : BOOLEAN ;
  415. BEGIN
  416. RETURN ((ch >= 'A') AND (ch <= 'Z')) OR ((ch >= 'a') AND (ch <= 'z'))
  417. OR (ch = '_')
  418. END Alpha ;
  419. PROCEDURE AlphaNum (ch : CHAR) : BOOLEAN ;
  420. BEGIN
  421. RETURN (Alpha (ch)) OR (Digit (ch))
  422. END AlphaNum ;
  423. PROCEDURE IsHexCh (ch : CHAR) : BOOLEAN ;
  424. BEGIN
  425. RETURN (Digit (ch)) OR ((ch >= 'A') AND (ch <= 'F'))
  426. OR ((ch >= 'a') AND (ch <= 'f'))
  427. END IsHexCh ;
  428. PROCEDURE Upper (ch : CHAR) : CHAR ;
  429. BEGIN
  430. IF (ch >= 'a') AND (ch <= 'z') THEN
  431. RETURN CHR (ORD (ch) - ORD ('a') + ORD ('A'))
  432. END ;
  433. RETURN ch
  434. END Upper ;
  435. PROCEDURE W16 (x : LONGINT) : CARDINAL ;
  436. (* fold x modulo 10000H, handling negatives (no negative MOD) *)
  437. VAR m : CARDINAL ;
  438. BEGIN
  439. IF x >= 0 THEN
  440. RETURN VAL (CARDINAL, x MOD 10000H)
  441. END ;
  442. m := VAL (CARDINAL, (0 - x) MOD 10000H) ;
  443. RETURN (10000H - m) MOD 10000H
  444. END W16 ;
  445. PROCEDURE DropCh (v : CHAR) ;
  446. BEGIN
  447. END DropCh ;
  448. PROCEDURE DropB (v : BOOLEAN) ;
  449. BEGIN
  450. END DropB ;
  451. PROCEDURE DropC (v : CARDINAL) ;
  452. BEGIN
  453. END DropC ;
  454. PROCEDURE BitAnd (a, b : LONGINT) : LONGINT ;
  455. BEGIN
  456. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  457. * VAL (BITSET, W16 (b))))
  458. END BitAnd ;
  459. PROCEDURE BitOr (a, b : LONGINT) : LONGINT ;
  460. BEGIN
  461. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  462. + VAL (BITSET, W16 (b))))
  463. END BitOr ;
  464. PROCEDURE BitNot (a : LONGINT) : LONGINT ;
  465. BEGIN
  466. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, 0FFFFH)
  467. - VAL (BITSET, W16 (a))))
  468. END BitNot ;
  469. (* ---------------------------------------------------------------- *)
  470. (* errors *)
  471. (* ---------------------------------------------------------------- *)
  472. PROCEDURE Err (n : CARDINAL) ;
  473. BEGIN
  474. IF NOT abortFac THEN
  475. abortFac := TRUE ;
  476. errNum := n ;
  477. txerrPos := srcPos
  478. END
  479. END Err ;
  480. PROCEDURE OK () : BOOLEAN ;
  481. BEGIN
  482. RETURN NOT abortFac
  483. END OK ;
  484. (* ---------------------------------------------------------------- *)
  485. (* {$I file} include *)
  486. (* ---------------------------------------------------------------- *)
  487. PROCEDURE SetSource (path : ARRAY OF CHAR) ;
  488. (* remember the path the buffer was loaded from; MakeIncludePath keeps only its
  489. directory *)
  490. VAR i : CARDINAL ;
  491. BEGIN
  492. i := 0 ;
  493. WHILE (i < 255) AND (i <= HIGH (path)) AND (path [i] # 0C) DO
  494. srcName [i] := path [i] ;
  495. INC (i)
  496. END ;
  497. srcName [i] := 0C
  498. END SetSource ;
  499. PROCEDURE ReadWholeFile (path : ARRAY OF CHAR ; VAR n : CARDINAL) : BOOLEAN ;
  500. (* Read path into incBuf with the same CR/LF normalisation as LoadWorkFile,
  501. and report its length in n. FALSE if it could not be opened. ^Z ends the
  502. text, as it does for every other reader here. *)
  503. VAR fd : INTEGER ;
  504. k : LONGINT ;
  505. b : BYTE ;
  506. ch : CHAR ;
  507. prevCR, emit : BOOLEAN ;
  508. BEGIN
  509. n := 0 ;
  510. fd := open (ADR (path), 0, 0) ;
  511. IF fd < 0 THEN
  512. RETURN FALSE
  513. END ;
  514. prevCR := FALSE ;
  515. LOOP
  516. k := read (fd, ADR (b), 1) ;
  517. IF k # 1 THEN EXIT END ;
  518. IF b = 26 THEN EXIT END ; (* ^Z *)
  519. emit := TRUE ;
  520. IF b = 10 THEN
  521. IF prevCR THEN
  522. emit := FALSE
  523. ELSE
  524. ch := CHR (13) (* lone LF -> CR *)
  525. END ;
  526. prevCR := FALSE
  527. ELSIF b = 13 THEN
  528. ch := CHR (13) ;
  529. prevCR := TRUE
  530. ELSE
  531. ch := CHR (ORD (b)) ;
  532. prevCR := FALSE
  533. END ;
  534. IF emit AND (n <= TextLimit) THEN
  535. incBuf [n] := ch ;
  536. INC (n)
  537. END
  538. END ;
  539. k := close (fd) ;
  540. RETURN TRUE
  541. END ReadWholeFile ;
  542. PROCEDURE MakeIncludePath () ;
  543. (* inclPath := directory (srcName) + inclName, defaulting the extension to
  544. .PAS when the name has none (TPSRC10 kpasext). *)
  545. VAR i, j, last : CARDINAL ; dot : BOOLEAN ;
  546. BEGIN
  547. dot := FALSE ;
  548. i := 0 ;
  549. WHILE (i < 127) AND (inclName [i] # 0C) DO
  550. IF inclName [i] = '.' THEN dot := TRUE END ;
  551. INC (i)
  552. END ;
  553. IF (NOT dot) AND (i <= 123) THEN
  554. inclName [i] := '.' ;
  555. inclName [i + 1] := 'P' ;
  556. inclName [i + 2] := 'A' ;
  557. inclName [i + 3] := 'S' ;
  558. inclName [i + 4] := 0C
  559. END ;
  560. last := 0 ;
  561. i := 0 ;
  562. WHILE (i < 256) AND (srcName [i] # 0C) DO
  563. IF srcName [i] = '/' THEN last := i + 1 END ;
  564. INC (i)
  565. END ;
  566. j := 0 ;
  567. WHILE j < last DO
  568. inclPath [j] := srcName [j] ;
  569. INC (j)
  570. END ;
  571. i := 0 ;
  572. WHILE (i < 127) AND (inclName [i] # 0C) DO
  573. inclPath [j] := inclName [i] ;
  574. INC (j) ;
  575. INC (i)
  576. END ;
  577. inclPath [j] := 0C
  578. END MakeIncludePath ;
  579. PROCEDURE ExpandIncludes () ;
  580. (* Replace every {$I name} directive in the buffer with the named file's text,
  581. BEFORE parsing.
  582. This is a pre-pass, and it has to be. Skip is called by lookahead routines
  583. (DeclaresProc, PeekKw, KwAhead) that SAVE AND RESTORE srcPos; an include
  584. performed inside Skip would run once during the lookahead and once for real,
  585. and the second pass would see the first splice's text and report error 96.
  586. A splice also grows the buffer, which a rewind cannot undo. So the whole
  587. expansion is done here, in one forward scan with no lookahead, and the
  588. parser only ever sees the finished text.
  589. The scan has to recognise exactly what the lexer does, or it would expand a
  590. directive that the lexer would have read as a string or a comment: a quoted
  591. literal is skipped, then star-paren comments (which is why {$I} written
  592. inside one is inert - t56_include.inc relies on that), then brace comments,
  593. and only then a brace directive.
  594. Divergence from the original: TP3 STREAMS the include file line by line and
  595. switches back to the outer file at EOF (TPSRC10 fileline/getincl/fileeof);
  596. we hold the whole source in TextBuf and address it by index, so the include
  597. is spliced in place. A nested {$I} therefore cannot switch back on its own
  598. - which TP3 also refuses, and that is the error 96 reported here. *)
  599. VAR i, d0, d1, k, ni, n : CARDINAL ;
  600. c, letter : CHAR ;
  601. isInc : BOOLEAN ;
  602. BEGIN
  603. i := 0 ;
  604. inclActive := FALSE ;
  605. inclEnd := 0 ;
  606. WHILE (i < Length ()) AND OK () DO
  607. c := CharAt (i) ;
  608. IF c = "'" THEN
  609. INC (i) ;
  610. WHILE (i < Length ()) AND (CharAt (i) # "'") DO INC (i) END ;
  611. IF i < Length () THEN INC (i) END
  612. ELSIF (c = '(') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '*') THEN
  613. INC (i, 2) ;
  614. WHILE (i < Length ()) AND NOT ((CharAt (i) = '*')
  615. AND (i + 1 < Length ()) AND (CharAt (i + 1) = ')')) DO
  616. INC (i)
  617. END ;
  618. IF i < Length () THEN INC (i, 2) END
  619. ELSIF (c = '{') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '$') THEN
  620. d0 := i ;
  621. d1 := i + 2 ;
  622. WHILE (d1 < Length ()) AND (CharAt (d1) # '}') DO INC (d1) END ;
  623. IF i + 2 < Length () THEN
  624. letter := Upper (CharAt (i + 2))
  625. ELSE
  626. letter := 0C
  627. END ;
  628. isInc := FALSE ;
  629. IF letter = 'I' THEN
  630. k := i + 3 ;
  631. WHILE (k < d1) AND ((CharAt (k) = ' ') OR (CharAt (k) = CHR (9))) DO
  632. INC (k)
  633. END ;
  634. IF (k >= d1) OR ((CharAt (k) # '+') AND (CharAt (k) # '-')) THEN
  635. isInc := TRUE
  636. END
  637. END ;
  638. IF isInc THEN
  639. IF inclActive AND (d0 < inclEnd) THEN
  640. srcPos := d0 ;
  641. Err (EInclNest) ; (* 96 *)
  642. RETURN
  643. END ;
  644. ni := 0 ;
  645. WHILE (k < d1) AND (ni < 127) DO
  646. inclName [ni] := CharAt (k) ;
  647. INC (k) ;
  648. INC (ni)
  649. END ;
  650. WHILE (ni > 0) AND ((inclName [ni - 1] = ' ')
  651. OR (inclName [ni - 1] = CHR (9))) DO
  652. DEC (ni)
  653. END ;
  654. inclName [ni] := 0C ;
  655. MakeIncludePath () ;
  656. IF NOT ReadWholeFile (inclPath, n) THEN
  657. srcPos := d0 ;
  658. Err (EFileNF) ; (* 90 *)
  659. RETURN
  660. END ;
  661. DeleteFromTo (d0, d1 - d0 + 1) ;
  662. IF NOT InsertStr (d0, incBuf, n) THEN
  663. srcPos := d0 ;
  664. Err (EMemOvf) ;
  665. RETURN
  666. END ;
  667. inclEnd := d0 + n ;
  668. inclActive := TRUE ;
  669. i := d0 (* scan the new text too *)
  670. ELSE
  671. i := d1 + 1 (* ordinary directive: leave it *)
  672. END
  673. ELSIF c = '{' THEN
  674. INC (i) ;
  675. WHILE (i < Length ()) AND (CharAt (i) # '}') DO INC (i) END ;
  676. IF i < Length () THEN INC (i) END
  677. ELSE
  678. INC (i)
  679. END
  680. END ;
  681. srcLen := Length () ;
  682. srcPos := 0
  683. END ExpandIncludes ;
  684. (* ---------------------------------------------------------------- *)
  685. (* emission : ebyte / eword / ecall / ejump *)
  686. (* ---------------------------------------------------------------- *)
  687. PROCEDURE Ebyte (b : BYTE) ;
  688. BEGIN
  689. IF (pc >= MaxCode) OR (imgReady AND (pc >= CodeMax)) THEN
  690. (* The image buffer bound (MaxCode) and the boot harness's code ceiling
  691. (CodeMax). Globals no longer sit immediately above the code - they
  692. live at DataStart and initmem zeroes them - so this is purely a
  693. capacity check: cbuf cannot hold another byte, or the image would
  694. reach the stdin descriptor at memory 7000h. Reported as TP3's error
  695. 98 (memory overflow) rather than a silent truncation. *)
  696. Err (EMemOvf)
  697. ELSE
  698. cbuf [pc] := b ;
  699. INC (pc)
  700. END
  701. END Ebyte ;
  702. PROCEDURE Eword (w : CARDINAL) ;
  703. BEGIN
  704. Ebyte (VAL (BYTE, w MOD 100H)) ;
  705. Ebyte (VAL (BYTE, (w DIV 100H) MOD 100H))
  706. END Eword ;
  707. PROCEDURE PatchWord (at, w : CARDINAL) ;
  708. (* Store a 16-bit word into cbuf at an absolute offset.
  709. A helper, because writing this inline got it wrong in all four header
  710. words: the low byte was (w DIV 16) MOD 100H, which is a NIBBLE shift, not
  711. the byte shift (w MOD 100H). So 1181h - the data base - was stored as
  712. 0118h = 280. It was invisible for as long as nothing read those words,
  713. which is exactly what "write it inline once and trust it" buys you. *)
  714. BEGIN
  715. cbuf [at] := VAL (BYTE, w MOD 100H) ;
  716. cbuf [at + 1] := VAL (BYTE, (w DIV 100H) MOD 100H)
  717. END PatchWord ;
  718. PROCEDURE AddPatch (place, target : CARDINAL) ;
  719. BEGIN
  720. IF nPatch < MaxPatch THEN
  721. patches [nPatch].place := place ;
  722. patches [nPatch].target := target ;
  723. patches [nPatch].filled := FALSE ;
  724. INC (nPatch)
  725. ELSE
  726. Err (ECompOvf)
  727. END
  728. END AddPatch ;
  729. PROCEDURE SetPatTgt (idx, t : CARDINAL) ;
  730. BEGIN
  731. IF idx < nPatch THEN
  732. patches [idx].target := t
  733. END
  734. END SetPatTgt ;
  735. PROCEDURE EmCall (target : CARDINAL) : CARDINAL ;
  736. (* E8 rel16 near call; target = 0 => forward (patched later).
  737. Returns the patch slot, or 0 when resolved directly. *)
  738. VAR rel, p : CARDINAL ;
  739. BEGIN
  740. Ebyte (0E8H) ;
  741. IF target = 0 THEN
  742. Eword (0) ;
  743. p := nPatch ;
  744. AddPatch (pc - 2, 0) ;
  745. RETURN p
  746. END ;
  747. (* rel16 is measured from the END of the instruction. Here pc already
  748. points past the opcode(s) and at the displacement field, so the
  749. instruction ends at pc+2 - the same convention ResolvePatches uses
  750. with "place + 2". Omitting the +2 lands every direct call/jump 2 bytes
  751. past its target. *)
  752. rel := (target + 10000H - (pc + 2)) MOD 10000H ;
  753. Eword (rel) ;
  754. RETURN 0
  755. END EmCall ;
  756. PROCEDURE EmJmpNear (target : CARDINAL) : CARDINAL ;
  757. (* E9 rel16; target = 0 => forward. Returns patch slot or 0. *)
  758. VAR rel, p : CARDINAL ;
  759. BEGIN
  760. Ebyte (0E9H) ;
  761. IF target = 0 THEN
  762. Eword (0) ;
  763. p := nPatch ;
  764. AddPatch (pc - 2, 0) ;
  765. RETURN p
  766. END ;
  767. rel := (target + 10000H - (pc + 2)) MOD 10000H ; (* see EmCall *)
  768. Eword (rel) ;
  769. RETURN 0
  770. END EmJmpNear ;
  771. PROCEDURE JccShort (cc : BYTE) : BYTE ;
  772. (* The 8086 SHORT Jcc opcode for a condition nibble. 70h..7Fh is exactly
  773. 70h + nibble: 70 JO 71 JNO 72 JB 73 JAE 74 JE 75 JNE 76 JBE 77 JA
  774. 78 JS 79 JNS 7A JP 7B JNP 7C JL 7D JGE 7E JLE 7F JG.
  775. So 70H + cc is the same condition the 386-only `0F 8x rel16' (for a Jcc) or
  776. `0F 9x' (for a SETcc) encoded, which is what lets the seven EmJcc sites and
  777. the six EmSetcc arms go on passing the low byte they always passed. *)
  778. VAR n : CARDINAL ;
  779. BEGIN
  780. n := VAL (CARDINAL, cc) MOD 10H ;
  781. RETURN VAL (BYTE, 70H + n)
  782. END JccShort ;
  783. PROCEDURE JccShortInv (cc : BYTE) : BYTE ;
  784. (* The same, for a jump that is taken when the condition does NOT hold.
  785. EmJcc needs this one and EmSetcc needs the other, and the difference is the
  786. whole bug, so it is worth being explicit about where it comes from: the low
  787. bit of a Jcc code IS the negation bit. 4/5, C/D, E/F, 2/3, 6/7, A/9, B/8 and
  788. 0/1 are the eight (condition, its negation) pairs, so negating a condition is
  789. `n XOR 1' and nothing more - `JE' and `JNE' are 0x74 and 0x75.
  790. Gm2 under -fiso has no XOR on integers at all: BITAND and BAND are both
  791. syntax errors, and arithmetic on a BYTE operand is rejected too, which is
  792. why every operand here goes through VAL. n + 1 - 2*(n MOD 2) is XOR 1 for a
  793. four-bit n and it lives in one named place rather than open-coded, because
  794. an open-coded negation at two call sites is how they end up disagreeing. *)
  795. VAR n : CARDINAL ;
  796. BEGIN
  797. n := VAL (CARDINAL, cc) MOD 10H ;
  798. RETURN VAL (BYTE, 70H + n + 1 - 2 * (n MOD 2))
  799. END JccShortInv ;
  800. PROCEDURE EmJcc (cc : BYTE ; target : CARDINAL) : CARDINAL ;
  801. (* A conditional branch, 8086 style. `cc' is the condition nibble, and it is
  802. exactly the low byte of the `0F 8x rel16' this used to emit.
  803. That was a real fault and nothing in the build could see it: `0F' is a
  804. 386-and-later opcode prefix and the 8086 has none, so EVERY conditional
  805. branch in EVERY compiled program was an illegal instruction on the machine
  806. TP3 targets. FCML decoded it happily, because FCML's -m16 mode is 386 --
  807. and FCML is this project's independent disassembler, so the one tool that
  808. could have objected was the one guaranteed to agree. qemu-system-i386 has
  809. no 8086 model either; its lowest is 486. So the compile succeeded, the
  810. .COM linked, the layout checked, the golden held and all 30 fixtures ran to
  811. the right answers, all at once, with the bug in.
  812. TPSRC8 lays IF, WHILE and REPEAT out as
  813. MOV AL,brnchop ; MOV AH,#$03 ; CALL eword ; PUSH pc ; CALL ejump
  814. i.e. a SHORT Jcc of displacement 3, stepping over a 3-byte EJMP. That is
  815. the shape here too, and EmJmpNear already owns the displacement arithmetic
  816. and the patch slot, so it is three lines and there is no second copy of
  817. that rule.
  818. The one thing that is NOT the same as TPSRC8, and cost a round of "every
  819. conditional is inverted" (t09_if printed pos/nonpos/lt for a program that
  820. must print nonpos/pos/ge): TP3's brnchop is the branch taken when the
  821. condition is TRUE, and TP3 steps over the EJMP when it is taken. Here `cc'
  822. is the branch taken when the condition is FALSE -- IF's `EmJcc (84H)' is
  823. JZ, patched to the ELSE, so it must fire when the test failed. EmJcc jumps
  824. to the target, it does not step over it, so stepping over an EJMP and then
  825. falling into the destination is the wrong way round: the byte has to be
  826. JccShortInv, not JccShort. The control flow that comes out is identical to
  827. the `0F 8x' form this replaces; only which of the pair is spelled differs.
  828. The flags survive, and the FOR test needs them to: it emits CMP and then
  829. Jcc with nothing in between, so anything that wrote a flag here would
  830. break the loop. Jcc and EJMP both leave the flags alone. *)
  831. BEGIN
  832. Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)
  833. Ebyte (03H) ; (* rel8: step over the 3-byte EJMP *)
  834. RETURN EmJmpNear (target) (* target = 0 => forward, see above *)
  835. END EmJcc ;
  836. PROCEDURE ResolvePatches () ;
  837. VAR i : CARDINAL ;
  838. rel : CARDINAL ;
  839. BEGIN
  840. i := 0 ;
  841. WHILE i < nPatch DO
  842. IF NOT patches [i].filled THEN
  843. rel := (patches [i].target + 10000H - (patches [i].place + 2))
  844. MOD 10000H ;
  845. cbuf [patches [i].place] := VAL (BYTE, rel MOD 100H) ;
  846. cbuf [patches [i].place + 1] := VAL (BYTE, (rel DIV 100H) MOD 100H) ;
  847. patches [i].filled := TRUE
  848. END ;
  849. INC (i)
  850. END
  851. END ResolvePatches ;
  852. (* 1-byte const emitters *)
  853. PROCEDURE EmMovAxi (imm : CARDINAL) ;
  854. BEGIN
  855. Ebyte (0B8H) ; Eword (imm)
  856. END EmMovAxi ;
  857. PROCEDURE EmMovCxi (imm : CARDINAL) ;
  858. BEGIN
  859. Ebyte (0B9H) ; Eword (imm)
  860. END EmMovCxi ;
  861. PROCEDURE EmMovBpSp () ;
  862. BEGIN
  863. Ebyte (8BH) ; Ebyte (0ECH)
  864. END EmMovBpSp ;
  865. PROCEDURE EmMovAh0 () ;
  866. BEGIN
  867. Ebyte (0B4H) ; Ebyte (0H)
  868. END EmMovAh0 ;
  869. PROCEDURE EmMovAxSp () ;
  870. (* Read the top of the stack into AX, leaving the stack unchanged.
  871. The obvious encoding, MOV AX,[SP], DOES NOT EXIST on the 8086. There is
  872. no encoding of [SP] as a memory operand: SIB bytes, which is how [ESP]
  873. would be written, did not exist until the 386, and mod=00 / rm=100 is
  874. [SI], not [SP]. The first version of this emitted 8B 44 24 00 - mod=01,
  875. rm=100, SIB=24h, disp8=0 - which is correct only on a 386 and above. Two
  876. of this project's oracles agree that it is wrong: fcml in 16-bit mode
  877. decodes it as MOV AX,[SI+0x24h], and so does qemu executing it, because
  878. qemu follows the CPU's rules for the encoding it is given rather than
  879. guessing. It was not the encoder's fault that the bytes were well formed;
  880. they were, and they read SI+24h.
  881. The observable effect was that CASE compiled to no branches at all: each
  882. label test loaded a garbage address, every comparison failed, and the
  883. program fell straight past the whole statement and exited without printing.
  884. A CASE fixture caught it. Nothing else could have - the encoding is
  885. valid, the size is right, and the byte-level checks have no way to know
  886. what register was meant.
  887. So: POP then PUSH the same value. Two bytes, no SIB, correct on every
  888. 8086, and observationally identical to peeking - the stack pointer ends
  889. where it started, holding the same value. *)
  890. BEGIN
  891. Ebyte (58H) ; (* POP AX *)
  892. Ebyte (50H) (* PUSH AX *)
  893. END EmMovAxSp ;
  894. PROCEDURE EmMovCxSp () ;
  895. (* The same, for CX - the FOR loop's bound, pushed by the FOR statement and
  896. re-read on every iteration. This one was emitting 8B 0C and nothing else,
  897. which is MOV CX,[SI] with the SIB slot missing: the *next* instruction was
  898. consumed as the SIB byte and the displacement. Same root cause, same fix,
  899. and it had not been noticed only because no FOR fixture is executed yet. *)
  900. BEGIN
  901. Ebyte (59H) ; (* POP CX *)
  902. Ebyte (51H) (* PUSH CX *)
  903. END EmMovCxSp ;
  904. PROCEDURE EmPushAx () ;
  905. BEGIN
  906. Ebyte (50H)
  907. END EmPushAx ;
  908. PROCEDURE EmPopCx () ;
  909. BEGIN
  910. Ebyte (59H)
  911. END EmPopCx ;
  912. PROCEDURE EmPopDx () ;
  913. BEGIN
  914. Ebyte (5AH)
  915. END EmPopDx ;
  916. PROCEDURE EmPopSi () ;
  917. BEGIN
  918. Ebyte (5EH) (* POP SI *)
  919. END EmPopSi ;
  920. PROCEDURE EmPopAx () ;
  921. BEGIN
  922. Ebyte (58H) (* POP AX *)
  923. END EmPopAx ;
  924. (* 91 = XCHG AX,CX, and NOT 93. LoadPair hands the operator the left
  925. operand in CX and the right in AX (in the original, and still the
  926. commonest, shape: it pushes the left, loads the right, then pops the
  927. left into CX), so the exchange is what puts LEFT in AX for the
  928. operation to act on.
  929. Without it, `a - b` computes `b - a`; with the wrong register, `a + b`
  930. computes `AX' + a` where AX' is whatever BX happened to hold.
  931. This emitted 93H = XCHG BX,AX for its entire life, which is the same class
  932. of mistake as MovSiBx = 89 DC in Runtime.mod: the right opcode, the wrong
  933. ModRM, decoding cleanly. Byte counts were right, the compile matrix was
  934. green, and no exec fixture did arithmetic on two variables - the first one
  935. to do so, `c := a + b` with a=7 b=5, printed 263 = 0100h+7, where 0100h
  936. was the caller's leftover BX. The name was the only thing wrong, and
  937. nothing read the name: audit_helpers.py swept Runtime.mod and not
  938. Compiler.mod, which is where most of these emitters live. It does both
  939. modules now. *)
  940. PROCEDURE EmXchgAxCx () ;
  941. BEGIN
  942. Ebyte (91H)
  943. END EmXchgAxCx ;
  944. PROCEDURE EmXorAxAx () ;
  945. BEGIN
  946. Ebyte (33H) ; Ebyte (0C0H)
  947. END EmXorAxAx ;
  948. PROCEDURE EmAddAxCx () ;
  949. BEGIN
  950. Ebyte (3H) ; Ebyte (0C1H)
  951. END EmAddAxCx ;
  952. PROCEDURE EmSubAxCx () ;
  953. BEGIN
  954. Ebyte (2BH) ; Ebyte (0C1H)
  955. END EmSubAxCx ;
  956. PROCEDURE EmMulAxCx () ;
  957. BEGIN
  958. Ebyte (0F7H) ; Ebyte (0E9H)
  959. END EmMulAxCx ;
  960. PROCEDURE EmIDivAxCx () ;
  961. BEGIN
  962. Ebyte (99H) ; Ebyte (0F7H) ; Ebyte (0F9H)
  963. END EmIDivAxCx ;
  964. PROCEDURE EmAndAxCx () ;
  965. BEGIN
  966. Ebyte (23H) ; Ebyte (0C1H)
  967. END EmAndAxCx ;
  968. PROCEDURE EmOrAxCx () ;
  969. BEGIN
  970. Ebyte (0BH) ; Ebyte (0C1H)
  971. END EmOrAxCx ;
  972. PROCEDURE EmOrAxAx () ;
  973. (* 09 C0: OR AX,AX - the 8086's flag-only test of AX, and the one the string
  974. comparison needs, because cmpstr hands back a signed -1/0/+1 rather than
  975. flags. OR AX,AX sets SF and ZF from the value and clears OF and CF, which
  976. is exactly the flag state a CMP AX,0 would leave - see EmSetcc and
  977. ParseCmp's EmRelSetcc. TEST AX,AX (85 C0) does the same thing, but
  978. tests/audit_helpers.py's name grammar has no `Test' mnemonic, and an
  979. emitter that cannot be name-checked is worse than one that can.
  980. It is NOT EmXorAxAx: XORing AX with itself zeroes it, which would throw
  981. away the very value the flags are supposed to describe. *)
  982. BEGIN
  983. Ebyte (09H) ; Ebyte (0C0H)
  984. END EmOrAxAx ;
  985. PROCEDURE EmNegAx () ;
  986. BEGIN
  987. Ebyte (0F7H) ; Ebyte (0D8H)
  988. END EmNegAx ;
  989. PROCEDURE EmNotAx () ;
  990. BEGIN
  991. Ebyte (0F7H) ; Ebyte (0D0H)
  992. END EmNotAx ;
  993. PROCEDURE EmXorAl01 () ;
  994. (* XOR AL,#01 - TPSRC9 neglevel's *boolean* NOT:
  995. CALL loadatom ; CALL ecode ; B $02,$34,$01
  996. neglevel tests the type first (CMP CL,#$0A -> integer -> NOT AX,
  997. CMP CL,#$0B -> boolean -> XOR AL,#01) and reports error 47 for anything
  998. else. Emitting NOT AX for a boolean leaves 0FFFEh or 0FFFFh, and the
  999. runtime's wrbool tests [BP+4] <> 0, so `not (a = a)' came out TRUE. *)
  1000. BEGIN
  1001. Ebyte (34H) ; Ebyte (01H)
  1002. END EmXorAl01 ;
  1003. PROCEDURE EmCmpAxCx () ;
  1004. BEGIN
  1005. Ebyte (3BH) ; Ebyte (0C1H)
  1006. END EmCmpAxCx ;
  1007. PROCEDURE EmCmpAxi (imm : CARDINAL) ;
  1008. BEGIN
  1009. Ebyte (03DH) ; Eword (imm)
  1010. END EmCmpAxi ;
  1011. PROCEDURE EmSetcc (cc : BYTE) ;
  1012. (* Flags -> a Boolean in AX, on an 8086. `cc' is the SETcc opcode's low byte
  1013. (94H = E, 95H = NE, 9CH = L, 9DH = GE, 9EH = LE, 9FH = G), i.e. the same
  1014. condition nibble EmJcc takes.
  1015. This used to emit `0F cc C0' - SETcc - which is 386-and-later, and then a
  1016. MOV AH,0. The 8086 cannot read its flags as a value at all, so there was
  1017. nothing else to fall back on.
  1018. TPSRC9's flgbool is the fallback, and emits exactly this for exactly this
  1019. case (CH = 04h, a comparison whose result is wanted as a value rather than
  1020. as a branch):
  1021. CALL ecode ; B $03,$B8,$01,$00 -> MOV AX,#0001
  1022. MOV AL,brnchop ; CALL ebyte -> JNZ +1
  1023. CALL ecode ; B $02,$01,$48 -> DEC AX
  1024. AX stays 1 because the DEC was stepped over, and becomes 0 because it ran.
  1025. So the shape is one MOV, one short Jcc whose displacement is the length of
  1026. the DEC, and the DEC - which is EmJcc's shape with a different displacement,
  1027. and the reason both are two instructions and a byte.
  1028. The polarity is the opposite of EmJcc's, and deliberately so: here the jump
  1029. must be taken when the comparison is TRUE, because what is being asked is
  1030. "is this comparison true", and the nibble the six ParseCmp arms pass is the
  1031. comparison's own opcode. So this is JccShort and EmJcc is JccShortInv --
  1032. see EmJcc for why the difference is there at all. TP3's flgbool writes JNZ
  1033. for the same reason; in the one case IT reaches flgbool from, the boolean is
  1034. sitting in AX rather than in the flags, so JNZ is how it says "AX is
  1035. non-zero".
  1036. AH comes out 0 for free, which is why the EmMovAh0 this used to end with is
  1037. gone: 6 bytes here where the old sequence was 5. The FLAGS do not survive,
  1038. which the old SETcc did - and nothing reads them. Every conditional branch
  1039. in the compiler is preceded by its own CMP (see EmJcc's note on the FOR
  1040. test), and a comparison's value is consumed either as an AX operand or by
  1041. the test that follows it; the 30 executed fixtures are what holds that
  1042. down, not this comment. *)
  1043. BEGIN
  1044. Ebyte (0B8H) ; Eword (1) ; (* MOV AX,#0001 *)
  1045. Ebyte (JccShort (cc)) ; (* taken when the comparison HOLDS *)
  1046. Ebyte (01H) ; (* rel8: step over the DEC AX *)
  1047. Ebyte (48H) (* DEC AX *)
  1048. END EmSetcc ;
  1049. PROCEDURE EmRelSetcc (op : CARDINAL) ;
  1050. (* The relational operator -> SETcc table, in ONE place, because there are now
  1051. two callers: ParseCmp's numeric arm, whose flags come from EmCmpAxCx, and
  1052. its string arm, whose flags come from a cmpstr result put through
  1053. EmOrAxAx. It was factored out of ParseCmp when the string arm arrived, and
  1054. the note it carried is repeated here rather than referenced, because a
  1055. comment in the caller about a table in another routine is a comment nobody
  1056. reads.
  1057. The mnemonic is written next to every opcode on purpose. `op' is a number,
  1058. so the arm for ">" and the arm for ">=" differed only by two hex digits
  1059. that are each one letter from the other meaning -- SETG (9FH) and SETGE
  1060. (9DH). They were swapped once, which made a > b mean a >= b and a >= b
  1061. mean a > b. Only the equality boundary could see it: 6>5, 5<5, -1>-2 and
  1062. every other case I tried were already right. An opcode on its own does not
  1063. say which comparison it is the answer to.
  1064. `op' is ParseCmp's own numbering: 1 "=", 2 "<>", 3 "<", 4 ">", 5 ">=",
  1065. 6 "<=". The condition nibbles are the SIGNED ones (L/G/GE/LE), and both
  1066. callers hand it a value whose SIGN is the answer - ParseCmp's numeric arm
  1067. compares with CMP AX,CX on signed data, and cmpstr answers -1/0/+1 - so
  1068. the signed test is the right one in both places. One table also means that
  1069. swap cannot come back in one arm and not the other: tests/nonvacuity.sh
  1070. mutates exactly these two lines, and it now breaks the string comparison
  1071. at the same time as the numeric one. *)
  1072. BEGIN
  1073. CASE op OF
  1074. 1 : EmSetcc (94H) ; (* = SETE *)
  1075. | 2 : EmSetcc (95H) ; (* <> SETNE *)
  1076. | 3 : EmSetcc (9CH) ; (* < SETL *)
  1077. | 4 : EmSetcc (9FH) ; (* > SETG *)
  1078. | 5 : EmSetcc (9DH) ; (* >= SETGE *)
  1079. | 6 : EmSetcc (9EH) (* <= SETLE *)
  1080. END
  1081. END EmRelSetcc ;
  1082. PROCEDURE EmIncAx () ;
  1083. BEGIN
  1084. Ebyte (40H)
  1085. END EmIncAx ;
  1086. PROCEDURE EmDecAx () ;
  1087. BEGIN
  1088. Ebyte (48H)
  1089. END EmDecAx ;
  1090. PROCEDURE EmBpDisp (off, regf : CARDINAL) ;
  1091. (* Emit the ModR/M byte and displacement for a [BP+off] operand, picking the
  1092. encoding from the size of off. This is the ONE place that choice is made,
  1093. because getting it wrong is invisible: 8B 46 d8 and 8B 86 lo hi are both
  1094. well-formed MOVs, both decode cleanly, and only one of them reads the
  1095. variable the symbol table names. So the two are chosen here, once, rather
  1096. than re-derived at each of the four call sites. See the ModR/M table in
  1097. Runtime.mod.
  1098. off <= 127 -> mod=01 rm=110 -> 46 <disp8> 3 bytes with the opcode
  1099. otherwise -> mod=10 rm=110 -> 86 <disp16> 4 bytes with the opcode
  1100. Both displacements are SIGNED, and that is the whole subtlety:
  1101. - `off` is a 16-bit value and locals are packed top-anchored below BP:
  1102. locFree is the highest still-free byte (0FFFFh = -1 at entry), a local of
  1103. size n is based so its LAST byte sits on locFree, and locFree then drops
  1104. by n. So the first INTEGER local is at off = 0FFFEh = -2, the second at
  1105. 0FFFCh = -4, and so on - and a string local, which grows UP from its
  1106. base, lands wholly below BP instead of straddling it. The disp16 form
  1107. reads those same two bytes as a signed value and addresses the negative
  1108. slot correctly. There is no overflow case: all 65536 values of `off`
  1109. are representable, and a frame larger than 64K is a different problem.
  1110. - The old code took `off MOD 100H` and always emitted disp8. That is
  1111. the correct low byte for every displacement, so it was accidentally
  1112. right across -32768..+127, which is where locals actually live. It
  1113. went wrong at +128, where disp8 80h is -128 and not +128. So this
  1114. changes no existing program's bytes and fixes the one case that was
  1115. broken -- a bug nobody had hit yet, which is exactly why it wanted a
  1116. test rather than an argument. *)
  1117. BEGIN
  1118. (* mod=01 rm=110 -> 40H + regf*8 + 6H, mod=10 rm=110 -> 80H + regf*8 + 6H.
  1119. regf is the ModR/M reg field: 0 when the opcode's register is the
  1120. accumulator (every original caller), 7 for the DI forms EmLeaDi needs.
  1121. rm is 110 ([BP+disp]) in both. *)
  1122. IF off <= 127 THEN
  1123. Ebyte (VAL (BYTE, 40H + regf * 8 + 6H)) ; Ebyte (VAL (BYTE, off))
  1124. ELSE
  1125. Ebyte (VAL (BYTE, 80H + regf * 8 + 6H)) ; Eword (off)
  1126. END
  1127. END EmBpDisp ;
  1128. PROCEDURE EmLoadVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1129. (* A local is [BP+off] and `off' is already a frame displacement, so it needs
  1130. no bias. A global is [off] with a DIRECT displacement, i.e. an absolute
  1131. address, and that is the image offset + LoadBias - see Runtime.LoadBias. *)
  1132. BEGIN
  1133. IF nbytes = 1 THEN
  1134. IF local THEN
  1135. Ebyte (8AH) ; EmBpDisp (off, 0)
  1136. ELSE
  1137. Ebyte (0A0H) ; Eword ((off + LoadBias) MOD 10000H)
  1138. END
  1139. ELSE
  1140. IF local THEN
  1141. Ebyte (8BH) ; EmBpDisp (off, 0)
  1142. ELSE
  1143. Ebyte (0A1H) ; Eword ((off + LoadBias) MOD 10000H)
  1144. END
  1145. END
  1146. END EmLoadVar ;
  1147. PROCEDURE EmStoreVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1148. BEGIN
  1149. IF nbytes = 1 THEN
  1150. IF local THEN
  1151. Ebyte (88H) ; EmBpDisp (off, 0)
  1152. ELSE
  1153. Ebyte (0A2H) ; Eword ((off + LoadBias) MOD 10000H)
  1154. END
  1155. ELSE
  1156. IF local THEN
  1157. Ebyte (89H) ; EmBpDisp (off, 0)
  1158. ELSE
  1159. Ebyte (0A3H) ; Eword ((off + LoadBias) MOD 10000H)
  1160. END
  1161. END
  1162. END EmStoreVar ;
  1163. PROCEDURE EmPushVarAddr (local : BOOLEAN ; off : CARDINAL) ;
  1164. (* LEA AX,[BP+disp] / LEA AX,[off] then PUSH AX - READ passes the address of
  1165. a variable, not its value. 8D 46 disp is LEA AX,[BP+disp8] and
  1166. 8D 86 lo hi is LEA AX,[BP+disp16]; 8D 06 off is LEA AX,[off]
  1167. (mod=00 rm=110 = the direct disp16 form). All three are 8086-legal.
  1168. The [off] form is absolute and so carries LoadBias; the [BP+disp] forms
  1169. are displacements and so do not. *)
  1170. BEGIN
  1171. IF local THEN
  1172. Ebyte (8DH) ; EmBpDisp (off, 0)
  1173. ELSE
  1174. Ebyte (8DH) ; Ebyte (06H) ; Eword ((off + LoadBias) MOD 10000H)
  1175. END ;
  1176. EmPushAx ()
  1177. END EmPushVarAddr ;
  1178. PROCEDURE EmLeaDi (local : BOOLEAN ; off : CARDINAL) ;
  1179. (* LEA DI,[BP+disp] / LEA DI,[off] - the run-time address of an indexed
  1180. string's element, computed once in ParseSub and read by LoadAtom,
  1181. Assignment and IoCall.
  1182. It is the same three encodings EmPushVarAddr uses for AX - 8D 7E disp8,
  1183. 8D BE disp16, 8D 3E off - with the ModR/M reg field set to DI (111)
  1184. instead of the accumulator, which is why EmBpDisp now takes that field and
  1185. this is still the one place the disp8/disp16 choice is made. A local is
  1186. [BP+disp] with no bias; a global is [off] and carries LoadBias, absolute.
  1187. The later `MOV AL,[DI]` / `MOV [DI],AL` read through DS rather than SS.
  1188. That is correct here for the same reason TP3's own string ops use DI with
  1189. the default segment: a .COM loads with DS=SS=CS=ES, and nothing in this
  1190. compiler or its runtime ever reloads a segment register, so a BP-relative
  1191. frame address held in DI addresses the same byte. *)
  1192. BEGIN
  1193. IF local THEN
  1194. Ebyte (8DH) ; EmBpDisp (off, 7)
  1195. ELSE
  1196. Ebyte (8DH) ; Ebyte (3EH) ; Eword ((off + LoadBias) MOD 10000H)
  1197. END
  1198. END EmLeaDi ;
  1199. PROCEDURE EmAddDiAx () ;
  1200. BEGIN Ebyte (01H) ; Ebyte (0C7H) END EmAddDiAx ; (* 01 C7: DI := DI + AX *)
  1201. PROCEDURE EmAddDiImm (n : CARDINAL) ;
  1202. (* ADD DI,imm16: a record field's offset when the element's address is already
  1203. in DI (`Sheet[I,J].Field', `with Sheet[I,J] do'). *)
  1204. BEGIN
  1205. Ebyte (81H) ; Ebyte (0C7H) ; Eword (n MOD 10000H)
  1206. END EmAddDiImm ;
  1207. PROCEDURE EmLdDiGlob (off : CARDINAL) ;
  1208. (* MOV DI,[off]: recover the base address WITH saved in a scratch word. The
  1209. body of a WITH may clobber DI, so the address is parked in the data area
  1210. and reloaded for every field access. *)
  1211. BEGIN
  1212. Ebyte (8BH) ; Ebyte (3EH) ; Eword ((off + LoadBias) MOD 10000H)
  1213. END EmLdDiGlob ;
  1214. PROCEDURE EmStDiGlob (off : CARDINAL) ;
  1215. (* MOV [off],DI: the WITH statement's base-address scratch. *)
  1216. BEGIN
  1217. Ebyte (89H) ; Ebyte (3EH) ; Eword ((off + LoadBias) MOD 10000H)
  1218. END EmStDiGlob ;
  1219. PROCEDURE EmLdAlDi () ;
  1220. BEGIN Ebyte (8AH) ; Ebyte (05H) END EmLdAlDi ; (* 8A 05: AL := [DI] *)
  1221. PROCEDURE EmMovDiAx () ;
  1222. BEGIN Ebyte (89H) ; Ebyte (0C7H) END EmMovDiAx ; (* 89 C7: DI := AX *)
  1223. PROCEDURE EmLdAxDi () ;
  1224. BEGIN Ebyte (8BH) ; Ebyte (05H) END EmLdAxDi ; (* 8B 05: AX := [DI] *)
  1225. PROCEDURE EmStDiAl () ;
  1226. BEGIN Ebyte (88H) ; Ebyte (05H) END EmStDiAl ; (* 88 05: [DI] := AL *)
  1227. PROCEDURE EmPushDi () ;
  1228. BEGIN Ebyte (57H) END EmPushDi ; (* PUSH DI *)
  1229. PROCEDURE EmPopDi () ;
  1230. BEGIN Ebyte (5FH) END EmPopDi ; (* POP DI *)
  1231. PROCEDURE EmLoadVarInd (off, nbytes : CARDINAL) ;
  1232. (* AX := the value of a VAR parameter. [BP+off] holds the ADDRESS; BX carries
  1233. it so the byte/word load has a base register. The address is a DS offset:
  1234. a .COM has one segment, which is why no segment register appears here. *)
  1235. BEGIN
  1236. EmLoadVar (TRUE, off, 2) ; (* AX := [BP+off], the address *)
  1237. Ebyte (89H) ; Ebyte (0C3H) ; (* MOV BX,AX *)
  1238. IF nbytes = 1 THEN
  1239. Ebyte (8AH) ; Ebyte (07H) ; (* MOV AL,[BX] *)
  1240. EmMovAh0 ()
  1241. ELSE
  1242. Ebyte (8BH) ; Ebyte (07H) (* MOV AX,[BX] *)
  1243. END
  1244. END EmLoadVarInd ;
  1245. PROCEDURE EmStoreVarIndPrep (off : CARDINAL) ;
  1246. (* DI := the address of a VAR parameter, then PUSH DI. The push protects it
  1247. across the parse of the right-hand side, which may use DI for a string
  1248. element of its own. EmStoreInd finishes the store after POP DI. *)
  1249. BEGIN
  1250. Ebyte (8BH) ; EmBpDisp (off, 7) ; (* MOV DI,[BP+off] *)
  1251. EmPushDi ()
  1252. END EmStoreVarIndPrep ;
  1253. PROCEDURE EmStDiImm (off, v : CARDINAL) ;
  1254. (* MOV byte [DI+off],imm8: one byte of a set constructor stored through a
  1255. DI-addressed record field. Sets are at most 32 bytes, so disp8 is enough. *)
  1256. BEGIN
  1257. Ebyte (0C6H) ; Ebyte (45H) ; Ebyte (VAL (BYTE, off)) ; Ebyte (VAL (BYTE, v))
  1258. END EmStDiImm ;
  1259. PROCEDURE EmStDiAlOff (off : CARDINAL) ;
  1260. (* MOV [DI+off],AL: one byte of a real copied through a DI-addressed field. *)
  1261. BEGIN
  1262. Ebyte (88H) ; Ebyte (45H) ; Ebyte (VAL (BYTE, off))
  1263. END EmStDiAlOff ;
  1264. PROCEDURE EmLdAlDiOff (off : CARDINAL) ;
  1265. (* MOV AL,[DI+off]: the byte of a set variable that holds an element's bit. *)
  1266. BEGIN
  1267. Ebyte (8AH) ; Ebyte (45H) ; Ebyte (VAL (BYTE, off))
  1268. END EmLdAlDiOff ;
  1269. PROCEDURE EmCmpAlImm (v : CARDINAL) ;
  1270. BEGIN Ebyte (3CH) ; Ebyte (VAL (BYTE, v)) END EmCmpAlImm ; (* CMP AL,imm8 *)
  1271. PROCEDURE EmSubAlImm (v : CARDINAL) ;
  1272. BEGIN Ebyte (2CH) ; Ebyte (VAL (BYTE, v)) END EmSubAlImm ; (* SUB AL,imm8 *)
  1273. PROCEDURE EmMovClAl () ;
  1274. BEGIN Ebyte (88H) ; Ebyte (0C1H) END EmMovClAl ; (* MOV CL,AL *)
  1275. PROCEDURE EmAndClImm (v : CARDINAL) ;
  1276. BEGIN Ebyte (80H) ; Ebyte (0E1H) ; Ebyte (VAL (BYTE, v)) END EmAndClImm ;
  1277. PROCEDURE EmShrAx1 () ;
  1278. BEGIN Ebyte (0D1H) ; Ebyte (0E8H) END EmShrAx1 ; (* SHR AX,1 *)
  1279. PROCEDURE EmMovBxi (v : CARDINAL) ;
  1280. BEGIN Ebyte (0BBH) ; Eword (v MOD 10000H) END EmMovBxi ; (* MOV BX,imm16 *)
  1281. PROCEDURE EmLeaBx (off : CARDINAL) ;
  1282. (* LEA BX,[BP+off]: the address of a local set. *)
  1283. BEGIN
  1284. Ebyte (8DH) ; EmBpDisp (off, 3)
  1285. END EmLeaBx ;
  1286. PROCEDURE EmMovBxDi () ;
  1287. BEGIN Ebyte (89H) ; Ebyte (0FBH) END EmMovBxDi ; (* MOV BX,DI *)
  1288. PROCEDURE EmAddBxAx () ;
  1289. BEGIN Ebyte (01H) ; Ebyte (0C3H) END EmAddBxAx ; (* ADD BX,AX *)
  1290. PROCEDURE EmLdAlBx () ;
  1291. BEGIN Ebyte (8AH) ; Ebyte (07H) END EmLdAlBx ; (* MOV AL,[BX] *)
  1292. PROCEDURE EmMovDlImm (v : CARDINAL) ;
  1293. BEGIN Ebyte (0B2H) ; Ebyte (VAL (BYTE, v)) END EmMovDlImm ;
  1294. PROCEDURE EmShlDlCl () ;
  1295. BEGIN Ebyte (0D2H) ; Ebyte (0E2H) END EmShlDlCl ; (* SHL DL,CL *)
  1296. PROCEDURE EmAndAlDl () ;
  1297. BEGIN Ebyte (20H) ; Ebyte (0D0H) END EmAndAlDl ; (* AND AL,DL *)
  1298. PROCEDURE EmAndAlImm (v : CARDINAL) ;
  1299. BEGIN Ebyte (24H) ; Ebyte (VAL (BYTE, v)) END EmAndAlImm ; (* AND AL,imm8 *)
  1300. PROCEDURE EmStoreInd (nbytes : CARDINAL) ;
  1301. (* [DI] := AL/WORD, after POP DI - the companion of EmStoreVarIndPrep. *)
  1302. BEGIN
  1303. IF nbytes = 1 THEN
  1304. EmStDiAl () (* MOV [DI],AL *)
  1305. ELSE
  1306. Ebyte (89H) ; Ebyte (05H) (* MOV [DI],AX *)
  1307. END
  1308. END EmStoreInd ;
  1309. PROCEDURE EmFileIo (reading : BOOLEAN ; fileLocal : BOOLEAN ; fileOff : CARDINAL ;
  1310. addrKind : CARDINAL ; addrLocal : BOOLEAN ;
  1311. addrOff, count : CARDINAL ; stringArg : BOOLEAN) ;
  1312. (* Typed-file block I/O: read/write `count' bytes at the data argument to the
  1313. open file in the file variable.
  1314. ABI to DOS: BX = handle, CX = byte count, DS:DX = buffer, AH = 3Fh read /
  1315. 40h write. The handle is the first word of the file control block. For a
  1316. DI-addressed record (`Sheet[I,J]') the address is already in DI; a plain
  1317. variable's address is formed by LEA. The DOS result is handed to the
  1318. io_store runtime entry, so IOResult sees it.
  1319. This is emitted directly rather than through a runtime entry because the
  1320. runtime has only ~45 bytes of probe headroom left; the code is two words
  1321. per call site and the compiler's code budget is the loose one. *)
  1322. BEGIN
  1323. IF addrKind = 5 THEN
  1324. (* DI already holds a kind-5 element's address. *)
  1325. ELSIF addrKind = 4 THEN
  1326. EmLeaDi (FALSE, addrOff) (* a code-resident blob *)
  1327. ELSIF addrKind = 1 THEN
  1328. EmLeaDi (addrLocal, addrOff)
  1329. ELSE
  1330. Err (ETypeErr) ;
  1331. RETURN
  1332. END ;
  1333. Ebyte (89H) ; Ebyte (0FAH) ; (* MOV DX,DI *)
  1334. IF stringArg THEN
  1335. (* DX points at the characters, CX = the length byte at [DI]. *)
  1336. Ebyte (42H) ; (* INC DX *)
  1337. EmLdAlDi () ;
  1338. EmMovClAl () ;
  1339. Ebyte (30H) ; Ebyte (0EDH) (* XOR CH,CH *)
  1340. ELSE
  1341. EmMovCxi (count)
  1342. END ;
  1343. EmLoadVar (fileLocal, fileOff, 2) ; (* AX := the DOS handle *)
  1344. Ebyte (89H) ; Ebyte (0C3H) ; (* MOV BX,AX *)
  1345. Ebyte (0B4H) ; (* MOV AH,3Fh/40h *)
  1346. IF reading THEN Ebyte (3FH) ELSE Ebyte (40H) END ;
  1347. Ebyte (0CDH) ; Ebyte (21H) ; (* INT 21h *)
  1348. DropC (EmCall (TU_IoStore))
  1349. END EmFileIo ;
  1350. PROCEDURE EmInlineCh (ch : CARDINAL) : CARDINAL ;
  1351. (* Emit a one-character string literal behind a JMP and return the image
  1352. offset of its length byte. Used by text-file Write(File, ' '). *)
  1353. VAR here : CARDINAL ;
  1354. BEGIN
  1355. Ebyte (0EBH) ; Ebyte (2) ;
  1356. here := pc ;
  1357. Ebyte (1) ; Ebyte (VAL (BYTE, ch)) ;
  1358. RETURN here
  1359. END EmInlineCh ;
  1360. PROCEDURE EmInlineCrLf () : CARDINAL ;
  1361. (* The CR LF pair every text-file Writeln emits. *)
  1362. VAR here : CARDINAL ;
  1363. BEGIN
  1364. Ebyte (0EBH) ; Ebyte (3) ;
  1365. here := pc ;
  1366. Ebyte (2) ; Ebyte (13) ; Ebyte (10) ;
  1367. RETURN here
  1368. END EmInlineCrLf ;
  1369. PROCEDURE EmSubSp (n : CARDINAL) ;
  1370. BEGIN
  1371. Ebyte (81H) ; Ebyte (0ECH) ; Eword (n MOD 10000H)
  1372. END EmSubSp ;
  1373. PROCEDURE EmAddSp (n : CARDINAL) ;
  1374. BEGIN
  1375. IF n <= 126 THEN
  1376. Ebyte (83H) ; Ebyte (0C4H) ; Ebyte (VAL (BYTE, n))
  1377. ELSE
  1378. Ebyte (81H) ; Ebyte (0C4H) ; Eword (n MOD 10000H)
  1379. END
  1380. END EmAddSp ;
  1381. PROCEDURE EmPushBp () ;
  1382. BEGIN
  1383. Ebyte (55H)
  1384. END EmPushBp ;
  1385. PROCEDURE EmLeave () ;
  1386. BEGIN
  1387. Ebyte (0C9H)
  1388. END EmLeave ;
  1389. PROCEDURE EmRet () ;
  1390. BEGIN
  1391. Ebyte (0C3H)
  1392. END EmRet ;
  1393. (* ---------------------------------------------------------------- *)
  1394. (* symbol table *)
  1395. (* ---------------------------------------------------------------- *)
  1396. PROCEDURE NameEq (a : ARRAY OF CHAR ; b : ARRAY OF CHAR) : BOOLEAN ;
  1397. VAR i : CARDINAL ;
  1398. BEGIN
  1399. i := 0 ;
  1400. LOOP
  1401. IF i > HIGH (a) THEN
  1402. RETURN FALSE
  1403. END ;
  1404. IF i > HIGH (b) THEN
  1405. RETURN FALSE
  1406. END ;
  1407. IF a [i] # b [i] THEN
  1408. RETURN FALSE
  1409. END ;
  1410. IF a [i] = 0C THEN
  1411. RETURN TRUE
  1412. END ;
  1413. INC (i)
  1414. END
  1415. END NameEq ;
  1416. PROCEDURE CopyStr (VAR dst : ARRAY OF CHAR ; src : ARRAY OF CHAR) ;
  1417. VAR i : CARDINAL ;
  1418. BEGIN
  1419. i := 0 ;
  1420. LOOP
  1421. IF i > HIGH (dst) THEN
  1422. dst [HIGH (dst)] := 0C ;
  1423. RETURN
  1424. END ;
  1425. IF i > HIGH (src) THEN
  1426. dst [i] := 0C ;
  1427. RETURN
  1428. END ;
  1429. dst [i] := src [i] ;
  1430. IF src [i] = 0C THEN
  1431. RETURN
  1432. END ;
  1433. INC (i)
  1434. END
  1435. END CopyStr ;
  1436. PROCEDURE CopyWord (name : ARRAY OF CHAR) ;
  1437. (* stash current word into global wrd (uppercased) *)
  1438. VAR i : CARDINAL ;
  1439. BEGIN
  1440. i := 0 ;
  1441. LOOP
  1442. IF i > HIGH (name) THEN
  1443. wrd [i] := 0C ;
  1444. RETURN
  1445. END ;
  1446. IF i > MaxName THEN
  1447. wrd [MaxName] := 0C ;
  1448. RETURN
  1449. END ;
  1450. IF name [i] = 0C THEN
  1451. wrd [i] := 0C ;
  1452. RETURN
  1453. END ;
  1454. wrd [i] := Upper (name [i]) ;
  1455. INC (i)
  1456. END
  1457. END CopyWord ;
  1458. PROCEDURE SaveWord (VAR dst : ARRAY OF CHAR) ;
  1459. (* copy wrd into dst *)
  1460. VAR i : CARDINAL ;
  1461. BEGIN
  1462. i := 0 ;
  1463. LOOP
  1464. IF i > HIGH (dst) THEN
  1465. dst [HIGH (dst)] := 0C ;
  1466. RETURN
  1467. END ;
  1468. IF i > MaxName THEN
  1469. dst [MaxName] := 0C ;
  1470. RETURN
  1471. END ;
  1472. dst [i] := wrd [i] ;
  1473. IF wrd [i] = 0C THEN
  1474. RETURN
  1475. END ;
  1476. INC (i)
  1477. END
  1478. END SaveWord ;
  1479. PROCEDURE NumToName (n : CARDINAL ; VAR dst : ARRAY OF CHAR) ;
  1480. VAR buf : ARRAY [0..9] OF CHAR ;
  1481. i, j : CARDINAL ;
  1482. BEGIN
  1483. IF n = 0 THEN
  1484. dst [0] := '0' ;
  1485. dst [1] := 0C ;
  1486. RETURN
  1487. END ;
  1488. i := 0 ;
  1489. WHILE n > 0 DO
  1490. IF i <= 9 THEN
  1491. buf [i] := CHR (ORD ('0') + (n MOD 10)) ;
  1492. INC (i)
  1493. END ;
  1494. n := n DIV 10
  1495. END ;
  1496. j := 0 ;
  1497. WHILE i > 0 DO
  1498. DEC (i) ;
  1499. IF j <= HIGH (dst) THEN
  1500. dst [j] := buf [i] ;
  1501. INC (j)
  1502. END
  1503. END ;
  1504. IF j <= HIGH (dst) THEN
  1505. dst [j] := 0C
  1506. END
  1507. END NumToName ;
  1508. PROCEDURE NewSym (name : ARRAY OF CHAR ; tag : CARDINAL ;
  1509. cls, size, elem, off : CARDINAL ; v : LONGINT ;
  1510. local : BOOLEAN) : CARDINAL ;
  1511. VAR e : SymEntry ;
  1512. BEGIN
  1513. IF symTop >= MaxSym THEN
  1514. Err (ECompOvf) ;
  1515. RETURN 0
  1516. END ;
  1517. CopyWord (name) ;
  1518. CopyStr (e.name, wrd) ;
  1519. e.tag := tag ;
  1520. e.cls := cls ;
  1521. e.size := size ;
  1522. e.elem := elem ;
  1523. e.off := off ;
  1524. e.lval := v ;
  1525. e.lo := 0 ;
  1526. e.hi := 0 ;
  1527. e.fldFirst := 0 ;
  1528. e.fldLast := 0 ;
  1529. e.arrIdx := 0 ;
  1530. e.parmFirst := 0 ;
  1531. e.parmCount := 0 ;
  1532. e.isKbd := FALSE ;
  1533. e.isVar := FALSE ;
  1534. e.level := lexnest ;
  1535. e.local := local ;
  1536. e.resvar := 0 ;
  1537. e.goPos := 0 ;
  1538. e.defnd := FALSE ;
  1539. e.fwd := FALSE ;
  1540. symtab [symTop] := e ;
  1541. INC (symTop) ;
  1542. RETURN symTop - 1
  1543. END NewSym ;
  1544. PROCEDURE Search (nm : ARRAY OF CHAR ; VAR idx : CARDINAL) : BOOLEAN ;
  1545. (* find nm among symbols visible at the current lexical level *)
  1546. VAR p : CARDINAL ;
  1547. BEGIN
  1548. CopyWord (nm) ;
  1549. p := symTop ;
  1550. WHILE p > 0 DO
  1551. DEC (p) ;
  1552. IF symtab [p].level <= lexnest THEN
  1553. IF NameEq (symtab [p].name, wrd) THEN
  1554. idx := p ;
  1555. RETURN TRUE
  1556. END
  1557. END
  1558. END ;
  1559. RETURN FALSE
  1560. END Search ;
  1561. PROCEDURE DupTest (nm : ARRAY OF CHAR) ;
  1562. (* A name may be declared twice only in the SAME scope. This used to reject
  1563. any name Search could see, so a parameter could not shadow a global - legal
  1564. ISO Pascal, and CALC.INC's `procedure IBMCh(var Ch: Char)' does exactly
  1565. that (`Ch' is a global). Same-level duplicates stay errors: two parameters
  1566. in one list, two locals, or two globals. *)
  1567. VAR i : CARDINAL ;
  1568. BEGIN
  1569. IF Search (nm, i) THEN
  1570. IF symtab [i].level = lexnest THEN
  1571. Err (EUnknown)
  1572. END
  1573. END
  1574. END DupTest ;
  1575. PROCEDURE HideLocals (from : CARDINAL) ;
  1576. (* Make every symbol from index `from' up invisible to everything outside the
  1577. procedure that declared it.
  1578. Search accepts a symbol when its level is <= lexnest, and every procedure
  1579. body is compiled at the same depth (lexnest 1), so a finished procedure's
  1580. parameters stayed visible to the NEXT procedure: a second `a : integer'
  1581. was a duplicate (err 41) and an unqualified `a' inside procedure two read
  1582. procedure one's argument. Level 0FFFFH fails `level <= lexnest' at every
  1583. depth a later procedure can be at, and by the time this runs the body that
  1584. could still legitimately see them is finished.
  1585. The symbols are relabelled, not popped: symtab[old].resvar holds an INDEX,
  1586. and a function's result variable is one of the entries being hidden. *)
  1587. VAR p : CARDINAL ;
  1588. BEGIN
  1589. p := from ;
  1590. WHILE p < symTop DO
  1591. symtab [p].level := 0FFFFH ;
  1592. INC (p)
  1593. END
  1594. END HideLocals ;
  1595. (* ---------------------------------------------------------------- *)
  1596. (* lexer *)
  1597. (* ---------------------------------------------------------------- *)
  1598. PROCEDURE InitKeys () ;
  1599. VAR i : CARDINAL ;
  1600. BEGIN
  1601. FOR i := 0 TO 42 DO
  1602. kTk [i] := 0 ;
  1603. kName [i] [0] := 0C
  1604. END ;
  1605. kName [1] := "PROGRAM" ; kTk [1] := TkProgram ;
  1606. kName [2] := "BEGIN" ; kTk [2] := TkBegin ;
  1607. kName [3] := "END" ; kTk [3] := TkEnd ;
  1608. kName [4] := "IF" ; kTk [4] := TkIf ;
  1609. kName [5] := "THEN" ; kTk [5] := TkThen ;
  1610. kName [6] := "ELSE" ; kTk [6] := TkElse ;
  1611. kName [7] := "WHILE" ; kTk [7] := TkWhile ;
  1612. kName [8] := "DO" ; kTk [8] := TkDo ;
  1613. kName [9] := "REPEAT" ; kTk [9] := TkRepeat ;
  1614. kName [10] := "UNTIL" ; kTk [10] := TkUntil ;
  1615. kName [11] := "FOR" ; kTk [11] := TkFor ;
  1616. kName [12] := "TO" ; kTk [12] := TkTo ;
  1617. kName [13] := "DOWNTO" ; kTk [13] := TkDownto ;
  1618. kName [14] := "CASE" ; kTk [14] := TkCase ;
  1619. kName [15] := "OF" ; kTk [15] := TkOf ;
  1620. kName [16] := "GOTO" ; kTk [16] := TkGoto ;
  1621. kName [17] := "EXIT" ; kTk [17] := TkExit ;
  1622. kName [18] := "WITH" ; kTk [18] := TkWith ;
  1623. kName [19] := "VAR" ; kTk [19] := TkVar ;
  1624. kName [20] := "CONST" ; kTk [20] := TkConst ;
  1625. kName [21] := "TYPE" ; kTk [21] := TkType ;
  1626. kName [22] := "LABEL" ; kTk [22] := TkLabel ;
  1627. kName [23] := "PROCEDURE" ; kTk [23] := TkProcedure ;
  1628. kName [24] := "FUNCTION" ; kTk [24] := TkFunction ;
  1629. kName [25] := "NIL" ; kTk [25] := TkNil ;
  1630. kName [26] := "AND" ; kTk [26] := TkAnd ;
  1631. kName [27] := "OR" ; kTk [27] := TkOr ;
  1632. kName [28] := "NOT" ; kTk [28] := TkNot ;
  1633. kName [29] := "DIV" ; kTk [29] := TkDiv ;
  1634. kName [30] := "MOD" ; kTk [30] := TkMod ;
  1635. kName [31] := "IN" ; kTk [31] := TkIn ;
  1636. kName [32] := "FILE" ; kTk [32] := TkFile ;
  1637. kName [33] := "TEXT" ; kTk [33] := TkText ;
  1638. kName [34] := "RECORD" ; kTk [34] := TkRecord ;
  1639. kName [35] := "ARRAY" ; kTk [35] := TkArray ;
  1640. kName [36] := "SET" ; kTk [36] := TkSet ;
  1641. kName [37] := "PACKED" ; kTk [37] := TkPacked ;
  1642. kName [38] := "FORWARD" ; kTk [38] := TkForward ;
  1643. kName [39] := "EXTERNAL" ; kTk [39] := TkExternal ;
  1644. kName [40] := "ABSOLUTE" ; kTk [40] := TkAbsolute ;
  1645. kName [41] := "OVERLAY" ; kTk [41] := TkOverlay ;
  1646. kName [42] := "STRING" ; kTk [42] := TkString
  1647. END InitKeys ;
  1648. PROCEDURE IsBlank (ch : CHAR) : BOOLEAN ;
  1649. BEGIN
  1650. RETURN (ch = ' ') OR (ORD (ch) = 09H) OR (ORD (ch) = 0DH) OR (ORD (ch) = 0AH) OR (ORD (ch) = 0CH)
  1651. END IsBlank ;
  1652. PROCEDURE Skip () ;
  1653. (* blanks, comments { } and (* *), compiler directives {$ } / (*$ *)
  1654. letter + sign toggles rng/chk. Include directives are already gone by the
  1655. time Skip runs: ExpandIncludes splices them into the buffer first, so the
  1656. {$I file} spelling never reaches here. {$I+}/{$I-} still do, and stay the
  1657. I/O-check toggle, exactly as TPSRC10 cdirec splits them on the sign. *)
  1658. VAR ch : CHAR ;
  1659. letter : CHAR ;
  1660. BEGIN
  1661. WHILE NOT abortFac DO
  1662. WHILE IsBlank (CurCh ()) DO
  1663. ch := GetCh ()
  1664. END ;
  1665. IF CurCh () = '{' THEN
  1666. ch := GetCh () ;
  1667. IF CurCh () = '$' THEN
  1668. ch := GetCh () ;
  1669. letter := Upper (GetCh ()) ;
  1670. IF CurCh () = '+' THEN
  1671. ch := GetCh () ;
  1672. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1673. IF letter = 'R' THEN dirs.rng := TRUE END
  1674. ELSIF CurCh () = '-' THEN
  1675. ch := GetCh () ;
  1676. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1677. IF letter = 'R' THEN dirs.rng := FALSE END
  1678. END
  1679. END ;
  1680. WHILE (CurCh () # '}') AND (CurCh () # 0C) DO
  1681. ch := GetCh ()
  1682. END ;
  1683. IF CurCh () = '}' THEN
  1684. ch := GetCh ()
  1685. END
  1686. ELSIF (CurCh () = '(') AND (PeekAhead (1) = '*') THEN
  1687. ch := GetCh () ;
  1688. ch := GetCh () ;
  1689. IF CurCh () = '$' THEN
  1690. ch := GetCh () ;
  1691. letter := Upper (GetCh ()) ;
  1692. IF CurCh () = '+' THEN
  1693. ch := GetCh () ;
  1694. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1695. IF letter = 'R' THEN dirs.rng := TRUE END
  1696. ELSIF CurCh () = '-' THEN
  1697. ch := GetCh () ;
  1698. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1699. IF letter = 'R' THEN dirs.rng := FALSE END
  1700. END
  1701. END ;
  1702. LOOP
  1703. IF (CurCh () = '*') AND (PeekAhead (1) = ')') THEN
  1704. ch := GetCh () ;
  1705. ch := GetCh () ;
  1706. EXIT
  1707. END ;
  1708. IF CurCh () = 0C THEN
  1709. EXIT
  1710. END ;
  1711. ch := GetCh ()
  1712. END
  1713. ELSE
  1714. RETURN
  1715. END
  1716. END
  1717. END Skip ;
  1718. PROCEDURE GetWord () ;
  1719. (* read identifier into wrd (uppercased); next char must be alpha *)
  1720. VAR i : CARDINAL ;
  1721. ch : CHAR ;
  1722. BEGIN
  1723. i := 0 ;
  1724. ch := GetCh () ;
  1725. LOOP
  1726. IF i > MaxName THEN
  1727. wrd [MaxName] := 0C ;
  1728. RETURN
  1729. END ;
  1730. wrd [i] := Upper (ch) ;
  1731. INC (i) ;
  1732. ch := CurCh () ;
  1733. IF NOT AlphaNum (ch) THEN
  1734. wrd [i] := 0C ;
  1735. RETURN
  1736. END ;
  1737. ch := GetCh ()
  1738. END
  1739. END GetWord ;
  1740. PROCEDURE WddTok () : CARDINAL ;
  1741. (* map wrd -> keyword token *)
  1742. VAR i : CARDINAL ;
  1743. BEGIN
  1744. i := 1 ;
  1745. WHILE i <= 42 DO
  1746. IF kName [i] [0] # 0C THEN
  1747. IF NameEq (wrd, kName [i]) THEN
  1748. RETURN kTk [i]
  1749. END
  1750. END ;
  1751. INC (i)
  1752. END ;
  1753. RETURN TkNone
  1754. END WddTok ;
  1755. PROCEDURE DeclaresProc () : BOOLEAN ;
  1756. (* Does the REST of the source declare a PROCEDURE or a FUNCTION?
  1757. Needed because the declaration part is compiled BEFORE the main statement
  1758. part, so a procedure's code lands between the program prologue and the
  1759. main body - and nothing jumps over it. A program with a procedure
  1760. therefore ran off the end of the prologue, straight into the first
  1761. procedure, which read its argument out of an uninitialised frame and
  1762. returned to address 0. Every Pascal program containing a procedure was
  1763. broken; `t13_proc` compiled and was never executed, so nothing saw it.
  1764. The jump that fixes it has to be emitted BEFORE the declaration part, but
  1765. whether one is needed is only known AFTER - so the only honest options are
  1766. to emit it unconditionally (3 dead bytes in every program, and every code
  1767. size in expected.tsv moves) or to know the answer in advance. This is the
  1768. second: it scans ahead and puts srcPos back.
  1769. That is safe because the whole program is already in `src` and `srcPos` is
  1770. a plain index into it - the same trick PeekKw and KwAhead use. The scan
  1771. looks for the keywords anywhere in the remainder rather than tracking the
  1772. nesting of `begin`s, which is deliberately loose: a program with no
  1773. procedures that merely mentions the word in a string literal would get a
  1774. 3-byte jump to the next instruction, which is harmless, whereas tracking
  1775. the main `begin` against a procedure's `begin` would be a second parser
  1776. to get wrong. *)
  1777. VAR save : CARDINAL ;
  1778. found : BOOLEAN ;
  1779. tk : CARDINAL ;
  1780. ch : CHAR ;
  1781. BEGIN
  1782. save := srcPos ;
  1783. found := FALSE ;
  1784. tk := TkNone ; (* so the answer is defined if src is empty *)
  1785. (* Step over delimiters as well as blanks. Stopping at the first
  1786. non-letter looked reasonable and was wrong: `var x : integer ;` is full
  1787. of ':' and ';', so the scan gave up inside the variable section and
  1788. never reached the PROCEDURE. The loop ends at the end of the source,
  1789. not at the first punctuation. *)
  1790. WHILE (NOT found) AND (srcPos < srcLen) DO
  1791. Skip () ;
  1792. IF Alpha (CurCh ()) THEN
  1793. GetWord () ;
  1794. tk := WddTok () ;
  1795. IF (tk = TkProcedure) OR (tk = TkFunction) THEN
  1796. found := TRUE
  1797. END
  1798. ELSE
  1799. ch := GetCh () (* a ':' or ';' - step over it *)
  1800. END
  1801. END ;
  1802. srcPos := save ;
  1803. RETURN (tk = TkProcedure) OR (tk = TkFunction)
  1804. END DeclaresProc ;
  1805. PROCEDURE KwAhead (word : ARRAY OF CHAR) : BOOLEAN ;
  1806. (* does the next token (past blanks/comments) equal the keyword 'word',
  1807. without consuming it? srcPos is saved and restored. *)
  1808. VAR save : CARDINAL ;
  1809. k : BOOLEAN ;
  1810. BEGIN
  1811. save := srcPos ;
  1812. Skip () ;
  1813. k := FALSE ;
  1814. IF Alpha (CurCh ()) THEN
  1815. GetWord () ;
  1816. k := NameEq (wrd, word)
  1817. END ;
  1818. srcPos := save ;
  1819. RETURN k
  1820. END KwAhead ;
  1821. PROCEDURE PeekKw (VAR tok : CARDINAL) ;
  1822. (* peek at the next keyword token without consuming it *)
  1823. VAR i : CARDINAL ;
  1824. BEGIN
  1825. tok := TkNone ;
  1826. i := 1 ;
  1827. WHILE i <= 42 DO
  1828. IF kName [i] [0] # 0C THEN
  1829. IF KwAhead (kName [i]) THEN
  1830. tok := kTk [i] ;
  1831. RETURN
  1832. END
  1833. END ;
  1834. INC (i)
  1835. END
  1836. END PeekKw ;
  1837. PROCEDURE MatchKey (VAR tok : CARDINAL) : BOOLEAN ;
  1838. (* skip; if next symbol is a word, read it into wrd and set its token.
  1839. Returns TRUE when a word was read (tok = TkNone for plain ids). *)
  1840. BEGIN
  1841. tok := TkNone ;
  1842. Skip () ;
  1843. IF NOT Alpha (CurCh ()) THEN
  1844. RETURN FALSE
  1845. END ;
  1846. GetWord () ;
  1847. tok := WddTok () ;
  1848. RETURN TRUE
  1849. END MatchKey ;
  1850. PROCEDURE MatchDelim (ch : CHAR) : BOOLEAN ;
  1851. BEGIN
  1852. Skip () ;
  1853. IF CurCh () = ch THEN
  1854. DropCh (GetCh ()) ;
  1855. RETURN TRUE
  1856. END ;
  1857. RETURN FALSE
  1858. END MatchDelim ;
  1859. PROCEDURE MatchAssign () : BOOLEAN ;
  1860. BEGIN
  1861. Skip () ;
  1862. IF (CurCh () = ':') AND (PeekAhead (1) = '=') THEN
  1863. DropCh (GetCh ()) ;
  1864. DropCh (GetCh ()) ;
  1865. RETURN TRUE
  1866. END ;
  1867. RETURN FALSE
  1868. END MatchAssign ;
  1869. PROCEDURE MatchRange () : BOOLEAN ;
  1870. BEGIN
  1871. Skip () ;
  1872. IF (CurCh () = '.') AND (PeekAhead (1) = '.') THEN
  1873. DropCh (GetCh ()) ;
  1874. DropCh (GetCh ()) ;
  1875. RETURN TRUE
  1876. END ;
  1877. RETURN FALSE
  1878. END MatchRange ;
  1879. PROCEDURE ExpectDelim (ch : CHAR ; n : CARDINAL) ;
  1880. BEGIN
  1881. Skip () ;
  1882. IF CurCh () = ch THEN
  1883. DropCh (GetCh ())
  1884. ELSE
  1885. Err (n)
  1886. END
  1887. END ExpectDelim ;
  1888. PROCEDURE HexVal (ch : CHAR) : CARDINAL ;
  1889. BEGIN
  1890. IF (ch >= '0') AND (ch <= '9') THEN
  1891. RETURN ORD (ch) - ORD ('0')
  1892. ELSIF (ch >= 'A') AND (ch <= 'F') THEN
  1893. RETURN ORD (ch) - ORD ('A') + 10
  1894. END ;
  1895. RETURN ORD (ch) - ORD ('a') + 10
  1896. END HexVal ;
  1897. PROCEDURE RdIntConst (VAR v : LONGINT) ;
  1898. (* bare integer constant; current char is digit or '$' *)
  1899. VAR acc : LONGINT ;
  1900. BEGIN
  1901. acc := 0 ;
  1902. IF CurCh () = '$' THEN
  1903. DropCh (GetCh ()) ;
  1904. WHILE IsHexCh (CurCh ()) DO
  1905. acc := acc * 16 + VAL (LONGINT, HexVal (CurCh ())) ;
  1906. DropCh (GetCh ())
  1907. END
  1908. ELSE
  1909. WHILE Digit (CurCh ()) DO
  1910. acc := acc * 10 + VAL (LONGINT, ORD (CurCh ()) - ORD ('0')) ;
  1911. DropCh (GetCh ())
  1912. END
  1913. END ;
  1914. v := acc
  1915. END RdIntConst ;
  1916. PROCEDURE StrNew (first : CARDINAL ; hasFirst : BOOLEAN ) : CARDINAL ;
  1917. (* Open a pool slot for a string literal, optionally pre-seeded with its
  1918. first character.
  1919. RdConst has to read the first character before it can tell a one-character
  1920. literal from a longer one - the "is the next character another quote?"
  1921. test only makes sense once something has been read - so the seeding has to
  1922. happen here and has to advance strTop. Leaving strTop alone and letting the
  1923. caller write the character by hand is a trap: strTop is the next FREE byte,
  1924. so the first StrPut lands on top of the seeded character and overwrites it.
  1925. (That bug shipped the literal 'hi' as 69 00 - 'i' then NUL.) *)
  1926. VAR x : CARDINAL ;
  1927. BEGIN
  1928. IF strCnt > HIGH (strOff) THEN
  1929. Err (ECompOvf) ; (* too many literals in one unit *)
  1930. RETURN 0
  1931. END ;
  1932. x := strCnt ;
  1933. strOff [x] := strTop ;
  1934. strLen [x] := 0 ;
  1935. INC (strCnt) ;
  1936. IF hasFirst THEN
  1937. strPool [strTop] := CHR (first) ;
  1938. INC (strTop) ;
  1939. strLen [x] := 1
  1940. END ;
  1941. rdStrX := x ;
  1942. RETURN x
  1943. END StrNew ;
  1944. PROCEDURE StrPut (x : CARDINAL ) ;
  1945. (* append the current source character to pool slot x *)
  1946. BEGIN
  1947. IF x > HIGH (strOff) THEN
  1948. RETURN
  1949. END ;
  1950. IF strTop > HIGH (strPool) THEN
  1951. Err (ECompOvf) ; (* literal longer than the pool *)
  1952. RETURN
  1953. END ;
  1954. strPool [strTop] := CurCh () ;
  1955. INC (strTop) ;
  1956. INC (strLen [x])
  1957. END StrPut ;
  1958. PROCEDURE RdConst (VAR v : LONGINT ; VAR cls : CARDINAL ;
  1959. VAR isStr : BOOLEAN) ;
  1960. (* scalar or string constant. A string literal's text is collected into the
  1961. pool and its slot index left in rdStrX; a single-character literal stays a
  1962. TScalar holding its character code, which is what "c := 'a'" wants. *)
  1963. CONST q = AposC ;
  1964. VAR ch : CHAR ;
  1965. idx : CARDINAL ;
  1966. BEGIN
  1967. isStr := FALSE ;
  1968. cls := TScalar ;
  1969. v := 0 ;
  1970. Skip () ;
  1971. IF CurCh () = '$' THEN
  1972. RdIntConst (v) ;
  1973. cls := TScalar
  1974. ELSIF Digit (CurCh ()) THEN
  1975. RdIntConst (v) ;
  1976. IF (CurCh () = '.') AND (Digit (PeekAhead (1))) THEN
  1977. cls := TReal ;
  1978. DropCh (GetCh ())
  1979. END ;
  1980. IF (CurCh () = 'E') OR (CurCh () = 'e') THEN
  1981. cls := TReal ;
  1982. DropCh (GetCh ())
  1983. END ;
  1984. IF cls = TReal THEN
  1985. WHILE AlphaNum (CurCh ()) OR (CurCh () = '.') OR (CurCh () = '-')
  1986. OR (CurCh () = '+') DO
  1987. DropCh (GetCh ())
  1988. END
  1989. END
  1990. ELSIF CurCh () = '^' THEN
  1991. (* TP3 caret character constant, unquoted: ^M is CR (13), ^[ is ESC
  1992. (27), ^@ is 0. The value is the upper-cased character minus 64, so
  1993. the +256-MOD-256 keeps ^@ and any control character from wrapping. *)
  1994. DropCh (GetCh ()) ;
  1995. IF CurCh () = 0C THEN
  1996. Err (EUnknown)
  1997. ELSE
  1998. ch := Upper (GetCh ()) ;
  1999. v := VAL (LONGINT, (ORD (ch) + 256 - 64) MOD 256) ;
  2000. cls := TScalar
  2001. END
  2002. ELSIF CurCh () = '#' THEN
  2003. (* TP3 decimal character constant: #27, #255. *)
  2004. DropCh (GetCh ()) ;
  2005. IF Digit (CurCh ()) THEN
  2006. RdIntConst (v) ;
  2007. cls := TScalar
  2008. ELSE
  2009. Err (EUnknown)
  2010. END
  2011. ELSIF Alpha (CurCh ()) THEN
  2012. (* TRUE / FALSE, or a NAMED constant - an enumerator (`[Constant,
  2013. Formula]'), or any earlier const. A constant expression may name a
  2014. constant, and set literals and `case' labels are full of enumerators. *)
  2015. GetWord () ;
  2016. IF NameEq (wrd, "TRUE") THEN
  2017. v := 1 ;
  2018. cls := TBool
  2019. ELSIF NameEq (wrd, "FALSE") THEN
  2020. v := 0 ;
  2021. cls := TBool
  2022. ELSIF Search (wrd, idx) AND (symtab [idx].tag = KConst) THEN
  2023. v := symtab [idx].lval ;
  2024. cls := symtab [idx].cls
  2025. ELSE
  2026. Err (EUnknown)
  2027. END
  2028. ELSIF ORD (CurCh ()) = q THEN
  2029. DropCh (GetCh ()) ;
  2030. IF ORD (CurCh ()) = q THEN
  2031. (* '' - the empty string. It used to be reported as the scalar 39,
  2032. so writeln('') printed a single quote mark. It is a string of
  2033. length zero, and an inline zero-length literal is exactly what the
  2034. runtime's JCXZ path is for. *)
  2035. DropCh (GetCh ()) ;
  2036. isStr := TRUE ;
  2037. cls := TString ;
  2038. v := 0 ;
  2039. rdStrX := StrNew (0, FALSE)
  2040. ELSIF (CurCh () = 0C) OR ((ORD (CurCh ()) = 0DH)) OR ((ORD (CurCh ()) = 0AH)) THEN
  2041. Err (EUnknown)
  2042. ELSE
  2043. v := VAL (LONGINT, ORD (GetCh ())) ;
  2044. cls := TScalar ;
  2045. IF ORD (CurCh ()) = q THEN
  2046. DropCh (GetCh ())
  2047. ELSE
  2048. isStr := TRUE ;
  2049. cls := TString ;
  2050. (* Scan to the closing quote. NB: the loop condition must test
  2051. the CURRENT character and only the current character. The
  2052. obvious-looking "while CurCh # quote" with a
  2053. "if PeekAhead(1) = quote then consume two" body is wrong:
  2054. consuming the quote moves the cursor past it, so the next
  2055. condition test sees the character AFTER the literal, is
  2056. satisfied, and the scan runs on to end-of-buffer - which
  2057. silently eats the rest of the program and makes every later
  2058. error point at end-of-file. Stop on the quote itself, and
  2059. treat a doubled quote as one embedded quote character.
  2060. The first character is already gone - it was read into v above -
  2061. so the pool slot is pre-seeded with it. *)
  2062. rdStrX := StrNew (VAL (CARDINAL, v), TRUE) ;
  2063. LOOP
  2064. IF ORD (CurCh ()) = q THEN
  2065. IF ORD (PeekAhead (1)) = q THEN
  2066. StrPut (rdStrX) ; (* '' inside *)
  2067. DropCh (GetCh ()) ; DropCh (GetCh ())
  2068. ELSE
  2069. EXIT (* closing quote *)
  2070. END
  2071. ELSIF (CurCh () = 0C) OR (ORD (CurCh ()) = 0DH) THEN
  2072. Err (EUnknown) ; (* unterminated *)
  2073. EXIT
  2074. ELSE
  2075. StrPut (rdStrX) ;
  2076. DropCh (GetCh ())
  2077. END
  2078. END ;
  2079. IF ORD (CurCh ()) = q THEN
  2080. DropCh (GetCh ())
  2081. END
  2082. END
  2083. END
  2084. ELSE
  2085. Err (EUnknown)
  2086. END
  2087. END RdConst ;
  2088. (* ---------------------------------------------------------------- *)
  2089. (* forward declarations *)
  2090. (* ---------------------------------------------------------------- *)
  2091. PROCEDURE ParseExpr (VAR r : ERes) ; FORWARD ;
  2092. PROCEDURE ParseAdd (VAR r : ERes) ; FORWARD ;
  2093. PROCEDURE ParseMul (VAR r : ERes) ; FORWARD ;
  2094. PROCEDURE ParseNeg (VAR r : ERes) ; FORWARD ;
  2095. PROCEDURE ParseAtom (VAR r : ERes) ; FORWARD ;
  2096. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ; FORWARD ;
  2097. PROCEDURE Statmnt () ; FORWARD ;
  2098. PROCEDURE ParseCall (idx : CARDINAL) ; FORWARD ;
  2099. PROCEDURE ParseCallArgs (idx : CARDINAL) ; FORWARD ;
  2100. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ; FORWARD ;
  2101. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ; FORWARD ;
  2102. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ; FORWARD ;
  2103. (* ---------------------------------------------------------------- *)
  2104. (* expressions (TPSRC9) *)
  2105. (* ---------------------------------------------------------------- *)
  2106. PROCEDURE VarSize (r : ERes) : CARDINAL ;
  2107. (* The width of a kind-1 value. An element (`b[i]') or a field (`r.f') has a
  2108. size of its own, which is NOT its variable's; when the parser has recorded
  2109. one, it wins. Otherwise the variable's declared size is the answer. *)
  2110. BEGIN
  2111. IF r.sz > 0 THEN
  2112. RETURN r.sz
  2113. END ;
  2114. RETURN symtab [r.idx].size
  2115. END VarSize ;
  2116. PROCEDURE LoadAtom (VAR r : ERes) ;
  2117. (* load value of r into AX (folding constants).
  2118. A string literal is refused here, and this is the single place that has to:
  2119. assignment, IF, WHILE, FOR, REPEAT, CASE, array subscripts and every
  2120. operator all reach their operand through LoadAtom, and none of them can use
  2121. a counted string where a 16-bit word is expected. Reporting it here rather
  2122. than in the parser means writeln('hi') still works - IoCall handles a
  2123. literal before it ever calls LoadAtom. *)
  2124. VAR emsz : CARDINAL ;
  2125. BEGIN
  2126. IF r.cls = TString THEN
  2127. Err (ENoLib) ; (* string value used as a number *)
  2128. r.kind := 2 ;
  2129. RETURN
  2130. END ;
  2131. IF r.cls = TSet THEN
  2132. (* A set is bytes, not a 16-bit value. It is legal as the right operand
  2133. of `in' (and later as a whole-value operand of `+'/`*'/'='/assignment),
  2134. all of which handle it BEFORE LoadAtom - but never as a number, which
  2135. would otherwise load its first two bytes as if it were an integer. *)
  2136. Err (ENoLib) ;
  2137. r.kind := 2 ;
  2138. RETURN
  2139. END ;
  2140. IF r.kind = 5 THEN
  2141. (* An element whose address ParseSub computed into DI (LEA DI,[base] /
  2142. ADD DI,AX): a string character, or an array element of one or two
  2143. bytes. Zeroing AH keeps a one-byte value a clean 16-bit char. The
  2144. read must happen HERE, before anything else is emitted: the caller
  2145. reaches this immediately after parsing the subscript, or - for a
  2146. binary operator - SaveLeft has already materialised it, so DI is
  2147. still the element's address. *)
  2148. IF VarSize (r) > 2 THEN
  2149. Err (ENoLib) ; (* a whole record/array as a value *)
  2150. r.kind := 2 ;
  2151. RETURN
  2152. END ;
  2153. IF VarSize (r) = 2 THEN
  2154. EmLdAxDi ()
  2155. ELSE
  2156. EmLdAlDi () ;
  2157. EmMovAh0 ()
  2158. END ;
  2159. r.kind := 2 ;
  2160. RETURN
  2161. END ;
  2162. IF r.kind = 0 THEN
  2163. EmMovAxi (W16 (r.imm)) ;
  2164. r.kind := 2
  2165. ELSIF r.kind = 1 THEN
  2166. IF symtab [r.idx].isVar THEN
  2167. (* A VAR parameter: [BP+off] holds the address, and the value is one
  2168. level down. r.boff is necessarily 0 - a by-reference parameter is
  2169. a scalar in this increment, so it has nothing to subscript. *)
  2170. IF r.boff # 0 THEN
  2171. Err (ENoLib) ;
  2172. r.kind := 2 ;
  2173. RETURN
  2174. END ;
  2175. EmLoadVarInd (symtab [r.idx].off, VarSize (r)) ;
  2176. r.kind := 2 ;
  2177. RETURN
  2178. END ;
  2179. IF (VarSize (r) > 2) AND NOT
  2180. ((r.cls = TChar) AND (symtab [r.idx].cls = TString)) THEN
  2181. Err (ENoLib)
  2182. ELSE
  2183. (* s[i] indexes one byte of a string, not the string, so its width is
  2184. one whatever the variable's declared width is. *)
  2185. emsz := VarSize (r) ;
  2186. IF (r.cls = TChar) AND (symtab [r.idx].cls = TString) THEN
  2187. emsz := 1
  2188. END ;
  2189. EmLoadVar (symtab [r.idx].local,
  2190. (symtab [r.idx].off + r.boff) MOD 10000H,
  2191. emsz) ;
  2192. IF emsz = 1 THEN
  2193. EmMovAh0 ()
  2194. END ;
  2195. r.kind := 2
  2196. END
  2197. END
  2198. END LoadAtom ;
  2199. PROCEDURE ParseSub (VAR r : ERes) ;
  2200. (* consume '[' expr ']' while present.
  2201. A CONSTANT index folds into the base offset boff, exactly as before. A
  2202. VARIABLE index on a STRING cannot fold - off+i is a run-time value - so it
  2203. is computed once here into DI and r.kind drops to 5, which is how LoadAtom,
  2204. Assignment and IoCall are told the element's address is in DI. Arrays
  2205. still accept only a constant index: a variable array subscript needs the
  2206. element-size scaling that a one-byte string element does not, and it is
  2207. item 2. *)
  2208. VAR t : ERes ;
  2209. ai, fi, nd, k, st : CARDINAL ;
  2210. coff : LONGINT ;
  2211. accOnStack, haveVar, more : BOOLEAN ;
  2212. found : BOOLEAN ;
  2213. BEGIN
  2214. LOOP
  2215. Skip () ;
  2216. IF CurCh () = '.' THEN
  2217. (* FIELD selection: `r.f'. The field's offset adds to the record
  2218. base's, and the value's class and WIDTH become the field's - which
  2219. is the whole reason a width rides on the expression (VarSize). *)
  2220. DropCh (GetCh ()) ;
  2221. Skip () ;
  2222. IF NOT Alpha (CurCh ()) THEN
  2223. Err (EUnknown) ;
  2224. RETURN
  2225. END ;
  2226. GetWord () ;
  2227. IF symtab [r.idx].fldFirst >= symtab [r.idx].fldLast THEN
  2228. Err (ESimpType) ; (* not a record *)
  2229. RETURN
  2230. END ;
  2231. fi := symtab [r.idx].fldFirst ;
  2232. found := FALSE ;
  2233. WHILE (fi < symtab [r.idx].fldLast) AND NOT found DO
  2234. IF NameEq (fields [fi].name, wrd) THEN
  2235. found := TRUE
  2236. ELSE
  2237. INC (fi)
  2238. END
  2239. END ;
  2240. IF NOT found THEN
  2241. Err (EUnknown) ;
  2242. RETURN
  2243. END ;
  2244. IF r.kind = 5 THEN
  2245. (* The element's address is in DI: a field is a fixed offset from
  2246. it. The array symbol already carries the element record's
  2247. field range (DefVar copies recFldFirst/recFldLast), which is
  2248. why the lookup above works for `Sheet[I,J].Field' too. *)
  2249. IF fields [fi].off # 0 THEN
  2250. EmAddDiImm (fields [fi].off)
  2251. END
  2252. ELSE
  2253. r.boff := W16 (VAL (LONGINT, r.boff)
  2254. + VAL (LONGINT, fields [fi].off)) ;
  2255. END ;
  2256. r.cls := fields [fi].cls ;
  2257. r.sz := fields [fi].size ;
  2258. IF r.cls = TSet THEN
  2259. (* ParseVar set setoff only when the SYMBOL itself was a set; for
  2260. an array/record the class was still TArray/TRecord then, so the
  2261. base offset has to be recorded now. *)
  2262. r.setoff := symtab [r.idx].off ;
  2263. r.setbase := fields [fi].elem ;
  2264. r.setsize := fields [fi].size
  2265. END
  2266. ELSIF CurCh () = '[' THEN
  2267. DropCh (GetCh ()) ;
  2268. IF symtab [r.idx].cls = TString THEN
  2269. (* s[i]: a STRING is a length byte at s[0] followed by the
  2270. characters, so index i selects the one byte at off+i. A second
  2271. subscript on a character is not a type. *)
  2272. ParseExpr (t) ;
  2273. IF OK () THEN
  2274. IF r.cls = TChar THEN
  2275. Err (ESimpType) ;
  2276. RETURN
  2277. END ;
  2278. IF symtab [r.idx].isVar THEN
  2279. (* VAR string parameter: the base is the address in the
  2280. parameter slot, not LEA of the slot. Compute DI once for
  2281. both constant and variable indices, so LoadAtom and
  2282. Assignment see the same kind-5 character address they do
  2283. for an ordinary string. *)
  2284. EmLoadVar (TRUE, symtab [r.idx].off, 2) ;
  2285. EmMovDiAx () ;
  2286. IF t.kind = 0 THEN
  2287. EmAddDiImm ((r.boff + W16 (t.imm)) MOD 10000H)
  2288. ELSE
  2289. IF r.boff # 0 THEN
  2290. EmAddDiImm (r.boff)
  2291. END ;
  2292. LoadAtom (t) ;
  2293. EmAddDiAx ()
  2294. END ;
  2295. r.kind := 5
  2296. ELSIF t.kind = 0 THEN
  2297. (* constant index: fold it into boff, as an array's does, and
  2298. r.cls drops to TChar so every consumer below - LoadAtom,
  2299. Assignment, IoCall - sees a one-byte value instead of the
  2300. whole string. *)
  2301. r.boff := W16 (VAL (LONGINT, r.boff) + t.imm)
  2302. ELSE
  2303. (* Variable index. Compute the element address once, now:
  2304. the index is evaluated into AX (LoadAtom is a no-op for a
  2305. kind-2 value and re-reads [DI] for a nested subscript), then
  2306. DI := base + AX. This is TP3's indstr/ialoop shape (TPSRC9
  2307. 1100-1111, 1200-1229), which likewise holds the address in
  2308. DI until the byte is loaded or stored; a register is what
  2309. lets a later LoadAtom read [DI] and a later assignment PUSH
  2310. DI across its right-hand side. *)
  2311. LoadAtom (t) ;
  2312. EmLeaDi (symtab [r.idx].local,
  2313. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  2314. EmAddDiAx () ;
  2315. r.kind := 5
  2316. END ;
  2317. r.cls := TChar ;
  2318. r.sz := 1
  2319. END ;
  2320. ExpectDelim (']', ENoSemi)
  2321. ELSIF symtab [r.idx].cls = TArray THEN
  2322. (* An array subscript LIST: one expression per dimension, comma
  2323. separated. The byte offset is
  2324. sum over k of (i[k] - lo[k]) * stride[k]
  2325. where stride[k] is the element size times the count of every
  2326. LATER dimension (row-major: the LAST dimension varies fastest).
  2327. A constant index folds into coff; a run-time one is scaled as
  2328. soon as it is parsed and summed on the STACK, because parsing
  2329. the next index may clobber AX and DI. *)
  2330. IF (r.kind = 5) OR (symtab [r.idx].arrIdx = 0) THEN
  2331. Err (ESimpType) ;
  2332. RETURN
  2333. END ;
  2334. ai := symtab [r.idx].arrIdx - 1 ;
  2335. nd := 0 ;
  2336. coff := 0 ;
  2337. accOnStack := FALSE ;
  2338. haveVar := FALSE ;
  2339. LOOP
  2340. IF nd >= arrs [ai].n THEN
  2341. Err (ETypeErr) ;
  2342. RETURN
  2343. END ;
  2344. ParseExpr (t) ;
  2345. IF NOT OK () THEN
  2346. RETURN
  2347. END ;
  2348. st := arrs [ai].elem ;
  2349. k := nd + 1 ;
  2350. WHILE k < arrs [ai].n DO
  2351. st := st * W16 (arrs [ai].hi [k] - arrs [ai].lo [k] + 1) ;
  2352. INC (k)
  2353. END ;
  2354. Skip () ;
  2355. more := CurCh () = ',' ;
  2356. IF t.kind = 0 THEN
  2357. coff := coff + (t.imm - arrs [ai].lo [nd])
  2358. * VAL (LONGINT, st)
  2359. ELSE
  2360. LoadAtom (t) ;
  2361. IF arrs [ai].lo [nd] # 0 THEN
  2362. EmMovCxi (W16 (arrs [ai].lo [nd])) ;
  2363. EmSubAxCx ()
  2364. END ;
  2365. IF st # 1 THEN
  2366. EmMovCxi (st) ;
  2367. EmMulAxCx ()
  2368. END ;
  2369. IF more THEN
  2370. (* the next dimension's expression will clobber AX: park
  2371. the running sum. A SINGLE index skips this entirely,
  2372. so 1-D code is byte-identical to the old path. *)
  2373. IF accOnStack THEN
  2374. EmPopCx () ;
  2375. EmAddAxCx () ;
  2376. EmPushAx ()
  2377. ELSE
  2378. EmPushAx () ;
  2379. accOnStack := TRUE
  2380. END
  2381. ELSE
  2382. (* last dimension: AX is the total *)
  2383. IF accOnStack THEN
  2384. EmPopCx () ;
  2385. EmAddAxCx () ;
  2386. accOnStack := FALSE
  2387. END ;
  2388. haveVar := TRUE
  2389. END
  2390. END ;
  2391. INC (nd) ;
  2392. IF more THEN
  2393. DropCh (GetCh ())
  2394. ELSE
  2395. EXIT
  2396. END
  2397. END ;
  2398. IF nd # arrs [ai].n THEN
  2399. (* fewer subscripts than dimensions: the value would be a
  2400. sub-array, which has no scalar representation *)
  2401. Err (ETypeErr) ;
  2402. RETURN
  2403. END ;
  2404. ExpectDelim (']', ENoSemi) ;
  2405. IF accOnStack THEN
  2406. (* the last dimensions were constant: the parked sum is still
  2407. on the stack, and AX is the total *)
  2408. EmPopAx () ;
  2409. accOnStack := FALSE
  2410. END ;
  2411. IF haveVar THEN
  2412. EmLeaDi (symtab [r.idx].local,
  2413. (symtab [r.idx].off + r.boff
  2414. + W16 (coff)) MOD 10000H) ;
  2415. EmAddDiAx () ;
  2416. r.kind := 5
  2417. ELSE
  2418. r.boff := W16 (VAL (LONGINT, r.boff) + coff)
  2419. END ;
  2420. r.sz := arrs [ai].elem ;
  2421. r.cls := arrs [ai].ecls
  2422. ELSE
  2423. ParseExpr (t) ;
  2424. IF OK () THEN
  2425. IF t.kind # 0 THEN
  2426. Err (ENoLib)
  2427. ELSE
  2428. Err (ESimpType)
  2429. END
  2430. END ;
  2431. ExpectDelim (']', ENoSemi)
  2432. END
  2433. ELSE
  2434. RETURN
  2435. END
  2436. END
  2437. END ParseSub ;
  2438. PROCEDURE ParseVar (VAR r : ERes) ;
  2439. (* name [ '[' constExpr ']' ]* ; a function name maps to its result var *)
  2440. VAR idx : CARDINAL ;
  2441. BEGIN
  2442. IF NOT Search (wrd, idx) THEN
  2443. Err (EUnknown) ;
  2444. RETURN
  2445. END ;
  2446. r.idx := idx ;
  2447. r.kind := 1 ;
  2448. r.boff := 0 ;
  2449. r.cls := symtab [idx].cls ;
  2450. IF symtab [idx].tag = KFunc THEN
  2451. idx := symtab [idx].resvar ;
  2452. r.idx := idx ;
  2453. r.cls := symtab [idx].cls
  2454. ELSIF (symtab [idx].tag # KVar) AND (symtab [idx].tag # KType) THEN
  2455. Err (EUnknown) ;
  2456. RETURN
  2457. END ;
  2458. IF r.cls = TSet THEN
  2459. (* a set value: carry where its bytes are so ParseCmp can fold `in' and
  2460. (later) compare. A set VARIABLE is still refused at its declaration,
  2461. so today this is a typed constant or an inline literal. *)
  2462. r.setoff := symtab [r.idx].off ;
  2463. r.setbase := symtab [r.idx].elem ;
  2464. r.setsize := symtab [r.idx].size
  2465. END ;
  2466. r.sz := symtab [r.idx].size ;
  2467. ParseSub (r)
  2468. END ParseVar ;
  2469. PROCEDURE ConstAdd (a, b : LONGINT) : LONGINT ;
  2470. BEGIN
  2471. RETURN VAL (LONGINT, W16 (a + b))
  2472. END ConstAdd ;
  2473. PROCEDURE ConstSub (a, b : LONGINT) : LONGINT ;
  2474. BEGIN
  2475. RETURN VAL (LONGINT, W16 (a - b))
  2476. END ConstSub ;
  2477. PROCEDURE ConstMul (a, b : LONGINT) : LONGINT ;
  2478. BEGIN
  2479. RETURN VAL (LONGINT, W16 (a * b))
  2480. END ConstMul ;
  2481. PROCEDURE EmXchgAxDx () ;
  2482. (* 92h = XCHG AX,DX. Named for what it EMITS, which is the point of the
  2483. whole naming convention: this used to be called EmMoveAxDx, which is what
  2484. somebody would expect the opcode to be, and it is not - 89 D8 is
  2485. MOV AX,DX, 92h is the exchange. Here the exchange is what is wanted, so
  2486. the name is the only thing that was wrong, and it was wrong in the exact
  2487. way this file's names are not allowed to be: reading as "a move" when it
  2488. is a swap. After EmIDivAxCx the remainder is in DX and `mod` wants it in
  2489. AX; an exchange gets it there in one byte where a move also would, so the
  2490. behaviour is identical either way and only the name lied. *)
  2491. BEGIN
  2492. Ebyte (92H)
  2493. END EmXchgAxDx ;
  2494. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ; FORWARD ;
  2495. PROCEDURE StrOperand (r : ERes) : BOOLEAN ; FORWARD ;
  2496. PROCEDURE BinOpEmit (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2497. (* binary operation at one precedence level; folds constant operands *)
  2498. VAR f : LONGINT ;
  2499. okc : BOOLEAN ;
  2500. BEGIN
  2501. IF StrOperand (left) OR StrOperand (right) THEN
  2502. (* A string OPERAND - a STRING or a CHAR, which is a one-character string
  2503. for this purpose - makes this a string operation, and `+' is the only
  2504. one ISO Modula-2 defines: every other binary operator reached here
  2505. (OR, and the multiplicative and additive numeric ops) has no meaning
  2506. over a STRING, and StrConcat rejects it.
  2507. The test is StrOperand and NOT `cls = TString' because of the two
  2508. CHAR operands. `'a' + 'b'' has no STRING in it at all, so a
  2509. TString-only test let it fall through to the integer path, where the
  2510. character codes were added and CHR(195) was printed - a silently
  2511. wrong program rather than an error (see t53_strcat_type). A CHAR
  2512. operand is still a string operand, which is also what makes `a + ch'
  2513. concatenate.
  2514. Handling it here, at the head of the one routine every binary
  2515. operator funnels through, is what keeps `a + b', `writeln(a + b)',
  2516. `(a + b) = c' and `s := a + b + c' all going through the same
  2517. emission. *)
  2518. StrConcat (op, left, right, res) ;
  2519. RETURN
  2520. END ;
  2521. IF op = TkAnd THEN
  2522. IF (left.kind = 0) AND (right.kind = 0) THEN
  2523. res.kind := 0 ;
  2524. res.imm := BitAnd (left.imm, right.imm) ;
  2525. res.cls := TBool ;
  2526. RETURN
  2527. END ;
  2528. LoadPair (left, right) ;
  2529. EmAndAxCx () ;
  2530. res.kind := 2 ; res.cls := TBool ;
  2531. RETURN
  2532. END ;
  2533. IF op = TkOr THEN
  2534. IF (left.kind = 0) AND (right.kind = 0) THEN
  2535. res.kind := 0 ;
  2536. res.imm := BitOr (left.imm, right.imm) ;
  2537. res.cls := TBool ;
  2538. RETURN
  2539. END ;
  2540. LoadPair (left, right) ;
  2541. EmOrAxCx () ;
  2542. res.kind := 2 ; res.cls := TBool ;
  2543. RETURN
  2544. END ;
  2545. IF (left.kind = 0) AND (right.kind = 0) THEN
  2546. okc := FALSE ;
  2547. CASE op OF
  2548. OpAdd : f := ConstAdd (left.imm, right.imm) ; okc := TRUE ;
  2549. | OpSub : f := ConstSub (left.imm, right.imm) ; okc := TRUE ;
  2550. | OpMul : f := ConstMul (left.imm, right.imm) ; okc := TRUE ;
  2551. | TkDiv : okc := (right.imm # 0) AND (right.imm > 0)
  2552. AND (left.imm >= 0) ;
  2553. IF okc THEN f := left.imm DIV right.imm END ;
  2554. | TkMod : okc := (right.imm # 0) AND (right.imm > 0)
  2555. AND (left.imm >= 0) ;
  2556. IF okc THEN f := left.imm MOD right.imm END ;
  2557. ELSE
  2558. okc := FALSE
  2559. END ;
  2560. IF okc THEN
  2561. res.kind := 0 ;
  2562. res.imm := VAL (LONGINT, W16 (f)) ;
  2563. res.cls := left.cls ;
  2564. RETURN
  2565. ELSIF op = TkDiv THEN
  2566. Err (EConstRange) ;
  2567. RETURN
  2568. END
  2569. END ;
  2570. LoadPair (left, right) ;
  2571. CASE op OF
  2572. OpAdd : EmAddAxCx ;
  2573. | OpSub : EmSubAxCx ;
  2574. | OpMul : EmMulAxCx ;
  2575. | TkDiv : EmIDivAxCx ;
  2576. | TkMod : EmIDivAxCx ; EmXchgAxDx ;
  2577. ELSE
  2578. Err (ETypeErr)
  2579. END ;
  2580. res.kind := 2 ;
  2581. res.cls := left.cls
  2582. END BinOpEmit ;
  2583. PROCEDURE ConstCmp (op : CARDINAL ; a, b : LONGINT ; VAR f : LONGINT)
  2584. : BOOLEAN ;
  2585. VAR a16, b16 : CARDINAL ;
  2586. BEGIN
  2587. a16 := W16 (a) ;
  2588. b16 := W16 (b) ;
  2589. f := 0 ;
  2590. CASE op OF
  2591. 1 : f := VAL (LONGINT, ORD (a16 = b16)) ;
  2592. | 2 : f := VAL (LONGINT, ORD (a16 # b16)) ;
  2593. | 3 : f := VAL (LONGINT, ORD (a16 < b16)) ;
  2594. | 4 : f := VAL (LONGINT, ORD (a16 >= b16)) ;
  2595. | 5 : f := VAL (LONGINT, ORD (a16 > b16)) ;
  2596. | 6 : f := VAL (LONGINT, ORD (a16 <= b16)) ;
  2597. ELSE
  2598. RETURN FALSE
  2599. END ;
  2600. RETURN TRUE
  2601. END ConstCmp ;
  2602. (* ---------------------------------------------------------------- *)
  2603. (* keeping an operand alive across the parse of the other one *)
  2604. (* ---------------------------------------------------------------- *)
  2605. PROCEDURE SaveLeft (VAR left : ERes) ;
  2606. (* Called the moment the operator has been recognised, i.e. *before* the
  2607. right-hand operand is parsed.
  2608. Every binary level in this parser has the shape
  2609. left := r ; ParseXxx (right) ; BinOpEmit (op, left, right, r) ;
  2610. so the right-hand operand's code is emitted between those two lines, and
  2611. the left-hand operand has to survive that. For kind 0 (a constant) and
  2612. kind 1 (a named variable) there is nothing to survive: LoadAtom re-emits
  2613. the MOV or the load at the operator site, and no code has been emitted
  2614. for the left yet. A kind-2 value is different - its code is already in
  2615. the image and its value exists only in AX, which the right-hand parse is
  2616. about to overwrite. The value had to be parked on the stack instead.
  2617. TPSRC9 does exactly this in the other order: addptr and mulptr CALL
  2618. pushres (which calls loadatom and sets flgpshax) *before* CALL mullevel,
  2619. so PUSH AX lands in the image ahead of the right-hand operand's code.
  2620. Without this, `(p > q) or (q > p)` emitted both comparisons and then
  2621. ORed the *second* comparison's result with itself - which is why it
  2622. printed FALSE for TRUE or FALSE. *)
  2623. BEGIN
  2624. IF left.kind = 2 THEN
  2625. EmPushAx () ;
  2626. left.kind := 4 (* 4 = on the top of the stack *)
  2627. ELSIF left.kind = 5 THEN
  2628. (* A string element whose address is in DI. This is the one place the
  2629. address must be spent BEFORE the right-hand operand is parsed: DI
  2630. cannot survive it, because the right operand may hold a subscript of
  2631. its own (which reuses DI) or call a routine (which may clobber it).
  2632. Reading [DI] now - which LoadAtom does, turning kind 5 into kind 2 -
  2633. and pushing the value is exactly what the kind-2 case above does
  2634. next, so the two branches converge on kind 4. A subscript on the
  2635. RIGHT is fine: it sets DI after this point and LoadPair reads it
  2636. immediately, with no parse in between. *)
  2637. LoadAtom (left) ; (* AL := [DI], AH := 0; kind := 2 *)
  2638. EmPushAx () ;
  2639. left.kind := 4
  2640. END
  2641. END SaveLeft ;
  2642. PROCEDURE LoadPair (VAR left, right : ERes) ;
  2643. (* Materialise both operands of a binary operator so that, once this
  2644. returns, AX holds the LEFT one and CX the RIGHT one - which is the state
  2645. EmAddAxCx/EmSubAxCx/EmMulAxCx/EmIDivAxCx/EmAndAxCx/EmOrAxCx/EmCmpAxCx
  2646. all expect (see EmXchgAxCx).
  2647. Three shapes, and only three:
  2648. left.kind = 4 SaveLeft pushed it before the right operand was
  2649. parsed, so the right value is in AX and the left one
  2650. is on the stack: load the right (a no-op for kind 2),
  2651. pop the left into CX, then swap.
  2652. right.kind = 2 The right value is in AX, and loading the left would
  2653. destroy it: push the right, load the left, then pop
  2654. the right straight into CX. No swap needed.
  2655. neither Both can still be materialised from scratch, and
  2656. neither is at risk, so this is the original sequence.
  2657. A kind-5 right-hand operand takes that last shape, and is safe there: the
  2658. only instruction emitted before its LoadAtom is the left's, and MOV AX,[var]
  2659. and MOV AX,imm do not touch DI, so [DI] still holds the element address.
  2660. Whichever shape is taken, exactly one push is matched by exactly one
  2661. pop. *)
  2662. BEGIN
  2663. IF left.kind = 4 THEN
  2664. LoadAtom (right) ;
  2665. EmPopCx () ;
  2666. EmXchgAxCx ()
  2667. ELSIF right.kind = 2 THEN
  2668. EmPushAx () ;
  2669. LoadAtom (left) ;
  2670. EmPopCx ()
  2671. ELSE
  2672. LoadAtom (left) ; EmPushAx () ;
  2673. LoadAtom (right) ; EmPopCx () ;
  2674. EmXchgAxCx ()
  2675. END
  2676. END LoadPair ;
  2677. PROCEDURE EmStrBlob (r : ERes) : CARDINAL ;
  2678. (* Emit a string literal's <len><chars> in the code stream behind a JMP and
  2679. return the image offset of the LENGTH byte. Shared by EmPushStrAddr (which
  2680. pushes that address) and EmPushStrSlot (which copies the bytes onto the
  2681. stack for a string value parameter). *)
  2682. VAR n, len, here : CARDINAL ;
  2683. BEGIN
  2684. len := strLen [r.strx] ;
  2685. IF len > 255 THEN
  2686. (* As in IoCall: the length is one byte, so a longer literal would wrap
  2687. and silently carry only its first (length MOD 256) characters.
  2688. TP3 strings are at most 255 characters. *)
  2689. Err (EConstRange) ;
  2690. RETURN 0
  2691. END ;
  2692. IF len + 1 <= 127 THEN
  2693. Ebyte (0EBH) ; Ebyte (VAL (BYTE, len + 1)) (* JMP rel8 over it *)
  2694. ELSE
  2695. Ebyte (0E9H) ; Eword (len + 1) (* JMP rel16 over it *)
  2696. END ;
  2697. here := pc ; (* the length byte: the literal's address *)
  2698. Ebyte (VAL (BYTE, len)) ;
  2699. n := 0 ;
  2700. WHILE n < len DO
  2701. Ebyte (VAL (BYTE, ORD (strPool [strOff [r.strx] + n]))) ;
  2702. INC (n)
  2703. END ;
  2704. RETURN here
  2705. END EmStrBlob ;
  2706. PROCEDURE EmPushSetAddr (r : ERes) ;
  2707. (* Push the ADDRESS of a set value: the runtime's set entries take addresses.
  2708. A set literal/typed constant is code-resident (kind 7), a set-expression
  2709. result is a data buffer (kind 8), a named set is symbol+boff, and a field
  2710. reached through DI is already addressed. *)
  2711. BEGIN
  2712. IF r.kind = 5 THEN
  2713. EmPushDi ()
  2714. ELSIF r.kind = 1 THEN
  2715. EmPushVarAddr (symtab [r.idx].local,
  2716. (symtab [r.idx].off + r.boff) MOD 10000H)
  2717. ELSIF (r.kind = 7) OR (r.kind = 8) THEN
  2718. EmPushVarAddr (FALSE, r.setoff)
  2719. ELSE
  2720. Err (ENoLib)
  2721. END
  2722. END EmPushSetAddr ;
  2723. PROCEDURE SetPairSize (left, right : ERes ; VAR size, base : CARDINAL) : BOOLEAN ;
  2724. (* The byte count for a set operation. An inline literal is a 32-byte
  2725. `set of Char' by default; when the other operand is a typed set (CALC's
  2726. one-byte `set of Attributes') that type wins. Two non-literals must have
  2727. the same origin and are taken at the smaller size; the runtime only ever
  2728. touches that many bytes. *)
  2729. BEGIN
  2730. IF left.setbase # right.setbase THEN
  2731. RETURN FALSE
  2732. END ;
  2733. base := left.setbase ;
  2734. IF left.kind = 7 THEN
  2735. IF right.kind = 7 THEN
  2736. size := left.setsize
  2737. ELSE
  2738. size := right.setsize
  2739. END
  2740. ELSIF right.kind = 7 THEN
  2741. size := left.setsize
  2742. ELSE
  2743. size := left.setsize ;
  2744. IF right.setsize < size THEN
  2745. size := right.setsize
  2746. END
  2747. END ;
  2748. RETURN (size > 0) AND (size <= 32)
  2749. END SetPairSize ;
  2750. PROCEDURE AllocSetScratch (size : CARDINAL) : CARDINAL ;
  2751. (* A fresh data buffer for one set expression. One per operation, so a nested
  2752. or repeated expression cannot overwrite the other side while it is still
  2753. being consumed. The bytes need no initialisation: every operation writes
  2754. all `size' of them before the value is read. *)
  2755. VAR off : CARDINAL ;
  2756. BEGIN
  2757. IF dc + size > 0F000H THEN
  2758. Err (EConstRange) ;
  2759. RETURN 0
  2760. END ;
  2761. off := dc ;
  2762. dc := dc + size ;
  2763. RETURN off
  2764. END AllocSetScratch ;
  2765. PROCEDURE SetBinEmit (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2766. (* The caller has already pushed the LEFT address (before parsing the right
  2767. operand, so a DI-addressed field survives). Finish the argument list -
  2768. right, destination, (op<<8)|size - call the runtime, and return the buffer
  2769. as a kind-8 set value. *)
  2770. VAR size, base, dest : CARDINAL ;
  2771. BEGIN
  2772. IF NOT SetPairSize (left, right, size, base) THEN
  2773. Err (ENoLib) ;
  2774. RETURN
  2775. END ;
  2776. dest := AllocSetScratch (size) ;
  2777. IF NOT OK () THEN
  2778. RETURN
  2779. END ;
  2780. EmPushSetAddr (right) ;
  2781. EmPushVarAddr (FALSE, dest) ;
  2782. EmMovAxi (W16 (op * 256 + size)) ;
  2783. EmPushAx () ;
  2784. DropC (EmCall (TU_SetOp)) ;
  2785. EmAddSp (8) ;
  2786. res.kind := 8 ;
  2787. res.cls := TSet ;
  2788. res.chr := FALSE ;
  2789. res.setoff := dest ;
  2790. res.setbase := base ;
  2791. res.setsize := size
  2792. END SetBinEmit ;
  2793. PROCEDURE EmPushStrAddr (r : ERes) ;
  2794. (* Push the ADDRESS of a whole-string operand - the argument shape cmpstr
  2795. takes, one per operand.
  2796. A string VARIABLE's value already is its address, so this is the same push
  2797. READ makes (EmPushVarAddr), through symtab's local/off.
  2798. A string LITERAL has no storage, and the image carries no initialised data
  2799. to put one in (globals are left to the loader's zero fill), so the
  2800. characters have to travel in the code stream and the operand is the address
  2801. of those bytes. TP3 does the same in TPSRC9 fullvar (993): it builds the
  2802. `JMP' opcode in AL and the length in AH (`MOV AL,#$EB' / `MOV.B AH,CH'),
  2803. emits that word, and takes the position immediately after it as varofs,
  2804. with varseg := CS - the instruction stream steps over the constant instead
  2805. of running into it.
  2806. The difference is one byte, and it is deliberate. TP3's constant is an
  2807. ARRAY [1..n] OF CHAR, and `estr2' (TPSRC10 85) emits it WITHOUT a length
  2808. byte because the length travelled on the stack instead. Every string in
  2809. THIS runtime - variable or literal - is a `string': a length byte and then
  2810. the characters, which is what rdstr writes and what cmpstr reads. So a
  2811. literal operand has to look the same, and the jump carries one extra byte:
  2812. <len><chars>, with the ADDRESS pushed being the length byte itself. The
  2813. jump still exists only to keep the CPU from walking into the characters.
  2814. Nothing is added to the data segment and no runtime entry is involved in
  2815. reading the literal; LEA AX,[that] is absolute into the code segment, which
  2816. is where a .COM's DS already is.
  2817. A 1-character literal is NOT a TString here: RdConst reports it as TScalar
  2818. (its character code), so `s = 'a'` compares a string with a character and
  2819. is a type error rather than a length-1 string compare. That is deliberate
  2820. - it is the same rule `c := 'a'` relies on - and the caller rejects it. *)
  2821. BEGIN
  2822. IF r.kind = 5 THEN
  2823. (* a string element/field computed through DI - `Sheet[X,Y].Contents'
  2824. and the `with' form. DI holds the field's address, which is exactly
  2825. what cmpstr/strcat/strstore take on the stack, so push it. This used
  2826. to be ENoLib, and it was the CALC rung after Write(Value:FW:DEC):
  2827. `if Sheet[UFX,UFY].Contents <> '' then'. *)
  2828. EmPushDi ()
  2829. ELSIF r.kind = 1 THEN
  2830. IF symtab [r.idx].isVar THEN
  2831. (* A VAR string parameter: the slot at [BP+off] holds the address of
  2832. the caller's characters, so push its CONTENTS, not the address of
  2833. the slot. boff is zero for the whole string; an element/subscript
  2834. is kind 5 and handled above. *)
  2835. IF r.boff # 0 THEN
  2836. Err (ENoLib)
  2837. ELSE
  2838. EmLoadVar (TRUE, symtab [r.idx].off, 2) ;
  2839. EmPushAx ()
  2840. END
  2841. ELSE
  2842. EmPushVarAddr (symtab [r.idx].local,
  2843. (symtab [r.idx].off + r.boff) MOD 10000H)
  2844. END
  2845. ELSIF r.kind = 3 THEN
  2846. EmPushVarAddr (FALSE, EmStrBlob (r)) (* the literal travels inline *)
  2847. ELSE
  2848. Err (ENoLib) (* a computed string is not a value *)
  2849. END
  2850. END EmPushStrAddr ;
  2851. PROCEDURE EmPushStrSlot (r : ERes ; reserve, copyN : CARDINAL) ;
  2852. (* Push a STRING VALUE argument's whole slot: reserve `reserve' bytes on the
  2853. stack and copy `copyN' of the source string's <len><chars> into them, so
  2854. that after the CALL the callee's BP+4 is the length byte and the characters
  2855. follow it.
  2856. <push the source address, then POP SI> ; local/global/literal alike
  2857. SUB SP,reserve ; MOV DI,SP ; MOV CX,copyN
  2858. loop: MOV AL,[SI] ; MOV [DI],AL ; INC SI ; INC DI ; LOOP loop
  2859. The address comes from EmPushStrAddr, which already knows how to form it for
  2860. a local ([BP+off]), a global (absolute) or a literal (inline blob) - so a
  2861. caller's LOCAL string can be passed too, not just a global.
  2862. A byte loop, not REP MOVSB, on purpose: MOVS/STOS address through ES, and a
  2863. .COM's ES happens to equal DS but nothing in this compiler establishes that
  2864. contract. Every access here is DS-relative, which is the one segment the
  2865. image already guarantees. `copyN' is at most `reserve' (a shorter actual
  2866. string than the formal leaves the tail of the slot untouched, harmless
  2867. because the length byte bounds every read). *)
  2868. BEGIN
  2869. EmPushStrAddr (r) ; (* push the source address *)
  2870. EmPopSi () ; (* SI := source *)
  2871. EmSubSp (reserve) ;
  2872. Ebyte (89H) ; Ebyte (0E7H) ; (* MOV DI,SP *)
  2873. EmMovCxi (copyN) ;
  2874. IF copyN > 0 THEN
  2875. Ebyte (8AH) ; Ebyte (04H) ; (* MOV AL,[SI] *)
  2876. Ebyte (88H) ; Ebyte (05H) ; (* MOV [DI],AL *)
  2877. Ebyte (46H) ; (* INC SI *)
  2878. Ebyte (47H) ; (* INC DI *)
  2879. Ebyte (0E2H) ; Ebyte (0F8H) (* LOOP -8: back to MOV AL,[SI] *)
  2880. END
  2881. END EmPushStrSlot ;
  2882. (* ---------------------------------------------------------------- *)
  2883. (* sets - type sizing, literals, compile-time membership *)
  2884. (* ---------------------------------------------------------------- *)
  2885. PROCEDURE SetRangeBits (VAR bytes : ARRAY OF CHAR ; size, base : CARDINAL ;
  2886. lo, hi : LONGINT) ;
  2887. (* Set the bits for every element in [lo, hi], using TP3's hybrid rule
  2888. (coeur-tp-ocr 4.7.2): element e is bit (e MOD 8) of byte
  2889. ((e DIV 8) - (base DIV 8)), and is IGNORED unless that byte is in
  2890. [0, size). A value that lands outside the used bytes is truncated away, as
  2891. TP3 does; one inside them but outside the DECLARED range still lands, which
  2892. is also TP3's behaviour. *)
  2893. VAR rel, first, last, bidx, bit, m, o : CARDINAL ;
  2894. BEGIN
  2895. IF (hi < 0) OR (lo > 255) THEN
  2896. RETURN
  2897. END ;
  2898. IF lo < 0 THEN first := 0 ELSE first := VAL (CARDINAL, lo) END ;
  2899. IF hi > 255 THEN last := 255 ELSE last := VAL (CARDINAL, hi) END ;
  2900. rel := first ;
  2901. WHILE rel <= last DO
  2902. IF rel >= base THEN
  2903. bidx := (rel - base) DIV 8 ;
  2904. IF bidx < size THEN
  2905. bit := (rel - base) MOD 8 ;
  2906. m := 1 ;
  2907. WHILE bit > 0 DO
  2908. m := m * 2 ; DEC (bit)
  2909. END ;
  2910. o := ORD (bytes [bidx]) ;
  2911. IF (o DIV m) MOD 2 = 0 THEN
  2912. bytes [bidx] := CHR (o + m)
  2913. END
  2914. END
  2915. END ;
  2916. INC (rel)
  2917. END
  2918. END SetRangeBits ;
  2919. PROCEDURE RdSetLiteral (base, size : CARDINAL ; VAR bytes : ARRAY OF CHAR) : BOOLEAN ;
  2920. (* Read a set constructor `[e, a..b, ...]' and fill `bytes' (already size
  2921. long). `[]' is the empty set. *)
  2922. VAR v, hi : LONGINT ; subcls : CARDINAL ; strf : BOOLEAN ; k : CARDINAL ;
  2923. BEGIN
  2924. k := 0 ;
  2925. WHILE k < size DO
  2926. bytes [k] := CHR (0) ;
  2927. INC (k)
  2928. END ;
  2929. ExpectDelim ('[', ENoSemi) ;
  2930. IF MatchDelim (']') THEN
  2931. RETURN OK () (* [] - the empty set *)
  2932. END ;
  2933. LOOP
  2934. RdConst (v, subcls, strf) ;
  2935. IF strf THEN
  2936. Err (ETypeErr) ;
  2937. RETURN FALSE
  2938. END ;
  2939. IF MatchRange () THEN
  2940. RdConst (hi, subcls, strf) ;
  2941. IF strf THEN
  2942. Err (ETypeErr) ;
  2943. RETURN FALSE
  2944. END
  2945. ELSE
  2946. hi := v
  2947. END ;
  2948. SetRangeBits (bytes, size, base, v, hi) ;
  2949. IF MatchDelim (',') THEN
  2950. (* another element *)
  2951. ELSE
  2952. EXIT
  2953. END
  2954. END ;
  2955. ExpectDelim (']', ENoSemi) ;
  2956. RETURN OK ()
  2957. END RdSetLiteral ;
  2958. PROCEDURE EmSetBlob (VAR bytes : ARRAY OF CHAR ; size : CARDINAL) : CARDINAL ;
  2959. (* Emit a set's bytes into the code stream behind a JMP over them - the same
  2960. trick EmPushStrAddr uses for a string literal - and return the image offset
  2961. of the first byte. Nothing goes in the data segment: a .COM's DS already
  2962. covers the code segment, which is why this port needs no `seg cs' where the
  2963. original did (see CALC-COMPILE.md's typed-constant storage decision). *)
  2964. VAR here, k : CARDINAL ;
  2965. BEGIN
  2966. IF size + 2 <= 127 THEN
  2967. Ebyte (0EBH) ; Ebyte (VAL (BYTE, size)) (* JMP rel8 over it *)
  2968. ELSE
  2969. Ebyte (0E9H) ; Eword (size) (* JMP rel16 over it *)
  2970. END ;
  2971. here := pc ;
  2972. k := 0 ;
  2973. WHILE k < size DO
  2974. Ebyte (VAL (BYTE, ORD (bytes [k]))) ;
  2975. INC (k)
  2976. END ;
  2977. RETURN here
  2978. END EmSetBlob ;
  2979. PROCEDURE FoldSetIn (left, right : ERes ; VAR res : ERes) ;
  2980. (* `e IN s' where e is a compile-time ordinal and s a set whose bytes are
  2981. already in the image: answer at compile time, exactly as TPSRC2's xsetin
  2982. answers at run time (AH > 255 -> FALSE, else test the bit). A run-time
  2983. element or a run-time set is still ENoLib - that is the next milestone, and
  2984. it must stay LOUD rather than silently answer wrong. *)
  2985. VAR off, base, size, rel, bidx, bit, m, o : CARDINAL ;
  2986. isIn, foldable : BOOLEAN ;
  2987. jl, jg, jmp : CARDINAL ;
  2988. BEGIN
  2989. res.kind := 0 ;
  2990. res.imm := 0 ;
  2991. res.cls := TBool ;
  2992. res.chr := FALSE ;
  2993. IF right.cls # TSet THEN
  2994. Err (ENoLib) ;
  2995. RETURN
  2996. END ;
  2997. IF left.kind # 0 THEN
  2998. (* A RUN-TIME element (`Upcase(Ch) in ['Y','N']', `Ch in ['a'..'z']').
  2999. Materialise it in AX, subtract the set's base, reject the out-of-range
  3000. values with the two signed tests the compiler declares (L and G), then
  3001. index the bit array: byte = (e-base) DIV 8, bit = (e-base) MOD 8.
  3002. The set's address is formed according to where its bytes live: an
  3003. inline literal or typed constant is code-resident (image offset +
  3004. LoadBias), a data set is an absolute or BP-relative address. A set
  3005. already addressed through DI and an element that itself needs DI are
  3006. refused: the address would be lost. *)
  3007. IF right.kind = 5 THEN
  3008. Err (ENoLib) ;
  3009. RETURN
  3010. END ;
  3011. LoadAtom (left) ;
  3012. IF NOT OK () THEN
  3013. RETURN
  3014. END ;
  3015. IF right.setbase # 0 THEN
  3016. EmMovCxi (W16 (right.setbase)) ;
  3017. EmSubAxCx ()
  3018. END ;
  3019. EmCmpAxi (0) ;
  3020. jl := EmJcc (8CH, 0) ; (* JL -> false *)
  3021. EmCmpAxi (W16 (right.setsize * 8)) ;
  3022. jg := EmJcc (8FH, 0) ; (* JG -> false *)
  3023. EmMovClAl () ;
  3024. EmAndClImm (7) ;
  3025. EmShrAx1 () ; EmShrAx1 () ; EmShrAx1 () ; (* AX := byte index *)
  3026. IF right.kind = 7 THEN
  3027. EmMovBxi (W16 (right.setoff + LoadBias))
  3028. ELSIF right.kind = 1 THEN
  3029. IF symtab [right.idx].local THEN
  3030. EmLeaBx ((right.setoff + right.boff) MOD 10000H)
  3031. ELSE
  3032. EmMovBxi ((right.setoff + right.boff + LoadBias) MOD 10000H)
  3033. END
  3034. ELSE
  3035. Err (ENoLib) ;
  3036. RETURN
  3037. END ;
  3038. EmAddBxAx () ; (* BX := the set's byte *)
  3039. EmLdAlBx () ;
  3040. EmMovDlImm (1) ;
  3041. EmShlDlCl () ; (* DL := 1 << bit *)
  3042. EmAndAlDl () ;
  3043. EmMovAh0 () ;
  3044. EmOrAxAx () ;
  3045. EmRelSetcc (2) ; (* SETNE: the bit was set *)
  3046. jmp := EmJmpNear (0) ;
  3047. SetPatTgt (jl, pc) ;
  3048. SetPatTgt (jg, pc) ;
  3049. EmMovAxi (0) ;
  3050. SetPatTgt (jmp, pc) ;
  3051. res.kind := 2 ;
  3052. res.cls := TBool ;
  3053. RETURN
  3054. END ;
  3055. (* A code-resident set (an inline literal or a typed constant) folds at
  3056. compile time. A DATA set - a record field, local or global, or one
  3057. addressed through DI - must be tested at run time: its byte is in the
  3058. image's data area, not in cbuf. A typed constant's offset is below
  3059. dataBase; a global's is at or above it. *)
  3060. foldable := (right.kind = 7) ;
  3061. IF (right.kind = 1) AND NOT symtab [right.idx].local
  3062. AND (right.setoff + right.boff < dataBase) THEN
  3063. foldable := TRUE
  3064. END ;
  3065. IF NOT foldable THEN
  3066. IF (left.imm >= 0) AND (left.imm <= 255) THEN
  3067. base := right.setbase ; size := right.setsize ;
  3068. rel := VAL (CARDINAL, left.imm) ;
  3069. IF rel >= base THEN
  3070. bidx := (rel - base) DIV 8 ;
  3071. IF bidx < size THEN
  3072. bit := (rel - base) MOD 8 ;
  3073. m := 1 ;
  3074. WHILE bit > 0 DO
  3075. m := m * 2 ; DEC (bit)
  3076. END ;
  3077. IF right.kind = 5 THEN
  3078. EmLdAlDiOff (bidx)
  3079. ELSIF right.kind = 1 THEN
  3080. EmLoadVar (symtab [right.idx].local,
  3081. (right.setoff + right.boff + bidx) MOD 10000H, 1)
  3082. ELSE
  3083. Err (ENoLib) ;
  3084. RETURN
  3085. END ;
  3086. EmAndAlImm (m) ;
  3087. EmMovAh0 () ;
  3088. EmOrAxAx () ;
  3089. EmRelSetcc (2) ; (* SETNE: the bit was set *)
  3090. res.kind := 2 ;
  3091. res.cls := TBool ;
  3092. RETURN
  3093. END
  3094. END
  3095. END ;
  3096. res.imm := 0 ;
  3097. RETURN
  3098. END ;
  3099. isIn := FALSE ;
  3100. IF (left.imm >= 0) AND (left.imm <= 255) THEN
  3101. off := right.setoff ; base := right.setbase ; size := right.setsize ;
  3102. rel := VAL (CARDINAL, left.imm) ;
  3103. IF rel >= base THEN
  3104. bidx := (rel - base) DIV 8 ;
  3105. IF bidx < size THEN
  3106. bit := (rel - base) MOD 8 ;
  3107. m := 1 ;
  3108. WHILE bit > 0 DO
  3109. m := m * 2 ; DEC (bit)
  3110. END ;
  3111. o := VAL (CARDINAL, cbuf [off + bidx]) ;
  3112. isIn := (o DIV m) MOD 2 # 0
  3113. END
  3114. END
  3115. END ;
  3116. res.imm := ORD (isIn)
  3117. END FoldSetIn ;
  3118. PROCEDURE RdSetBase (VAR baseCls : CARDINAL ; VAR lo, hi : LONGINT) ;
  3119. (* The base type of `set of ...': an ordinal range. `Char' and `byte' are
  3120. 0..255; a literal subrange `a..b' is read directly. A named or enumerated
  3121. base is ENoLib for now - `set of Attributes' waits for enums. *)
  3122. VAR idx, subcls : CARDINAL ; strf : BOOLEAN ;
  3123. BEGIN
  3124. baseCls := TScalar ;
  3125. Skip () ;
  3126. IF Alpha (CurCh ()) THEN
  3127. GetWord () ;
  3128. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  3129. IF symtab [idx].cls = TEnum THEN
  3130. lo := symtab [idx].lo ;
  3131. hi := symtab [idx].hi ;
  3132. baseCls := TEnum
  3133. ELSIF (symtab [idx].cls = TChar)
  3134. OR ((symtab [idx].cls = TScalar) AND (symtab [idx].size = 1)) THEN
  3135. lo := 0 ; hi := 255 ; baseCls := symtab [idx].cls
  3136. ELSE
  3137. Err (ENoLib)
  3138. END
  3139. ELSE
  3140. Err (EUnknown)
  3141. END
  3142. ELSE
  3143. RdConst (lo, subcls, strf) ;
  3144. IF NOT MatchRange () THEN
  3145. Err (ESimpType) ;
  3146. RETURN
  3147. END ;
  3148. RdConst (hi, subcls, strf) ;
  3149. IF (lo < 0) OR (hi > 255) OR (lo > hi) THEN
  3150. Err (EConstRange)
  3151. END
  3152. END
  3153. END RdSetBase ;
  3154. PROCEDURE NewScratchStr () : CARDINAL ;
  3155. (* Allocate a fresh 256-byte global STRING and return its symbol index.
  3156. A concatenation result needs STORAGE the emitted code can name. Making the
  3157. result a string VARIABLE (kind 1) is what keeps every downstream consumer
  3158. untouched: Assignment, IoCall and ParseCmp already handle kind 1, so `s :=
  3159. a + b', `writeln(a + b)' and `(a + b) = c' work with no code of their own.
  3160. One scratch PER `+' in the source, so a repeated or nested concatenation
  3161. never shares a destination - `a + b + c' is two occurrences and gets two
  3162. scratch strings, and the first result survives until the second consumes it.
  3163. (A loop reuses its site's scratch, which is correct because each execution
  3164. writes before it reads.) Recursion would break that, but this compiler
  3165. compiles no procedures yet - see the item list.
  3166. 256 bytes is the STRING type's own size, length byte plus 255 characters:
  3167. see ParseType's TkString arm and the predefined STRING in Inittur. The name
  3168. is a placeholder (nothing looks a scratch up by name) spelled with '@', as
  3169. tmpA/tmpB are, so it cannot collide with a Modula-2 identifier. *)
  3170. BEGIN
  3171. DropC (NewSym ("@@SC", KVar, TString, 256, 1, dc, 0, FALSE)) ;
  3172. dc := dc + 256 ;
  3173. RETURN symTop - 1
  3174. END NewScratchStr ;
  3175. PROCEDURE StrOperand (r : ERes) : BOOLEAN ;
  3176. (* Is r usable as one operand of `+'? A STRING, or a CHAR - which can appear
  3177. three ways: a quoted literal (cls TScalar with chr set), a CHAR variable
  3178. (cls TChar), and a string element s[i] (cls TChar, kind 5). A number is
  3179. not, and neither is a BOOLEAN. *)
  3180. BEGIN
  3181. RETURN (r.cls = TString) OR (r.cls = TChar) OR
  3182. ((r.cls = TScalar) AND r.chr)
  3183. END StrOperand ;
  3184. PROCEDURE EmPushStrOperand (r : ERes) ;
  3185. (* Push the ADDRESS of one concatenation operand, converting a CHAR to a
  3186. length-1 string first.
  3187. A STRING operand is pushed exactly as cmpstr pushes one (EmPushStrAddr):
  3188. a variable's value already IS its address, and a literal travels inline.
  3189. A CHAR operand has no such address, so it is materialised as a
  3190. `<length 1><character>' string in a fresh 2-byte scratch and the address of
  3191. THAT is pushed. This is TPSRC9's addch/addch2, which splice a character
  3192. into a concatenation by building a one-character string. The character is
  3193. loaded into AL (LoadAtom), the character is stored at [coff+1] and the
  3194. length 1 at [coff]. At most one operand of a concatenation is a CHAR -
  3195. StrConcat rejects char+char - so at most one such scratch is ever made. *)
  3196. VAR coff : CARDINAL ;
  3197. BEGIN
  3198. IF r.cls = TString THEN
  3199. EmPushStrAddr (r)
  3200. ELSE
  3201. coff := dc ;
  3202. dc := dc + 2 ;
  3203. LoadAtom (r) ; (* AX := the character *)
  3204. EmStoreVar (FALSE, (coff + 1) MOD 10000H, 1) ; (* [coff+1] := AL *)
  3205. EmMovAxi (1) ; (* AX := 1 *)
  3206. EmStoreVar (FALSE, coff MOD 10000H, 1) ; (* [coff] := AL = length *)
  3207. EmPushVarAddr (FALSE, coff MOD 10000H)
  3208. END
  3209. END EmPushStrOperand ;
  3210. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  3211. (* `left + right' for strings: TPSRC2's xconcat, emitted as two runtime calls.
  3212. The layout is `<length byte><characters>' and `+' needs a place to build its
  3213. result, so this allocates one 256-byte global scratch (NewScratchStr) and
  3214. copies into it: first `dest := left' through the runtime's strstore, then
  3215. `dest := dest + right' through strcat, which appends. Using strstore for
  3216. the left operand and strcat for the right keeps the append logic in one
  3217. place and gives the compiler exactly one new entry to reach; it also means
  3218. the two calls have the same argument shape (source pushed first, destination
  3219. last, limit in CX), so the emission differs only in the entry named.
  3220. The limit is 255 - the scratch's 255 usable characters. An overflowing
  3221. result is a RUNTIME ERROR with exit code 16, TP3's `String too long', not a
  3222. truncation; see Runtime.EmitStrCat.
  3223. The operator rule: `+' concatenates, anything else over a STRING is a type
  3224. error, and char+char is ALSO a type error. ISO Modula-2 gives no meaning to
  3225. two characters summed, and inventing one (a two-character string?) would be
  3226. a guess this compiler does not make; TP3's own behaviour there is not
  3227. something the reference pins down. That char+char choice is the one place
  3228. this differs from a literal reading of the reference, and it is recorded
  3229. here and in v-TP3-STRCAT.md rather than left to be discovered.
  3230. The guard below is what ENFORCES that rule, and it only runs because
  3231. BinOpEmit's hook routes a CHAR operand here too. A hook that tested for a
  3232. STRING operand only would send `'a' + 'b'' to the integer path instead and
  3233. this test would never be reached - which is exactly what it did until
  3234. t53_strcat_type caught it. Three ways to fail it: a non-`+' operator over
  3235. a string operand, an operand that is neither a string nor a CHAR (a number),
  3236. and two CHARs with no STRING on either side. *)
  3237. VAR dest : CARDINAL ;
  3238. BEGIN
  3239. (* A placeholder for the paths below that bail out through Err. Err only
  3240. records the first error and does not unwind, so the caller goes on to use
  3241. res regardless: after `Err (ETypeErr)' in the guard, ParseAdd hands res
  3242. straight back to IoCall, to Assignment or to an enclosing concatenation.
  3243. The placeholder's SHAPE therefore matters. It must not claim to be a
  3244. STRING, because the string consumers reach symtab[res.idx] for any TString
  3245. (IoCall's `writeln' arm does) and idx is not a symbol here; and it must be
  3246. something LoadAtom can fold, because the numeric consumers will try. The
  3247. integer 0 is both. Leaving kind-2/TString here, as this once did, turned
  3248. `writeln('a' + 'b')' - two CHARs, a type error - into a compiler segfault
  3249. instead of an error message. *)
  3250. res.kind := 0 ;
  3251. res.imm := 0 ;
  3252. res.cls := TScalar ;
  3253. res.boff := 0 ;
  3254. res.chr := FALSE ;
  3255. IF (op # OpAdd) OR NOT StrOperand (left) OR NOT StrOperand (right) OR
  3256. ((left.cls # TString) AND (right.cls # TString)) THEN
  3257. Err (ETypeErr) ; (* a STRING on the wrong operator, a number,
  3258. or two CHARs *)
  3259. RETURN
  3260. END ;
  3261. dest := NewScratchStr () ;
  3262. (* dest := left *)
  3263. EmPushStrOperand (left) ;
  3264. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  3265. EmMovCxi (255) ;
  3266. DropC (EmCall (TU_StrStore)) ;
  3267. EmAddSp (4) ; (* pop the two addresses strstore took *)
  3268. (* dest := dest + right *)
  3269. EmPushStrOperand (right) ;
  3270. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  3271. EmMovCxi (255) ;
  3272. DropC (EmCall (TU_StrCat)) ;
  3273. EmAddSp (4) ;
  3274. res.kind := 1 ;
  3275. res.idx := dest ;
  3276. res.cls := TString ;
  3277. res.boff := 0 ;
  3278. res.chr := FALSE
  3279. END StrConcat ;
  3280. PROCEDURE ParseCmp (VAR r : ERes) ;
  3281. (* "=" | "<>" | "<" | "<=" | ">" | ">=" *)
  3282. VAR op : CARDINAL ;
  3283. left, right : ERes ;
  3284. f : LONGINT ;
  3285. size, base : CARDINAL ;
  3286. BEGIN
  3287. ParseAdd (r) ;
  3288. LOOP
  3289. op := 0 ;
  3290. Skip () ;
  3291. IF CurCh () = '=' THEN
  3292. op := 1 ; DropCh (GetCh ())
  3293. ELSIF (CurCh () = '<') AND (PeekAhead (1) = '>') THEN
  3294. op := 2 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  3295. ELSIF CurCh () = '<' THEN
  3296. IF PeekAhead (1) = '=' THEN
  3297. op := 6 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  3298. ELSE
  3299. op := 3 ; DropCh (GetCh ())
  3300. END
  3301. ELSIF CurCh () = '>' THEN
  3302. IF PeekAhead (1) = '=' THEN
  3303. op := 5 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  3304. ELSE
  3305. op := 4 ; DropCh (GetCh ())
  3306. END
  3307. END ;
  3308. IF op = 0 THEN
  3309. IF KwAhead ("IN") THEN
  3310. (* `e IN s' is at the comparison level in TP3 (TPSRC9 cmpin, 116).
  3311. Only the compile-time case is implemented; see FoldSetIn. *)
  3312. GetWord () ;
  3313. left := r ;
  3314. ParseAdd (right) ;
  3315. FoldSetIn (left, right, r) ;
  3316. RETURN
  3317. END ;
  3318. RETURN
  3319. END ;
  3320. left := r ;
  3321. IF left.cls = TSet THEN
  3322. (* Set comparison. set_cmp returns a mask (bit 0 equal, bit 1 strict
  3323. subset, bit 2 strict superset); the operator selects which bits
  3324. answer it, and the shared EmRelSetcc arm turns the flags into a
  3325. boolean. The left address is pushed before the right operand is
  3326. parsed, for the same DI reason as strings and set arithmetic. *)
  3327. EmPushSetAddr (left) ;
  3328. ParseAdd (right) ;
  3329. IF NOT OK () THEN
  3330. RETURN
  3331. END ;
  3332. IF right.cls # TSet THEN
  3333. Err (ETypeErr) ;
  3334. RETURN
  3335. END ;
  3336. IF NOT SetPairSize (left, right, size, base) THEN
  3337. Err (ENoLib) ;
  3338. RETURN
  3339. END ;
  3340. EmPushSetAddr (right) ;
  3341. EmMovAxi (size) ;
  3342. EmPushAx () ;
  3343. DropC (EmCall (TU_SetCmp)) ;
  3344. EmAddSp (4) ;
  3345. CASE op OF
  3346. 1 : EmMovCxi (1) ; EmAndAxCx () ; EmOrAxAx () ; EmRelSetcc (2) ;
  3347. | 2 : EmMovCxi (1) ; EmAndAxCx () ; EmXorAl01 () ;
  3348. EmOrAxAx () ; EmRelSetcc (2) ;
  3349. | 3 : EmMovCxi (2) ; EmAndAxCx () ; EmOrAxAx () ; EmRelSetcc (2) ;
  3350. | 4 : EmMovCxi (4) ; EmAndAxCx () ; EmOrAxAx () ; EmRelSetcc (2) ;
  3351. | 5 : EmMovCxi (5) ; EmAndAxCx () ; EmOrAxAx () ; EmRelSetcc (2) ;
  3352. | 6 : EmMovCxi (3) ; EmAndAxCx () ; EmOrAxAx () ; EmRelSetcc (2)
  3353. END ;
  3354. r.kind := 2 ;
  3355. r.cls := TBool
  3356. ELSIF left.cls = TString THEN
  3357. (* A string comparison: cmpstr, the entry TPSRC9's vcompare (133)
  3358. reaches through TPSRC2's csteq/cstne/cstge/cstle/cstg/cstl
  3359. wrappers (890-925).
  3360. The operands are pushed as ADDRESSES, before the right-hand parse
  3361. can clobber DI. This is why the left is pushed here rather than
  3362. through SaveLeft: a kind-5 left is a string FIELD whose address is
  3363. in DI, and SaveLeft's job is to materialise a scalar in AX, which
  3364. would read the length byte as a number (or, for a whole string,
  3365. refuse it). `if Sheet[UFX,UFY].Contents <> '' then' was exactly
  3366. that: the CALC rung after Write(Value:FW:DEC).
  3367. cmpstr returns AX = -1/0/+1 (see Runtime.mod for why a value and
  3368. not flags), so the second half is exactly the numeric arm's: put
  3369. the sign in the flags and let the shared six-arm table answer.
  3370. EmOrAxAx is OR AX,AX rather than EmCmpAxi(0) on purpose: tests/
  3371. check_8086.py reads every `CMP AX,0000' in the program region as
  3372. an IF/WHILE/REPEAT test and requires a branch right after it, and
  3373. a comparison used as a VALUE (writeln(a = b)) is not one. *)
  3374. EmPushStrAddr (left) ;
  3375. ParseAdd (right) ;
  3376. IF right.cls # TString THEN
  3377. Err (ETypeErr) ; (* a string compared with a number/char *)
  3378. RETURN
  3379. END ;
  3380. EmPushStrAddr (right) ;
  3381. DropC (EmCall (TU_CmpStr)) ;
  3382. EmAddSp (4) ;
  3383. EmOrAxAx () ;
  3384. EmRelSetcc (op) ;
  3385. r.kind := 2 ;
  3386. r.cls := TBool
  3387. ELSE
  3388. SaveLeft (left) ;
  3389. ParseAdd (right) ;
  3390. IF (right.cls = TString) OR (right.cls = TSet) THEN
  3391. Err (ETypeErr) ; (* a number compared with a string/set *)
  3392. RETURN
  3393. END ;
  3394. IF (left.kind = 0) AND (right.kind = 0) THEN
  3395. IF ConstCmp (op, left.imm, right.imm, f) THEN
  3396. r.kind := 0 ;
  3397. r.imm := f ;
  3398. r.cls := TBool
  3399. ELSE
  3400. r.kind := 0 ;
  3401. r.imm := 0 ;
  3402. r.cls := TBool
  3403. END
  3404. ELSE
  3405. LoadPair (left, right) ;
  3406. EmCmpAxCx () ;
  3407. EmRelSetcc (op) ;
  3408. r.kind := 2 ;
  3409. r.cls := TBool
  3410. END
  3411. END
  3412. END
  3413. END ParseCmp ;
  3414. PROCEDURE ParseAdd (VAR r : ERes) ;
  3415. VAR op : CARDINAL ;
  3416. left, right : ERes ;
  3417. BEGIN
  3418. ParseMul (r) ;
  3419. LOOP
  3420. op := 0 ;
  3421. Skip () ;
  3422. IF CurCh () = '+' THEN
  3423. op := OpAdd ; DropCh (GetCh ())
  3424. ELSIF CurCh () = '-' THEN
  3425. op := OpSub ; DropCh (GetCh ())
  3426. ELSIF KwAhead ("OR") THEN
  3427. GetWord () ;
  3428. op := TkOr
  3429. ELSE
  3430. RETURN
  3431. END ;
  3432. left := r ;
  3433. IF left.cls = TSet THEN
  3434. (* Set union/difference. The left address goes on the stack BEFORE
  3435. the right is parsed: a DI-addressed set field must survive the
  3436. right-hand expression. `OR' is boolean, not set union. *)
  3437. IF (op = OpAdd) OR (op = OpSub) THEN
  3438. EmPushSetAddr (left) ;
  3439. ParseMul (right) ;
  3440. IF NOT OK () THEN
  3441. RETURN
  3442. END ;
  3443. IF right.cls # TSet THEN
  3444. Err (ETypeErr) ;
  3445. RETURN
  3446. END ;
  3447. IF op = OpAdd THEN
  3448. SetBinEmit (1, left, right, r)
  3449. ELSE
  3450. SetBinEmit (2, left, right, r)
  3451. END
  3452. ELSE
  3453. Err (ETypeErr) ;
  3454. RETURN
  3455. END
  3456. ELSE
  3457. SaveLeft (left) ;
  3458. ParseMul (right) ;
  3459. IF NOT OK () THEN
  3460. RETURN
  3461. END ;
  3462. IF right.cls = TSet THEN
  3463. Err (ETypeErr) ;
  3464. RETURN
  3465. END ;
  3466. BinOpEmit (op, left, right, r)
  3467. END
  3468. END
  3469. END ParseAdd ;
  3470. PROCEDURE ParseMul (VAR r : ERes) ;
  3471. VAR op : CARDINAL ;
  3472. left, right : ERes ;
  3473. BEGIN
  3474. ParseNeg (r) ;
  3475. LOOP
  3476. op := 0 ;
  3477. Skip () ;
  3478. IF CurCh () = '*' THEN
  3479. op := OpMul ; DropCh (GetCh ()) (* OpAdd here meant a*b -> a+b *)
  3480. ELSIF CurCh () = '/' THEN
  3481. op := 2 ; DropCh (GetCh ()) ; Err (ENoLib)
  3482. ELSIF KwAhead ("DIV") THEN
  3483. GetWord () ; op := TkDiv
  3484. ELSIF KwAhead ("MOD") THEN
  3485. GetWord () ; op := TkMod
  3486. ELSIF KwAhead ("AND") THEN
  3487. GetWord () ; op := TkAnd
  3488. ELSE
  3489. RETURN
  3490. END ;
  3491. IF op = 2 THEN
  3492. RETURN
  3493. END ;
  3494. left := r ;
  3495. IF left.cls = TSet THEN
  3496. (* Set intersection. Same push-before-the-right rule as ParseAdd. *)
  3497. IF op = OpMul THEN
  3498. EmPushSetAddr (left) ;
  3499. ParseNeg (right) ;
  3500. IF NOT OK () THEN
  3501. RETURN
  3502. END ;
  3503. IF right.cls # TSet THEN
  3504. Err (ETypeErr) ;
  3505. RETURN
  3506. END ;
  3507. SetBinEmit (0, left, right, r)
  3508. ELSE
  3509. Err (ETypeErr) ;
  3510. RETURN
  3511. END
  3512. ELSE
  3513. SaveLeft (left) ;
  3514. ParseNeg (right) ;
  3515. IF NOT OK () THEN
  3516. RETURN
  3517. END ;
  3518. IF right.cls = TSet THEN
  3519. Err (ETypeErr) ;
  3520. RETURN
  3521. END ;
  3522. BinOpEmit (op, left, right, r)
  3523. END
  3524. END
  3525. END ParseMul ;
  3526. PROCEDURE ParseNeg (VAR r : ERes) ;
  3527. BEGIN
  3528. Skip () ;
  3529. IF CurCh () = '+' THEN
  3530. DropCh (GetCh ()) ;
  3531. ParseNeg (r) ;
  3532. RETURN
  3533. ELSIF CurCh () = '-' THEN
  3534. DropCh (GetCh ()) ;
  3535. ParseNeg (r) ;
  3536. IF r.kind = 0 THEN
  3537. r.imm := VAL (LONGINT, W16 (0 - r.imm))
  3538. ELSE
  3539. LoadAtom (r) ;
  3540. EmNegAx () ;
  3541. r.kind := 2
  3542. END ;
  3543. RETURN
  3544. ELSIF KwAhead ("NOT") THEN
  3545. GetWord () ;
  3546. ParseNeg (r) ;
  3547. (* TPSRC9 neglevel branches on the operand's type before emitting
  3548. anything: CMP CL,#$0A (integer) -> NOT AX, CMP CL,#$0B (boolean)
  3549. -> XOR AL,#01, anything else -> error. This used to emit NOT AX
  3550. for both, so `not (a = a)' produced 0FFFEh and the runtime's
  3551. wrbool test ([BP+4] <> 0) read it as TRUE.
  3552. The integer constant fold stays: the 16 bits are the same either
  3553. way. A boolean constant must not go through BitNot - 0FFFFH-1 is
  3554. 0FFFEh, which wrbool also reads as TRUE - so it is loaded and
  3555. xor-ed, exactly as neglevel does it. *)
  3556. IF r.cls = TBool THEN
  3557. LoadAtom (r) ;
  3558. EmXorAl01 () ;
  3559. r.kind := 2
  3560. ELSIF r.cls = TScalar THEN
  3561. IF r.kind = 0 THEN
  3562. r.imm := BitNot (r.imm)
  3563. ELSE
  3564. LoadAtom (r) ;
  3565. EmNotAx () ;
  3566. r.kind := 2
  3567. END
  3568. ELSE
  3569. Err (ETypeErr)
  3570. END ;
  3571. RETURN
  3572. END ;
  3573. ParseAtom (r)
  3574. END ParseNeg ;
  3575. PROCEDURE WithLookup (nm : ARRAY OF CHAR ; VAR r : ERes) : BOOLEAN ;
  3576. (* Resolve a bare identifier against the active WITH scopes, innermost first.
  3577. ISO Pascal lets a record field shadow an outer declaration, so this is
  3578. consulted BEFORE Search. The result is filled exactly as a variable
  3579. reference: kind 1 (base symbol + boff) for a record variable or a
  3580. constant-index element, kind 5 (address in DI) for a run-time-indexed one,
  3581. where the base is reloaded from the WITH slot because the body may have
  3582. used DI. *)
  3583. VAR w, fi : CARDINAL ;
  3584. found : BOOLEAN ;
  3585. BEGIN
  3586. w := withN ;
  3587. WHILE w > 0 DO
  3588. DEC (w) ;
  3589. fi := withFF [w] ;
  3590. found := FALSE ;
  3591. WHILE (fi < withFL [w]) AND NOT found DO
  3592. IF NameEq (fields [fi].name, nm) THEN
  3593. found := TRUE
  3594. ELSE
  3595. INC (fi)
  3596. END
  3597. END ;
  3598. IF found THEN
  3599. IF withIsDI [w] THEN
  3600. EmLdDiGlob (withSlot [w]) ;
  3601. IF fields [fi].off # 0 THEN
  3602. EmAddDiImm (fields [fi].off)
  3603. END ;
  3604. r.kind := 5
  3605. ELSE
  3606. r.kind := 1 ;
  3607. r.setoff := symtab [withIdx [w]].off ;
  3608. r.boff := W16 (VAL (LONGINT, withBoff [w])
  3609. + VAL (LONGINT, fields [fi].off))
  3610. END ;
  3611. r.idx := withIdx [w] ;
  3612. r.cls := fields [fi].cls ;
  3613. r.sz := fields [fi].size ;
  3614. IF r.cls = TSet THEN
  3615. r.setbase := fields [fi].elem ;
  3616. r.setsize := fields [fi].size
  3617. END ;
  3618. r.chr := FALSE ;
  3619. RETURN TRUE
  3620. END
  3621. END ;
  3622. RETURN FALSE
  3623. END WithLookup ;
  3624. PROCEDURE ParseAtom (VAR r : ERes) ;
  3625. (* const | variable | func(params) | '(' expr ')' | '[' set ']' *)
  3626. VAR idx : CARDINAL ;
  3627. strf : BOOLEAN ;
  3628. quoted : BOOLEAN ;
  3629. ssize, sbase : CARDINAL ;
  3630. sbuf : ARRAY [0..31] OF CHAR ;
  3631. uj1, uj2 : CARDINAL ;
  3632. BEGIN
  3633. r.chr := FALSE ; (* default: not a quoted char literal *)
  3634. Skip () ;
  3635. IF CurCh () = '(' THEN
  3636. DropCh (GetCh ()) ;
  3637. ParseExpr (r) ;
  3638. ExpectDelim (')', ENoSemi) ;
  3639. RETURN
  3640. END ;
  3641. IF CurCh () = '[' THEN
  3642. (* An inline set literal. Full TP3 takes its type from context; here it
  3643. defaults to `set of Char' (0..255), which is what CALC writes
  3644. (`Ch in ['a'..'z']'), and its bytes are materialised in the code
  3645. stream. A typed/larger-base literal is a later milestone. *)
  3646. ssize := 32 ;
  3647. sbase := 0 ;
  3648. IF RdSetLiteral (sbase, ssize, sbuf) THEN
  3649. r.kind := 7 ;
  3650. r.cls := TSet ;
  3651. r.setoff := EmSetBlob (sbuf, ssize) ;
  3652. r.setbase := sbase ;
  3653. r.setsize := ssize
  3654. END ;
  3655. RETURN
  3656. END ;
  3657. IF (CurCh () = '$') OR (Digit (CurCh ())) OR (ORD (CurCh ()) = AposC)
  3658. OR (CurCh () = '^') OR (CurCh () = '#') THEN
  3659. (* remember that this was a quoted literal BEFORE RdConst consumes it:
  3660. RdConst reports a 1-character literal as TScalar (its char code),
  3661. which is right for "c := 'a'" but would make writeln('a') print 97.
  3662. Mark it so the writer picks the char entry, not the integer one. A
  3663. caret (^M) or decimal (#27) character constant is a character too. *)
  3664. quoted := (ORD (CurCh ()) = AposC) OR (CurCh () = '^')
  3665. OR (CurCh () = '#') ;
  3666. RdConst (r.imm, r.cls, strf) ;
  3667. r.chr := quoted AND (r.cls = TScalar) AND NOT strf ;
  3668. IF r.cls = TReal THEN
  3669. Err (ENoLib) ;
  3670. r.kind := 2 ;
  3671. RETURN
  3672. END ;
  3673. IF strf THEN
  3674. (* A string literal is legal here as a *value* - it is not rejected
  3675. at this point, because writeln('hi') needs it and IoCall is the
  3676. only place that knows how to emit one. Everywhere else the
  3677. literal has to end up as a machine word, and that is caught by
  3678. LoadAtom, which refuses a TString. *)
  3679. r.strx := rdStrX ;
  3680. r.kind := 3 ;
  3681. RETURN
  3682. END ;
  3683. r.kind := 0 ;
  3684. RETURN
  3685. END ;
  3686. IF NOT Alpha (CurCh ()) THEN
  3687. Err (EUnknown) ;
  3688. RETURN
  3689. END ;
  3690. GetWord () ;
  3691. IF WithLookup (wrd, r) THEN
  3692. ParseSub (r) ;
  3693. RETURN
  3694. END ;
  3695. IF NOT Search (wrd, idx) THEN
  3696. Err (EUnknown) ;
  3697. RETURN
  3698. END ;
  3699. IF symtab [idx].tag = KConst THEN
  3700. r.kind := 0 ;
  3701. r.imm := symtab [idx].lval ;
  3702. r.cls := symtab [idx].cls ;
  3703. RETURN
  3704. ELSIF symtab [idx].tag = KFunc THEN
  3705. ParseCall (idx) ;
  3706. r.kind := 2 ;
  3707. r.cls := symtab [idx].cls ;
  3708. RETURN
  3709. ELSIF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KType) THEN
  3710. (* ParseVar initialises boff to 0 and then ParseSub folds any constant
  3711. subscript into it. Do NOT reset boff here: doing so after ParseVar
  3712. returns threw away the subscript, so s[i] read/wrote off+0 (the
  3713. length byte) while still reporting itself as a char. This was
  3714. latent for arrays because an array cannot be declared yet, so no
  3715. fixture had ever exercised the fold. *)
  3716. ParseVar (r) ;
  3717. RETURN
  3718. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_Chr) THEN
  3719. (* Chr(n): the character with code n. A constant folds; otherwise the
  3720. integer is loaded and its class becomes CHAR. The value is one byte,
  3721. so an assignment stores AL and a CHAR writer uses AL. *)
  3722. IF NOT MatchDelim ('(') THEN
  3723. Err (ENoSemi) ;
  3724. RETURN
  3725. END ;
  3726. ParseExpr (r) ;
  3727. ExpectDelim (')', ENoSemi) ;
  3728. IF NOT OK () THEN
  3729. RETURN
  3730. END ;
  3731. IF (r.cls # TScalar) AND (r.cls # TChar) THEN
  3732. Err (ETypeErr) ;
  3733. RETURN
  3734. END ;
  3735. IF r.kind = 0 THEN
  3736. r.imm := VAL (LONGINT, W16 (r.imm) MOD 256) ;
  3737. r.chr := TRUE
  3738. ELSE
  3739. LoadAtom (r) ;
  3740. r.kind := 2 ;
  3741. r.chr := FALSE
  3742. END ;
  3743. r.cls := TChar ;
  3744. r.sz := 1 ;
  3745. RETURN
  3746. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_IoResult) THEN
  3747. (* IOResult: the last file operation's DOS status; reading it clears the
  3748. slot in the runtime. It is a no-argument function. *)
  3749. IF MatchDelim ('(') THEN
  3750. ExpectDelim (')', ENoSemi)
  3751. END ;
  3752. DropC (EmCall (TU_IoResult)) ;
  3753. r.kind := 2 ;
  3754. r.cls := TScalar ;
  3755. r.chr := FALSE ;
  3756. RETURN
  3757. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_UpCase) THEN
  3758. (* UpCase(c): a CHAR function. A constant folds; otherwise AL is
  3759. mapped 'a'..'z' -> 'A'..'Z' and left alone outside that range. The
  3760. test is JL/JG (signed), which is the same answer for 0..127 chars and
  3761. leaves 128..255 unchanged; it also stays inside the four branch
  3762. conditions this compiler declares (check_8086's set). *)
  3763. IF NOT MatchDelim ('(') THEN
  3764. Err (ENoSemi) ;
  3765. RETURN
  3766. END ;
  3767. ParseExpr (r) ;
  3768. ExpectDelim (')', ENoSemi) ;
  3769. IF NOT OK () THEN
  3770. RETURN
  3771. END ;
  3772. IF (r.cls # TChar) AND (r.cls # TScalar) THEN
  3773. Err (ETypeErr) ; (* the STRING form is not implemented *)
  3774. RETURN
  3775. END ;
  3776. IF r.kind = 0 THEN
  3777. IF (r.imm >= VAL (LONGINT, ORD ('a')))
  3778. AND (r.imm <= VAL (LONGINT, ORD ('z'))) THEN
  3779. r.imm := r.imm - 32
  3780. END ;
  3781. r.kind := 0 ;
  3782. r.cls := TChar ;
  3783. r.chr := TRUE ;
  3784. RETURN
  3785. END ;
  3786. LoadAtom (r) ;
  3787. EmCmpAlImm (ORD ('a')) ;
  3788. uj1 := EmJcc (8CH, 0) ; (* JL -> leave it *)
  3789. EmCmpAlImm (ORD ('z')) ;
  3790. uj2 := EmJcc (8FH, 0) ; (* JG -> leave it *)
  3791. EmSubAlImm (32) ;
  3792. SetPatTgt (uj1, pc) ;
  3793. SetPatTgt (uj2, pc) ;
  3794. EmMovAh0 () ;
  3795. r.kind := 2 ;
  3796. r.cls := TChar ;
  3797. r.chr := FALSE ;
  3798. RETURN
  3799. ELSIF (symtab [idx].tag = KBuiltin) AND
  3800. ((symtab [idx].cls = BI_Succ) OR (symtab [idx].cls = BI_Pred)) THEN
  3801. (* Succ(x) / Pred(x) on an ordinal. CALC's `FX := Succ(FX)' is the
  3802. first use. A constant folds; otherwise load the value and INC/DEC
  3803. it, preserving the operand's class so an assignment back to a CHAR
  3804. subrange stores one byte as before. *)
  3805. IF NOT MatchDelim ('(') THEN
  3806. Err (ENoSemi) ;
  3807. RETURN
  3808. END ;
  3809. ParseExpr (r) ;
  3810. ExpectDelim (')', ENoSemi) ;
  3811. IF NOT OK () THEN
  3812. RETURN
  3813. END ;
  3814. IF (r.cls # TChar) AND (r.cls # TScalar) THEN
  3815. Err (ETypeErr) ;
  3816. RETURN
  3817. END ;
  3818. IF r.kind = 0 THEN
  3819. IF symtab [idx].cls = BI_Succ THEN
  3820. r.imm := VAL (LONGINT, W16 (r.imm + 1))
  3821. ELSE
  3822. r.imm := VAL (LONGINT, W16 (r.imm - 1))
  3823. END
  3824. ELSE
  3825. LoadAtom (r) ;
  3826. IF symtab [idx].cls = BI_Succ THEN
  3827. EmIncAx ()
  3828. ELSE
  3829. EmDecAx ()
  3830. END ;
  3831. r.kind := 2
  3832. END ;
  3833. r.chr := FALSE ;
  3834. RETURN
  3835. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_KeyPressed) THEN
  3836. (* KeyPressed: a boolean FUNCTION with no argument, and TP3 lets it be
  3837. written without a parameter list (`until KeyPressed'). *)
  3838. EmCrtSeq (CrtKey) ;
  3839. r.kind := 2 ;
  3840. r.cls := TBool ;
  3841. r.chr := FALSE ;
  3842. RETURN
  3843. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_Length) THEN
  3844. (* LENGTH (s): the string's length byte, loaded inline. No runtime
  3845. entry, and no address is pushed - a string's value already carries its
  3846. length at [addr]. A literal is emitted inline (EmStrBlob) and the
  3847. byte is read from that image offset. *)
  3848. IF NOT MatchDelim ('(') THEN
  3849. Err (ENoSemi) ;
  3850. RETURN
  3851. END ;
  3852. ParseExpr (r) ;
  3853. ExpectDelim (')', ENoSemi) ;
  3854. IF NOT OK () THEN
  3855. RETURN
  3856. END ;
  3857. IF r.cls # TString THEN
  3858. Err (ETypeErr) ;
  3859. RETURN
  3860. END ;
  3861. IF (r.kind = 1) AND symtab [r.idx].isVar THEN
  3862. (* VAR string: the slot holds the address; read the length byte
  3863. through that pointer. *)
  3864. IF r.boff # 0 THEN
  3865. Err (ENoLib)
  3866. ELSE
  3867. EmLoadVarInd (symtab [r.idx].off, 1)
  3868. END
  3869. ELSIF r.kind = 1 THEN
  3870. EmLoadVar (symtab [r.idx].local,
  3871. (symtab [r.idx].off + r.boff) MOD 10000H, 1)
  3872. ELSIF r.kind = 3 THEN
  3873. EmLoadVar (FALSE, EmStrBlob (r), 1)
  3874. ELSE
  3875. Err (ENoLib) ;
  3876. RETURN
  3877. END ;
  3878. EmMovAh0 () ;
  3879. r.kind := 2 ;
  3880. r.cls := TScalar ;
  3881. r.chr := FALSE ;
  3882. RETURN
  3883. ELSE
  3884. Err (EUnknown)
  3885. END
  3886. END ParseAtom ;
  3887. PROCEDURE AddPend (kind, who, place : CARDINAL) ;
  3888. BEGIN
  3889. IF nPend < MaxPend THEN
  3890. pend [nPend].kind := kind ;
  3891. pend [nPend].who := who ;
  3892. pend [nPend].place := place ;
  3893. INC (nPend)
  3894. ELSE
  3895. Err (ECompOvf)
  3896. END
  3897. END AddPend ;
  3898. PROCEDURE ParmSlot (idx, k : CARDINAL) : CARDINAL ;
  3899. (* The stack slot of argument k (0-based) of procedure/function idx, from the
  3900. parameter list recorded on the symbol. Out of range means the source passed
  3901. more arguments than there are parameters: keep the old two-byte assumption
  3902. rather than inventing an arity error here. *)
  3903. VAR pi : CARDINAL ;
  3904. BEGIN
  3905. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3906. RETURN 2
  3907. END ;
  3908. pi := symtab [idx].parmFirst + k ;
  3909. RETURN ParamSlotBytes (symtab [pi])
  3910. END ParmSlot ;
  3911. PROCEDURE ParmIsVar (idx, k : CARDINAL) : BOOLEAN ;
  3912. (* Is argument k (0-based) of procedure/function idx declared VAR? Out of
  3913. range means the source passed more arguments than there are formals; treat
  3914. it as a value parameter, as ParmSlot already does. *)
  3915. VAR pi : CARDINAL ;
  3916. BEGIN
  3917. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3918. RETURN FALSE
  3919. END ;
  3920. pi := symtab [idx].parmFirst + k ;
  3921. RETURN symtab [pi].isVar
  3922. END ParmIsVar ;
  3923. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ;
  3924. (* emit the call to sym 'idx' and clean up `cleanup' bytes of arguments, which
  3925. is the SUM of their slot sizes - not 2 per argument once a slot can be
  3926. larger than a word. *)
  3927. VAR p : CARDINAL ;
  3928. BEGIN
  3929. IF symtab [idx].defnd THEN
  3930. DropC (EmCall (symtab [idx].goPos))
  3931. ELSE
  3932. p := EmCall (0) ;
  3933. AddPend (1, idx, p)
  3934. END ;
  3935. IF cleanup > 0 THEN
  3936. EmAddSp (cleanup)
  3937. END
  3938. END EmCallMost ;
  3939. PROCEDURE ParseCallArgs (idx : CARDINAL) ;
  3940. (* '(' already consumed: read args ')' then call.
  3941. Each argument is loaded and pushed the moment it has been parsed, which is
  3942. what TPSRC8 cproc/cprlp1/cprlp2 do - CALL exprsave, CALL epushax, one per
  3943. argument, then the CALL. A computed argument (kind 2) exists only in AX,
  3944. so parsing the argument after it would destroy it before the push loop
  3945. ever reached it: `p (a > b, x)' passed x twice.
  3946. Pushing in parse order is also the order the callee is laid out for: the
  3947. first argument goes on first and so ends up farthest from BP, and the LAST
  3948. declared parameter is the one at BP+4 (RESUME-TP3.md 3.11). *)
  3949. VAR arg : ERes ;
  3950. nArgs, cleanup, slot, nCopy : CARDINAL ;
  3951. BEGIN
  3952. nArgs := 0 ;
  3953. cleanup := 0 ;
  3954. IF CurCh () = ')' THEN
  3955. DropCh (GetCh ())
  3956. ELSE
  3957. LOOP
  3958. IF nArgs >= 16 THEN
  3959. Err (ECompOvf) ;
  3960. EXIT
  3961. END ;
  3962. ParseExpr (arg) ;
  3963. slot := ParmSlot (idx, nArgs) ;
  3964. IF ParmIsVar (idx, nArgs) THEN
  3965. (* VAR formal: push the actual's ADDRESS. Only a variable has
  3966. one; a constant or a computed value is refused rather than
  3967. quietly passed by value. An element with a constant index
  3968. (`s[i]') is a variable too: its address is off+boff, which
  3969. EmPushVarAddr forms directly. *)
  3970. IF arg.kind # 1 THEN
  3971. Err (ENoLib) ;
  3972. EXIT
  3973. END ;
  3974. IF symtab [arg.idx].isVar THEN
  3975. (* Passing a VAR parameter on: its slot already HOLDS the
  3976. address, so push that, not the address of the slot. *)
  3977. IF arg.boff # 0 THEN
  3978. Err (ENoLib) ;
  3979. EXIT
  3980. END ;
  3981. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  3982. EmPushAx ()
  3983. ELSE
  3984. EmPushVarAddr (symtab [arg.idx].local,
  3985. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  3986. END
  3987. ELSIF slot > 2 THEN
  3988. (* A STRING VALUE parameter: push its whole slot, copied.
  3989. `copyN' is at most the slot: an actual shorter than the formal
  3990. leaves the tail untouched, which is harmless because the length
  3991. byte bounds every read. *)
  3992. IF arg.cls # TString THEN
  3993. Err (ETypeErr) ;
  3994. EXIT
  3995. END ;
  3996. nCopy := slot ;
  3997. IF arg.kind = 1 THEN
  3998. IF VarSize (arg) < nCopy THEN
  3999. nCopy := VarSize (arg)
  4000. END
  4001. ELSIF arg.kind = 3 THEN
  4002. IF strLen [arg.strx] + 1 < nCopy THEN
  4003. nCopy := strLen [arg.strx] + 1
  4004. END
  4005. ELSE
  4006. Err (ENoLib) ; (* a computed string is not a value *)
  4007. EXIT
  4008. END ;
  4009. EmPushStrSlot (arg, slot, nCopy)
  4010. ELSE
  4011. LoadAtom (arg) ;
  4012. EmPushAx ()
  4013. END ;
  4014. cleanup := cleanup + slot ;
  4015. INC (nArgs) ;
  4016. IF NOT MatchDelim (',') THEN
  4017. EXIT
  4018. END
  4019. END ;
  4020. ExpectDelim (')', ENoSemi)
  4021. END ;
  4022. EmCallMost (idx, cleanup)
  4023. END ParseCallArgs ;
  4024. PROCEDURE ParseCall (idx : CARDINAL) ;
  4025. (* procedure/function call; '(' optional - same parse-then-push as above,
  4026. reached from ParseAtom when a FUNCTION is called in an expression *)
  4027. VAR arg : ERes ;
  4028. nArgs, cleanup, slot, nCopy : CARDINAL ;
  4029. BEGIN
  4030. nArgs := 0 ;
  4031. cleanup := 0 ;
  4032. IF MatchDelim ('(') THEN
  4033. IF CurCh () # ')' THEN
  4034. LOOP
  4035. IF nArgs >= 16 THEN
  4036. Err (ECompOvf) ;
  4037. EXIT
  4038. END ;
  4039. ParseExpr (arg) ;
  4040. slot := ParmSlot (idx, nArgs) ;
  4041. IF ParmIsVar (idx, nArgs) THEN
  4042. (* A VAR formal in a FUNCTION call: the callee wants the
  4043. address, exactly as ParseCallArgs does for a procedure. This
  4044. path was missing, so `Length(s)' inside a function whose
  4045. formal is `var s' pushed the string's VALUE and the callee
  4046. would have read it as an address. *)
  4047. IF arg.kind # 1 THEN
  4048. Err (ENoLib) ;
  4049. EXIT
  4050. END ;
  4051. IF symtab [arg.idx].isVar THEN
  4052. IF arg.boff # 0 THEN
  4053. Err (ENoLib) ;
  4054. EXIT
  4055. END ;
  4056. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  4057. EmPushAx ()
  4058. ELSE
  4059. EmPushVarAddr (symtab [arg.idx].local,
  4060. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  4061. END
  4062. ELSIF slot > 2 THEN
  4063. (* see ParseCallArgs: push the whole string slot *)
  4064. IF arg.cls # TString THEN
  4065. Err (ETypeErr) ;
  4066. EXIT
  4067. END ;
  4068. nCopy := slot ;
  4069. IF arg.kind = 1 THEN
  4070. IF VarSize (arg) < nCopy THEN
  4071. nCopy := VarSize (arg)
  4072. END
  4073. ELSIF arg.kind = 3 THEN
  4074. IF strLen [arg.strx] + 1 < nCopy THEN
  4075. nCopy := strLen [arg.strx] + 1
  4076. END
  4077. ELSE
  4078. Err (ENoLib) ;
  4079. EXIT
  4080. END ;
  4081. EmPushStrSlot (arg, slot, nCopy)
  4082. ELSE
  4083. LoadAtom (arg) ;
  4084. EmPushAx ()
  4085. END ;
  4086. cleanup := cleanup + slot ;
  4087. INC (nArgs) ;
  4088. IF NOT MatchDelim (',') THEN
  4089. EXIT
  4090. END
  4091. END ;
  4092. ExpectDelim (')', ENoSemi)
  4093. ELSE
  4094. DropCh (GetCh ())
  4095. END
  4096. END ;
  4097. EmCallMost (idx, cleanup)
  4098. END ParseCall ;
  4099. PROCEDURE ParseExpr (VAR r : ERes) ;
  4100. BEGIN
  4101. ParseCmp (r)
  4102. END ParseExpr ;
  4103. (* ---------------------------------------------------------------- *)
  4104. (* statements (TPSRC8) *)
  4105. (* ---------------------------------------------------------------- *)
  4106. PROCEDURE ParseLabelStmt () ;
  4107. (* numeric label definition 'n :' *)
  4108. VAR n : CARDINAL ;
  4109. nm : ARRAY [0..9] OF CHAR ;
  4110. idx : CARDINAL ;
  4111. i : CARDINAL ;
  4112. BEGIN
  4113. n := 0 ;
  4114. WHILE Digit (CurCh ()) DO
  4115. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  4116. DropCh (GetCh ())
  4117. END ;
  4118. ExpectDelim (':', ENoSemi) ;
  4119. NumToName (n, nm) ;
  4120. IF Search (nm, idx) THEN
  4121. IF symtab [idx].tag = KLabel THEN
  4122. symtab [idx].defnd := TRUE ;
  4123. symtab [idx].goPos := pc ;
  4124. i := 0 ;
  4125. WHILE i < nPend DO
  4126. IF (pend [i].kind = 0) AND (pend [i].who = idx) THEN
  4127. SetPatTgt (pend [i].place, pc) ;
  4128. pend [i].kind := 99
  4129. END ;
  4130. INC (i)
  4131. END
  4132. ELSE
  4133. Err (EUnknown)
  4134. END
  4135. ELSE
  4136. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  4137. symtab [idx].defnd := TRUE ;
  4138. symtab [idx].goPos := pc
  4139. END
  4140. END ParseLabelStmt ;
  4141. PROCEDURE IntToMbf (v : LONGINT ; VAR b : ARRAY OF CHAR) ;
  4142. (* TP3's 6-byte Real, as measured in CALC-PORT.md against the cells holding
  4143. 1, 2, 3, 4 and 5:
  4144. value = (1 + N / 2^39) * 2^(E - 129)
  4145. byte 0 is E (biased by 129); bytes 1..5 are N, little-endian; the SIGN is
  4146. bit 7 of byte 5 (the book's `sign + 39-bit mantissa'). An all-zero value
  4147. is 0.0. 1 -> 81 00 00 00 00 00, 3 -> 82 00 00 00 00 40,
  4148. 5 -> 83 00 00 00 00 20 - all cross-checked against CALCDEMO.MCS.
  4149. Only INTEGER values are converted; real arithmetic and formatting are a
  4150. later stage, and a real RHS that is not a constant or a copy is ENoLib. *)
  4151. VAR a, p, n : LONGINT ;
  4152. e, k, i : CARDINAL ;
  4153. neg : BOOLEAN ;
  4154. BEGIN
  4155. i := 0 ;
  4156. WHILE i < 6 DO
  4157. b [i] := CHR (0) ;
  4158. INC (i)
  4159. END ;
  4160. IF v = 0 THEN
  4161. RETURN
  4162. END ;
  4163. neg := v < 0 ;
  4164. IF neg THEN
  4165. a := -v
  4166. ELSE
  4167. a := v
  4168. END ;
  4169. (* k = floor(log2(a)); p = 2^k *)
  4170. p := 1 ;
  4171. k := 0 ;
  4172. WHILE (k < 39) AND (p * 2 <= a) DO
  4173. p := p * 2 ;
  4174. INC (k)
  4175. END ;
  4176. IF k >= 39 THEN
  4177. Err (EConstRange) ;
  4178. RETURN
  4179. END ;
  4180. e := 129 + k ;
  4181. b [0] := CHR (e) ;
  4182. n := a - p ;
  4183. i := 39 - k ;
  4184. WHILE i > 0 DO
  4185. n := n * 2 ;
  4186. DEC (i)
  4187. END ;
  4188. i := 1 ;
  4189. WHILE i <= 5 DO
  4190. b [i] := CHR (VAL (CARDINAL, n MOD 256)) ;
  4191. n := n DIV 256 ;
  4192. INC (i)
  4193. END ;
  4194. IF neg THEN
  4195. b [5] := CHR (ORD (b [5]) + 128)
  4196. END
  4197. END IntToMbf ;
  4198. PROCEDURE Assignment (r : ERes) ;
  4199. (* ':=' already consumed by the caller; store expression into r *)
  4200. VAR src : ERes ;
  4201. k, n : CARDINAL ;
  4202. sbuf : ARRAY [0..31] OF CHAR ;
  4203. rbuf : ARRAY [0..5] OF CHAR ;
  4204. BEGIN
  4205. IF (r.kind # 1) AND (r.kind # 5) THEN
  4206. Err (EUnknown) ;
  4207. RETURN
  4208. END ;
  4209. IF r.cls = TReal THEN
  4210. (* A 6-byte REAL. A compile-time ordinal constant is converted to the
  4211. measured MBF layout; another REAL field is copied byte for byte.
  4212. Real arithmetic and real-valued expressions are a later stage and
  4213. are refused, not guessed. *)
  4214. ParseExpr (src) ;
  4215. IF NOT OK () THEN
  4216. RETURN
  4217. END ;
  4218. IF (src.kind = 0) AND (src.cls # TString) AND (src.cls # TSet) THEN
  4219. IntToMbf (src.imm, rbuf) ;
  4220. IF r.kind = 5 THEN
  4221. k := 0 ;
  4222. WHILE k < 6 DO
  4223. EmStDiImm (k, ORD (rbuf [k])) ;
  4224. INC (k)
  4225. END
  4226. ELSIF r.kind = 1 THEN
  4227. k := 0 ;
  4228. WHILE k < 6 DO
  4229. EmMovAxi (ORD (rbuf [k])) ;
  4230. EmStoreVar (symtab [r.idx].local,
  4231. (symtab [r.idx].off + r.boff + k) MOD 10000H, 1) ;
  4232. INC (k)
  4233. END
  4234. ELSE
  4235. Err (ENoLib)
  4236. END ;
  4237. RETURN
  4238. END ;
  4239. IF (src.kind = 1) AND (src.cls = TReal) THEN
  4240. IF r.kind = 5 THEN
  4241. IF src.kind = 5 THEN
  4242. Err (ENoLib) ;
  4243. RETURN
  4244. END ;
  4245. k := 0 ;
  4246. WHILE k < 6 DO
  4247. EmLoadVar (symtab [src.idx].local,
  4248. (symtab [src.idx].off + src.boff + k) MOD 10000H, 1) ;
  4249. EmStDiAlOff (k) ;
  4250. INC (k)
  4251. END
  4252. ELSIF r.kind = 1 THEN
  4253. k := 0 ;
  4254. WHILE k < 6 DO
  4255. EmLoadVar (symtab [src.idx].local,
  4256. (symtab [src.idx].off + src.boff + k) MOD 10000H, 1) ;
  4257. EmStoreVar (symtab [r.idx].local,
  4258. (symtab [r.idx].off + r.boff + k) MOD 10000H, 1) ;
  4259. INC (k)
  4260. END
  4261. ELSE
  4262. Err (ENoLib)
  4263. END ;
  4264. RETURN
  4265. END ;
  4266. Err (ENoLib) ;
  4267. RETURN
  4268. END ;
  4269. IF r.cls = TSet THEN
  4270. (* `field := [elements]'. The constructor's TYPE comes from the target:
  4271. CALC's CellStatus is `set of Attributes' (one byte), not the default
  4272. 32-byte `set of Char' an untyped literal would become. The bytes are
  4273. known at compile time; store them at symbol+boff or through DI. *)
  4274. IF (r.setsize = 0) OR (r.setsize > 32) THEN
  4275. Err (ENoLib) ;
  4276. RETURN
  4277. END ;
  4278. Skip () ;
  4279. IF CurCh () # '[' THEN
  4280. (* `set := set' or a set expression. The destination is a variable
  4281. or a DI-addressed field; save the DI address BEFORE the right-hand
  4282. expression can reuse DI, then copy the runtime's bytes. *)
  4283. IF r.kind = 5 THEN
  4284. EmPushDi ()
  4285. END ;
  4286. ParseExpr (src) ;
  4287. IF NOT OK () THEN
  4288. RETURN
  4289. END ;
  4290. IF src.cls # TSet THEN
  4291. Err (ETypeErr) ;
  4292. RETURN
  4293. END ;
  4294. IF r.kind = 1 THEN
  4295. EmPushVarAddr (symtab [r.idx].local,
  4296. (symtab [r.idx].off + r.boff) MOD 10000H)
  4297. ELSIF r.kind # 5 THEN
  4298. Err (ENoLib) ;
  4299. RETURN
  4300. END ;
  4301. EmPushSetAddr (src) ;
  4302. n := r.setsize ;
  4303. IF (src.kind = 8) AND (src.setsize < n) THEN
  4304. n := src.setsize
  4305. END ;
  4306. EmMovAxi (n) ;
  4307. EmPushAx () ;
  4308. DropC (EmCall (TU_SetCopy)) ;
  4309. EmAddSp (4) ;
  4310. RETURN
  4311. END ;
  4312. IF NOT RdSetLiteral (r.setbase, r.setsize, sbuf) THEN
  4313. RETURN
  4314. END ;
  4315. IF r.kind = 5 THEN
  4316. k := 0 ;
  4317. WHILE k < r.setsize DO
  4318. EmStDiImm (k, ORD (sbuf [k])) ;
  4319. INC (k)
  4320. END
  4321. ELSIF r.kind = 1 THEN
  4322. k := 0 ;
  4323. WHILE k < r.setsize DO
  4324. EmMovAxi (ORD (sbuf [k])) ;
  4325. EmStoreVar (symtab [r.idx].local,
  4326. (symtab [r.idx].off + r.boff + k) MOD 10000H, 1) ;
  4327. INC (k)
  4328. END
  4329. ELSE
  4330. Err (ENoLib)
  4331. END ;
  4332. RETURN
  4333. END ;
  4334. IF (r.kind = 5) AND (r.cls = TString) THEN
  4335. (* A string field of a DI-addressed record element (CALC's
  4336. `with Sheet[I,J] do Contents := '''). DI is the field's address.
  4337. A literal's bytes are known: store <len><chars>, truncated to the
  4338. field's capacity (size-1). A string VARIABLE source uses strstore,
  4339. with DI pushed as the destination. *)
  4340. ParseExpr (src) ;
  4341. IF NOT OK () THEN
  4342. RETURN
  4343. END ;
  4344. n := VarSize (r) - 1 ; (* usable characters *)
  4345. IF src.kind = 3 THEN
  4346. IF strLen [src.strx] < n THEN
  4347. n := strLen [src.strx]
  4348. END ;
  4349. EmStDiImm (0, n) ; (* the length byte *)
  4350. k := 1 ;
  4351. WHILE k <= n DO
  4352. EmStDiImm (k, ORD (strPool [strOff [src.strx] + k - 1])) ;
  4353. INC (k)
  4354. END
  4355. ELSIF src.kind = 1 THEN
  4356. EmPushVarAddr (symtab [src.idx].local,
  4357. (symtab [src.idx].off + src.boff) MOD 10000H) ;
  4358. EmPushDi () ; (* destination = the field *)
  4359. EmMovCxi (n) ; (* strstore's limit *)
  4360. DropC (EmCall (TU_StrStore)) ;
  4361. EmAddSp (4)
  4362. ELSE
  4363. Err (ENoLib)
  4364. END ;
  4365. RETURN
  4366. END ;
  4367. IF (r.kind = 1) AND (r.cls = TString) AND symtab [r.idx].isVar THEN
  4368. (* A VAR string parameter: the slot holds the caller's string address.
  4369. Copy through the runtime, exactly as a normal string variable does:
  4370. source address first, destination address second, limit in CX. This
  4371. covers literals and whole-string expressions alike; the destination
  4372. address is loaded from the parameter slot rather than formed with
  4373. LEA, which would point at the slot itself. *)
  4374. ParseExpr (src) ;
  4375. IF NOT OK () THEN
  4376. RETURN
  4377. END ;
  4378. IF src.cls # TString THEN
  4379. Err (ETypeErr) ;
  4380. RETURN
  4381. END ;
  4382. EmPushStrAddr (src) ;
  4383. EmLoadVar (TRUE, symtab [r.idx].off, 2) ;
  4384. EmPushAx () ;
  4385. EmMovCxi ((VarSize (r) - 1) MOD 10000H) ;
  4386. DropC (EmCall (TU_StrStore)) ;
  4387. EmAddSp (4) ;
  4388. RETURN
  4389. END ;
  4390. IF (r.kind = 1) AND symtab [r.idx].isVar THEN
  4391. (* `varparam := expr': store through the address the slot holds. DI is
  4392. parked across the right-hand side because that expression may use DI
  4393. for a string element of its own. *)
  4394. IF r.boff # 0 THEN
  4395. Err (ENoLib) ;
  4396. RETURN
  4397. END ;
  4398. EmStoreVarIndPrep (symtab [r.idx].off) ;
  4399. ParseExpr (src) ;
  4400. LoadAtom (src) ;
  4401. EmPopDi () ;
  4402. EmStoreInd (VarSize (r)) ;
  4403. RETURN
  4404. END ;
  4405. IF (r.cls = TString) AND (VarSize (r) > 1) THEN
  4406. (* s := <string literal>. TPSRC8 asn2 sends a string through the scalar
  4407. store path, and estcpl's string arm emits `MOV CL,max_len' (max_len =
  4408. varsize-1) then `CALL strstore', which copies the source - length byte
  4409. and characters - into the destination and TRUNCATES a source longer
  4410. than max_len by rewriting the length byte (TPSRC2 strstore's
  4411. `CMP.B CL,AL / JBE stslenok / MOV.B [SI],AL'). Here the literal is
  4412. known at compile time, so its bytes become immediate stores instead of
  4413. a stack push and a block move. The variable that results is the same,
  4414. truncation included, and the tail past the new length is left as it
  4415. was, exactly as strstore leaves it. *)
  4416. ParseExpr (src) ;
  4417. IF (src.cls # TString) THEN
  4418. Err (ENoLib) ;
  4419. RETURN
  4420. END ;
  4421. IF src.kind # 3 THEN
  4422. (* s := <string variable>. TPSRC8 asnvar pushes the destination
  4423. address, then the expression (strload) pushes the source, and
  4424. estcpl emits MOV CL,max_len then CALL strstore, which copies
  4425. length byte + chars, TRUNCATING to max_len and leaving the
  4426. destination tail past the new length untouched. Here both
  4427. addresses are pushed - source first, so it sits at [BP+6] and the
  4428. destination at [BP+4] - the caller pops both, and the limit is a
  4429. full MOV CX,imm16 because this runtime reads it in CX outright. *)
  4430. IF src.kind # 1 THEN
  4431. Err (ENoLib) ; (* a computed string is not a value *)
  4432. RETURN
  4433. END ;
  4434. EmPushVarAddr (symtab [src.idx].local,
  4435. (symtab [src.idx].off + src.boff) MOD 10000H) ;
  4436. EmPushVarAddr (symtab [r.idx].local,
  4437. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  4438. EmMovCxi ((VarSize (r) - 1) MOD 10000H) ;
  4439. DropC (EmCall (TU_StrStore)) ;
  4440. EmAddSp (4) ;
  4441. RETURN
  4442. END ;
  4443. n := strLen [src.strx] ;
  4444. IF n > VarSize (r) - 1 THEN
  4445. n := VarSize (r) - 1
  4446. END ;
  4447. EmMovAxi (n) ;
  4448. EmStoreVar (symtab [r.idx].local,
  4449. (symtab [r.idx].off + r.boff) MOD 10000H, 1) ;
  4450. k := 0 ;
  4451. WHILE k < n DO
  4452. EmMovAxi (ORD (strPool [strOff [src.strx] + k])) ;
  4453. EmStoreVar (symtab [r.idx].local,
  4454. (symtab [r.idx].off + r.boff + 1 + k) MOD 10000H, 1) ;
  4455. INC (k)
  4456. END ;
  4457. RETURN
  4458. END ;
  4459. IF (r.kind = 5) OR (VarSize (r) > 2) THEN
  4460. IF r.kind = 5 THEN
  4461. (* An element addressed by DI: a string character (one byte) or an
  4462. array element (one or two). A wider element - a record - is
  4463. refused rather than stored as its first two bytes.
  4464. The destination address is in DI, and the right-hand side is
  4465. parsed next, so DI has to be saved first - the RHS may hold a
  4466. subscript of its own, which reuses DI, or call a routine that
  4467. clobbers it. This is TPSRC8 asnscal2/asnscal3 (758-760, 786-789),
  4468. which set flgpshdi around the expression for the same reason. *)
  4469. IF VarSize (r) > 2 THEN
  4470. Err (ENoLib) ;
  4471. RETURN
  4472. END ;
  4473. EmPushDi () ;
  4474. ParseExpr (src) ;
  4475. LoadAtom (src) ;
  4476. EmPopDi () ; (* DI := the destination again *)
  4477. EmStoreInd (VarSize (r)) ; (* [DI] := AL or AX *)
  4478. RETURN
  4479. END ;
  4480. (* A value wider than a word with no address to store through: an
  4481. assignment to a whole string/record/array is not a scalar store. *)
  4482. Err (ENoLib) ;
  4483. RETURN
  4484. END ;
  4485. ParseExpr (src) ;
  4486. LoadAtom (src) ;
  4487. EmStoreVar (symtab [r.idx].local,
  4488. (symtab [r.idx].off + r.boff) MOD 10000H,
  4489. VarSize (r))
  4490. END Assignment ;
  4491. PROCEDURE Compound () ;
  4492. (* BEGIN statement ';' ... END; END is consumed here *)
  4493. VAR tok : CARDINAL ;
  4494. BEGIN
  4495. LOOP
  4496. PeekKw (tok) ;
  4497. IF tok = TkEnd THEN
  4498. DropB (MatchKey (tok)) ;
  4499. RETURN
  4500. END ;
  4501. Statmnt () ;
  4502. IF NOT OK () THEN
  4503. RETURN
  4504. END ;
  4505. IF NOT MatchDelim (';') THEN
  4506. PeekKw (tok) ;
  4507. IF tok = TkEnd THEN
  4508. DropB (MatchKey (tok)) ;
  4509. RETURN
  4510. END ;
  4511. Err (ENoSemi) ;
  4512. RETURN
  4513. END
  4514. END
  4515. END Compound ;
  4516. PROCEDURE EmCrtSeq (which : CARDINAL) ;
  4517. (* The CRT byte sequences, in one parameterised helper. Every one is a fixed
  4518. BIOS call:
  4519. CrtClr - INT 10h AH=06 blank the whole window, then AH=02 home the cursor
  4520. CrtDl - DEC AX ; MOV DL,AL (a 1-based column -> 0-based)
  4521. CrtDh - DEC AX ; MOV DH,AL (a 1-based row)
  4522. CrtCaret - INT 10h AH=02, page 0, cursor at DH,DL
  4523. It takes a parameter on purpose: audit_helpers audits helpers with an EMPTY
  4524. parameter list byte-for-byte, and these multi-instruction sequences have no
  4525. single name grammar. Listed as COMP in NON_ONE_LINE, like SetBlob. *)
  4526. BEGIN
  4527. IF which = CrtClr THEN
  4528. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h *)
  4529. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  4530. Ebyte (0B9H) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV CX,0000h *)
  4531. Ebyte (0BAH) ; Ebyte (4FH) ; Ebyte (18H) ; (* MOV DX,184Fh *)
  4532. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h *)
  4533. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (02H) ; (* MOV AX,0200h *)
  4534. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  4535. Ebyte (0BAH) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV DX,0000h *)
  4536. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  4537. ELSIF which = CrtDl THEN
  4538. Ebyte (48H) ; (* DEC AX *)
  4539. Ebyte (88H) ; Ebyte (0C2H) (* MOV DL,AL *)
  4540. ELSIF which = CrtDh THEN
  4541. Ebyte (48H) ; (* DEC AX *)
  4542. Ebyte (88H) ; Ebyte (0C6H) (* MOV DH,AL *)
  4543. ELSIF which = CrtEol THEN
  4544. Ebyte (0B4H) ; Ebyte (03H) ; (* MOV AH,03h get cursor *)
  4545. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  4546. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h -> DH,DL *)
  4547. Ebyte (89H) ; Ebyte (0D1H) ; (* MOV CX,DX upper-left *)
  4548. Ebyte (0B2H) ; Ebyte (4FH) ; (* MOV DL,4Fh col 79 *)
  4549. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h blank *)
  4550. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  4551. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  4552. ELSIF which = CrtLow THEN
  4553. (* [crtAttr] := 7: the dim attribute ClrScr/ClrEol use from now on. The
  4554. runtime's console writer is INT 21h teletype, which has no attribute
  4555. channel, but the clear operations do - so this is where the setting is
  4556. observable, not a no-op. *)
  4557. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (07H)
  4558. ELSIF which = CrtNorm THEN
  4559. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (0FH)
  4560. ELSIF which = CrtKey THEN
  4561. (* KeyPressed: DOS AH=0Bh asks whether a character is waiting. AL is
  4562. 0FFh when one is, 0 when not; the boolean representation here is 0/1.
  4563. AND AX,1, not AND AL,1: the interrupt leaves AH = 0Bh, so the
  4564. comparison that follows (`CMP AX,0') would read 0B00h and call the
  4565. false case TRUE. bootcom happened to return AH=0 (it IRETs the
  4566. handler's whole AX) and hid this; hlt. No argument, no runtime
  4567. entry. *)
  4568. Ebyte (0B4H) ; Ebyte (0BH) ; (* MOV AH,0Bh *)
  4569. Ebyte (0CDH) ; Ebyte (21H) ; (* INT 21h *)
  4570. Ebyte (25H) ; Ebyte (01H) ; Ebyte (00H) (* AND AX,1 *)
  4571. ELSIF which = CrtDelay THEN
  4572. (* Delay(AX) milliseconds: TP3's xdelay, a calibrated busy loop. The
  4573. count 110 is TP3's default `delaycnt' for 1 ms (TPSRC1). AX = 0 does
  4574. nothing. *)
  4575. (* OR AX,AX, not CMP AX,0: check_8086 treats every `CMP AX,0000' in the
  4576. program region as one of the IF/WHILE/REPEAT tests and demands
  4577. Jcc+3;EJMP after it. This is neither. *)
  4578. Ebyte (0BH) ; Ebyte (0C0H) ; (* OR AX,AX *)
  4579. Ebyte (74H) ; Ebyte (08H) ; (* JZ past the loop *)
  4580. Ebyte (0B9H) ; Ebyte (6EH) ; Ebyte (00H) ; (* MOV CX,110 (1 ms) *)
  4581. Ebyte (0E2H) ; Ebyte (0FEH) ; (* LOOP -> itself *)
  4582. Ebyte (48H) ; (* DEC AX *)
  4583. Ebyte (75H) ; Ebyte (0F8H) (* JNZ -> MOV CX *)
  4584. ELSE
  4585. Ebyte (0B4H) ; Ebyte (02H) ; (* MOV AH,02h *)
  4586. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  4587. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  4588. END
  4589. END EmCrtSeq ;
  4590. PROCEDURE IoCall (idx : CARDINAL) ;
  4591. (* WRITE / WRITELN / READ / READLN / HALT.
  4592. TP3 (TPSRC8 pwriteln, pwrloop, prdtyped) does not pass a descriptor to
  4593. the runtime: it looks at each argument's class and emits a *different*
  4594. call per type, so the formatting is fixed at compile time. Mirrored
  4595. here - one call per argument, then a final call for the line break.
  4596. WRITE/WRITELN push the value; READ/READLN push the address, so the
  4597. runtime can store. As everywhere else in this compiler the caller
  4598. cleans the argument off the stack. *)
  4599. VAR arg : ERes ;
  4600. nArgs, ent, which, acls : CARDINAL ;
  4601. argBytes : CARDINAL ; (* bytes pushed for this argument: 2, or 4 with
  4602. a field width *)
  4603. reading : BOOLEAN ;
  4604. pushed : BOOLEAN ;
  4605. skipArg : BOOLEAN ;
  4606. n : CARDINAL ;
  4607. dummy : ERes ;
  4608. BEGIN
  4609. which := symtab [idx].cls ; (* BI_* *)
  4610. IF which = BI_Halt THEN
  4611. IF MatchDelim ('(') THEN (* halt(0) - code ignored *)
  4612. ParseExpr (dummy) ;
  4613. ExpectDelim (')', ENoSemi)
  4614. END ;
  4615. DropC (EmCall (TU_Halt)) ;
  4616. RETURN
  4617. END ;
  4618. IF which = BI_ClrScr THEN
  4619. EmCrtSeq (CrtClr) ;
  4620. RETURN
  4621. END ;
  4622. IF which = BI_ClrEol THEN
  4623. (* clear from the cursor to the end of the line - a real INT 10h call,
  4624. not a no-op: AH=03 reads the cursor, CX := it, DL := 79, AH=06 blanks
  4625. that window. *)
  4626. EmCrtSeq (CrtEol) ;
  4627. RETURN
  4628. END ;
  4629. IF which = BI_GotoXY THEN
  4630. (* GotoXY (x, y): 1-based; evaluate x first and park it, then y, so the
  4631. code for y cannot clobber DL. *)
  4632. IF MatchDelim ('(') THEN
  4633. ParseExpr (dummy) ;
  4634. IF OK () THEN
  4635. LoadAtom (dummy) ;
  4636. EmPushAx ()
  4637. END ;
  4638. ExpectDelim (',', ENoSemi) ;
  4639. ParseExpr (dummy) ;
  4640. IF OK () THEN
  4641. LoadAtom (dummy) ;
  4642. EmCrtSeq (CrtDh)
  4643. END ;
  4644. ExpectDelim (')', ENoSemi) ;
  4645. EmPopAx () ;
  4646. EmCrtSeq (CrtDl) ;
  4647. EmCrtSeq (CrtCaret)
  4648. ELSE
  4649. Err (ENoSemi)
  4650. END ;
  4651. RETURN
  4652. END ;
  4653. IF which = BI_LowVideo THEN
  4654. (* set the attribute the CLEAR operations use to 7; see EmCrtSeq *)
  4655. EmCrtSeq (CrtLow) ;
  4656. RETURN
  4657. END ;
  4658. IF which = BI_NormVideo THEN
  4659. EmCrtSeq (CrtNorm) ;
  4660. RETURN
  4661. END ;
  4662. IF which = BI_Delay THEN
  4663. (* Delay(ms): a real busy loop (EmCrtSeq's CrtDelay), no INT, so it is
  4664. identical under qemu and Exec86. *)
  4665. IF MatchDelim ('(') THEN
  4666. ParseExpr (dummy) ;
  4667. IF OK () THEN
  4668. LoadAtom (dummy) ;
  4669. EmCrtSeq (CrtDelay)
  4670. END ;
  4671. ExpectDelim (')', ENoSemi)
  4672. ELSE
  4673. Err (ENoSemi)
  4674. END ;
  4675. RETURN
  4676. END ;
  4677. IF which = BI_Assign THEN
  4678. (* Assign(F, Name): the file variable's address and the counted
  4679. string's address. The runtime copies the characters into the file
  4680. control block and marks it closed; Reset/Rewrite do the DOS open.
  4681. Name is pushed first, so the runtime sees F at [BP+4] and Name at
  4682. [BP+6]. *)
  4683. IF MatchDelim ('(') THEN
  4684. ParseExpr (arg) ;
  4685. IF OK () AND (arg.kind = 1) AND
  4686. ((arg.cls = TFile) OR (arg.cls = TText) OR (arg.cls = TUntyp)) THEN
  4687. ExpectDelim (',', ENoSemi) ;
  4688. ParseExpr (dummy) ;
  4689. IF OK () THEN
  4690. IF dummy.cls = TString THEN
  4691. EmPushStrAddr (dummy) ;
  4692. EmPushVarAddr (symtab [arg.idx].local,
  4693. (symtab [arg.idx].off + arg.boff) MOD 10000H) ;
  4694. DropC (EmCall (TU_FileAssign)) ;
  4695. EmAddSp (4)
  4696. ELSE
  4697. Err (ETypeErr)
  4698. END
  4699. END
  4700. ELSIF OK () THEN
  4701. Err (ETypeErr)
  4702. END ;
  4703. ExpectDelim (')', ENoSemi)
  4704. ELSE
  4705. Err (ENoSemi)
  4706. END ;
  4707. RETURN
  4708. END ;
  4709. IF (which = BI_Reset) OR (which = BI_Rewrite) OR (which = BI_Close) THEN
  4710. IF MatchDelim ('(') THEN
  4711. ParseExpr (arg) ;
  4712. IF OK () THEN
  4713. IF (arg.kind = 1) AND
  4714. ((arg.cls = TFile) OR (arg.cls = TText) OR (arg.cls = TUntyp)) THEN
  4715. EmPushVarAddr (symtab [arg.idx].local,
  4716. (symtab [arg.idx].off + arg.boff) MOD 10000H) ;
  4717. IF which = BI_Reset THEN
  4718. DropC (EmCall (TU_FileReset))
  4719. ELSIF which = BI_Rewrite THEN
  4720. DropC (EmCall (TU_FileRewrite))
  4721. ELSE
  4722. DropC (EmCall (TU_FileClose))
  4723. END ;
  4724. EmAddSp (2)
  4725. ELSE
  4726. Err (ETypeErr)
  4727. END
  4728. END ;
  4729. ExpectDelim (')', ENoSemi)
  4730. ELSE
  4731. Err (ENoSemi)
  4732. END ;
  4733. RETURN
  4734. END ;
  4735. reading := (which = BI_Read) OR (which = BI_ReadLn) ;
  4736. nArgs := 0 ;
  4737. IF MatchDelim ('(') THEN
  4738. IF CurCh () # ')' THEN
  4739. LOOP
  4740. IF nArgs >= 16 THEN
  4741. Err (ECompOvf) ;
  4742. EXIT
  4743. END ;
  4744. ParseExpr (arg) ;
  4745. IF NOT OK () THEN
  4746. (* An argument that did not type-check has no value and arg.idx
  4747. is not a symbol. The string arm below dereferences
  4748. symtab[arg.idx] for ANY value whose class is TString - unlike
  4749. the string assign in Assignment, which can tell a failed
  4750. concat from a real one by its kind - so a `writeln' of a
  4751. rejected expression read symtab with whatever idx held
  4752. before and dereferenced it. That is exactly how
  4753. `writeln('a' + 'b')' - two CHARs, a type error since
  4754. v-TP3-STRCAT - segfaulted the compiler instead of reporting
  4755. the error. ParseSub guards its subscript the same way (see
  4756. `IF OK () THEN' before symtab[r.idx] there), and the
  4757. statement loop stops at the next iteration, so leaving the
  4758. rest of this WRITELN unparsed is harmless. *)
  4759. RETURN
  4760. END ;
  4761. (* One argument at a time: parse it, give it its own push or its
  4762. own runtime call, and only then read the next one. TPSRC8
  4763. pwrloop does exactly this, and it has to - a computed argument
  4764. exists only in AX, so parsing the argument after it, and the
  4765. call made for THIS one, are both free to destroy it. Reading
  4766. the whole list first and emitting afterwards printed the first
  4767. argument as the last argument's value, and pushed an argument
  4768. that an earlier inline string's call had already overwritten. *)
  4769. skipArg := FALSE ;
  4770. IF (nArgs = 0) AND (arg.cls = TText) THEN
  4771. (* A leading TEXT file argument. KBD is the console keyboard
  4772. and this runtime's read entries already read the console, so
  4773. the file is dropped and the rest of the argument list is read
  4774. exactly as without it. *)
  4775. IF reading AND (arg.kind = 1) AND symtab [arg.idx].isKbd THEN
  4776. IF NOT MatchDelim (',') THEN
  4777. Err (ENoSemi) ;
  4778. RETURN
  4779. END ;
  4780. skipArg := TRUE
  4781. ELSIF reading THEN
  4782. (* Text-file Read/Readln is the next increment. *)
  4783. Err (ENoLib) ;
  4784. RETURN
  4785. ELSE
  4786. (* Text-file output: Writeln(File) is CRLF, Write(File, C)
  4787. is one CHAR, and writeln(File, S) is S followed by CRLF.
  4788. Write each byte range with DOS AH=40h; a string argument
  4789. carries its own length byte, a one-CHAR literal becomes a
  4790. tiny code-resident <1><char>. *)
  4791. IF (arg.kind # 1) OR (symtab [arg.idx].cls # TText) THEN
  4792. Err (ETypeErr) ;
  4793. RETURN
  4794. END ;
  4795. IF MatchDelim (',') THEN
  4796. ParseExpr (dummy) ;
  4797. IF NOT OK () THEN
  4798. RETURN
  4799. END ;
  4800. IF dummy.cls = TString THEN
  4801. IF dummy.kind = 1 THEN
  4802. EmFileIo (FALSE, symtab [arg.idx].local,
  4803. symtab [arg.idx].off, 1,
  4804. symtab [dummy.idx].local,
  4805. (symtab [dummy.idx].off + dummy.boff)
  4806. MOD 10000H,
  4807. 0, TRUE)
  4808. ELSIF dummy.kind = 3 THEN
  4809. EmFileIo (FALSE, symtab [arg.idx].local,
  4810. symtab [arg.idx].off, 4, FALSE,
  4811. EmStrBlob (dummy), 0, TRUE)
  4812. ELSE
  4813. Err (ENoLib) ;
  4814. RETURN
  4815. END
  4816. ELSIF (dummy.cls = TScalar) AND dummy.chr THEN
  4817. EmFileIo (FALSE, symtab [arg.idx].local,
  4818. symtab [arg.idx].off, 4, FALSE,
  4819. EmInlineCh (VAL (CARDINAL, dummy.imm)),
  4820. 0, TRUE)
  4821. ELSE
  4822. Err (ENoLib) ;
  4823. RETURN
  4824. END
  4825. END ;
  4826. IF which = BI_WriteLn THEN
  4827. EmFileIo (FALSE, symtab [arg.idx].local,
  4828. symtab [arg.idx].off, 4, FALSE,
  4829. EmInlineCrLf (), 0, TRUE)
  4830. END ;
  4831. ExpectDelim (')', ENoSemi) ;
  4832. RETURN
  4833. END
  4834. ELSIF (nArgs = 0) AND (arg.cls = TFile) THEN
  4835. (* Typed-file block I/O: `write(MCfile, Sheet[I,J])' and the
  4836. symmetric `read(MCfile, Sheet[FX,FY])'. TP3 moves exactly
  4837. one element per call, so consume the single data argument
  4838. here and emit the DOS block call. The element size comes
  4839. from the data expression and must agree with the file's
  4840. declared element size; a mismatch is a type error, not a
  4841. reason to write the wrong number of bytes. *)
  4842. IF (arg.kind # 1) OR NOT MatchDelim (',') THEN
  4843. Err (ETypeErr) ;
  4844. RETURN
  4845. END ;
  4846. ParseExpr (dummy) ;
  4847. IF NOT OK () THEN
  4848. RETURN
  4849. END ;
  4850. IF ((dummy.kind # 1) AND (dummy.kind # 5))
  4851. OR (VarSize (dummy) # symtab [arg.idx].elem) THEN
  4852. Err (ETypeErr) ;
  4853. RETURN
  4854. END ;
  4855. IF dummy.kind = 5 THEN
  4856. EmFileIo (reading, symtab [arg.idx].local,
  4857. symtab [arg.idx].off, 5, FALSE, 0, VarSize (dummy),
  4858. FALSE)
  4859. ELSE
  4860. EmFileIo (reading, symtab [arg.idx].local,
  4861. symtab [arg.idx].off, 1, symtab [dummy.idx].local,
  4862. (symtab [dummy.idx].off + dummy.boff) MOD 10000H,
  4863. VarSize (dummy), FALSE)
  4864. END ;
  4865. ExpectDelim (')', ENoSemi) ;
  4866. RETURN
  4867. END ;
  4868. IF NOT skipArg THEN
  4869. pushed := TRUE ; (* default: value is on the stack -> call + pop *)
  4870. argBytes := 2 ;
  4871. IF reading THEN
  4872. IF (arg.kind # 1) AND (arg.kind # 5) THEN
  4873. Err (ETypeErr) ; (* READ needs a variable *)
  4874. RETURN
  4875. END ;
  4876. IF arg.kind = 5 THEN
  4877. (* A DI-addressed element: its TYPE is on the expression
  4878. (WithLookup/ParseSub set it), because the symbol is the
  4879. containing array/record. s[i] is TChar; a WITH string
  4880. field is TString. *)
  4881. acls := arg.cls
  4882. ELSE
  4883. acls := symtab [arg.idx].cls ;
  4884. (* s[i] is a CHAR variable, so read(s[i]) must read one byte
  4885. at off+boff, not the whole string at off. arg.cls is
  4886. TChar (set by ParseSub) while the symbol's own class is
  4887. still TString, which is exactly how the element is told
  4888. from the whole string; the address push has to carry boff.
  4889. For a plain variable arg.boff is 0, so nothing changes. *)
  4890. IF (acls = TString) AND (arg.cls = TChar) THEN
  4891. acls := TChar
  4892. END
  4893. END ;
  4894. IF arg.kind = 5 THEN
  4895. (* A variable index: ParseSub computed the element's address
  4896. into DI, and nothing has been emitted since, so that is
  4897. the address READ wants. A constant index folds into boff
  4898. and takes the LEA path below. *)
  4899. EmPushDi ()
  4900. ELSIF symtab [arg.idx].isVar THEN
  4901. (* A VAR parameter: its slot holds the address READ must
  4902. store through, not the address of the slot. *)
  4903. IF arg.boff # 0 THEN
  4904. Err (ENoLib) ;
  4905. RETURN
  4906. END ;
  4907. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  4908. EmPushAx ()
  4909. ELSE
  4910. EmPushVarAddr (symtab [arg.idx].local,
  4911. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  4912. END ;
  4913. IF acls = TString THEN
  4914. (* readln(s)/read(s) of a string variable: TPSRC8 prdstr
  4915. pushes the address, emits MOV CL,max_len and CALL
  4916. xrdstr. Here the limit is a full MOV CX,imm16 (this
  4917. runtime has no byte-register CH/CL setup), and rdstr
  4918. leaves the terminator pending so the readln wrapper can
  4919. consume the newline. *)
  4920. EmMovCxi ((VarSize (arg) - 1) MOD 10000H) ;
  4921. ent := TU_RdStr
  4922. ELSIF acls = TReal THEN
  4923. ent := TU_RdInt (* real reads: not yet *)
  4924. ELSIF acls = TBool THEN
  4925. (* TP3 refuses boolean I/O: TPSRC8 prderrtp is error 66,
  4926. "I/O not allowed here", and the runtime has no xrdbool
  4927. at all. rdbool stores a WORD, so one byte of an
  4928. accepted read would land on the variable AFTER b - the
  4929. exact overflow t37_readbyte pins for a byte. TP3's
  4930. answer to the whole class is the error; so is ours. *)
  4931. Err (EIoHere) ;
  4932. RETURN
  4933. ELSIF acls = TChar THEN
  4934. ent := TU_RdChar (* one byte, not a word *)
  4935. ELSIF acls = TScalar THEN
  4936. (* Dispatch on the SIZE, as TPSRC8 prdnum does:
  4937. `CMP varsize,#$01 / JA prdemit' keeps xrdint for
  4938. anything wider and falls through to `MOV AX,#xrdbyte'
  4939. for a one-byte variable. A BYTE is still TScalar (it
  4940. is *written* as an integer, as in TP3), but reading one
  4941. through rdint stored a word - and the second byte of
  4942. that word is the byte that FOLLOWS the variable. *)
  4943. IF VarSize (arg) = 1 THEN
  4944. ent := TU_RdByte
  4945. ELSE
  4946. ent := TU_RdInt
  4947. END
  4948. ELSE
  4949. Err (ETypeErr) ;
  4950. RETURN
  4951. END
  4952. ELSE
  4953. acls := arg.cls ;
  4954. IF (acls = TString) AND (arg.kind = 3) THEN
  4955. (* An inline string literal. TP3 TPSRC8 pwrinlin special-cases a
  4956. literal that is followed directly by ',' or ')' - i.e. an
  4957. argument, not an expression - and emits
  4958. CALL wrtinl <length byte> <characters...>
  4959. with no stack argument at all; wrtinl reads the length from the
  4960. return address and returns to just past the last character.
  4961. Mirrored exactly, so the literal costs only its own characters
  4962. in the code stream and nothing in the data segment. *)
  4963. IF strLen [arg.strx] > 255 THEN
  4964. (* The length is one byte, so a literal of 256 characters or
  4965. more would wrap: 300 characters emitted behind a length of
  4966. 44, and the runtime would print 44 of them and silently drop
  4967. the rest. TP3 strings are at most 255 characters, so refuse
  4968. rather than truncate. *)
  4969. Err (EConstRange) ;
  4970. RETURN
  4971. END ;
  4972. DropC (EmCall (TU_WrInl)) ;
  4973. Ebyte (VAL (BYTE, strLen [arg.strx])) ;
  4974. n := 0 ;
  4975. WHILE n < strLen [arg.strx] DO
  4976. Ebyte (VAL (BYTE, ORD (strPool [strOff [arg.strx] + n]))) ;
  4977. INC (n)
  4978. END ;
  4979. pushed := FALSE (* nothing was pushed for this one *)
  4980. ELSE
  4981. IF acls = TString THEN
  4982. (* A string *variable*. Its value IS its address, so it is
  4983. passed exactly the way READ passes an address: push it
  4984. and call the owner of the layout - wrstr - which reads
  4985. the length byte and prints that many characters. TPSRC8
  4986. pwrstr/pwrchk route a string argument to xwrtstr, and
  4987. xwrtstr reaches its argument through BP just like WrChar
  4988. does. The only difference from the inline-literal arm
  4989. above is where the bytes live: a literal's are in the
  4990. code stream (wrtinl) and a variable's are in the data
  4991. segment or the frame (wrstr). *)
  4992. (* off + boff: a string FIELD of a record/array has a
  4993. non-zero boff, and the address is the field's, not the
  4994. containing variable's. `writeln (g[2,3].S)' printed
  4995. the empty first element before this.
  4996. A DI-addressed field (`with Sheet[I,J] do
  4997. Write(Contents)') already HAS its address in DI. *)
  4998. IF arg.kind = 5 THEN
  4999. EmPushDi ()
  5000. ELSIF symtab [arg.idx].isVar THEN
  5001. (* VAR string: the slot holds the address of the
  5002. caller's characters; push that, not the slot. *)
  5003. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  5004. EmPushAx ()
  5005. ELSE
  5006. EmPushVarAddr (symtab [arg.idx].local,
  5007. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  5008. END ;
  5009. ent := TU_WrStr
  5010. ELSE
  5011. IF acls = TReal THEN
  5012. (* A REAL is six bytes, so the writer takes its
  5013. ADDRESS, not its value: push the address first,
  5014. then the width, then the decimals. The entry is
  5015. real_write, with [BP+4]=decimals, [BP+6]=width and
  5016. [BP+8]=real. TP3's defaults are width 18 and
  5017. decimals FFFFh (its scientific mode); a width with
  5018. no second colon keeps that default, which is
  5019. exactly what TPSRC8 pwrdef/pwrdef3 push. *)
  5020. IF arg.kind = 5 THEN
  5021. EmPushDi ()
  5022. ELSE
  5023. EmPushVarAddr (symtab [arg.idx].local,
  5024. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  5025. END ;
  5026. IF MatchDelim (':') THEN
  5027. ParseExpr (dummy) ;
  5028. IF NOT OK () THEN
  5029. RETURN
  5030. END ;
  5031. LoadAtom (dummy) ;
  5032. EmPushAx () ;
  5033. IF MatchDelim (':') THEN
  5034. ParseExpr (dummy) ;
  5035. IF NOT OK () THEN
  5036. RETURN
  5037. END ;
  5038. LoadAtom (dummy) ;
  5039. EmPushAx ()
  5040. ELSE
  5041. EmMovAxi (0FFFFH) ;
  5042. EmPushAx ()
  5043. END
  5044. ELSE
  5045. EmMovAxi (18) ;
  5046. EmPushAx () ;
  5047. EmMovAxi (0FFFFH) ;
  5048. EmPushAx ()
  5049. END ;
  5050. ent := TU_RealWrite ;
  5051. argBytes := 6
  5052. ELSE
  5053. LoadAtom (arg) ;
  5054. EmPushAx () ;
  5055. IF arg.chr THEN
  5056. ent := TU_WrChar (* 'a' - one char, not 97 *)
  5057. ELSIF acls = TBool THEN
  5058. ent := TU_WrBool
  5059. ELSIF acls = TChar THEN
  5060. ent := TU_WrChar (* c : char - one char *)
  5061. ELSIF acls = TScalar THEN
  5062. ent := TU_WrInt
  5063. ELSE
  5064. Err (ETypeErr) ;
  5065. RETURN
  5066. END ;
  5067. IF MatchDelim (':') THEN
  5068. (* Field width: `writeln(I:2)'. TP3 evaluates the
  5069. width (CALC passes `FW', a variable), so it is
  5070. parsed and pushed AFTER the value: width at BP+4,
  5071. value at BP+6. Only an integer has a width entry
  5072. yet - a CHAR/BOOLEAN/STRING width needs its own
  5073. writer, and `:decimals' is the REAL form. *)
  5074. IF (acls # TScalar) OR arg.chr THEN
  5075. Err (ENoLib) ;
  5076. RETURN
  5077. END ;
  5078. ParseExpr (dummy) ;
  5079. IF NOT OK () THEN
  5080. RETURN
  5081. END ;
  5082. LoadAtom (dummy) ;
  5083. EmPushAx () ;
  5084. IF MatchDelim (':') THEN
  5085. Err (ENoLib) ;
  5086. RETURN
  5087. END ;
  5088. ent := TU_WrIntW ;
  5089. argBytes := 4
  5090. END
  5091. END
  5092. END
  5093. END
  5094. END ;
  5095. IF pushed THEN
  5096. DropC (EmCall (ent)) ;
  5097. EmAddSp (argBytes) (* 2, or 4 with a width *)
  5098. END ;
  5099. INC (nArgs)
  5100. END ;
  5101. IF NOT skipArg THEN
  5102. IF NOT MatchDelim (',') THEN
  5103. EXIT
  5104. END
  5105. END
  5106. END ;
  5107. IF NOT MatchDelim (')') THEN
  5108. Err (ENoSemi) ;
  5109. RETURN
  5110. END
  5111. ELSE
  5112. DropCh (GetCh ())
  5113. END
  5114. END ;
  5115. IF reading AND (nArgs = 0) THEN
  5116. (* readln with no variable: just skip to the next line *)
  5117. DropC (EmCall (TU_RdLn)) ;
  5118. RETURN
  5119. END ;
  5120. IF which = BI_WriteLn THEN
  5121. DropC (EmCall (TU_WrLn))
  5122. ELSIF which = BI_ReadLn THEN
  5123. DropC (EmCall (TU_RdLn))
  5124. END
  5125. END IoCall ;
  5126. PROCEDURE Statmnt () ;
  5127. VAR tok : CARDINAL ;
  5128. idx, i2 : CARDINAL ;
  5129. t, src : ERes ;
  5130. L1, zj, zj2, exj : CARDINAL ;
  5131. lo, hi, v : LONGINT ;
  5132. clso : CARDINAL ;
  5133. i : CARDINAL ;
  5134. k, nlbl, nlblJmp, bodyPc, skipJmp : CARDINAL ;
  5135. nm : ARRAY [0..MaxName] OF CHAR ;
  5136. strf : BOOLEAN ;
  5137. dow : BOOLEAN ;
  5138. savedWith : CARDINAL ;
  5139. BEGIN
  5140. Skip () ;
  5141. IF Digit (CurCh ()) THEN
  5142. ParseLabelStmt () ; (* consumed 'n' ':' *)
  5143. Statmnt () ; (* 'n : statement' - the statement follows
  5144. the label directly, with no ';' between *)
  5145. RETURN
  5146. END ;
  5147. IF NOT Alpha (CurCh ()) THEN
  5148. ExpectDelim (';', ENoSemi) ;
  5149. RETURN
  5150. END ;
  5151. DropB (MatchKey (tok)) ;
  5152. IF tok = TkBegin THEN
  5153. Compound ()
  5154. ELSIF tok = TkIf THEN
  5155. ParseExpr (t) ;
  5156. LoadAtom (t) ;
  5157. EmCmpAxi (0) ;
  5158. zj := EmJcc (84H, 0) ; (* JZ -> else/end *)
  5159. IF NOT (MatchKey (tok) AND (tok = TkThen)) THEN
  5160. Err (ENoSemi)
  5161. END ;
  5162. Statmnt () ;
  5163. (* Peek the ELSE, do not match it. `MatchKey (tok) AND (tok = TkElse)`
  5164. consumes whatever the next keyword is even when the AND fails, so an
  5165. `if` that was the LAST statement of a BEGIN..END block ate the block's
  5166. own END: Compound then found neither ';' nor END and raised ENoSemi.
  5167. Any `if` as the last statement of a compound was unparseable - not
  5168. in a loop, not anywhere - and no fixture had one, so nothing noticed.
  5169. The visible symptom was a parse error at the statement AFTER the
  5170. block, which points at entirely the wrong piece of source. *)
  5171. PeekKw (tok) ;
  5172. IF tok = TkElse THEN
  5173. DropB (MatchKey (tok)) ;
  5174. exj := EmJmpNear (0) ;
  5175. SetPatTgt (zj, pc) ;
  5176. Statmnt () ;
  5177. SetPatTgt (exj, pc)
  5178. ELSE
  5179. SetPatTgt (zj, pc)
  5180. END
  5181. ELSIF tok = TkWhile THEN
  5182. L1 := pc ;
  5183. ParseExpr (t) ;
  5184. LoadAtom (t) ;
  5185. EmCmpAxi (0) ;
  5186. zj := EmJcc (84H, 0) ; (* JZ -> end *)
  5187. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  5188. Err (ENoSemi)
  5189. END ;
  5190. brkSave [brkN] := exitCnt ;
  5191. loopTy [brkN] := 1 ;
  5192. INC (brkN) ;
  5193. Statmnt () ;
  5194. DEC (brkN) ;
  5195. i := brkSave [brkN] ;
  5196. WHILE i < exitCnt DO
  5197. SetPatTgt (exitPatch [i], pc) ;
  5198. INC (i)
  5199. END ;
  5200. exitCnt := brkSave [brkN] ;
  5201. DropC (EmJmpNear (L1)) ;
  5202. SetPatTgt (zj, pc)
  5203. ELSIF tok = TkRepeat THEN
  5204. L1 := pc ;
  5205. brkSave [brkN] := exitCnt ;
  5206. loopTy [brkN] := 1 ;
  5207. INC (brkN) ;
  5208. (* The body is a STATEMENT SEQUENCE, not one statement: `repeat a; b
  5209. until c'. This used to call Statmnt once and then demand UNTIL, so
  5210. any body with a second statement was ENoSemi at the first ';'. t12's
  5211. two bodies are single statements and never saw it; CALC's `Flash' does
  5212. (GotoXY; Blink := not Blink; if ...; Write; Delay). Same shape as
  5213. Compound, stopping at UNTIL instead of END. *)
  5214. LOOP
  5215. PeekKw (tok) ;
  5216. IF tok = TkUntil THEN
  5217. DropB (MatchKey (tok)) ;
  5218. EXIT
  5219. END ;
  5220. Statmnt () ;
  5221. IF NOT OK () THEN
  5222. RETURN
  5223. END ;
  5224. IF NOT MatchDelim (';') THEN
  5225. PeekKw (tok) ;
  5226. IF tok = TkUntil THEN
  5227. DropB (MatchKey (tok)) ;
  5228. EXIT
  5229. END ;
  5230. Err (ENoSemi) ;
  5231. RETURN
  5232. END
  5233. END ;
  5234. ParseExpr (t) ;
  5235. LoadAtom (t) ;
  5236. EmCmpAxi (0) ;
  5237. (* UNTIL exits when the condition is TRUE, so the body runs again when
  5238. it is FALSE. The condition is a 0/1 in AX and EmCmpAxi (0) has just
  5239. compared it with 0, so ZF=1 means "condition false" -- which is
  5240. exactly the case that loops, hence JZ.
  5241. This was JNZ, which compiled repeat-until as while-until: the body
  5242. ran once, the condition was tested, and it stopped. t12_repeat is
  5243. `i:=0; repeat i:=i+1 until i>5' and it printed 1.
  5244. No patch slot: L1 is backwards and already known, so EmJcc returns
  5245. 0 and there is nothing to SetPatTgt. *)
  5246. DropC (EmJcc (84H, L1)) ; (* JZ -> body again *)
  5247. DEC (brkN) ;
  5248. i := brkSave [brkN] ;
  5249. WHILE i < exitCnt DO
  5250. SetPatTgt (exitPatch [i], pc) ;
  5251. INC (i)
  5252. END ;
  5253. exitCnt := brkSave [brkN]
  5254. ELSIF tok = TkFor THEN
  5255. (* control variable *)
  5256. Skip () ; (* after the FOR keyword: skip blanks *)
  5257. IF NOT Alpha (CurCh ()) THEN
  5258. Err (EUnknown) ;
  5259. RETURN
  5260. END ;
  5261. GetWord () ;
  5262. IF NOT Search (wrd, idx) THEN
  5263. Err (EUnknown) ;
  5264. RETURN
  5265. END ;
  5266. IF symtab [idx].size > 2 THEN
  5267. Err (ENoLib) ;
  5268. RETURN
  5269. END ;
  5270. IF NOT MatchAssign () THEN
  5271. Err (ENoSemi)
  5272. END ;
  5273. ParseExpr (src) ;
  5274. LoadAtom (src) ;
  5275. EmStoreVar (symtab [idx].local, symtab [idx].off,
  5276. symtab [idx].size) ;
  5277. IF NOT MatchKey (tok) THEN
  5278. Err (ESimpType) ;
  5279. RETURN
  5280. END ;
  5281. IF (tok = TkTo) OR (tok = TkDownto) THEN
  5282. dow := (tok = TkDownto)
  5283. ELSE
  5284. Err (ESimpType) ;
  5285. RETURN
  5286. END ;
  5287. ParseExpr (t) ;
  5288. LoadAtom (t) ;
  5289. EmPushAx () ; (* loop bound on the stack *)
  5290. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  5291. Err (ENoSemi)
  5292. END ;
  5293. brkSave [brkN] := exitCnt ;
  5294. loopTy [brkN] := 2 ;
  5295. INC (brkN) ;
  5296. L1 := pc ; (* Ltest: the test comes FIRST *)
  5297. (* The test is emitted before the body, not after it. It used to be
  5298. emitted after, which is a post-test loop and runs the body one time
  5299. too many: with `for i := 1 to 5`, the sequence of i at the test is
  5300. 1,2,3,4,5,6 - the test at i=5 is `5 > 5`, which is false, so the
  5301. body ran a sixth time with i=6. `for i := 1 to 5 do s := s + i`
  5302. printed 21. The size was right and the shape was right; only the
  5303. order was wrong, and no byte check can see an order.
  5304. The bound stays on the stack for the whole loop, so EmMovCxSp has to
  5305. re-read it every iteration - which is also what makes the bound a
  5306. *variable* rather than a constant. [SP] cannot be encoded on the
  5307. 8086, so EmMovCxSp is POP CX ; PUSH CX, an observational no-op that
  5308. leaves the bound in place. *)
  5309. EmMovCxSp () ;
  5310. EmLoadVar (symtab [idx].local, symtab [idx].off,
  5311. symtab [idx].size) ;
  5312. EmCmpAxCx () ;
  5313. IF dow THEN
  5314. zj := EmJcc (8CH, 0) (* JL -> done *)
  5315. ELSE
  5316. zj := EmJcc (8FH, 0) (* JG -> done *)
  5317. END ;
  5318. Statmnt () ;
  5319. DEC (brkN) ;
  5320. (* A FOR's exits are NOT patched here, even though `done` is not known
  5321. yet. For a WHILE or REPEAT, "just after the body" is a correct
  5322. target: the jump back to the test re-evaluates the condition and
  5323. leaves. For a FOR there is a STEP between the body and `done`, so
  5324. an EXIT that jumped here would increment the control variable and
  5325. jump back to the test - and if the incremented value still satisfied
  5326. the bound, it would run the body AGAIN. `exit` did not exit.
  5327. The fix needs no new bookkeeping: `brkSave [brkN] .. exitCnt` still
  5328. names exactly this loop's exits, because Statmnt may have added more
  5329. and nothing has reset exitCnt. So they are patched at `done`, below.
  5330. A WHILE nested inside the FOR saves and restores its own range and
  5331. leaves this one intact. *)
  5332. (* step *)
  5333. EmLoadVar (symtab [idx].local, symtab [idx].off,
  5334. symtab [idx].size) ;
  5335. IF dow THEN
  5336. EmDecAx ()
  5337. ELSE
  5338. EmIncAx ()
  5339. END ;
  5340. EmStoreVar (symtab [idx].local, symtab [idx].off,
  5341. symtab [idx].size) ;
  5342. DropC (EmJmpNear (L1)) ;
  5343. SetPatTgt (zj, pc) ; (* done: *)
  5344. (* A WHILE loop here, not a FOR over the exit range. The range is
  5345. usually EMPTY - most loops have no `exit` - and `exitCnt` is a
  5346. CARDINAL, so `TO exitCnt - 1` with exitCnt = 0 is `TO 65535`: the
  5347. loop does not terminate, it wraps, and it walks exitPatch [0..65535]
  5348. off the end of a 64-element array. `for i := 1 to 10 do i := i` has
  5349. no exit, so this is the ORDINARY case, and it faulted with
  5350. "invalid address referenced" on every FOR loop without an exit. *)
  5351. i := brkSave [brkN] ;
  5352. WHILE i < exitCnt DO
  5353. SetPatTgt (exitPatch [i], pc) ;
  5354. INC (i)
  5355. END ;
  5356. exitCnt := brkSave [brkN] ;
  5357. EmAddSp (2) (* drop the loop bound *)
  5358. ELSIF tok = TkCase THEN
  5359. ParseExpr (t) ;
  5360. LoadAtom (t) ;
  5361. EmPushAx () ; (* selector on the stack *)
  5362. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  5363. Err (ENoSemi)
  5364. END ;
  5365. caseN := 0 ;
  5366. LOOP
  5367. Skip () ;
  5368. IF MatchDelim (';') THEN
  5369. Skip ()
  5370. END ;
  5371. PeekKw (tok) ;
  5372. IF (tok = TkEnd) OR (tok = TkElse) THEN
  5373. EXIT
  5374. END ;
  5375. (* Case labels: `v' | `lo..hi', comma-separated, all selecting the
  5376. same statement (CALC's `'G', 'I', 'O', 'Q':'). Read the whole list
  5377. first; the emission then knows whether this is the one-label path
  5378. or a list. *)
  5379. nlbl := 0 ;
  5380. LOOP
  5381. IF Alpha (CurCh ()) THEN
  5382. GetWord () ;
  5383. IF Search (wrd, i2) AND (symtab [i2].tag = KConst) THEN
  5384. lo := symtab [i2].lval
  5385. ELSE
  5386. Err (EUnknown) ;
  5387. RETURN
  5388. END
  5389. ELSE
  5390. RdConst (lo, clso, strf)
  5391. END ;
  5392. IF MatchRange () THEN
  5393. RdConst (hi, clso, strf)
  5394. ELSE
  5395. hi := lo
  5396. END ;
  5397. IF nlbl >= 32 THEN
  5398. Err (ECompOvf) ;
  5399. RETURN
  5400. END ;
  5401. lblLo [nlbl] := lo ;
  5402. lblHi [nlbl] := hi ;
  5403. INC (nlbl) ;
  5404. IF MatchDelim (',') THEN
  5405. Skip ()
  5406. ELSE
  5407. EXIT
  5408. END
  5409. END ;
  5410. Skip () ;
  5411. ExpectDelim (':', ENoSemi) ;
  5412. IF NOT OK () THEN
  5413. RETURN
  5414. END ;
  5415. EmMovAxSp () ;
  5416. IF nlbl = 1 THEN
  5417. (* One label: the original bytes, except that a RANGE is now a
  5418. real range. It used to compare AX with lo and then with hi,
  5419. both demanding equality, so `1..5' matched NOTHING unless
  5420. lo = hi - a silently wrong answer, not an error. *)
  5421. lo := lblLo [0] ;
  5422. hi := lblHi [0] ;
  5423. IF hi = lo THEN
  5424. EmCmpAxi (W16 (lo)) ;
  5425. zj := EmJcc (85H, 0) ; (* JNZ -> next arm *)
  5426. zj2 := 0
  5427. ELSE
  5428. EmCmpAxi (W16 (lo)) ;
  5429. zj := EmJcc (8CH, 0) ; (* JL -> next arm *)
  5430. EmCmpAxi (W16 (hi)) ;
  5431. zj2 := EmJcc (8FH, 0) (* JG -> next arm *)
  5432. END ;
  5433. Statmnt () ;
  5434. IF caseN >= 64 THEN
  5435. Err (ECompOvf) ;
  5436. RETURN
  5437. END ;
  5438. caseJmp [caseN] := EmJmpNear (0) ;
  5439. INC (caseN) ;
  5440. SetPatTgt (zj, pc) ;
  5441. IF zj2 # 0 THEN
  5442. SetPatTgt (zj2, pc)
  5443. END
  5444. ELSE
  5445. (* A list. A single label branches INTO the statement; a range
  5446. first sends AX below lo to the next label, then `<= hi' to the
  5447. body. The body jumps are patched once the body's address is
  5448. known, and the no-match EJMP skips the body to the next arm. *)
  5449. nlblJmp := 0 ;
  5450. FOR k := 0 TO nlbl - 1 DO
  5451. IF lblHi [k] = lblLo [k] THEN
  5452. EmCmpAxi (W16 (lblLo [k])) ;
  5453. lblJmp [nlblJmp] := EmJcc (84H, 0) ; (* JZ -> body *)
  5454. INC (nlblJmp)
  5455. ELSE
  5456. (* `lo <= AX <= hi', built from the two conditions this
  5457. compiler declares for a branch (L and G): below lo skips
  5458. the label, above hi skips it, otherwise an unconditional
  5459. jump enters the body. JLE would be shorter and is legal
  5460. 8086, but check_8086's declared condition set is exactly
  5461. Z/NZ/L/G (the four the parser's comparisons use), and a
  5462. new condition in CASE would rightly be reported there. *)
  5463. EmCmpAxi (W16 (lblLo [k])) ;
  5464. zj := EmJcc (8CH, 0) ; (* JL -> next label *)
  5465. EmCmpAxi (W16 (lblHi [k])) ;
  5466. zj2 := EmJcc (8FH, 0) ; (* JG -> next label *)
  5467. lblJmp [nlblJmp] := EmJmpNear (0) ; (* in range -> body *)
  5468. INC (nlblJmp) ;
  5469. SetPatTgt (zj, pc) ;
  5470. SetPatTgt (zj2, pc)
  5471. END
  5472. END ;
  5473. skipJmp := EmJmpNear (0) ;
  5474. bodyPc := pc ;
  5475. FOR k := 0 TO nlblJmp - 1 DO
  5476. SetPatTgt (lblJmp [k], bodyPc)
  5477. END ;
  5478. Statmnt () ;
  5479. IF caseN >= 64 THEN
  5480. Err (ECompOvf) ;
  5481. RETURN
  5482. END ;
  5483. caseJmp [caseN] := EmJmpNear (0) ;
  5484. INC (caseN) ;
  5485. SetPatTgt (skipJmp, pc)
  5486. END
  5487. END ;
  5488. IF tok = TkElse THEN
  5489. DropB (MatchKey (tok)) ;
  5490. Statmnt () ;
  5491. IF NOT (MatchKey (tok) AND (tok = TkEnd)) THEN
  5492. Err (ENoSemi)
  5493. END
  5494. ELSE
  5495. DropB (MatchKey (tok))
  5496. END ;
  5497. EmAddSp (2) ;
  5498. FOR i := 0 TO caseN - 1 DO
  5499. SetPatTgt (caseJmp [i], pc)
  5500. END
  5501. ELSIF tok = TkGoto THEN
  5502. v := 0 ;
  5503. Skip () ; (* after the GOTO keyword: skip blanks *)
  5504. IF Digit (CurCh ()) THEN
  5505. RdIntConst (v) ;
  5506. NumToName (W16 (v), nm) ;
  5507. IF Search (nm, idx) THEN
  5508. IF symtab [idx].tag = KLabel THEN
  5509. IF symtab [idx].defnd THEN
  5510. DropC (EmJmpNear (symtab [idx].goPos))
  5511. ELSE
  5512. zj := EmJmpNear (0) ;
  5513. AddPend (0, idx, zj)
  5514. END
  5515. ELSE
  5516. Err (EUnknown)
  5517. END
  5518. ELSE
  5519. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  5520. zj := EmJmpNear (0) ;
  5521. AddPend (0, idx, zj)
  5522. END
  5523. ELSE
  5524. Err (EUnknown)
  5525. END
  5526. ELSIF tok = TkExit THEN
  5527. IF brkN = 0 THEN
  5528. Err (EUnknown)
  5529. ELSE
  5530. (* No EmAddSp (2) here, even inside a FOR. The FOR's `done` label
  5531. drops the bound, so an EXIT that jumped to `done` would drop it a
  5532. second time - 4 bytes off a stack that only had 2 to give, which
  5533. silently corrupts the caller's frame. It used to do exactly
  5534. that, and it was doubly wrong: the exits were patched to the STEP
  5535. rather than to `done`, so the EXIT also incremented the control
  5536. variable and jumped back into the test. *)
  5537. zj := EmJmpNear (0) ;
  5538. IF exitCnt < 64 THEN
  5539. exitPatch [exitCnt] := zj ;
  5540. INC (exitCnt)
  5541. END
  5542. END
  5543. ELSIF tok = TkWith THEN
  5544. (* WITH base (, base)* DO statement. The record's field range comes from
  5545. the base symbol: DefVar copies the ELEMENT record's recFldFirst/
  5546. recFldLast onto an array variable, which is what makes
  5547. `Sheet[I,J].Field' and `with Sheet[I,J] do' work. Each base is
  5548. pushed on the scope stack and popped after the statement. *)
  5549. savedWith := withN ;
  5550. LOOP
  5551. ParseExpr (t) ;
  5552. IF NOT OK () THEN
  5553. RETURN
  5554. END ;
  5555. IF t.cls # TRecord THEN
  5556. Err (ETypeErr) ;
  5557. RETURN
  5558. END ;
  5559. IF withN >= 4 THEN
  5560. Err (ECompOvf) ;
  5561. RETURN
  5562. END ;
  5563. IF symtab [t.idx].fldFirst >= symtab [t.idx].fldLast THEN
  5564. Err (ETypeErr) ;
  5565. RETURN
  5566. END ;
  5567. IF t.kind = 5 THEN
  5568. (* the base address is in DI; park it. Allocating two data bytes
  5569. here is safe: the statement is parsed once, and the store
  5570. executes wherever the WITH does. *)
  5571. withSlot [withN] := dc ;
  5572. dc := dc + 2 ;
  5573. EmStDiGlob (withSlot [withN]) ;
  5574. withIsDI [withN] := TRUE ;
  5575. withBoff [withN] := 0
  5576. ELSIF t.kind = 1 THEN
  5577. withIsDI [withN] := FALSE ;
  5578. withBoff [withN] := t.boff
  5579. ELSE
  5580. Err (ENoLib) ;
  5581. RETURN
  5582. END ;
  5583. withIdx [withN] := t.idx ;
  5584. withFF [withN] := symtab [t.idx].fldFirst ;
  5585. withFL [withN] := symtab [t.idx].fldLast ;
  5586. INC (withN) ;
  5587. IF MatchDelim (',') THEN
  5588. (* another base; the last one is innermost *)
  5589. ELSE
  5590. EXIT
  5591. END
  5592. END ;
  5593. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  5594. Err (ENoSemi) ;
  5595. RETURN
  5596. END ;
  5597. Statmnt () ;
  5598. withN := savedWith
  5599. ELSE
  5600. (* identifier statement: assignment or call *)
  5601. IF WithLookup (wrd, t) THEN
  5602. IF MatchAssign () THEN
  5603. Assignment (t) ;
  5604. RETURN
  5605. END ;
  5606. Err (ENoSemi) ;
  5607. RETURN
  5608. END ;
  5609. IF NOT Search (wrd, idx) THEN
  5610. Err (EUnknown) ;
  5611. RETURN
  5612. END ;
  5613. IF symtab [idx].tag = KBuiltin THEN
  5614. IoCall (idx) ;
  5615. RETURN
  5616. END ;
  5617. IF symtab [idx].tag = KProc THEN
  5618. IF MatchDelim ('(') THEN
  5619. ParseCallArgs (idx)
  5620. ELSE
  5621. ParseCall (idx)
  5622. END ;
  5623. RETURN
  5624. END ;
  5625. IF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KFunc) THEN
  5626. t.idx := idx ;
  5627. t.kind := 1 ;
  5628. t.boff := 0 ;
  5629. t.cls := symtab [idx].cls ;
  5630. IF symtab [idx].tag = KFunc THEN
  5631. t.idx := symtab [idx].resvar ;
  5632. t.cls := symtab [t.idx].cls
  5633. END ;
  5634. t.sz := symtab [t.idx].size ; (* ParseSub may narrow it further *)
  5635. ParseSub (t) ;
  5636. IF MatchAssign () THEN
  5637. Assignment (t) ;
  5638. RETURN
  5639. END ;
  5640. Err (ENoSemi) ;
  5641. RETURN
  5642. END ;
  5643. Err (ENoSemi)
  5644. END
  5645. END Statmnt ;
  5646. (* ---------------------------------------------------------------- *)
  5647. (* types and declarations (TPSRC7) *)
  5648. (* ---------------------------------------------------------------- *)
  5649. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ;
  5650. VAR tok : CARDINAL ;
  5651. idx : CARDINAL ;
  5652. lo, hi : LONGINT ;
  5653. s2, e2 : CARDINAL ;
  5654. subcls : CARDINAL ;
  5655. strf : BOOLEAN ;
  5656. consumed : BOOLEAN ;
  5657. running, groupFirst, i, an, recStart : CARDINAL ;
  5658. alo, ahi : ARRAY [0..3] OF LONGINT ;
  5659. ecls2 : CARDINAL ;
  5660. BEGIN
  5661. cls := TNone ; size := 0 ; elem := 0 ;
  5662. consumed := FALSE ;
  5663. newArrIdx := 0 ;
  5664. Skip () ; (* after ':' / '=' : skip blanks *)
  5665. IF CurCh () = '(' THEN
  5666. (* An enumeration: `(Constant, Formula, Txt, ...)'. Each enumerator
  5667. becomes a constant with its ordinal position as its value, and the
  5668. TYPE is 1 byte (TP3 uses one below 256 values) with bounds 0..n-1,
  5669. which DefType records so `set of Attributes' can size its base.
  5670. Enumerators are TScalar, not TEnum: they behave as ordinals; only the
  5671. TYPE carries the enum identity and its bounds. *)
  5672. DropCh (GetCh ()) ;
  5673. lo := 0 ;
  5674. hi := -1 ;
  5675. LOOP
  5676. Skip () ;
  5677. IF NOT Alpha (CurCh ()) THEN
  5678. Err (EUnknown) ;
  5679. RETURN
  5680. END ;
  5681. GetWord () ;
  5682. DupTest (wrd) ;
  5683. DropC (NewSym (wrd, KConst, TScalar, 1, 1, 0, hi + 1, FALSE)) ;
  5684. hi := hi + 1 ;
  5685. IF MatchDelim (',') THEN
  5686. (* another enumerator *)
  5687. ELSE
  5688. EXIT
  5689. END
  5690. END ;
  5691. ExpectDelim (')', ENoSemi) ;
  5692. enumLo := lo ;
  5693. enumHi := hi ;
  5694. cls := TEnum ;
  5695. size := 1 ;
  5696. elem := 1 ;
  5697. RETURN
  5698. END ;
  5699. IF Alpha (CurCh ()) THEN
  5700. DropB (MatchKey (tok)) ;
  5701. consumed := TRUE
  5702. ELSE
  5703. tok := TkNone
  5704. END ;
  5705. IF tok = TkArray THEN
  5706. (* array [range, range, ...] of T. Several ranges are allowed; the LAST
  5707. varies fastest (row-major), so `Sheet[fx,fy]' strides the first range
  5708. by the second's count (RESUME-TP3.md §2). The shape is kept in the
  5709. array table; the symbol carries a pointer to it (SymEntry.arrIdx) so
  5710. indexing can scale by the element size and subtract each lower bound. *)
  5711. ExpectDelim ('[', ENoSemi) ;
  5712. an := 0 ;
  5713. LOOP
  5714. RdConst (lo, subcls, strf) ;
  5715. IF NOT MatchRange () THEN
  5716. Err (ESimpType) ;
  5717. RETURN
  5718. END ;
  5719. RdConst (hi, subcls, strf) ;
  5720. IF an < 4 THEN
  5721. alo [an] := lo ;
  5722. ahi [an] := hi ;
  5723. INC (an)
  5724. END ;
  5725. IF MatchDelim (',') THEN
  5726. (* another range *)
  5727. ELSE
  5728. EXIT
  5729. END
  5730. END ;
  5731. ExpectDelim (']', ENoSemi) ;
  5732. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  5733. Err (ENoSemi) ;
  5734. RETURN
  5735. END ;
  5736. ParseType (cls, s2, e2) ;
  5737. ecls2 := cls ;
  5738. cls := TArray ;
  5739. elem := s2 ;
  5740. size := s2 ;
  5741. i := 0 ;
  5742. WHILE i < an DO
  5743. size := size * W16 (VAL (LONGINT, W16 (ahi [i]))
  5744. - VAL (LONGINT, W16 (alo [i])) + 1) ;
  5745. INC (i)
  5746. END ;
  5747. (* register the shape so indexing can scale by element size and subtract
  5748. each lower bound; the symbol points at this slot *)
  5749. IF arrTop < MaxArrs THEN
  5750. arrs [arrTop].n := an ;
  5751. arrs [arrTop].elem := s2 ;
  5752. arrs [arrTop].ecls := ecls2 ;
  5753. i := 0 ;
  5754. WHILE i < an DO
  5755. arrs [arrTop].lo [i] := alo [i] ;
  5756. arrs [arrTop].hi [i] := ahi [i] ;
  5757. INC (i)
  5758. END ;
  5759. newArrIdx := arrTop + 1 ;
  5760. INC (arrTop)
  5761. ELSE
  5762. Err (ECompOvf)
  5763. END
  5764. ELSIF tok = TkString THEN
  5765. cls := TString ;
  5766. size := 256 ;
  5767. elem := 1 ;
  5768. IF MatchDelim ('[') THEN
  5769. RdConst (hi, subcls, strf) ;
  5770. ExpectDelim (']', ENoSemi) ;
  5771. size := W16 (hi) + 1
  5772. END
  5773. ELSIF tok = TkSet THEN
  5774. (* set of <ordinal>. TP3's hybrid layout (coeur-tp-ocr 4.7.2): only the
  5775. whole BYTES covering the base range are stored, so `set of Char' is 32
  5776. bytes and `set of 12..17' is 2. `elem' carries the origin - the first
  5777. element of the first byte, a multiple of 8 - which is all the
  5778. membership and constructor arithmetic needs. *)
  5779. PeekKw (tok) ;
  5780. IF tok = TkOf THEN
  5781. DropB (MatchKey (tok)) ;
  5782. RdSetBase (subcls, lo, hi) ;
  5783. IF OK () THEN
  5784. cls := TSet ;
  5785. elem := (VAL (CARDINAL, lo) DIV 8) * 8 ;
  5786. size := (VAL (CARDINAL, hi) DIV 8)
  5787. - (VAL (CARDINAL, lo) DIV 8) + 1
  5788. END
  5789. ELSE
  5790. Err (ENoSemi)
  5791. END
  5792. ELSIF tok = TkRecord THEN
  5793. (* record fieldList end, fields NON-COMPACTED and juxtaposed
  5794. (RESUME-TP3.md §2). Each name in a `a, b : T' group is a field of its
  5795. own at the running offset; the field table is where `x.f' looks, keyed
  5796. per record so field names need not be globally unique.
  5797. recFldFirst/recFldLast hand the range to DefType, or to the enclosing
  5798. record's field entry when records nest. *)
  5799. recStart := fldTop ;
  5800. recFldFirst := fldTop ;
  5801. running := 0 ;
  5802. LOOP
  5803. PeekKw (tok) ;
  5804. IF tok = TkEnd THEN
  5805. DropB (MatchKey (tok)) ;
  5806. EXIT
  5807. END ;
  5808. IF CurCh () = 0C THEN
  5809. Err (EUnknown) ;
  5810. EXIT
  5811. END ;
  5812. (* the group's names, then ONE `: type' *)
  5813. groupFirst := fldTop ;
  5814. LOOP
  5815. Skip () ;
  5816. IF NOT Alpha (CurCh ()) THEN
  5817. Err (EUnknown) ;
  5818. RETURN
  5819. END ;
  5820. GetWord () ;
  5821. IF fldTop < MaxFields THEN
  5822. CopyStr (fields [fldTop].name, wrd) ;
  5823. fields [fldTop].off := 0 ;
  5824. INC (fldTop)
  5825. ELSE
  5826. Err (ECompOvf)
  5827. END ;
  5828. IF NOT MatchDelim (',') THEN
  5829. EXIT
  5830. END
  5831. END ;
  5832. ExpectDelim (':', ENoSemi) ;
  5833. ParseType (subcls, s2, e2) ;
  5834. IF NOT OK () THEN
  5835. RETURN
  5836. END ;
  5837. (* every name in the group gets the type and its own slot *)
  5838. i := groupFirst ;
  5839. WHILE i < fldTop DO
  5840. fields [i].cls := subcls ;
  5841. fields [i].size := s2 ;
  5842. fields [i].elem := e2 ;
  5843. fields [i].off := running ;
  5844. fields [i].lo := enumLo ;
  5845. fields [i].hi := enumHi ;
  5846. running := running + s2 ;
  5847. INC (i)
  5848. END ;
  5849. IF NOT MatchDelim (';') THEN
  5850. Err (ENoSemi) ;
  5851. RETURN
  5852. END
  5853. END ;
  5854. (* The field TYPES are parsed by ParseType, and its named-type arm
  5855. copies the TYPE's field range into recFldFirst/recFldLast - for
  5856. `Integer' that is 0/0. So recFldFirst set at the top of this branch
  5857. is overwritten by every field type. It happens to be right for the
  5858. FIRST record in a compile (fldTop is 0 then), and wrong for every
  5859. later one: t77's second record started at 2 but recorded 0, which
  5860. made a WITH field lookup scan the previous record's fields. Restore
  5861. the saved start here, after the last field type has been parsed. *)
  5862. recFldFirst := recStart ;
  5863. recFldLast := fldTop ;
  5864. cls := TRecord ;
  5865. size := running ;
  5866. elem := running
  5867. ELSIF tok = TkText THEN
  5868. (* A TEXT file variable. We do our own unbuffered INT 21h I/O, so the
  5869. file variable is just our control block (see FileVarSize) and the
  5870. element is one byte; TP3 keeps a 128-byte buffer in its own, which is
  5871. a divergence we do not need. *)
  5872. cls := TText ;
  5873. size := FileVarSize ;
  5874. elem := 1
  5875. ELSIF tok = TkFile THEN
  5876. (* `file' (untyped) or `file of T'. The element type is parsed for its
  5877. SIZE, which is what a Read/Write moves per record; the variable
  5878. itself is always the control block. CALC.INC's Exist declares
  5879. `F : file', so the OF must be optional: requiring it produced ENoSemi
  5880. at the declaration's semicolon, which was misread as the function
  5881. declaration being unsupported. TUntyp keeps the untyped file
  5882. distinguishable, because a Read/Write through it has no element size
  5883. and must stay refused. *)
  5884. PeekKw (tok) ;
  5885. IF tok = TkOf THEN
  5886. DropB (MatchKey (tok)) ;
  5887. ParseType (subcls, s2, e2) ;
  5888. IF OK () THEN
  5889. cls := TFile ;
  5890. size := FileVarSize ;
  5891. elem := s2
  5892. END
  5893. ELSE
  5894. cls := TUntyp ;
  5895. size := FileVarSize ;
  5896. elem := 1
  5897. END
  5898. ELSE
  5899. IF consumed THEN
  5900. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  5901. cls := symtab [idx].cls ;
  5902. size := symtab [idx].size ;
  5903. (* The type's ELEMENT size, not its total size. They are equal for
  5904. a record, but not for an array (`Letters' is 6 bytes of 3
  5905. Integers) or a file. A named array typed constant used to get
  5906. typElem = 6, wrote six bytes per element and wrapped the
  5907. little-endian divider to zero: SIGFPE in DefConst. *)
  5908. elem := symtab [idx].elem ;
  5909. enumLo := symtab [idx].lo ;
  5910. enumHi := symtab [idx].hi ;
  5911. recFldFirst := symtab [idx].fldFirst ;
  5912. recFldLast := symtab [idx].fldLast ;
  5913. newArrIdx := symtab [idx].arrIdx
  5914. ELSE
  5915. Err (EUnknown)
  5916. END
  5917. ELSE
  5918. (* subrange lo .. hi. TP3 sizes it by its bounds: ONE byte when both
  5919. are inside 0..255, else two (RESUME-TP3.md §2). `0..20' and
  5920. `'A'..'G'' are one byte - which is what makes CellRec 80 and not
  5921. 82, and `Sheet' 147*80. The bounds are kept for `set of T'. *)
  5922. RdConst (lo, subcls, strf) ;
  5923. IF NOT MatchRange () THEN
  5924. Err (ESimpType) ;
  5925. RETURN
  5926. END ;
  5927. RdConst (hi, subcls, strf) ;
  5928. cls := TScalar ;
  5929. IF (lo >= 0) AND (hi <= 255) AND (lo <= hi) THEN
  5930. size := 1
  5931. ELSE
  5932. size := 2
  5933. END ;
  5934. elem := size ;
  5935. enumLo := lo ;
  5936. enumHi := hi
  5937. END
  5938. END
  5939. END ParseType ;
  5940. PROCEDURE DefVar () ;
  5941. (* 'name' (',' name)* ':' type [ABSOLUTE addr] ; group repeated until a
  5942. declaration keyword appears *)
  5943. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  5944. cls, size, elem : CARDINAL ;
  5945. tok : CARDINAL ;
  5946. v : LONGINT ;
  5947. off : CARDINAL ;
  5948. first, i : CARDINAL ;
  5949. BEGIN
  5950. LOOP
  5951. Skip () ; (* after the VAR keyword: skip blanks *)
  5952. IF NOT Alpha (CurCh ()) THEN
  5953. Err (EUnknown) ;
  5954. RETURN
  5955. END ;
  5956. (* A group is `name (, name)* : type' - TPSRC7 rdvarlst/rdvloop collects
  5957. the whole comma-separated list of names FIRST (`CALL ccomma / JZ
  5958. rdvloop'), then reads one `: type' with ecolon/rdvartp, then vardef2
  5959. gives every name in the list that one type. The names are created as
  5960. placeholders here and filled in once the type is known, which is the
  5961. same shape as TP3 reserving a symtab slot per name and storing the
  5962. type pointer into each afterwards. *)
  5963. first := symTop ;
  5964. LOOP
  5965. Skip () ; (* GetWord does not skip blanks, and the cursor
  5966. sits on the space after the ',' *)
  5967. IF NOT Alpha (CurCh ()) THEN
  5968. Err (EUnknown) ;
  5969. RETURN
  5970. END ;
  5971. GetWord () ;
  5972. SaveWord (nm) ;
  5973. DupTest (nm) ;
  5974. DropC (NewSym (nm, KVar, TNone, 0, 0, 0, 0, lexnest # 0)) ;
  5975. IF NOT MatchDelim (',') THEN
  5976. EXIT
  5977. END
  5978. END ;
  5979. ExpectDelim (':', ENoSemi) ;
  5980. ParseType (cls, size, elem) ;
  5981. IF OK () THEN
  5982. IF lexnest = 0 THEN
  5983. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  5984. AND (cls # TArray) AND (cls # TFile) AND (cls # TText)
  5985. AND (cls # TUntyp) THEN
  5986. (* Still the catch-all for a type whose storage this compiler does
  5987. not lay out yet (an ARRAY at its point of use, a RECORD, ...).
  5988. A STRING is the exception now: its layout is length byte +
  5989. characters, and the rest of the compiler knows it - see
  5990. Assignment and IoCall. *)
  5991. Err (ENoLib) ;
  5992. RETURN
  5993. END ;
  5994. PeekKw (tok) ;
  5995. IF tok = TkAbsolute THEN
  5996. DropB (MatchKey (tok)) ;
  5997. IF (CurCh () = '$') OR (Digit (CurCh ())) THEN
  5998. RdIntConst (v) ;
  5999. off := W16 (v)
  6000. ELSE
  6001. Err (EUnknown) ;
  6002. off := 0
  6003. END ;
  6004. (* TP3's absolute path (vdstore) leaves the offset fixed, so
  6005. every name in the group aliases the same address. *)
  6006. i := first ;
  6007. WHILE i < symTop DO
  6008. symtab [i].cls := cls ; symtab [i].size := size ;
  6009. symtab [i].elem := elem ; symtab [i].off := off ;
  6010. symtab [i].fldFirst := recFldFirst ;
  6011. symtab [i].fldLast := recFldLast ;
  6012. symtab [i].arrIdx := newArrIdx ;
  6013. INC (i)
  6014. END
  6015. ELSE
  6016. i := first ;
  6017. WHILE i < symTop DO
  6018. symtab [i].cls := cls ; symtab [i].size := size ;
  6019. symtab [i].elem := elem ; symtab [i].off := dc ;
  6020. symtab [i].fldFirst := recFldFirst ;
  6021. symtab [i].fldLast := recFldLast ;
  6022. symtab [i].arrIdx := newArrIdx ;
  6023. dc := dc + size ;
  6024. INC (i)
  6025. END
  6026. END ;
  6027. varspc := varspc + size * (symTop - first)
  6028. ELSE
  6029. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  6030. AND (cls # TArray) AND (cls # TFile) AND (cls # TText)
  6031. AND (cls # TUntyp) THEN
  6032. Err (ENoLib) ;
  6033. RETURN
  6034. END ;
  6035. (* A local occupies [off, off+size-1] and lives BELOW the saved BP,
  6036. because BP-relative locals grow down from the top of the frame
  6037. while a STRING grows UP from its base (length byte, then chars).
  6038. Top-anchored packing keeps both true at once: locFree is the
  6039. highest still-free byte (-1 at the top), the new symbol's base
  6040. is placed so that its LAST byte lands on that byte, and locFree
  6041. then drops by the whole size. So the first INTEGER (size 2) is
  6042. at -2 and the second at -4, byte for byte what the old
  6043. pre-decrement rule produced, while a string[5] local (size 6) is
  6044. at -6..-1 instead of the old -2..+3 - which straddled the saved
  6045. BP at [BP] and the return address at [BP+2] and made `readln(s)'
  6046. into a local store characters over its own return address.
  6047. Each name in the group gets its own slot. *)
  6048. i := first ;
  6049. WHILE i < symTop DO
  6050. symtab [i].cls := cls ; symtab [i].size := size ;
  6051. symtab [i].elem := elem ;
  6052. symtab [i].fldFirst := recFldFirst ;
  6053. symtab [i].fldLast := recFldLast ;
  6054. symtab [i].arrIdx := newArrIdx ;
  6055. symtab [i].off := (locFree - size + 1) MOD 10000H ;
  6056. locFree := (locFree - size) MOD 10000H ;
  6057. INC (i)
  6058. END ;
  6059. locBytes := locBytes + size * (symTop - first)
  6060. END
  6061. END ;
  6062. IF MatchDelim (',') THEN
  6063. (* The older `name : type, name : type' spelling: another group
  6064. follows without a semicolon. TP3's grammar is names-then-one-type
  6065. with ',' inside a group and ';' between groups (TPSRC7 rdvarlst /
  6066. rdvloop then ecolon/rdvartp), and both spellings reach the same
  6067. symbols, so both separators are accepted here. *)
  6068. ELSIF MatchDelim (';') THEN
  6069. PeekKw (tok) ;
  6070. IF tok # TkNone THEN
  6071. RETURN
  6072. END
  6073. ELSE
  6074. Err (ENoSemi) ;
  6075. RETURN
  6076. END
  6077. END
  6078. END DefVar ;
  6079. PROCEDURE DefConst () ;
  6080. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  6081. v : LONGINT ;
  6082. cls, typCls, typSize, typElem, soff, ci : CARDINAL ;
  6083. isStr : BOOLEAN ;
  6084. tok : CARDINAL ;
  6085. typed, setTyped, arrTyped : BOOLEAN ;
  6086. nb, k, divi, w : CARDINAL ;
  6087. BEGIN
  6088. LOOP
  6089. PeekKw (tok) ;
  6090. IF tok # TkNone THEN
  6091. RETURN
  6092. END ;
  6093. Skip () ; (* after the CONST keyword: skip blanks *)
  6094. IF NOT Alpha (CurCh ()) THEN
  6095. Err (EUnknown) ;
  6096. RETURN
  6097. END ;
  6098. GetWord () ;
  6099. SaveWord (nm) ;
  6100. DupTest (nm) ;
  6101. (* Two spellings: a plain constant `name = value', and a TYPED constant
  6102. `name : Type = value', which TP3 3.0 added (TPSRC7's constant reader
  6103. takes the type first and the value second). For a SCALAR type the
  6104. value still folds to an immediate, so the declared type is simply
  6105. recorded as the symbol's class - `FXMax : Char = 'G'' is a TChar
  6106. constant holding 71, and `writeln (FXMax)' prints G rather than 71.
  6107. A SET typed constant (`Numbers : set of Char = ['0'..'9']') is a value
  6108. with a layout, so it cannot fold: its bytes are emitted code-resident
  6109. and the name becomes an addressable value. See the storage decision
  6110. in CALC-COMPILE.md. An ARRAY or RECORD typed constant is still
  6111. refused loudly - those layouts come later. *)
  6112. typed := FALSE ;
  6113. setTyped := FALSE ;
  6114. arrTyped := FALSE ;
  6115. Skip () ;
  6116. IF CurCh () = ':' THEN
  6117. DropCh (GetCh ()) ;
  6118. ParseType (typCls, typSize, typElem) ;
  6119. IF OK () THEN
  6120. IF typCls = TSet THEN
  6121. setTyped := TRUE
  6122. ELSIF typCls = TArray THEN
  6123. arrTyped := TRUE
  6124. ELSIF typSize > 2 THEN
  6125. Err (ENoLib)
  6126. ELSE
  6127. typed := TRUE
  6128. END
  6129. END
  6130. END ;
  6131. IF OK () AND setTyped THEN
  6132. ExpectDelim ('=', ENoSemi) ;
  6133. IF RdSetLiteral (typElem, typSize, constBlob) THEN
  6134. soff := EmSetBlob (constBlob, typSize) ;
  6135. DropC (NewSym (nm, KVar, TSet, typSize, typElem, soff, 0, FALSE))
  6136. END
  6137. ELSIF OK () AND arrTyped THEN
  6138. (* array typed constant: `(v1, v2, ...)' in element order, each value
  6139. written little-endian in typElem bytes. CALC's is XPOS (seven
  6140. Integers, 14 bytes). An element that is a STRING (CALC.INC's
  6141. StandardfunctionNames) is a later increment, and is refused here. *)
  6142. ExpectDelim ('=', ENoSemi) ;
  6143. ExpectDelim ('(', ENoSemi) ;
  6144. nb := 0 ;
  6145. LOOP
  6146. RdConst (v, cls, isStr) ;
  6147. IF isStr OR (nb + typElem > 512) THEN
  6148. Err (ENoLib) ;
  6149. EXIT
  6150. END ;
  6151. w := VAL (CARDINAL, W16 (v)) ;
  6152. divi := 1 ;
  6153. k := 0 ;
  6154. WHILE k < typElem DO
  6155. constBlob [nb] := CHR ((w DIV divi) MOD 256) ;
  6156. divi := divi * 256 ;
  6157. INC (nb) ;
  6158. INC (k)
  6159. END ;
  6160. IF MatchDelim (',') THEN
  6161. (* another element *)
  6162. ELSE
  6163. EXIT
  6164. END
  6165. END ;
  6166. ExpectDelim (')', ENoSemi) ;
  6167. IF OK () THEN
  6168. soff := EmSetBlob (constBlob, typSize) ;
  6169. ci := NewSym (nm, KVar, TArray, typSize, typElem, soff, 0, FALSE) ;
  6170. symtab [ci].arrIdx := newArrIdx
  6171. END
  6172. ELSIF OK () THEN
  6173. ExpectDelim ('=', ENoSemi) ;
  6174. RdConst (v, cls, isStr) ;
  6175. IF isStr THEN
  6176. Err (ENoLib)
  6177. END ;
  6178. IF OK () THEN
  6179. IF typed THEN
  6180. cls := typCls
  6181. END ;
  6182. DropC (NewSym (nm, KConst, cls, 0, 0, 0, v, FALSE))
  6183. END
  6184. END ;
  6185. IF NOT MatchDelim (';') THEN
  6186. Err (ENoSemi) ;
  6187. RETURN
  6188. END
  6189. END
  6190. END DefConst ;
  6191. PROCEDURE DefLabelPart () ;
  6192. VAR nm : ARRAY [0..9] OF CHAR ;
  6193. n : CARDINAL ;
  6194. BEGIN
  6195. LOOP
  6196. Skip () ;
  6197. IF NOT Digit (CurCh ()) THEN
  6198. Err (EUnknown) ;
  6199. RETURN
  6200. END ;
  6201. n := 0 ;
  6202. WHILE Digit (CurCh ()) DO
  6203. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  6204. DropCh (GetCh ())
  6205. END ;
  6206. NumToName (n, nm) ;
  6207. IF NOT Search (nm, n) THEN
  6208. DropC (NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE))
  6209. END ;
  6210. IF NOT MatchDelim (',') THEN
  6211. IF MatchDelim (';') THEN
  6212. RETURN
  6213. END ;
  6214. Err (ENoSemi) ;
  6215. RETURN
  6216. END
  6217. END
  6218. END DefLabelPart ;
  6219. PROCEDURE IfMatchSemi () ;
  6220. BEGIN
  6221. IF NOT MatchDelim (';') THEN
  6222. Err (ENoSemi)
  6223. END
  6224. END IfMatchSemi ;
  6225. PROCEDURE SymEpi () ;
  6226. (* function result: AX := result var *)
  6227. BEGIN
  6228. IF curIsFunc THEN
  6229. IF OK () THEN
  6230. EmLoadVar (TRUE, symtab [resultVar].off, symtab [resultVar].size)
  6231. END
  6232. END
  6233. END SymEpi ;
  6234. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ;
  6235. (* How many bytes a value parameter occupies in the callee's stack frame.
  6236. TP3's `tstscal' (TPSRC7 1243): a scalar-like parameter is AT LEAST two
  6237. bytes on the stack even when its type is one byte; anything larger spends
  6238. its own size. Generalised here so step 2 can put a string's 71 bytes on
  6239. the stack without changing what a scalar does today. *)
  6240. BEGIN
  6241. IF (cls = TScalar) OR (cls = TChar) OR (cls = TBool) OR (cls = TEnum) THEN
  6242. RETURN 2
  6243. END ;
  6244. RETURN size
  6245. END SlotSize ;
  6246. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ;
  6247. (* The bytes a parameter occupies in the frame. A VAR parameter's slot is the
  6248. ADDRESS, always two bytes, whatever its type: `size' stays the type's width
  6249. so loads and stores know whether they read one byte or two. *)
  6250. BEGIN
  6251. IF e.isVar THEN
  6252. RETURN 2
  6253. END ;
  6254. RETURN SlotSize (e.cls, e.size)
  6255. END ParamSlotBytes ;
  6256. PROCEDURE ProcFunc () ;
  6257. (* PROCEDURE name (params) ; body | FUNCTION name (params) : type ; body *)
  6258. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  6259. idx, old : CARDINAL ;
  6260. tok, tok2 : CARDINAL ;
  6261. parmNm : ARRAY [0..MaxName] OF CHAR ;
  6262. cls, size, elem : CARDINAL ;
  6263. isFunc, groupVar : BOOLEAN ;
  6264. saveNest, saveLoc, saveRes, saveF : CARDINAL ;
  6265. saveLB, savePO : CARDINAL ;
  6266. nestMark : CARDINAL ; (* symTop just inside this procedure *)
  6267. i, first : CARDINAL ;
  6268. BEGIN
  6269. isFunc := curIsFunc ;
  6270. Skip () ; (* after the PROCEDURE/FUNCTION keyword *)
  6271. IF NOT Alpha (CurCh ()) THEN
  6272. Err (EUnknown) ;
  6273. RETURN
  6274. END ;
  6275. GetWord () ;
  6276. SaveWord (nm) ;
  6277. IF Search (nm, idx) AND (symtab [idx].tag = KProc)
  6278. AND (symtab [idx].fwd) THEN
  6279. old := idx
  6280. ELSIF Search (nm, idx) THEN
  6281. Err (EUnknown) ;
  6282. RETURN
  6283. ELSE
  6284. old := NewSym (nm, KProc, TNone, 0, 0, 0, 0, FALSE)
  6285. END ;
  6286. IF isFunc THEN
  6287. symtab [old].tag := KFunc
  6288. END ;
  6289. saveNest := lexnest ;
  6290. saveLoc := locFree ;
  6291. saveRes := resultVar ;
  6292. saveF := VAL (CARDINAL, ORD (curIsFunc)) ;
  6293. saveLB := locBytes ;
  6294. savePO := parmOff ;
  6295. INC (lexnest) ;
  6296. nestMark := symTop ; (* after the proc's own name, before its params *)
  6297. locFree := 0FFFFH ;
  6298. locBytes := 0 ;
  6299. parmOff := 4 ;
  6300. IF MatchDelim ('(') THEN
  6301. IF CurCh () # ')' THEN
  6302. LOOP
  6303. (* PeekKw, not MatchKey: MatchKey CONSUMES the word it reads, so
  6304. using it to test for VAR would eat the parameter's name. *)
  6305. PeekKw (tok) ;
  6306. groupVar := FALSE ;
  6307. IF tok = TkVar THEN
  6308. (* A by-reference parameter: the slot will hold an ADDRESS.
  6309. `size' still carries the type's own width, because the
  6310. callee's loads and stores must know whether they move one
  6311. byte or two. *)
  6312. DropB (MatchKey (tok)) ;
  6313. groupVar := TRUE
  6314. END ;
  6315. first := symTop ;
  6316. LOOP
  6317. Skip () ; (* blanks before the parameter name *)
  6318. IF NOT Alpha (CurCh ()) THEN
  6319. Err (EUnknown) ;
  6320. RETURN
  6321. END ;
  6322. GetWord () ;
  6323. SaveWord (parmNm) ;
  6324. DupTest (parmNm) ;
  6325. DropC (NewSym (parmNm, KVar, TNone, 0, 0, 0, 0, TRUE)) ;
  6326. IF NOT MatchDelim (',') THEN
  6327. EXIT
  6328. END
  6329. END ;
  6330. ExpectDelim (':', ENoSemi) ; (* formal is 'name : type' *)
  6331. ParseType (cls, size, elem) ;
  6332. IF groupVar AND (size > 2) AND (cls # TString) THEN
  6333. (* A VAR parameter of a record or array would need the callee
  6334. to address through a larger object than the scalar [BX]
  6335. paths; refusing is the honest answer. A VAR STRING is the
  6336. exception: its slot is the ADDRESS of the characters (two
  6337. bytes), so the callee can hand that address to the string
  6338. runtime exactly as it hands a global's address. *)
  6339. Err (ENoLib) ;
  6340. RETURN
  6341. END ;
  6342. IF (size > 2) AND (cls # TString) THEN
  6343. (* A string VALUE parameter is a whole-slot copy (n+1 bytes on
  6344. the stack); any other type wider than a word - a record, an
  6345. array, a set - is still refused. *)
  6346. Err (ENoLib) ;
  6347. RETURN
  6348. END ;
  6349. i := first ;
  6350. WHILE i < symTop DO
  6351. symtab [i].cls := cls ; symtab [i].size := size ;
  6352. symtab [i].elem := elem ;
  6353. symtab [i].off := parmOff ;
  6354. symtab [i].isVar := groupVar ;
  6355. IF groupVar THEN
  6356. parmOff := parmOff + 2 (* the address, whatever the type *)
  6357. ELSE
  6358. parmOff := parmOff + SlotSize (cls, size)
  6359. END ;
  6360. INC (i)
  6361. END ;
  6362. IF MatchDelim (')') THEN
  6363. EXIT
  6364. END ;
  6365. IF MatchDelim (';') THEN
  6366. (* next group *)
  6367. ELSIF MatchDelim (',') THEN
  6368. (* the older `name : type, name : type' spelling *)
  6369. ELSE
  6370. Err (ENoSemi) ;
  6371. EXIT
  6372. END
  6373. END
  6374. ELSE
  6375. DropCh (GetCh ())
  6376. END
  6377. END ;
  6378. (* TP3 lays a parameter list out BACKWARDS from BP+4: the LAST declared
  6379. parameter sits at BP+4 and each earlier one is 2 bytes farther from BP
  6380. (RESUME-TP3.md 3.11 - "le dernier paramètre déclaré est le plus proche
  6381. (BP+4)" - and the Code Generation Internals stack frame, "BP+4: last
  6382. parameter"). This is the other half of pushing the arguments as they
  6383. are parsed: the first argument is pushed first and so ends up farthest
  6384. from BP, which has to be the FIRST declared parameter's slot.
  6385. During the loop the offsets were provisional, in declaration order
  6386. (parmOff starts at 4 and grows by each parameter's SLOT size), so
  6387. parameter k sat at 4 + sum of the slots before it. For slot sizes s and
  6388. frame total T, the parameter's final base is
  6389. 4 + (T - prefix - s) = 8 + T - off - s, which sends the FIRST declared
  6390. parameter to the far end and the LAST to BP+4. With every slot 2 -
  6391. every scalar, which is all this compiler accepts today - that reduces
  6392. exactly to the old `parmOff + 2 - off`, so no existing frame moves.
  6393. A slot larger than 2 (a string's 71 bytes) falls out of the same
  6394. formula, and a VAR parameter is exactly 2 even when its TYPE is one
  6395. byte: ParamSlotBytes carries that rule.
  6396. The range is exactly the parameters: the only symbol created while the
  6397. list is read is the parameter itself (NewSym inside the loop),
  6398. ParseType creates no symbols, the procedure's own name predates
  6399. nestMark, and a function's result variable is created after this point. *)
  6400. i := nestMark ;
  6401. WHILE i < symTop DO
  6402. symtab [i].off := 8 + (parmOff - 4) - symtab [i].off
  6403. - ParamSlotBytes (symtab [i]) ;
  6404. INC (i)
  6405. END ;
  6406. (* Record the parameter list on the procedure symbol: a call site has to
  6407. know each argument's SLOT size to push and clean up the right number of
  6408. bytes. Only when this definition actually read a list - a FORWARD's
  6409. list is kept, and the later `function Expression;' that repeats only the
  6410. name must not wipe it. *)
  6411. IF symTop > nestMark THEN
  6412. symtab [old].parmFirst := nestMark ;
  6413. symtab [old].parmCount := symTop - nestMark
  6414. END ;
  6415. IF isFunc THEN
  6416. IF MatchDelim (':') THEN
  6417. ParseType (cls, size, elem)
  6418. ELSE
  6419. cls := TScalar ;
  6420. size := 2 ;
  6421. elem := 2
  6422. END ;
  6423. IF size > 2 THEN
  6424. Err (ENoLib) ;
  6425. RETURN
  6426. END ;
  6427. symtab [old].cls := cls ;
  6428. symtab [old].size := size ;
  6429. resultVar := NewSym (nm, KVar, cls, size, elem,
  6430. (locFree - size + 1) MOD 10000H, 0, TRUE) ;
  6431. symtab [old].resvar := resultVar ;
  6432. locFree := (locFree - size) MOD 10000H ;
  6433. locBytes := locBytes + size
  6434. END ;
  6435. IfMatchSemi () ;
  6436. PeekKw (tok2) ;
  6437. IF (tok2 = TkForward) OR (tok2 = TkExternal) THEN
  6438. DropB (MatchKey (tok2)) ;
  6439. symtab [old].fwd := TRUE ;
  6440. symtab [old].defnd := (tok2 = TkExternal) ;
  6441. IfMatchSemi () ;
  6442. HideLocals (nestMark) ; (* a FORWARD's parameters are not the
  6443. caller's to see either *)
  6444. lexnest := saveNest ;
  6445. locFree := saveLoc ;
  6446. resultVar := saveRes ;
  6447. curIsFunc := (saveF # 0) ;
  6448. locBytes := saveLB ;
  6449. parmOff := savePO ;
  6450. RETURN
  6451. END ;
  6452. (* body *)
  6453. symtab [old].goPos := pc ;
  6454. symtab [old].defnd := TRUE ;
  6455. EmPushBp () ;
  6456. EmMovBpSp () ;
  6457. DefPart () ; (* nested declarations; stops at BEGIN *)
  6458. IF locBytes > 0 THEN
  6459. EmSubSp (locBytes)
  6460. END ;
  6461. DropC (EmCall (TU_StackChk)) ;
  6462. Statmnt () ; (* body *)
  6463. IF OK () THEN
  6464. SymEpi () ;
  6465. EmLeave () ;
  6466. EmRet ()
  6467. END ;
  6468. (* patch pending forward calls to this proc *)
  6469. i := 0 ;
  6470. WHILE i < nPend DO
  6471. IF (pend [i].kind = 1) AND (pend [i].who = old) THEN
  6472. SetPatTgt (pend [i].place, symtab [old].goPos) ;
  6473. pend [i].kind := 99
  6474. END ;
  6475. INC (i)
  6476. END ;
  6477. HideLocals (nestMark) ; (* parameters and locals stop here *)
  6478. lexnest := saveNest ;
  6479. locFree := saveLoc ;
  6480. resultVar := saveRes ;
  6481. curIsFunc := (saveF # 0) ;
  6482. locBytes := saveLB ;
  6483. parmOff := savePO
  6484. END ProcFunc ;
  6485. PROCEDURE DefType () ;
  6486. (* 'name' '=' typeDef ; ... until a declaration keyword appears *)
  6487. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  6488. cls, size, elem, tidx : CARDINAL ;
  6489. tok : CARDINAL ;
  6490. BEGIN
  6491. LOOP
  6492. PeekKw (tok) ;
  6493. IF tok # TkNone THEN
  6494. RETURN
  6495. END ;
  6496. Skip () ; (* after the TYPE keyword: skip blanks *)
  6497. IF NOT Alpha (CurCh ()) THEN
  6498. Err (EUnknown) ;
  6499. RETURN
  6500. END ;
  6501. GetWord () ;
  6502. SaveWord (nm) ;
  6503. DupTest (nm) ;
  6504. ExpectDelim ('=', ENoSemi) ;
  6505. ParseType (cls, size, elem) ;
  6506. IF NOT OK () THEN
  6507. RETURN
  6508. END ;
  6509. tidx := NewSym (nm, KType, cls, size, elem, 0, 0, FALSE) ;
  6510. IF cls = TEnum THEN
  6511. (* the enumeration's bounds, set by ParseType, belong to the type - so
  6512. `set of Attributes' can size its base (0..n-1, one byte) *)
  6513. symtab [tidx].lo := enumLo ;
  6514. symtab [tidx].hi := enumHi
  6515. END ;
  6516. IF cls = TRecord THEN
  6517. (* and a record's fields live in the field table; the type records
  6518. which range is its own *)
  6519. symtab [tidx].fldFirst := recFldFirst ;
  6520. symtab [tidx].fldLast := recFldLast
  6521. END ;
  6522. IF cls = TArray THEN
  6523. symtab [tidx].arrIdx := newArrIdx ;
  6524. (* ...and the ELEMENT's field table, if it is a record. A variable
  6525. declared `Sheet : Cells' gets its field metadata through the named
  6526. type; without this, `Sheet[I,J].Field' and `with Sheet[I,J]' found
  6527. fldFirst = fldLast = 0 and reported "not a record". An INLINE
  6528. `array ... of Rec' worked because ParseType's element call left
  6529. the globals set for DefVar; the named form had lost them. *)
  6530. symtab [tidx].fldFirst := recFldFirst ;
  6531. symtab [tidx].fldLast := recFldLast
  6532. END ;
  6533. DropC (tidx) ;
  6534. IF NOT MatchDelim (';') THEN
  6535. Err (ENoSemi) ;
  6536. RETURN
  6537. END
  6538. END
  6539. END DefType ;
  6540. PROCEDURE DefPart () ;
  6541. (* LABEL / CONST / TYPE / VAR / OVERLAY / PROC / FUNCTION / BEGIN *)
  6542. VAR tok : CARDINAL ;
  6543. BEGIN
  6544. LOOP
  6545. IF MatchDelim (';') THEN
  6546. (* separator between declarations *)
  6547. ELSE
  6548. PeekKw (tok) ;
  6549. IF tok = TkBegin THEN
  6550. RETURN
  6551. END ;
  6552. IF NOT MatchKey (tok) THEN
  6553. Err (EUnknown) ;
  6554. RETURN
  6555. END ;
  6556. CASE tok OF
  6557. TkLabel : DefLabelPart () ;
  6558. | TkConst : DefConst () ;
  6559. | TkType : DefType () ;
  6560. | TkVar : DefVar () ;
  6561. | TkOverlay :
  6562. LOOP
  6563. Skip () ;
  6564. IF CurCh () = ';' THEN
  6565. DropCh (GetCh ()) ;
  6566. EXIT
  6567. END ;
  6568. IF CurCh () = 0C THEN
  6569. Err (ENoSemi) ;
  6570. EXIT
  6571. END ;
  6572. DropCh (GetCh ())
  6573. END ;
  6574. | TkProcedure : curIsFunc := FALSE ; ProcFunc () ;
  6575. | TkFunction : curIsFunc := TRUE ; ProcFunc () ;
  6576. ELSE
  6577. Err (EUnknown) ;
  6578. RETURN
  6579. END ;
  6580. IF NOT OK () THEN
  6581. RETURN
  6582. END
  6583. END
  6584. END
  6585. END DefPart ;
  6586. (* ---------------------------------------------------------------- *)
  6587. (* driver (TPSRC7 compile) *)
  6588. (* ---------------------------------------------------------------- *)
  6589. PROCEDURE DefBuiltins () ;
  6590. (* The standard procedures. Without these, WRITELN is absent from the
  6591. symbol table, Statmnt's identifier branch fails its Search and every
  6592. program that prints anything dies with EUnknown (41) on the '(' after the
  6593. call name - the single remaining cause of failure in the fixture matrix.
  6594. Tagged KBuiltin (not KProc) because these are not called generically:
  6595. WRITE/WRITELN/READ/READLN need TP3's per-argument type dispatch
  6596. (IoCall), and HALT takes no argument at all. defnd is TRUE because the
  6597. entry point is known - there is no forward reference to patch. *)
  6598. VAR i : CARDINAL ;
  6599. BEGIN
  6600. i := NewSym ("WRITE" , KBuiltin, BI_Write , 0, 0, 0, 0, FALSE) ;
  6601. symtab [i].defnd := TRUE ;
  6602. symtab [i].goPos := TU_WrInt ;
  6603. i := NewSym ("WRITELN", KBuiltin, BI_WriteLn, 0, 0, 0, 0, FALSE) ;
  6604. symtab [i].defnd := TRUE ;
  6605. symtab [i].goPos := TU_WrInt ;
  6606. i := NewSym ("READ" , KBuiltin, BI_Read , 0, 0, 0, 0, FALSE) ;
  6607. symtab [i].defnd := TRUE ;
  6608. symtab [i].goPos := TU_RdInt ;
  6609. i := NewSym ("READLN" , KBuiltin, BI_ReadLn , 0, 0, 0, 0, FALSE) ;
  6610. symtab [i].defnd := TRUE ;
  6611. symtab [i].goPos := TU_RdInt ;
  6612. i := NewSym ("HALT" , KBuiltin, BI_Halt , 0, 0, 0, 0, FALSE) ;
  6613. symtab [i].defnd := TRUE ;
  6614. symtab [i].goPos := TU_Halt ;
  6615. i := NewSym ("LENGTH" , KBuiltin, BI_Length , 0, 0, 0, 0, FALSE) ;
  6616. symtab [i].defnd := TRUE ;
  6617. symtab [i].goPos := 0 ; (* inline: the length byte, no entry *)
  6618. (* The CRT identifiers. ClrScr and GotoXY emit real INT 10h code; the other
  6619. four are registered so they are recognised, and IoCall refuses them with
  6620. ENoLib - loud, not inert. *)
  6621. i := NewSym ("CLRSCR" , KBuiltin, BI_ClrScr , 0, 0, 0, 0, FALSE) ;
  6622. symtab [i].defnd := TRUE ;
  6623. i := NewSym ("GOTOXY" , KBuiltin, BI_GotoXY , 0, 0, 0, 0, FALSE) ;
  6624. symtab [i].defnd := TRUE ;
  6625. i := NewSym ("LOWVIDEO", KBuiltin, BI_LowVideo, 0, 0, 0, 0, FALSE) ;
  6626. symtab [i].defnd := TRUE ;
  6627. i := NewSym ("NORMVIDEO", KBuiltin, BI_NormVideo, 0, 0, 0, 0, FALSE) ;
  6628. symtab [i].defnd := TRUE ;
  6629. i := NewSym ("CLREOL" , KBuiltin, BI_ClrEol , 0, 0, 0, 0, FALSE) ;
  6630. symtab [i].defnd := TRUE ;
  6631. i := NewSym ("DELAY" , KBuiltin, BI_Delay , 0, 0, 0, 0, FALSE) ;
  6632. symtab [i].defnd := TRUE ;
  6633. i := NewSym ("KEYPRESSED", KBuiltin, BI_KeyPressed, 0, 0, 0, 0, FALSE) ;
  6634. symtab [i].defnd := TRUE ;
  6635. i := NewSym ("UPCASE", KBuiltin, BI_UpCase, 0, 0, 0, 0, FALSE) ;
  6636. i := NewSym ("SUCC", KBuiltin, BI_Succ, 0, 0, 0, 0, FALSE) ;
  6637. i := NewSym ("PRED", KBuiltin, BI_Pred, 0, 0, 0, 0, FALSE) ;
  6638. symtab [i].defnd := TRUE ;
  6639. (* File operations. These are the names CALC actually uses; Eof, not
  6640. EndOfFile, because CALC declares a variable called EndOfFile. *)
  6641. i := NewSym ("ASSIGN", KBuiltin, BI_Assign, 0, 0, 0, 0, FALSE) ;
  6642. symtab [i].defnd := TRUE ;
  6643. i := NewSym ("RESET", KBuiltin, BI_Reset, 0, 0, 0, 0, FALSE) ;
  6644. symtab [i].defnd := TRUE ;
  6645. i := NewSym ("REWRITE", KBuiltin, BI_Rewrite, 0, 0, 0, 0, FALSE) ;
  6646. symtab [i].defnd := TRUE ;
  6647. i := NewSym ("CLOSE", KBuiltin, BI_Close, 0, 0, 0, 0, FALSE) ;
  6648. symtab [i].defnd := TRUE ;
  6649. i := NewSym ("IORESULT", KBuiltin, BI_IoResult, 0, 0, 0, 0, FALSE) ;
  6650. symtab [i].defnd := TRUE ;
  6651. i := NewSym ("CHR", KBuiltin, BI_Chr, 0, 0, 0, 0, FALSE) ;
  6652. symtab [i].defnd := TRUE ;
  6653. (* KBD: the console keyboard as a TEXT file. This runtime's read entries
  6654. already read the console, so `Read(Kbd, Ch)' drops the file argument and
  6655. reads a character exactly as `Read(Ch)' does. *)
  6656. i := NewSym ("KBD", KVar, TText, FileVarSize, 1, 0, 0, FALSE) ;
  6657. symtab [i].isKbd := TRUE
  6658. END DefBuiltins ;
  6659. PROCEDURE Inittur () ;
  6660. (* reset compiler state and define the standard types *)
  6661. VAR i, rt : CARDINAL ;
  6662. BEGIN
  6663. abortFac := FALSE ;
  6664. errNum := 0 ;
  6665. txerrPos := 0 ;
  6666. srcPos := 0 ;
  6667. srcLen := Length () ;
  6668. inclActive := FALSE ;
  6669. inclEnd := 0 ;
  6670. (* The image layout is
  6671. [JMP rel16][runtime][program header][program code]
  6672. The runtime is copied to the front, which is what the original does:
  6673. TPSRC7 "copyrt" runs REPZ MOVSB with SI=DI=0 and then "MOV pc,#$2D7C".
  6674. Because the runtime sits at (near) offset 0, every address the compiler
  6675. emits is already image-absolute - the data symbols' offsets, the TU_*
  6676. call targets and the rel16 displacements all need no relocation pass.
  6677. (The base shift would in fact cancel in EmCall's arithmetic, since both
  6678. sides of a CALL move together; making the offsets absolute just means
  6679. the linker has nothing to do but copy bytes.)
  6680. The JMP is new, and it is not cosmetic. A DOS .COM is entered at
  6681. CS:0100, i.e. FILE offset 0, and for a long time offset 0 held the
  6682. runtime's first bytes - so a .COM built by this compiler started by
  6683. executing initmem with AX holding whatever the loader left in it. Every
  6684. test up to that point checked bytes and never ran the thing, so it could
  6685. not see this. The jump is the program's entry and the runtime is
  6686. ordinary data to it; keeping the runtime at the front is what preserves
  6687. the no-relocation property, so the jump goes in front of the runtime
  6688. rather than the runtime being moved behind the program.
  6689. dc is put a fixed 4 KiB above the end of the program so that data cannot
  6690. collide with code in a single 64 KiB .COM segment. LIMITATION: a
  6691. program whose code exceeds 4 KiB overruns its own data area. TP3 had
  6692. overlay segments for this; we do not, and the check belongs where the
  6693. limit is documented rather than as a silent truncation. *)
  6694. RT_Build (EntSize) ;
  6695. rt := RT_Size () ;
  6696. IF rt >= MaxCode THEN
  6697. Err (EMemOvf) ; (* cannot happen: rt is 436 *)
  6698. RETURN
  6699. END ;
  6700. (* The entry jump, at image offset 0. See the layout note above: a DOS
  6701. .COM is entered at CS:0100, which is file offset 0, so whatever sits
  6702. at offset 0 is the program's first executed instruction. *)
  6703. (* The jump's three bytes are written out longhand rather than through
  6704. Eword, because Eword writes at pc and advances it, and pc is stale at
  6705. this point -- the operand landed wherever the last compile left pc. *)
  6706. cbuf [0] := 0E9H ; (* JMP rel16 *)
  6707. entRel := 1 ;
  6708. cbuf [entRel] := 0 ;
  6709. cbuf [entRel + 1] := 0 ;
  6710. i := EntSize ;
  6711. WHILE i - EntSize < rt DO
  6712. cbuf [i] := RT_Byte (i - EntSize) ;
  6713. INC (i)
  6714. END ;
  6715. pc := rt + EntSize ;
  6716. rtSz := rt + EntSize ;
  6717. dataBase := DataStart ;
  6718. dc := dataBase ;
  6719. imgReady := TRUE ;
  6720. strTop := 0 ;
  6721. strCnt := 0 ;
  6722. rdStrX := 0 ;
  6723. varspc := 0 ;
  6724. symTop := 0 ;
  6725. (* Per-compile tables. They used to survive into the next file when the
  6726. driver compiles several in one process (the compile matrix does exactly
  6727. that): array indices kept growing, and a record's field range could be
  6728. read against a stale table. One compile must not depend on the last. *)
  6729. fldTop := 0 ;
  6730. arrTop := 0 ;
  6731. withN := 0 ;
  6732. nPatch := 0 ;
  6733. nPend := 0 ;
  6734. exitCnt := 0 ;
  6735. brkN := 0 ;
  6736. caseN := 0 ;
  6737. lexnest := 0 ;
  6738. curIsFunc := FALSE ;
  6739. resultVar := 0 ;
  6740. locFree := 0FFFFH ;
  6741. locBytes := 0 ;
  6742. parmOff := 4 ;
  6743. dirs.rng := TRUE ;
  6744. dirs.chk := TRUE ;
  6745. InitKeys () ;
  6746. DropC (NewSym ("INTEGER", KType, TScalar, 2, 2, 0, 0, FALSE)) ;
  6747. DropC (NewSym ("BYTE" , KType, TScalar, 1, 1, 0, 0, FALSE)) ;
  6748. DropC (NewSym ("CHAR" , KType, TChar, 1, 1, 0, 0, FALSE)) ;
  6749. DropC (NewSym ("BOOLEAN", KType, TBool , 1, 1, 0, 0, FALSE)) ;
  6750. DropC (NewSym ("REAL" , KType, TReal , 6, 6, 0, 0, FALSE)) ;
  6751. DropC (NewSym ("STRING" , KType, TString, 256, 1, 0, 0, FALSE)) ;
  6752. DropC (NewSym ("TRUE" , KConst, TBool, 1, 1, 0, 1, FALSE)) ;
  6753. DropC (NewSym ("FALSE" , KConst, TBool, 1, 1, 0, 0, FALSE)) ;
  6754. DefBuiltins () ;
  6755. tmpA := NewSym ("@@T1", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  6756. dc := dc + 2 ;
  6757. tmpB := NewSym ("@@T2", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  6758. dc := dc + 2 ;
  6759. (* The text attribute LowVideo/NormVideo set (default 7, written by the
  6760. prologue). One byte, and its address is baked into the clear sequences. *)
  6761. crtAttrOff := dc ;
  6762. DropC (NewSym ("@@ATTR", KVar, TScalar, 1, 1, dc, 0, FALSE)) ;
  6763. dc := dc + 1 ;
  6764. (* Runtime entry offsets, derived from the blob rather than assumed. This
  6765. has to happen after RT_Build, since RT_Entry only knows where the code
  6766. landed once the blob is assembled.
  6767. RT_Entry returns an IMAGE-ABSOLUTE address, already biased by the base
  6768. RT_Build was given, so nothing here has to know where the runtime
  6769. landed. It used to return a blob-relative offset, and the bias was
  6770. applied here instead - three bytes' worth, for the entry jump. With
  6771. that line missing, every CALL landed three bytes short, in the middle of
  6772. a neighbouring runtime entry, and a CALL into the middle of wrtin's
  6773. `INT 21h' behaves perfectly plausibly: the program runs, prints nothing
  6774. and hangs. Only running it finds that. *)
  6775. IF (RT_Entry (13) = 0) OR (RT_Entry (11) = 0) OR (RT_Entry (3) = 0) THEN
  6776. (* RT_Entry returns 0 for an unknown selector. initmem sits at 0
  6777. legitimately, so it cannot appear in this test - but wrtinl, rdln
  6778. and wrint never can, so catching them is enough to catch a runtime
  6779. that failed to build or a selector that went stale. This test is on
  6780. 0 is not a usable address here, since RT_Entry returns an
  6781. image-absolute address and the base is EntSize. *)
  6782. Err (EMemOvf)
  6783. END ;
  6784. TU_InitMem := RT_Entry (0) ;
  6785. TU_ProgEnd := RT_Entry (1) ;
  6786. TU_StackChk := RT_Entry (2) ;
  6787. TU_WrInt := RT_Entry (3) ;
  6788. TU_WrChar := RT_Entry (4) ;
  6789. TU_WrBool := RT_Entry (5) ;
  6790. TU_WrReal := RT_Entry (6) ;
  6791. TU_RealWrite := RT_Entry (30) ; (* fmtreal + padding + output *)
  6792. TU_WrLn := RT_Entry (7) ;
  6793. TU_RdInt := RT_Entry (8) ;
  6794. TU_RdChar := RT_Entry (9) ;
  6795. TU_RdBool := RT_Entry (10) ;
  6796. TU_RdLn := RT_Entry (11) ;
  6797. TU_Halt := RT_Entry (12) ;
  6798. TU_WrInl := RT_Entry (13) ; (* inline string literal *)
  6799. TU_RdByte := RT_Entry (14) ; (* a BYTE read stores one byte *)
  6800. TU_SetOp := RT_Entry (31) ;
  6801. TU_SetCmp := RT_Entry (32) ;
  6802. TU_SetCopy := RT_Entry (33) ;
  6803. TU_FileAssign := RT_Entry (34) ;
  6804. TU_FileReset := RT_Entry (35) ;
  6805. TU_FileRewrite := RT_Entry (36) ;
  6806. TU_FileClose := RT_Entry (37) ;
  6807. TU_IoResult := RT_Entry (38) ;
  6808. TU_IoStore := RT_Entry (39) ;
  6809. TU_WrStr := RT_Entry (15) ; (* a string variable is written through
  6810. the address on the stack *)
  6811. TU_RdStr := RT_Entry (16) ; (* readln(s)/read(s): TPSRC8 prdstr,
  6812. TPSRC4 xrdstr *)
  6813. TU_StrStore := RT_Entry (17) ; (* s := t: TPSRC8 asnvar, TPSRC2 strstore *)
  6814. TU_CmpStr := RT_Entry (18) ; (* string compare: TPSRC9 vcompare,
  6815. TPSRC2 cmpstr *)
  6816. TU_StrCat := RT_Entry (19) ; (* string concatenation: TPSRC2 xconcat *)
  6817. TU_WrIntW := RT_Entry (20) ; (* width-aware integer: `I:2' *)
  6818. END Inittur ;
  6819. PROCEDURE HeadWord (VAR slot : CARDINAL) ;
  6820. BEGIN
  6821. slot := pc ;
  6822. Eword (0)
  6823. END HeadWord ;
  6824. PROCEDURE Compile (VAR errNo, errPos : CARDINAL) : BOOLEAN ;
  6825. VAR tok : CARDINAL ;
  6826. overProc : CARDINAL ;
  6827. hasProc : BOOLEAN ;
  6828. BEGIN
  6829. Inittur () ;
  6830. IF OK () THEN
  6831. (* Resolve every {$I} first: the parser (and DeclaresProc's lookahead)
  6832. must see one finished buffer. See ExpandIncludes. *)
  6833. ExpandIncludes ()
  6834. END ;
  6835. IF OK () THEN
  6836. (* program prologue: header words, CALL initmem, MOV BP,SP *)
  6837. HeadWord (hdrFlag) ;
  6838. HeadWord (hdrCS) ;
  6839. HeadWord (hdrDS) ;
  6840. HeadWord (hdrHeap) ;
  6841. HeadWord (hdrMax) ;
  6842. Eword (16) ; (* max open files *)
  6843. Eword (0) ; (* input buffer word *)
  6844. Eword (0) ; (* output buffer word *)
  6845. (* Here, and not one line earlier, is the first instruction of the
  6846. program: everything above is the header, which is DATA. The entry
  6847. jump has to land exactly here. Recorded rather than assumed, so that
  6848. a header that grows a word moves the target with it. *)
  6849. prologAt := pc ;
  6850. (* TU_InitMem takes the header offset in AX, not on the stack, so the
  6851. AX load has to precede the call. Previously the prologue called
  6852. offset 8 - which in this layout is the hdrMax word - and that was
  6853. coherent only because the runtime was not there. Now it is the
  6854. real header. *)
  6855. EmMovAxi ((rtSz + LoadBias) MOD 10000H) ;
  6856. DropC (EmCall (TU_InitMem)) ;
  6857. EmMovBpSp () ;
  6858. (* [@@ATTR] := 7 - the default text attribute, before any LowVideo or
  6859. NormVideo runs. The data area is zero-filled, and attribute 0 would
  6860. make every clear black-on-black. Through EmCrtSeq, not raw Ebyte:
  6861. Compile is not a one-line emitter, and the helper audit rightly
  6862. refuses to let a byte-emitting statement hide inside it. *)
  6863. EmCrtSeq (CrtLow) ;
  6864. IF MatchKey (tok) AND (tok = TkProgram) THEN
  6865. (* MatchKey stops right after "PROGRAM", so the optional program
  6866. name normally follows blanks. Skip them before testing for the
  6867. name: otherwise Alpha sees the blank, the name is never consumed
  6868. and IfMatchSemi reports ENoSemi at the name. *)
  6869. Skip () ;
  6870. IF Alpha (CurCh ()) THEN
  6871. GetWord ()
  6872. END ;
  6873. IF MatchDelim ('(') THEN
  6874. WHILE NOT MatchDelim (')') DO
  6875. IF Alpha (CurCh ()) THEN
  6876. GetWord ()
  6877. END ;
  6878. IF CurCh () = ',' THEN
  6879. DropCh (GetCh ())
  6880. END
  6881. END
  6882. END ;
  6883. IfMatchSemi ()
  6884. END ;
  6885. IF OK () THEN
  6886. (* Jump over the procedure bodies, if there are any. DefPart
  6887. compiles them HERE, between the prologue and the main statement
  6888. part, and there was no jump - so a program with a procedure fell
  6889. off the end of the prologue into the first procedure. See
  6890. DeclaresProc for why the condition is asked before DefPart runs
  6891. and not after. *)
  6892. hasProc := DeclaresProc () ;
  6893. IF hasProc THEN
  6894. overProc := EmJmpNear (0)
  6895. END ;
  6896. DefPart () ;
  6897. IF OK () THEN
  6898. (* A separate flag, NOT `overProc # 0`. EmJmpNear returns a
  6899. patch SLOT, and slot 0 is a perfectly ordinary slot - the
  6900. first forward jump in a program is slot 0. So a zero test
  6901. cannot tell "no forward jump" from "forward jump in slot 0",
  6902. it just skips the first patch, and the jump keeps its
  6903. placeholder target of 0. The program then jumped to image
  6904. offset 0, i.e. back to the entry jump, and ran the runtime
  6905. and the whole program again, forever. The slot is only
  6906. valid together with a boolean saying a slot was taken. *)
  6907. IF hasProc THEN
  6908. SetPatTgt (overProc, pc)
  6909. END ;
  6910. IF MatchKey (tok) AND (tok = TkBegin) THEN
  6911. Compound () ;
  6912. IF OK () THEN
  6913. EmXorAxAx () ;
  6914. DropC (EmCall (TU_ProgEnd)) ;
  6915. ResolvePatches () ;
  6916. (* Program-only sizes. The runtime is not part of the
  6917. program's code, and the fixture table has always meant
  6918. "the program's own code", so subtract it here rather
  6919. than making every expectation in expected.tsv wrong. *)
  6920. codeSz := pc - rtSz ;
  6921. dataSz := dc - dataBase ;
  6922. (* Header words. The layout is ours (the original's is
  6923. bigger and serves a real overlay loader), but
  6924. Runtime.EmitInitMem reads +4 and +8, so hdrDS and
  6925. hdrHeap must be the data base and the data end. *)
  6926. (* The entry jump's displacement. A .COM is entered at
  6927. CS:0100 = file offset 0, so the jump is the only thing
  6928. that decides where execution starts, and it has to land
  6929. on the START of the program code - the prologue, which is
  6930. at rtSz - not on pc, which is the END of it. (Patching
  6931. pc - EntSize, i.e. the end, lands one byte past the last
  6932. instruction, in the zero-filled code/data gap, where the
  6933. CPU slides through `ADD [BX+SI],AL' until it faults.)
  6934. The displacement is measured from the END of the jump,
  6935. and both addresses are image-absolute, so the load
  6936. segment cancels. *)
  6937. (* The entry jump's displacement. A .COM is entered at
  6938. CS:0100 = file offset 0, so this jump is the only thing
  6939. that decides where execution starts.
  6940. The target is prologAt - where the prologue ACTUALLY
  6941. began, recorded before the header words were emitted,
  6942. and the header is 16 bytes long, so this is rtSz + 16 and
  6943. NOT rtSz. Landing on rtSz lands on the HEADER, which is
  6944. data, and the CPU then decodes sixteen bytes of it as
  6945. instructions. That failure is spectacularly
  6946. non-deterministic across programs: 01 00 is
  6947. `ADD [BX+SI],AX' and is harmless, so writeln('hi') ran
  6948. fine by sliding through the header into the prologue,
  6949. while t07's hdrHeap word 90 12 decodes as a LOCK-prefixed
  6950. ADD whose displacement crosses a page and faults, and the
  6951. program hung with no output at all. Both looked like
  6952. "the jump is in the right area". Recording the position
  6953. rather than assuming it means a future header that grows
  6954. a word cannot silently reintroduce this. *)
  6955. PatchWord (entRel, (prologAt - EntSize) MOD 10000H) ;
  6956. PatchWord (hdrFlag, 1) ;
  6957. (* Every OFFSET field in the header is a segment offset,
  6958. i.e. an image offset plus LoadBias - one convention for
  6959. the whole structure, so that nobody has to remember
  6960. which of these five words is numbered which way.
  6961. hdrFlag 1 set, so a loader can recognise the header
  6962. hdrCS end of the generated code
  6963. hdrDS first byte of the data area <- read by initmem
  6964. hdrHeap one past the last <- read by initmem
  6965. hdrMax 0 (no overlay loader yet)
  6966. hdrDS and hdrHeap are the two that are CONSUMED, and
  6967. omitting the bias there is a silent no-op: initmem would
  6968. clear a range starting 0100h below the data, off the
  6969. front of the image, and never reach the globals at the
  6970. end. Nothing crashes, and the globals keep whatever the
  6971. loader left in them. *)
  6972. PatchWord (hdrCS, pc + LoadBias) ;
  6973. PatchWord (hdrDS, dataBase + LoadBias) ;
  6974. PatchWord (hdrHeap, dc + LoadBias) ;
  6975. PatchWord (hdrMax, 0)
  6976. END
  6977. ELSE
  6978. Err (EUnknown)
  6979. END
  6980. END
  6981. END
  6982. END ;
  6983. IF NOT MatchDelim ('.') THEN
  6984. Err (EPointExp)
  6985. END ;
  6986. IF abortFac THEN
  6987. errNo := errNum ; (* was "errNo := errNo": a self-assignment,
  6988. because the formal shadowed the module
  6989. variable, so the error code always
  6990. reached the caller as 0 *)
  6991. errPos := txerrPos ;
  6992. RETURN FALSE
  6993. END ;
  6994. errNo := 0 ;
  6995. errPos := 0 ;
  6996. RETURN TRUE
  6997. END Compile ;
  6998. PROCEDURE CodeBytes () : CARDINAL ;
  6999. BEGIN
  7000. RETURN codeSz
  7001. END CodeBytes ;
  7002. PROCEDURE DataBytes () : CARDINAL ;
  7003. BEGIN
  7004. RETURN dataSz
  7005. END DataBytes ;
  7006. PROCEDURE ImageBytes () : CARDINAL ;
  7007. (* Total linked image size: rtSz (the runtime) + CodeBytes (the program).
  7008. The data is NOT part of this image: globals live at DataBase (8000h image)
  7009. and initmem zeroes them. The .COM is exactly these bytes. *)
  7010. BEGIN
  7011. RETURN rtSz + codeSz
  7012. END ImageBytes ;
  7013. PROCEDURE DataBase () : CARDINAL ;
  7014. (* image-absolute offset at which the data area begins (DataStart = 8000H).
  7015. The data is outside the .COM; initmem zeroes [dataBase, dataBase+dataSz)
  7016. through the header's hdrDS/hdrHeap words. *)
  7017. BEGIN
  7018. RETURN dataBase
  7019. END DataBase ;
  7020. PROCEDURE ImageByteAt (i : CARDINAL) : BYTE ;
  7021. (* i-th byte of the WHOLE image, runtime included, so a test can check the
  7022. real thing a .COM would contain. Returns 0 past the end. *)
  7023. BEGIN
  7024. IF i >= rtSz + codeSz THEN
  7025. RETURN 0
  7026. END ;
  7027. RETURN cbuf [i]
  7028. END ImageByteAt ;
  7029. PROCEDURE CodeByteAt (i : CARDINAL) : BYTE ;
  7030. (* i-th byte of the emitted image, for test harnesses that need to check
  7031. the generated 8086 code rather than just its size. Returns 0 past the
  7032. end of the image. *)
  7033. BEGIN
  7034. IF i >= codeSz THEN
  7035. RETURN 0
  7036. END ;
  7037. RETURN cbuf [i]
  7038. END CodeByteAt ;
  7039. END Compiler.