Compiler.mod 241 KB

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