Compiler.mod 268 KB

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