Compiler.mod 286 KB

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