Compiler.mod 306 KB

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