Compiler.mod 263 KB

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