Compiler.mod 350 KB

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