Compiler.mod 319 KB

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