Compiler.mod 326 KB

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