Compiler.mod 282 KB

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