Compiler.mod 222 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997
  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. MaxSym = 3000 ;
  66. MaxPatch = 2000 ;
  67. MaxPend = 400 ;
  68. MaxFields = 2000 ; (* record fields, in a table of their own: a
  69. field is scoped to its record, not global *)
  70. MaxArrs = 1000 ; (* array SHAPES, likewise: a symbol points at
  71. one, and 2-D indexing needs both ranges *)
  72. FileVarSize = 4 ; (* a file variable is our control block: the DOS
  73. handle (word) and a mode word (0 closed, 1
  74. read, 2 write). TP3 keeps a buffer here too;
  75. we do unbuffered INT 21h I/O. *)
  76. (* type codes (TP3 vartp) *)
  77. TNone = 0 ; TArray = 1 ; TRecord = 2 ; TSet = 3 ;
  78. TPtr = 4 ; TFile = 5 ; TText = 6 ; TUntyp = 7 ;
  79. TString = 8 ; TReal = 9 ; TScalar = 10 ; TBool = 11 ;
  80. (* CHAR needs a class of its own. It used to be registered as TScalar,
  81. which made a CHAR variable indistinguishable from an INTEGER one: the
  82. class is all IoCall has to dispatch on, so `write(c)` called wrint (the
  83. value 65 became the *address* 65 and it printed whatever lived at 0x41)
  84. and `readln(c)` called rdint (which stores a 16-bit result, so it wrote
  85. two bytes into a one-byte variable). TP3 TPSRC8 prdtyped/pwriteln
  86. dispatches on the type identifier for exactly this reason. BYTE stays
  87. TScalar: a BYTE is written as an integer, as in TP3 - but a READ of one
  88. is dispatched on the variable's size instead (TPSRC8 prdnum
  89. `CMP varsize,#$01 / JA -> rdint, else rdbyte'), so the one thing class
  90. alone cannot tell apart is told apart where the size is in hand. *)
  91. TChar = 12 ;
  92. TEnum = 13 ; (* an enumeration type: ordinal, size 1 (TP3 uses 1
  93. byte below 256 values), bounds in SymEntry.lo/hi *)
  94. (* symbol kinds *)
  95. KLabel = 100H ; KConst = 200H ; KType = 300H ;
  96. KVar = 400H ; KProc = 500H ; KFunc = 600H ;
  97. KBuiltin = 700H ; (* standard procedure, see BI_* below *)
  98. (* which standard procedure a KBuiltin symbol denotes *)
  99. BI_Write = 0 ; BI_WriteLn = 1 ; BI_Read = 2 ;
  100. BI_ReadLn = 3 ; BI_Halt = 4 ; BI_Length = 5 ;
  101. (* CRT identifiers. There is no unit system, so these are builtins. They
  102. are statements (except Length), dispatched in IoCall; each one that is
  103. not implemented yet is a loud ENoLib, never a silent no-op. *)
  104. BI_ClrScr = 6 ; BI_GotoXY = 7 ; BI_LowVideo = 8 ;
  105. BI_NormVideo = 9 ; BI_ClrEol = 10 ; BI_Delay = 11 ;
  106. BI_KeyPressed = 12 ;
  107. (* the sub-codes EmCrtSeq takes *)
  108. CrtClr = 0 ; CrtDl = 1 ; CrtDh = 2 ; CrtCaret = 3 ; CrtEol = 4 ;
  109. CrtLow = 5 ; CrtNorm = 6 ; CrtDelay = 7 ; CrtKey = 8 ;
  110. (* keyword tokens *)
  111. TkNone = 0 ; TkProgram = 1 ; TkBegin = 2 ; TkEnd = 3 ;
  112. TkIf = 4 ; TkThen = 5 ; TkElse = 6 ; TkWhile = 7 ;
  113. TkDo = 8 ; TkRepeat = 9 ; TkUntil = 10 ; TkFor = 11 ;
  114. TkTo = 12 ; TkDownto = 13 ; TkCase = 14 ; TkOf = 15 ;
  115. TkGoto = 16 ; TkExit = 17 ; TkWith = 18 ; TkVar = 19 ;
  116. TkConst= 20 ; TkType = 21 ; TkLabel = 22 ; TkProcedure = 23 ;
  117. TkFunction = 24 ; TkNil = 25 ; TkAnd = 26 ; TkOr = 27 ;
  118. TkNot = 28 ; TkDiv = 29 ; TkMod = 30 ; TkIn = 31 ;
  119. TkFile = 32 ; TkText = 33 ; TkRecord = 34 ; TkArray = 35 ;
  120. TkSet = 36 ; TkPacked = 37 ; TkForward = 38 ; TkExternal = 39 ;
  121. TkAbsolute = 40 ; TkOverlay = 41 ; TkString = 42 ;
  122. (* Codes for the SYMBOL operators, as BinOpEmit numbers them. The word
  123. operators carry their own Tk* token and need no code here.
  124. These are named, not bare numbers, because every precedence level's
  125. parser picks its own code out of the same set and BinOpEmit cannot see
  126. which level called it. ParseAdd chose 1 for '+' and ParseMul chose 1
  127. for '*', so every multiplication dispatched to EmAddAxCx and a * b
  128. compiled to a + b. Only the constant-folding path was right, which is
  129. why n * n with n a CONST was correct and a * b with a a variable was
  130. not. *)
  131. OpAdd = 1 ; OpSub = 2 ; OpMul = 3 ;
  132. (* TP3 error numbers *)
  133. ENoSemi = 1 ; EPointExp = 10 ; ESimpType = 30 ;
  134. EUnknown = 41 ; EConstRange = 45 ; EMemOvf = 98 ;
  135. ECompOvf = 99 ; ENoLib = 102 ; ETypeErr = 56 ;
  136. EIoHere = 66 ; (* I/O not allowed here - TPSRC8 prderrtp *)
  137. EFileNF = 90 ; (* File not found - TPSRC10 cdincl, errb *)
  138. EInclNest = 96 ; (* Illegal nesting of include files - TPSRC10 cdincl *)
  139. AposC = 39 ; (* ORD ("'") - avoids quote-in-quote *)
  140. (* ---------------------------------------------------------------- *)
  141. (* types *)
  142. (* ---------------------------------------------------------------- *)
  143. TYPE
  144. SymEntry =
  145. RECORD
  146. name : ARRAY [0..MaxName] OF CHAR ;
  147. tag : CARDINAL ;
  148. cls : CARDINAL ;
  149. size : CARDINAL ;
  150. elem : CARDINAL ;
  151. off : CARDINAL ;
  152. lval : LONGINT ;
  153. lo, hi : LONGINT ; (* an ORDINAL type's bounds: an enumeration
  154. (0..n-1) or a subrange. Needed so
  155. `set of T' can size its base. *)
  156. fldFirst, fldLast : CARDINAL ; (* a RECORD type's field range in the
  157. field table (0,0 when not a record) *)
  158. arrIdx : CARDINAL ; (* an ARRAY type's shape in ArrRec (0 = no) *)
  159. parmFirst, parmCount : CARDINAL ; (* a PROCEDURE/FUNCTION's parameters:
  160. symtab indices, in declaration order *)
  161. isKbd : BOOLEAN ; (* the predefined KBD file: reads are console *)
  162. isVar : BOOLEAN ; (* a VAR parameter: the slot holds an address *)
  163. level : CARDINAL ;
  164. local : BOOLEAN ;
  165. resvar : CARDINAL ;
  166. goPos : CARDINAL ;
  167. defnd : BOOLEAN ;
  168. fwd : BOOLEAN ;
  169. END ;
  170. PatchRec =
  171. RECORD
  172. place : CARDINAL ;
  173. target : CARDINAL ;
  174. filled : BOOLEAN ;
  175. END ;
  176. PendRec =
  177. RECORD
  178. kind : CARDINAL ; (* 0 goto, 1 call *)
  179. who : CARDINAL ;
  180. place : CARDINAL ; (* patch slot index *)
  181. END ;
  182. ERes =
  183. RECORD
  184. cls : CARDINAL ;
  185. kind : CARDINAL ; (* 0 const, 1 var, 2 value in AX,
  186. 3 string literal (cls = TString),
  187. 4 value on the stack (SaveLeft),
  188. 5 string element, address in DI,
  189. 7 set value (cls = TSet) *)
  190. imm : LONGINT ;
  191. idx : CARDINAL ;
  192. boff : CARDINAL ; (* constant fold-in for subscripts *)
  193. chr : BOOLEAN ; (* single-quoted literal, e.g. 'a' *)
  194. strx : CARDINAL ; (* string literal: index into strPool *)
  195. setoff : CARDINAL ; (* SET value: image offset of the bytes *)
  196. setbase : CARDINAL ; (* ... the first byte's first element,
  197. a multiple of 8 (TP3's hybrid origin) *)
  198. setsize : CARDINAL ; (* ... and how many bytes there are *)
  199. sz : CARDINAL ; (* width of a kind-1 value: an element or
  200. field's size, not its variable's *)
  201. END ;
  202. DirRec = RECORD rng, chk : BOOLEAN END ;
  203. FldRec =
  204. RECORD
  205. name : ARRAY [0..MaxName] OF CHAR ;
  206. cls : CARDINAL ;
  207. size : CARDINAL ;
  208. elem : CARDINAL ;
  209. off : CARDINAL ; (* byte offset within the record *)
  210. lo, hi : LONGINT ; (* bounds, for a subrange/enum field *)
  211. END ;
  212. ArrRec =
  213. RECORD
  214. n : CARDINAL ; (* number of ranges (1 for array[1..5]) *)
  215. lo, hi : ARRAY [0..3] OF LONGINT ;
  216. elem : CARDINAL ; (* element size in bytes *)
  217. ecls : CARDINAL ; (* element CLASS, for a subscripted value *)
  218. END ;
  219. (* ---------------------------------------------------------------- *)
  220. (* state *)
  221. (* ---------------------------------------------------------------- *)
  222. VAR
  223. srcPos, srcLen : CARDINAL ;
  224. (* Include state. srcName is the path the buffer was loaded from, set by
  225. SetSource; only its directory is used, because a {$I file} directive
  226. names the file relative to the INCLUDING file. Includes are expanded by
  227. ExpandIncludes BEFORE parsing, so inclEnd is the end of the include
  228. region currently being scanned and inclActive says one is open - a
  229. nested {$I} inside that region is error 96, since TP3 permits only one
  230. level. incBuf holds one whole include file while it is spliced. *)
  231. srcName : ARRAY [0..255] OF CHAR ; inclName : ARRAY [0..127] OF CHAR ;
  232. inclPath : ARRAY [0..383] OF CHAR ;
  233. inclEnd : CARDINAL ;
  234. inclActive : BOOLEAN ;
  235. incBuf : ARRAY [0..TextLimit] OF CHAR ;
  236. enumLo, enumHi : LONGINT ; (* bounds of the enumeration ParseType just read,
  237. handed to DefType which owns the type NAME *)
  238. fields : ARRAY [0..MaxFields - 1] OF FldRec ;
  239. fldTop : CARDINAL ; (* next free field-table slot *)
  240. recFldFirst, recFldLast : CARDINAL ; (* field range ParseType just built *)
  241. arrs : ARRAY [0..MaxArrs - 1] OF ArrRec ;
  242. arrTop : CARDINAL ; (* next free array-shape slot *)
  243. newArrIdx : CARDINAL ; (* ArrRec index+1 for the type just parsed *)
  244. constBlob : ARRAY [0..511] OF CHAR ; (* bytes of a set/array typed constant
  245. while it is being built *)
  246. wrd : ARRAY [0..MaxName] OF CHAR ;
  247. (* String-literal pool.
  248. TP3 does not put a literal in the data segment at all: it emits the
  249. literal *inline in the code stream* as <length byte><characters>, and
  250. the runtime entry "wrtinl" reads the length from the return address and
  251. returns to just past the last character (TPSRC4 xwrtinl, TPSRC10
  252. estring). So nothing here ends up in the image as data - the pool only
  253. has to survive from the moment the literal is scanned until IoCall
  254. decides to emit it, because by then the parser has moved on. *)
  255. strPool : ARRAY [0..4095] OF CHAR ;
  256. strOff : ARRAY [0..255] OF CARDINAL ;
  257. strLen : ARRAY [0..255] OF CARDINAL ;
  258. strTop : CARDINAL ; (* next free byte in strPool *)
  259. strCnt : CARDINAL ; (* literals collected so far *)
  260. rdStrX : CARDINAL ; (* pool index of the literal RdConst just read *)
  261. symtab : ARRAY [0..MaxSym - 1] OF SymEntry ;
  262. symTop : CARDINAL ;
  263. patches : ARRAY [0..MaxPatch - 1] OF PatchRec ;
  264. nPatch : CARDINAL ;
  265. pend : ARRAY [0..MaxPend - 1] OF PendRec ;
  266. nPend : CARDINAL ;
  267. exitPatch : ARRAY [0..63] OF CARDINAL ;
  268. exitCnt : CARDINAL ;
  269. brkSave : ARRAY [0..15] OF CARDINAL ;
  270. loopTy : ARRAY [0..15] OF CARDINAL ; (* 1 while/repeat, 2 for *)
  271. brkN : CARDINAL ;
  272. caseJmp : ARRAY [0..63] OF CARDINAL ;
  273. caseN : CARDINAL ;
  274. lblLo, lblHi : ARRAY [0..31] OF LONGINT ; (* one arm's label list *)
  275. lblJmp : ARRAY [0..63] OF CARDINAL ; (* its body jumps: 1 or 2 per label *)
  276. pc, dc : CARDINAL ;
  277. varspc : CARDINAL ;
  278. cbuf : ARRAY [0..MaxCode - 1] OF BYTE ;
  279. codeSz, dataSz : CARDINAL ;
  280. (* Image layout, all image-absolute. rtSz is where the runtime ends and
  281. the program header begins; dataBase is where the data area begins
  282. (rtSz + 1000H, a fixed 4 KiB above the code). codeSz and dataSz are
  283. PROGRAM sizes - the runtime is excluded - so the numbers the fixture
  284. table pins keep meaning what they meant before the runtime was
  285. prepended. *)
  286. rtSz, dataBase : CARDINAL ;
  287. (* TRUE once Compile has computed rtSz/dataBase, i.e. once the code window
  288. has been measured. Ebyte refuses to write past dataBase (the 4 KiB code
  289. window) and needs to know the window is real before it can: dataBase is
  290. 0 until it is set, and `pc >= 0' would abort on the very first byte. *)
  291. imgReady : BOOLEAN ;
  292. (* Image offset of the entry jump's rel16 operand, patched at the end of
  293. Compile. The jump is at image offset 0, so its displacement is simply
  294. the program code's end - 3. *)
  295. entRel, prologAt : CARDINAL ;
  296. (* Runtime entry offsets as IMAGE-ABSOLUTE addresses, which is what
  297. EmCall and EmJmp want. They are derived from Runtime.RT_Entry in
  298. Inittur (after RT_Build, since RT_Entry only knows where the code
  299. landed once the blob is assembled) rather than written down, so a moved
  300. entry cannot leave the compiler calling the old address. Not a CONST
  301. block because RT_Entry is a function.
  302. Standard-procedure entries: TP3 does NOT pass a descriptor -
  303. TPSRC8 pwriteln/pwrloop inspects each argument's class in CL and emits
  304. a *different* call per type, so the type is fixed at compile time and
  305. the runtime needs only the value. Mirrored here. *)
  306. TU_InitMem : CARDINAL ;
  307. TU_ProgEnd : CARDINAL ;
  308. TU_StackChk : CARDINAL ;
  309. TU_WrInt : CARDINAL ; TU_WrChar : CARDINAL ; TU_WrBool : CARDINAL ;
  310. TU_WrReal : CARDINAL ; TU_WrLn : CARDINAL ;
  311. TU_RdInt : CARDINAL ; TU_RdChar : CARDINAL ; TU_RdBool : CARDINAL ;
  312. TU_RdLn : CARDINAL ; TU_Halt : CARDINAL ;
  313. TU_RdByte : CARDINAL ; (* one-byte variable reads; see IoCall *)
  314. TU_WrInl : CARDINAL ; (* inline string literal; NO stack argument *)
  315. TU_WrStr : CARDINAL ; (* string variable; address is the stack argument *)
  316. TU_RdStr : CARDINAL ; (* readln(s)/read(s); address on the stack, limit
  317. in CX *)
  318. TU_StrStore : CARDINAL ; (* s := t; dest and source addresses on the stack,
  319. limit in CX *)
  320. TU_CmpStr : CARDINAL ; (* string comparison; two addresses on the stack,
  321. signed -1/0/+1 in AX *)
  322. TU_StrCat : CARDINAL ; (* string concatenation; dest and source addresses
  323. on the stack, limit in CX; exit code 16 if the
  324. result would be too long *)
  325. abortFac : BOOLEAN ;
  326. errNum : CARDINAL ; (* NOT "errNo": Compile's formal of that
  327. name would shadow it, and the caller's
  328. errNo would never be filled in *)
  329. txerrPos : CARDINAL ;
  330. lexnest : CARDINAL ;
  331. curIsFunc : BOOLEAN ;
  332. resultVar : CARDINAL ;
  333. locFree : CARDINAL ; (* next local slot (BP-relative, 8-bit) *)
  334. locBytes : CARDINAL ; (* frame size for SUB SP *)
  335. parmOff : CARDINAL ; (* provisional parameter slot, in declaration
  336. order; remapped to TP3's BP+4 rule when the
  337. list has been read (see ProcFunc) *)
  338. dirs : DirRec ;
  339. tmpA, tmpB : CARDINAL ; (* global scratch word addresses *)
  340. crtAttrOff : CARDINAL ; (* image offset of the text attribute byte that
  341. LowVideo/NormVideo set and ClrScr/ClrEol use *)
  342. hdrFlag, hdrCS, hdrDS, hdrHeap, hdrMax : CARDINAL ;
  343. kName : ARRAY [0..42] OF ARRAY [0..15] OF CHAR ;
  344. kTk : ARRAY [0..42] OF CARDINAL ;
  345. (* ---------------------------------------------------------------- *)
  346. (* small char helpers *)
  347. (* ---------------------------------------------------------------- *)
  348. PROCEDURE CurCh () : CHAR ;
  349. BEGIN
  350. IF srcPos >= srcLen THEN
  351. RETURN 0C
  352. END ;
  353. RETURN CharAt (srcPos)
  354. END CurCh ;
  355. PROCEDURE GetCh () : CHAR ;
  356. VAR ch : CHAR ;
  357. BEGIN
  358. ch := CurCh () ;
  359. IF srcPos < srcLen THEN
  360. INC (srcPos)
  361. END ;
  362. RETURN ch
  363. END GetCh ;
  364. PROCEDURE PeekAhead (k : CARDINAL) : CHAR ;
  365. BEGIN
  366. IF srcPos + k >= srcLen THEN
  367. RETURN 0C
  368. END ;
  369. RETURN CharAt (srcPos + k)
  370. END PeekAhead ;
  371. PROCEDURE Digit (ch : CHAR) : BOOLEAN ;
  372. BEGIN
  373. RETURN (ch >= '0') AND (ch <= '9')
  374. END Digit ;
  375. PROCEDURE Alpha (ch : CHAR) : BOOLEAN ;
  376. BEGIN
  377. RETURN ((ch >= 'A') AND (ch <= 'Z')) OR ((ch >= 'a') AND (ch <= 'z'))
  378. OR (ch = '_')
  379. END Alpha ;
  380. PROCEDURE AlphaNum (ch : CHAR) : BOOLEAN ;
  381. BEGIN
  382. RETURN (Alpha (ch)) OR (Digit (ch))
  383. END AlphaNum ;
  384. PROCEDURE IsHexCh (ch : CHAR) : BOOLEAN ;
  385. BEGIN
  386. RETURN (Digit (ch)) OR ((ch >= 'A') AND (ch <= 'F'))
  387. OR ((ch >= 'a') AND (ch <= 'f'))
  388. END IsHexCh ;
  389. PROCEDURE Upper (ch : CHAR) : CHAR ;
  390. BEGIN
  391. IF (ch >= 'a') AND (ch <= 'z') THEN
  392. RETURN CHR (ORD (ch) - ORD ('a') + ORD ('A'))
  393. END ;
  394. RETURN ch
  395. END Upper ;
  396. PROCEDURE W16 (x : LONGINT) : CARDINAL ;
  397. (* fold x modulo 10000H, handling negatives (no negative MOD) *)
  398. VAR m : CARDINAL ;
  399. BEGIN
  400. IF x >= 0 THEN
  401. RETURN VAL (CARDINAL, x MOD 10000H)
  402. END ;
  403. m := VAL (CARDINAL, (0 - x) MOD 10000H) ;
  404. RETURN (10000H - m) MOD 10000H
  405. END W16 ;
  406. PROCEDURE DropCh (v : CHAR) ;
  407. BEGIN
  408. END DropCh ;
  409. PROCEDURE DropB (v : BOOLEAN) ;
  410. BEGIN
  411. END DropB ;
  412. PROCEDURE DropC (v : CARDINAL) ;
  413. BEGIN
  414. END DropC ;
  415. PROCEDURE BitAnd (a, b : LONGINT) : LONGINT ;
  416. BEGIN
  417. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  418. * VAL (BITSET, W16 (b))))
  419. END BitAnd ;
  420. PROCEDURE BitOr (a, b : LONGINT) : LONGINT ;
  421. BEGIN
  422. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  423. + VAL (BITSET, W16 (b))))
  424. END BitOr ;
  425. PROCEDURE BitNot (a : LONGINT) : LONGINT ;
  426. BEGIN
  427. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, 0FFFFH)
  428. - VAL (BITSET, W16 (a))))
  429. END BitNot ;
  430. (* ---------------------------------------------------------------- *)
  431. (* errors *)
  432. (* ---------------------------------------------------------------- *)
  433. PROCEDURE Err (n : CARDINAL) ;
  434. BEGIN
  435. IF NOT abortFac THEN
  436. abortFac := TRUE ;
  437. errNum := n ;
  438. txerrPos := srcPos
  439. END
  440. END Err ;
  441. PROCEDURE OK () : BOOLEAN ;
  442. BEGIN
  443. RETURN NOT abortFac
  444. END OK ;
  445. (* ---------------------------------------------------------------- *)
  446. (* {$I file} include *)
  447. (* ---------------------------------------------------------------- *)
  448. PROCEDURE SetSource (path : ARRAY OF CHAR) ;
  449. (* remember the path the buffer was loaded from; MakeIncludePath keeps only its
  450. directory *)
  451. VAR i : CARDINAL ;
  452. BEGIN
  453. i := 0 ;
  454. WHILE (i < 255) AND (i <= HIGH (path)) AND (path [i] # 0C) DO
  455. srcName [i] := path [i] ;
  456. INC (i)
  457. END ;
  458. srcName [i] := 0C
  459. END SetSource ;
  460. PROCEDURE ReadWholeFile (path : ARRAY OF CHAR ; VAR n : CARDINAL) : BOOLEAN ;
  461. (* Read path into incBuf with the same CR/LF normalisation as LoadWorkFile,
  462. and report its length in n. FALSE if it could not be opened. ^Z ends the
  463. text, as it does for every other reader here. *)
  464. VAR fd : INTEGER ;
  465. k : LONGINT ;
  466. b : BYTE ;
  467. ch : CHAR ;
  468. prevCR, emit : BOOLEAN ;
  469. BEGIN
  470. n := 0 ;
  471. fd := open (ADR (path), 0, 0) ;
  472. IF fd < 0 THEN
  473. RETURN FALSE
  474. END ;
  475. prevCR := FALSE ;
  476. LOOP
  477. k := read (fd, ADR (b), 1) ;
  478. IF k # 1 THEN EXIT END ;
  479. IF b = 26 THEN EXIT END ; (* ^Z *)
  480. emit := TRUE ;
  481. IF b = 10 THEN
  482. IF prevCR THEN
  483. emit := FALSE
  484. ELSE
  485. ch := CHR (13) (* lone LF -> CR *)
  486. END ;
  487. prevCR := FALSE
  488. ELSIF b = 13 THEN
  489. ch := CHR (13) ;
  490. prevCR := TRUE
  491. ELSE
  492. ch := CHR (ORD (b)) ;
  493. prevCR := FALSE
  494. END ;
  495. IF emit AND (n <= TextLimit) THEN
  496. incBuf [n] := ch ;
  497. INC (n)
  498. END
  499. END ;
  500. k := close (fd) ;
  501. RETURN TRUE
  502. END ReadWholeFile ;
  503. PROCEDURE MakeIncludePath () ;
  504. (* inclPath := directory (srcName) + inclName, defaulting the extension to
  505. .PAS when the name has none (TPSRC10 kpasext). *)
  506. VAR i, j, last : CARDINAL ; dot : BOOLEAN ;
  507. BEGIN
  508. dot := FALSE ;
  509. i := 0 ;
  510. WHILE (i < 127) AND (inclName [i] # 0C) DO
  511. IF inclName [i] = '.' THEN dot := TRUE END ;
  512. INC (i)
  513. END ;
  514. IF (NOT dot) AND (i <= 123) THEN
  515. inclName [i] := '.' ;
  516. inclName [i + 1] := 'P' ;
  517. inclName [i + 2] := 'A' ;
  518. inclName [i + 3] := 'S' ;
  519. inclName [i + 4] := 0C
  520. END ;
  521. last := 0 ;
  522. i := 0 ;
  523. WHILE (i < 256) AND (srcName [i] # 0C) DO
  524. IF srcName [i] = '/' THEN last := i + 1 END ;
  525. INC (i)
  526. END ;
  527. j := 0 ;
  528. WHILE j < last DO
  529. inclPath [j] := srcName [j] ;
  530. INC (j)
  531. END ;
  532. i := 0 ;
  533. WHILE (i < 127) AND (inclName [i] # 0C) DO
  534. inclPath [j] := inclName [i] ;
  535. INC (j) ;
  536. INC (i)
  537. END ;
  538. inclPath [j] := 0C
  539. END MakeIncludePath ;
  540. PROCEDURE ExpandIncludes () ;
  541. (* Replace every {$I name} directive in the buffer with the named file's text,
  542. BEFORE parsing.
  543. This is a pre-pass, and it has to be. Skip is called by lookahead routines
  544. (DeclaresProc, PeekKw, KwAhead) that SAVE AND RESTORE srcPos; an include
  545. performed inside Skip would run once during the lookahead and once for real,
  546. and the second pass would see the first splice's text and report error 96.
  547. A splice also grows the buffer, which a rewind cannot undo. So the whole
  548. expansion is done here, in one forward scan with no lookahead, and the
  549. parser only ever sees the finished text.
  550. The scan has to recognise exactly what the lexer does, or it would expand a
  551. directive that the lexer would have read as a string or a comment: a quoted
  552. literal is skipped, then star-paren comments (which is why {$I} written
  553. inside one is inert - t56_include.inc relies on that), then brace comments,
  554. and only then a brace directive.
  555. Divergence from the original: TP3 STREAMS the include file line by line and
  556. switches back to the outer file at EOF (TPSRC10 fileline/getincl/fileeof);
  557. we hold the whole source in TextBuf and address it by index, so the include
  558. is spliced in place. A nested {$I} therefore cannot switch back on its own
  559. - which TP3 also refuses, and that is the error 96 reported here. *)
  560. VAR i, d0, d1, k, ni, n : CARDINAL ;
  561. c, letter : CHAR ;
  562. isInc : BOOLEAN ;
  563. BEGIN
  564. i := 0 ;
  565. inclActive := FALSE ;
  566. inclEnd := 0 ;
  567. WHILE (i < Length ()) AND OK () DO
  568. c := CharAt (i) ;
  569. IF c = "'" THEN
  570. INC (i) ;
  571. WHILE (i < Length ()) AND (CharAt (i) # "'") DO INC (i) END ;
  572. IF i < Length () THEN INC (i) END
  573. ELSIF (c = '(') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '*') THEN
  574. INC (i, 2) ;
  575. WHILE (i < Length ()) AND NOT ((CharAt (i) = '*')
  576. AND (i + 1 < Length ()) AND (CharAt (i + 1) = ')')) DO
  577. INC (i)
  578. END ;
  579. IF i < Length () THEN INC (i, 2) END
  580. ELSIF (c = '{') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '$') THEN
  581. d0 := i ;
  582. d1 := i + 2 ;
  583. WHILE (d1 < Length ()) AND (CharAt (d1) # '}') DO INC (d1) END ;
  584. IF i + 2 < Length () THEN
  585. letter := Upper (CharAt (i + 2))
  586. ELSE
  587. letter := 0C
  588. END ;
  589. isInc := FALSE ;
  590. IF letter = 'I' THEN
  591. k := i + 3 ;
  592. WHILE (k < d1) AND ((CharAt (k) = ' ') OR (CharAt (k) = CHR (9))) DO
  593. INC (k)
  594. END ;
  595. IF (k >= d1) OR ((CharAt (k) # '+') AND (CharAt (k) # '-')) THEN
  596. isInc := TRUE
  597. END
  598. END ;
  599. IF isInc THEN
  600. IF inclActive AND (d0 < inclEnd) THEN
  601. srcPos := d0 ;
  602. Err (EInclNest) ; (* 96 *)
  603. RETURN
  604. END ;
  605. ni := 0 ;
  606. WHILE (k < d1) AND (ni < 127) DO
  607. inclName [ni] := CharAt (k) ;
  608. INC (k) ;
  609. INC (ni)
  610. END ;
  611. WHILE (ni > 0) AND ((inclName [ni - 1] = ' ')
  612. OR (inclName [ni - 1] = CHR (9))) DO
  613. DEC (ni)
  614. END ;
  615. inclName [ni] := 0C ;
  616. MakeIncludePath () ;
  617. IF NOT ReadWholeFile (inclPath, n) THEN
  618. srcPos := d0 ;
  619. Err (EFileNF) ; (* 90 *)
  620. RETURN
  621. END ;
  622. DeleteFromTo (d0, d1 - d0 + 1) ;
  623. IF NOT InsertStr (d0, incBuf, n) THEN
  624. srcPos := d0 ;
  625. Err (EMemOvf) ;
  626. RETURN
  627. END ;
  628. inclEnd := d0 + n ;
  629. inclActive := TRUE ;
  630. i := d0 (* scan the new text too *)
  631. ELSE
  632. i := d1 + 1 (* ordinary directive: leave it *)
  633. END
  634. ELSIF c = '{' THEN
  635. INC (i) ;
  636. WHILE (i < Length ()) AND (CharAt (i) # '}') DO INC (i) END ;
  637. IF i < Length () THEN INC (i) END
  638. ELSE
  639. INC (i)
  640. END
  641. END ;
  642. srcLen := Length () ;
  643. srcPos := 0
  644. END ExpandIncludes ;
  645. (* ---------------------------------------------------------------- *)
  646. (* emission : ebyte / eword / ecall / ejump *)
  647. (* ---------------------------------------------------------------- *)
  648. PROCEDURE Ebyte (b : BYTE) ;
  649. BEGIN
  650. IF (pc >= MaxCode) OR (imgReady AND (pc >= dataBase)) THEN
  651. (* The image buffer bound, and the code window. dataBase is a fixed
  652. 4 KiB above the end of the runtime, so a program whose code reaches
  653. it has grown into its own data area - the two cannot share a 64 KiB
  654. .COM segment. Reported as TP3's error 98 (memory overflow) rather
  655. than a silent truncation; see the layout note in Compile and
  656. SUMMARY.md "Known limit". *)
  657. Err (EMemOvf)
  658. ELSE
  659. cbuf [pc] := b ;
  660. INC (pc)
  661. END
  662. END Ebyte ;
  663. PROCEDURE Eword (w : CARDINAL) ;
  664. BEGIN
  665. Ebyte (VAL (BYTE, w MOD 100H)) ;
  666. Ebyte (VAL (BYTE, (w DIV 100H) MOD 100H))
  667. END Eword ;
  668. PROCEDURE PatchWord (at, w : CARDINAL) ;
  669. (* Store a 16-bit word into cbuf at an absolute offset.
  670. A helper, because writing this inline got it wrong in all four header
  671. words: the low byte was (w DIV 16) MOD 100H, which is a NIBBLE shift, not
  672. the byte shift (w MOD 100H). So 1181h - the data base - was stored as
  673. 0118h = 280. It was invisible for as long as nothing read those words,
  674. which is exactly what "write it inline once and trust it" buys you. *)
  675. BEGIN
  676. cbuf [at] := VAL (BYTE, w MOD 100H) ;
  677. cbuf [at + 1] := VAL (BYTE, (w DIV 100H) MOD 100H)
  678. END PatchWord ;
  679. PROCEDURE AddPatch (place, target : CARDINAL) ;
  680. BEGIN
  681. IF nPatch < MaxPatch THEN
  682. patches [nPatch].place := place ;
  683. patches [nPatch].target := target ;
  684. patches [nPatch].filled := FALSE ;
  685. INC (nPatch)
  686. ELSE
  687. Err (ECompOvf)
  688. END
  689. END AddPatch ;
  690. PROCEDURE SetPatTgt (idx, t : CARDINAL) ;
  691. BEGIN
  692. IF idx < nPatch THEN
  693. patches [idx].target := t
  694. END
  695. END SetPatTgt ;
  696. PROCEDURE EmCall (target : CARDINAL) : CARDINAL ;
  697. (* E8 rel16 near call; target = 0 => forward (patched later).
  698. Returns the patch slot, or 0 when resolved directly. *)
  699. VAR rel, p : CARDINAL ;
  700. BEGIN
  701. Ebyte (0E8H) ;
  702. IF target = 0 THEN
  703. Eword (0) ;
  704. p := nPatch ;
  705. AddPatch (pc - 2, 0) ;
  706. RETURN p
  707. END ;
  708. (* rel16 is measured from the END of the instruction. Here pc already
  709. points past the opcode(s) and at the displacement field, so the
  710. instruction ends at pc+2 - the same convention ResolvePatches uses
  711. with "place + 2". Omitting the +2 lands every direct call/jump 2 bytes
  712. past its target. *)
  713. rel := (target + 10000H - (pc + 2)) MOD 10000H ;
  714. Eword (rel) ;
  715. RETURN 0
  716. END EmCall ;
  717. PROCEDURE EmJmpNear (target : CARDINAL) : CARDINAL ;
  718. (* E9 rel16; target = 0 => forward. Returns patch slot or 0. *)
  719. VAR rel, p : CARDINAL ;
  720. BEGIN
  721. Ebyte (0E9H) ;
  722. IF target = 0 THEN
  723. Eword (0) ;
  724. p := nPatch ;
  725. AddPatch (pc - 2, 0) ;
  726. RETURN p
  727. END ;
  728. rel := (target + 10000H - (pc + 2)) MOD 10000H ; (* see EmCall *)
  729. Eword (rel) ;
  730. RETURN 0
  731. END EmJmpNear ;
  732. PROCEDURE JccShort (cc : BYTE) : BYTE ;
  733. (* The 8086 SHORT Jcc opcode for a condition nibble. 70h..7Fh is exactly
  734. 70h + nibble: 70 JO 71 JNO 72 JB 73 JAE 74 JE 75 JNE 76 JBE 77 JA
  735. 78 JS 79 JNS 7A JP 7B JNP 7C JL 7D JGE 7E JLE 7F JG.
  736. So 70H + cc is the same condition the 386-only `0F 8x rel16' (for a Jcc) or
  737. `0F 9x' (for a SETcc) encoded, which is what lets the seven EmJcc sites and
  738. the six EmSetcc arms go on passing the low byte they always passed. *)
  739. VAR n : CARDINAL ;
  740. BEGIN
  741. n := VAL (CARDINAL, cc) MOD 10H ;
  742. RETURN VAL (BYTE, 70H + n)
  743. END JccShort ;
  744. PROCEDURE JccShortInv (cc : BYTE) : BYTE ;
  745. (* The same, for a jump that is taken when the condition does NOT hold.
  746. EmJcc needs this one and EmSetcc needs the other, and the difference is the
  747. whole bug, so it is worth being explicit about where it comes from: the low
  748. bit of a Jcc code IS the negation bit. 4/5, C/D, E/F, 2/3, 6/7, A/9, B/8 and
  749. 0/1 are the eight (condition, its negation) pairs, so negating a condition is
  750. `n XOR 1' and nothing more - `JE' and `JNE' are 0x74 and 0x75.
  751. Gm2 under -fiso has no XOR on integers at all: BITAND and BAND are both
  752. syntax errors, and arithmetic on a BYTE operand is rejected too, which is
  753. why every operand here goes through VAL. n + 1 - 2*(n MOD 2) is XOR 1 for a
  754. four-bit n and it lives in one named place rather than open-coded, because
  755. an open-coded negation at two call sites is how they end up disagreeing. *)
  756. VAR n : CARDINAL ;
  757. BEGIN
  758. n := VAL (CARDINAL, cc) MOD 10H ;
  759. RETURN VAL (BYTE, 70H + n + 1 - 2 * (n MOD 2))
  760. END JccShortInv ;
  761. PROCEDURE EmJcc (cc : BYTE ; target : CARDINAL) : CARDINAL ;
  762. (* A conditional branch, 8086 style. `cc' is the condition nibble, and it is
  763. exactly the low byte of the `0F 8x rel16' this used to emit.
  764. That was a real fault and nothing in the build could see it: `0F' is a
  765. 386-and-later opcode prefix and the 8086 has none, so EVERY conditional
  766. branch in EVERY compiled program was an illegal instruction on the machine
  767. TP3 targets. FCML decoded it happily, because FCML's -m16 mode is 386 --
  768. and FCML is this project's independent disassembler, so the one tool that
  769. could have objected was the one guaranteed to agree. qemu-system-i386 has
  770. no 8086 model either; its lowest is 486. So the compile succeeded, the
  771. .COM linked, the layout checked, the golden held and all 30 fixtures ran to
  772. the right answers, all at once, with the bug in.
  773. TPSRC8 lays IF, WHILE and REPEAT out as
  774. MOV AL,brnchop ; MOV AH,#$03 ; CALL eword ; PUSH pc ; CALL ejump
  775. i.e. a SHORT Jcc of displacement 3, stepping over a 3-byte EJMP. That is
  776. the shape here too, and EmJmpNear already owns the displacement arithmetic
  777. and the patch slot, so it is three lines and there is no second copy of
  778. that rule.
  779. The one thing that is NOT the same as TPSRC8, and cost a round of "every
  780. conditional is inverted" (t09_if printed pos/nonpos/lt for a program that
  781. must print nonpos/pos/ge): TP3's brnchop is the branch taken when the
  782. condition is TRUE, and TP3 steps over the EJMP when it is taken. Here `cc'
  783. is the branch taken when the condition is FALSE -- IF's `EmJcc (84H)' is
  784. JZ, patched to the ELSE, so it must fire when the test failed. EmJcc jumps
  785. to the target, it does not step over it, so stepping over an EJMP and then
  786. falling into the destination is the wrong way round: the byte has to be
  787. JccShortInv, not JccShort. The control flow that comes out is identical to
  788. the `0F 8x' form this replaces; only which of the pair is spelled differs.
  789. The flags survive, and the FOR test needs them to: it emits CMP and then
  790. Jcc with nothing in between, so anything that wrote a flag here would
  791. break the loop. Jcc and EJMP both leave the flags alone. *)
  792. BEGIN
  793. Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)
  794. Ebyte (03H) ; (* rel8: step over the 3-byte EJMP *)
  795. RETURN EmJmpNear (target) (* target = 0 => forward, see above *)
  796. END EmJcc ;
  797. PROCEDURE ResolvePatches () ;
  798. VAR i : CARDINAL ;
  799. rel : CARDINAL ;
  800. BEGIN
  801. i := 0 ;
  802. WHILE i < nPatch DO
  803. IF NOT patches [i].filled THEN
  804. rel := (patches [i].target + 10000H - (patches [i].place + 2))
  805. MOD 10000H ;
  806. cbuf [patches [i].place] := VAL (BYTE, rel MOD 100H) ;
  807. cbuf [patches [i].place + 1] := VAL (BYTE, (rel DIV 100H) MOD 100H) ;
  808. patches [i].filled := TRUE
  809. END ;
  810. INC (i)
  811. END
  812. END ResolvePatches ;
  813. (* 1-byte const emitters *)
  814. PROCEDURE EmMovAxi (imm : CARDINAL) ;
  815. BEGIN
  816. Ebyte (0B8H) ; Eword (imm)
  817. END EmMovAxi ;
  818. PROCEDURE EmMovCxi (imm : CARDINAL) ;
  819. BEGIN
  820. Ebyte (0B9H) ; Eword (imm)
  821. END EmMovCxi ;
  822. PROCEDURE EmMovBpSp () ;
  823. BEGIN
  824. Ebyte (8BH) ; Ebyte (0ECH)
  825. END EmMovBpSp ;
  826. PROCEDURE EmMovAh0 () ;
  827. BEGIN
  828. Ebyte (0B4H) ; Ebyte (0H)
  829. END EmMovAh0 ;
  830. PROCEDURE EmMovAxSp () ;
  831. (* Read the top of the stack into AX, leaving the stack unchanged.
  832. The obvious encoding, MOV AX,[SP], DOES NOT EXIST on the 8086. There is
  833. no encoding of [SP] as a memory operand: SIB bytes, which is how [ESP]
  834. would be written, did not exist until the 386, and mod=00 / rm=100 is
  835. [SI], not [SP]. The first version of this emitted 8B 44 24 00 - mod=01,
  836. rm=100, SIB=24h, disp8=0 - which is correct only on a 386 and above. Two
  837. of this project's oracles agree that it is wrong: fcml in 16-bit mode
  838. decodes it as MOV AX,[SI+0x24h], and so does qemu executing it, because
  839. qemu follows the CPU's rules for the encoding it is given rather than
  840. guessing. It was not the encoder's fault that the bytes were well formed;
  841. they were, and they read SI+24h.
  842. The observable effect was that CASE compiled to no branches at all: each
  843. label test loaded a garbage address, every comparison failed, and the
  844. program fell straight past the whole statement and exited without printing.
  845. A CASE fixture caught it. Nothing else could have - the encoding is
  846. valid, the size is right, and the byte-level checks have no way to know
  847. what register was meant.
  848. So: POP then PUSH the same value. Two bytes, no SIB, correct on every
  849. 8086, and observationally identical to peeking - the stack pointer ends
  850. where it started, holding the same value. *)
  851. BEGIN
  852. Ebyte (58H) ; (* POP AX *)
  853. Ebyte (50H) (* PUSH AX *)
  854. END EmMovAxSp ;
  855. PROCEDURE EmMovCxSp () ;
  856. (* The same, for CX - the FOR loop's bound, pushed by the FOR statement and
  857. re-read on every iteration. This one was emitting 8B 0C and nothing else,
  858. which is MOV CX,[SI] with the SIB slot missing: the *next* instruction was
  859. consumed as the SIB byte and the displacement. Same root cause, same fix,
  860. and it had not been noticed only because no FOR fixture is executed yet. *)
  861. BEGIN
  862. Ebyte (59H) ; (* POP CX *)
  863. Ebyte (51H) (* PUSH CX *)
  864. END EmMovCxSp ;
  865. PROCEDURE EmPushAx () ;
  866. BEGIN
  867. Ebyte (50H)
  868. END EmPushAx ;
  869. PROCEDURE EmPopCx () ;
  870. BEGIN
  871. Ebyte (59H)
  872. END EmPopCx ;
  873. PROCEDURE EmPopDx () ;
  874. BEGIN
  875. Ebyte (5AH)
  876. END EmPopDx ;
  877. PROCEDURE EmPopSi () ;
  878. BEGIN
  879. Ebyte (5EH) (* POP SI *)
  880. END EmPopSi ;
  881. PROCEDURE EmPopAx () ;
  882. BEGIN
  883. Ebyte (58H) (* POP AX *)
  884. END EmPopAx ;
  885. (* 91 = XCHG AX,CX, and NOT 93. LoadPair hands the operator the left
  886. operand in CX and the right in AX (in the original, and still the
  887. commonest, shape: it pushes the left, loads the right, then pops the
  888. left into CX), so the exchange is what puts LEFT in AX for the
  889. operation to act on.
  890. Without it, `a - b` computes `b - a`; with the wrong register, `a + b`
  891. computes `AX' + a` where AX' is whatever BX happened to hold.
  892. This emitted 93H = XCHG BX,AX for its entire life, which is the same class
  893. of mistake as MovSiBx = 89 DC in Runtime.mod: the right opcode, the wrong
  894. ModRM, decoding cleanly. Byte counts were right, the compile matrix was
  895. green, and no exec fixture did arithmetic on two variables - the first one
  896. to do so, `c := a + b` with a=7 b=5, printed 263 = 0100h+7, where 0100h
  897. was the caller's leftover BX. The name was the only thing wrong, and
  898. nothing read the name: audit_helpers.py swept Runtime.mod and not
  899. Compiler.mod, which is where most of these emitters live. It does both
  900. modules now. *)
  901. PROCEDURE EmXchgAxCx () ;
  902. BEGIN
  903. Ebyte (91H)
  904. END EmXchgAxCx ;
  905. PROCEDURE EmXorAxAx () ;
  906. BEGIN
  907. Ebyte (33H) ; Ebyte (0C0H)
  908. END EmXorAxAx ;
  909. PROCEDURE EmAddAxCx () ;
  910. BEGIN
  911. Ebyte (3H) ; Ebyte (0C1H)
  912. END EmAddAxCx ;
  913. PROCEDURE EmSubAxCx () ;
  914. BEGIN
  915. Ebyte (2BH) ; Ebyte (0C1H)
  916. END EmSubAxCx ;
  917. PROCEDURE EmMulAxCx () ;
  918. BEGIN
  919. Ebyte (0F7H) ; Ebyte (0E9H)
  920. END EmMulAxCx ;
  921. PROCEDURE EmIDivAxCx () ;
  922. BEGIN
  923. Ebyte (99H) ; Ebyte (0F7H) ; Ebyte (0F9H)
  924. END EmIDivAxCx ;
  925. PROCEDURE EmAndAxCx () ;
  926. BEGIN
  927. Ebyte (23H) ; Ebyte (0C1H)
  928. END EmAndAxCx ;
  929. PROCEDURE EmOrAxCx () ;
  930. BEGIN
  931. Ebyte (0BH) ; Ebyte (0C1H)
  932. END EmOrAxCx ;
  933. PROCEDURE EmOrAxAx () ;
  934. (* 09 C0: OR AX,AX - the 8086's flag-only test of AX, and the one the string
  935. comparison needs, because cmpstr hands back a signed -1/0/+1 rather than
  936. flags. OR AX,AX sets SF and ZF from the value and clears OF and CF, which
  937. is exactly the flag state a CMP AX,0 would leave - see EmSetcc and
  938. ParseCmp's EmRelSetcc. TEST AX,AX (85 C0) does the same thing, but
  939. tests/audit_helpers.py's name grammar has no `Test' mnemonic, and an
  940. emitter that cannot be name-checked is worse than one that can.
  941. It is NOT EmXorAxAx: XORing AX with itself zeroes it, which would throw
  942. away the very value the flags are supposed to describe. *)
  943. BEGIN
  944. Ebyte (09H) ; Ebyte (0C0H)
  945. END EmOrAxAx ;
  946. PROCEDURE EmNegAx () ;
  947. BEGIN
  948. Ebyte (0F7H) ; Ebyte (0D8H)
  949. END EmNegAx ;
  950. PROCEDURE EmNotAx () ;
  951. BEGIN
  952. Ebyte (0F7H) ; Ebyte (0D0H)
  953. END EmNotAx ;
  954. PROCEDURE EmXorAl01 () ;
  955. (* XOR AL,#01 - TPSRC9 neglevel's *boolean* NOT:
  956. CALL loadatom ; CALL ecode ; B $02,$34,$01
  957. neglevel tests the type first (CMP CL,#$0A -> integer -> NOT AX,
  958. CMP CL,#$0B -> boolean -> XOR AL,#01) and reports error 47 for anything
  959. else. Emitting NOT AX for a boolean leaves 0FFFEh or 0FFFFh, and the
  960. runtime's wrbool tests [BP+4] <> 0, so `not (a = a)' came out TRUE. *)
  961. BEGIN
  962. Ebyte (34H) ; Ebyte (01H)
  963. END EmXorAl01 ;
  964. PROCEDURE EmCmpAxCx () ;
  965. BEGIN
  966. Ebyte (3BH) ; Ebyte (0C1H)
  967. END EmCmpAxCx ;
  968. PROCEDURE EmCmpAxi (imm : CARDINAL) ;
  969. BEGIN
  970. Ebyte (03DH) ; Eword (imm)
  971. END EmCmpAxi ;
  972. PROCEDURE EmSetcc (cc : BYTE) ;
  973. (* Flags -> a Boolean in AX, on an 8086. `cc' is the SETcc opcode's low byte
  974. (94H = E, 95H = NE, 9CH = L, 9DH = GE, 9EH = LE, 9FH = G), i.e. the same
  975. condition nibble EmJcc takes.
  976. This used to emit `0F cc C0' - SETcc - which is 386-and-later, and then a
  977. MOV AH,0. The 8086 cannot read its flags as a value at all, so there was
  978. nothing else to fall back on.
  979. TPSRC9's flgbool is the fallback, and emits exactly this for exactly this
  980. case (CH = 04h, a comparison whose result is wanted as a value rather than
  981. as a branch):
  982. CALL ecode ; B $03,$B8,$01,$00 -> MOV AX,#0001
  983. MOV AL,brnchop ; CALL ebyte -> JNZ +1
  984. CALL ecode ; B $02,$01,$48 -> DEC AX
  985. AX stays 1 because the DEC was stepped over, and becomes 0 because it ran.
  986. So the shape is one MOV, one short Jcc whose displacement is the length of
  987. the DEC, and the DEC - which is EmJcc's shape with a different displacement,
  988. and the reason both are two instructions and a byte.
  989. The polarity is the opposite of EmJcc's, and deliberately so: here the jump
  990. must be taken when the comparison is TRUE, because what is being asked is
  991. "is this comparison true", and the nibble the six ParseCmp arms pass is the
  992. comparison's own opcode. So this is JccShort and EmJcc is JccShortInv --
  993. see EmJcc for why the difference is there at all. TP3's flgbool writes JNZ
  994. for the same reason; in the one case IT reaches flgbool from, the boolean is
  995. sitting in AX rather than in the flags, so JNZ is how it says "AX is
  996. non-zero".
  997. AH comes out 0 for free, which is why the EmMovAh0 this used to end with is
  998. gone: 6 bytes here where the old sequence was 5. The FLAGS do not survive,
  999. which the old SETcc did - and nothing reads them. Every conditional branch
  1000. in the compiler is preceded by its own CMP (see EmJcc's note on the FOR
  1001. test), and a comparison's value is consumed either as an AX operand or by
  1002. the test that follows it; the 30 executed fixtures are what holds that
  1003. down, not this comment. *)
  1004. BEGIN
  1005. Ebyte (0B8H) ; Eword (1) ; (* MOV AX,#0001 *)
  1006. Ebyte (JccShort (cc)) ; (* taken when the comparison HOLDS *)
  1007. Ebyte (01H) ; (* rel8: step over the DEC AX *)
  1008. Ebyte (48H) (* DEC AX *)
  1009. END EmSetcc ;
  1010. PROCEDURE EmRelSetcc (op : CARDINAL) ;
  1011. (* The relational operator -> SETcc table, in ONE place, because there are now
  1012. two callers: ParseCmp's numeric arm, whose flags come from EmCmpAxCx, and
  1013. its string arm, whose flags come from a cmpstr result put through
  1014. EmOrAxAx. It was factored out of ParseCmp when the string arm arrived, and
  1015. the note it carried is repeated here rather than referenced, because a
  1016. comment in the caller about a table in another routine is a comment nobody
  1017. reads.
  1018. The mnemonic is written next to every opcode on purpose. `op' is a number,
  1019. so the arm for ">" and the arm for ">=" differed only by two hex digits
  1020. that are each one letter from the other meaning -- SETG (9FH) and SETGE
  1021. (9DH). They were swapped once, which made a > b mean a >= b and a >= b
  1022. mean a > b. Only the equality boundary could see it: 6>5, 5<5, -1>-2 and
  1023. every other case I tried were already right. An opcode on its own does not
  1024. say which comparison it is the answer to.
  1025. `op' is ParseCmp's own numbering: 1 "=", 2 "<>", 3 "<", 4 ">", 5 ">=",
  1026. 6 "<=". The condition nibbles are the SIGNED ones (L/G/GE/LE), and both
  1027. callers hand it a value whose SIGN is the answer - ParseCmp's numeric arm
  1028. compares with CMP AX,CX on signed data, and cmpstr answers -1/0/+1 - so
  1029. the signed test is the right one in both places. One table also means that
  1030. swap cannot come back in one arm and not the other: tests/nonvacuity.sh
  1031. mutates exactly these two lines, and it now breaks the string comparison
  1032. at the same time as the numeric one. *)
  1033. BEGIN
  1034. CASE op OF
  1035. 1 : EmSetcc (94H) ; (* = SETE *)
  1036. | 2 : EmSetcc (95H) ; (* <> SETNE *)
  1037. | 3 : EmSetcc (9CH) ; (* < SETL *)
  1038. | 4 : EmSetcc (9FH) ; (* > SETG *)
  1039. | 5 : EmSetcc (9DH) ; (* >= SETGE *)
  1040. | 6 : EmSetcc (9EH) (* <= SETLE *)
  1041. END
  1042. END EmRelSetcc ;
  1043. PROCEDURE EmIncAx () ;
  1044. BEGIN
  1045. Ebyte (40H)
  1046. END EmIncAx ;
  1047. PROCEDURE EmDecAx () ;
  1048. BEGIN
  1049. Ebyte (48H)
  1050. END EmDecAx ;
  1051. PROCEDURE EmBpDisp (off, regf : CARDINAL) ;
  1052. (* Emit the ModR/M byte and displacement for a [BP+off] operand, picking the
  1053. encoding from the size of off. This is the ONE place that choice is made,
  1054. because getting it wrong is invisible: 8B 46 d8 and 8B 86 lo hi are both
  1055. well-formed MOVs, both decode cleanly, and only one of them reads the
  1056. variable the symbol table names. So the two are chosen here, once, rather
  1057. than re-derived at each of the four call sites. See the ModR/M table in
  1058. Runtime.mod.
  1059. off <= 127 -> mod=01 rm=110 -> 46 <disp8> 3 bytes with the opcode
  1060. otherwise -> mod=10 rm=110 -> 86 <disp16> 4 bytes with the opcode
  1061. Both displacements are SIGNED, and that is the whole subtlety:
  1062. - `off` is a 16-bit value and locals are packed top-anchored below BP:
  1063. locFree is the highest still-free byte (0FFFFh = -1 at entry), a local of
  1064. size n is based so its LAST byte sits on locFree, and locFree then drops
  1065. by n. So the first INTEGER local is at off = 0FFFEh = -2, the second at
  1066. 0FFFCh = -4, and so on - and a string local, which grows UP from its
  1067. base, lands wholly below BP instead of straddling it. The disp16 form
  1068. reads those same two bytes as a signed value and addresses the negative
  1069. slot correctly. There is no overflow case: all 65536 values of `off`
  1070. are representable, and a frame larger than 64K is a different problem.
  1071. - The old code took `off MOD 100H` and always emitted disp8. That is
  1072. the correct low byte for every displacement, so it was accidentally
  1073. right across -32768..+127, which is where locals actually live. It
  1074. went wrong at +128, where disp8 80h is -128 and not +128. So this
  1075. changes no existing program's bytes and fixes the one case that was
  1076. broken -- a bug nobody had hit yet, which is exactly why it wanted a
  1077. test rather than an argument. *)
  1078. BEGIN
  1079. (* mod=01 rm=110 -> 40H + regf*8 + 6H, mod=10 rm=110 -> 80H + regf*8 + 6H.
  1080. regf is the ModR/M reg field: 0 when the opcode's register is the
  1081. accumulator (every original caller), 7 for the DI forms EmLeaDi needs.
  1082. rm is 110 ([BP+disp]) in both. *)
  1083. IF off <= 127 THEN
  1084. Ebyte (VAL (BYTE, 40H + regf * 8 + 6H)) ; Ebyte (VAL (BYTE, off))
  1085. ELSE
  1086. Ebyte (VAL (BYTE, 80H + regf * 8 + 6H)) ; Eword (off)
  1087. END
  1088. END EmBpDisp ;
  1089. PROCEDURE EmLoadVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1090. (* A local is [BP+off] and `off' is already a frame displacement, so it needs
  1091. no bias. A global is [off] with a DIRECT displacement, i.e. an absolute
  1092. address, and that is the image offset + LoadBias - see Runtime.LoadBias. *)
  1093. BEGIN
  1094. IF nbytes = 1 THEN
  1095. IF local THEN
  1096. Ebyte (8AH) ; EmBpDisp (off, 0)
  1097. ELSE
  1098. Ebyte (0A0H) ; Eword ((off + LoadBias) MOD 10000H)
  1099. END
  1100. ELSE
  1101. IF local THEN
  1102. Ebyte (8BH) ; EmBpDisp (off, 0)
  1103. ELSE
  1104. Ebyte (0A1H) ; Eword ((off + LoadBias) MOD 10000H)
  1105. END
  1106. END
  1107. END EmLoadVar ;
  1108. PROCEDURE EmStoreVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1109. BEGIN
  1110. IF nbytes = 1 THEN
  1111. IF local THEN
  1112. Ebyte (88H) ; EmBpDisp (off, 0)
  1113. ELSE
  1114. Ebyte (0A2H) ; Eword ((off + LoadBias) MOD 10000H)
  1115. END
  1116. ELSE
  1117. IF local THEN
  1118. Ebyte (89H) ; EmBpDisp (off, 0)
  1119. ELSE
  1120. Ebyte (0A3H) ; Eword ((off + LoadBias) MOD 10000H)
  1121. END
  1122. END
  1123. END EmStoreVar ;
  1124. PROCEDURE EmPushVarAddr (local : BOOLEAN ; off : CARDINAL) ;
  1125. (* LEA AX,[BP+disp] / LEA AX,[off] then PUSH AX - READ passes the address of
  1126. a variable, not its value. 8D 46 disp is LEA AX,[BP+disp8] and
  1127. 8D 86 lo hi is LEA AX,[BP+disp16]; 8D 06 off is LEA AX,[off]
  1128. (mod=00 rm=110 = the direct disp16 form). All three are 8086-legal.
  1129. The [off] form is absolute and so carries LoadBias; the [BP+disp] forms
  1130. are displacements and so do not. *)
  1131. BEGIN
  1132. IF local THEN
  1133. Ebyte (8DH) ; EmBpDisp (off, 0)
  1134. ELSE
  1135. Ebyte (8DH) ; Ebyte (06H) ; Eword ((off + LoadBias) MOD 10000H)
  1136. END ;
  1137. EmPushAx ()
  1138. END EmPushVarAddr ;
  1139. PROCEDURE EmLeaDi (local : BOOLEAN ; off : CARDINAL) ;
  1140. (* LEA DI,[BP+disp] / LEA DI,[off] - the run-time address of an indexed
  1141. string's element, computed once in ParseSub and read by LoadAtom,
  1142. Assignment and IoCall.
  1143. It is the same three encodings EmPushVarAddr uses for AX - 8D 7E disp8,
  1144. 8D BE disp16, 8D 3E off - with the ModR/M reg field set to DI (111)
  1145. instead of the accumulator, which is why EmBpDisp now takes that field and
  1146. this is still the one place the disp8/disp16 choice is made. A local is
  1147. [BP+disp] with no bias; a global is [off] and carries LoadBias, absolute.
  1148. The later `MOV AL,[DI]` / `MOV [DI],AL` read through DS rather than SS.
  1149. That is correct here for the same reason TP3's own string ops use DI with
  1150. the default segment: a .COM loads with DS=SS=CS=ES, and nothing in this
  1151. compiler or its runtime ever reloads a segment register, so a BP-relative
  1152. frame address held in DI addresses the same byte. *)
  1153. BEGIN
  1154. IF local THEN
  1155. Ebyte (8DH) ; EmBpDisp (off, 7)
  1156. ELSE
  1157. Ebyte (8DH) ; Ebyte (3EH) ; Eword ((off + LoadBias) MOD 10000H)
  1158. END
  1159. END EmLeaDi ;
  1160. PROCEDURE EmAddDiAx () ;
  1161. BEGIN Ebyte (01H) ; Ebyte (0C7H) END EmAddDiAx ; (* 01 C7: DI := DI + AX *)
  1162. PROCEDURE EmLdAlDi () ;
  1163. BEGIN Ebyte (8AH) ; Ebyte (05H) END EmLdAlDi ; (* 8A 05: AL := [DI] *)
  1164. PROCEDURE EmLdAxDi () ;
  1165. BEGIN Ebyte (8BH) ; Ebyte (05H) END EmLdAxDi ; (* 8B 05: AX := [DI] *)
  1166. PROCEDURE EmStDiAl () ;
  1167. BEGIN Ebyte (88H) ; Ebyte (05H) END EmStDiAl ; (* 88 05: [DI] := AL *)
  1168. PROCEDURE EmPushDi () ;
  1169. BEGIN Ebyte (57H) END EmPushDi ; (* PUSH DI *)
  1170. PROCEDURE EmPopDi () ;
  1171. BEGIN Ebyte (5FH) END EmPopDi ; (* POP DI *)
  1172. PROCEDURE EmLoadVarInd (off, nbytes : CARDINAL) ;
  1173. (* AX := the value of a VAR parameter. [BP+off] holds the ADDRESS; BX carries
  1174. it so the byte/word load has a base register. The address is a DS offset:
  1175. a .COM has one segment, which is why no segment register appears here. *)
  1176. BEGIN
  1177. EmLoadVar (TRUE, off, 2) ; (* AX := [BP+off], the address *)
  1178. Ebyte (89H) ; Ebyte (0C3H) ; (* MOV BX,AX *)
  1179. IF nbytes = 1 THEN
  1180. Ebyte (8AH) ; Ebyte (07H) ; (* MOV AL,[BX] *)
  1181. EmMovAh0 ()
  1182. ELSE
  1183. Ebyte (8BH) ; Ebyte (07H) (* MOV AX,[BX] *)
  1184. END
  1185. END EmLoadVarInd ;
  1186. PROCEDURE EmStoreVarIndPrep (off : CARDINAL) ;
  1187. (* DI := the address of a VAR parameter, then PUSH DI. The push protects it
  1188. across the parse of the right-hand side, which may use DI for a string
  1189. element of its own. EmStoreInd finishes the store after POP DI. *)
  1190. BEGIN
  1191. Ebyte (8BH) ; EmBpDisp (off, 7) ; (* MOV DI,[BP+off] *)
  1192. EmPushDi ()
  1193. END EmStoreVarIndPrep ;
  1194. PROCEDURE EmStoreInd (nbytes : CARDINAL) ;
  1195. (* [DI] := AL/WORD, after POP DI - the companion of EmStoreVarIndPrep. *)
  1196. BEGIN
  1197. IF nbytes = 1 THEN
  1198. EmStDiAl () (* MOV [DI],AL *)
  1199. ELSE
  1200. Ebyte (89H) ; Ebyte (05H) (* MOV [DI],AX *)
  1201. END
  1202. END EmStoreInd ;
  1203. PROCEDURE EmSubSp (n : CARDINAL) ;
  1204. BEGIN
  1205. Ebyte (81H) ; Ebyte (0ECH) ; Eword (n MOD 10000H)
  1206. END EmSubSp ;
  1207. PROCEDURE EmAddSp (n : CARDINAL) ;
  1208. BEGIN
  1209. IF n <= 126 THEN
  1210. Ebyte (83H) ; Ebyte (0C4H) ; Ebyte (VAL (BYTE, n))
  1211. ELSE
  1212. Ebyte (81H) ; Ebyte (0C4H) ; Eword (n MOD 10000H)
  1213. END
  1214. END EmAddSp ;
  1215. PROCEDURE EmPushBp () ;
  1216. BEGIN
  1217. Ebyte (55H)
  1218. END EmPushBp ;
  1219. PROCEDURE EmLeave () ;
  1220. BEGIN
  1221. Ebyte (0C9H)
  1222. END EmLeave ;
  1223. PROCEDURE EmRet () ;
  1224. BEGIN
  1225. Ebyte (0C3H)
  1226. END EmRet ;
  1227. (* ---------------------------------------------------------------- *)
  1228. (* symbol table *)
  1229. (* ---------------------------------------------------------------- *)
  1230. PROCEDURE NameEq (a : ARRAY OF CHAR ; b : ARRAY OF CHAR) : BOOLEAN ;
  1231. VAR i : CARDINAL ;
  1232. BEGIN
  1233. i := 0 ;
  1234. LOOP
  1235. IF i > HIGH (a) THEN
  1236. RETURN FALSE
  1237. END ;
  1238. IF i > HIGH (b) THEN
  1239. RETURN FALSE
  1240. END ;
  1241. IF a [i] # b [i] THEN
  1242. RETURN FALSE
  1243. END ;
  1244. IF a [i] = 0C THEN
  1245. RETURN TRUE
  1246. END ;
  1247. INC (i)
  1248. END
  1249. END NameEq ;
  1250. PROCEDURE CopyStr (VAR dst : ARRAY OF CHAR ; src : ARRAY OF CHAR) ;
  1251. VAR i : CARDINAL ;
  1252. BEGIN
  1253. i := 0 ;
  1254. LOOP
  1255. IF i > HIGH (dst) THEN
  1256. dst [HIGH (dst)] := 0C ;
  1257. RETURN
  1258. END ;
  1259. IF i > HIGH (src) THEN
  1260. dst [i] := 0C ;
  1261. RETURN
  1262. END ;
  1263. dst [i] := src [i] ;
  1264. IF src [i] = 0C THEN
  1265. RETURN
  1266. END ;
  1267. INC (i)
  1268. END
  1269. END CopyStr ;
  1270. PROCEDURE CopyWord (name : ARRAY OF CHAR) ;
  1271. (* stash current word into global wrd (uppercased) *)
  1272. VAR i : CARDINAL ;
  1273. BEGIN
  1274. i := 0 ;
  1275. LOOP
  1276. IF i > HIGH (name) THEN
  1277. wrd [i] := 0C ;
  1278. RETURN
  1279. END ;
  1280. IF i > MaxName THEN
  1281. wrd [MaxName] := 0C ;
  1282. RETURN
  1283. END ;
  1284. IF name [i] = 0C THEN
  1285. wrd [i] := 0C ;
  1286. RETURN
  1287. END ;
  1288. wrd [i] := Upper (name [i]) ;
  1289. INC (i)
  1290. END
  1291. END CopyWord ;
  1292. PROCEDURE SaveWord (VAR dst : ARRAY OF CHAR) ;
  1293. (* copy wrd into dst *)
  1294. VAR i : CARDINAL ;
  1295. BEGIN
  1296. i := 0 ;
  1297. LOOP
  1298. IF i > HIGH (dst) THEN
  1299. dst [HIGH (dst)] := 0C ;
  1300. RETURN
  1301. END ;
  1302. IF i > MaxName THEN
  1303. dst [MaxName] := 0C ;
  1304. RETURN
  1305. END ;
  1306. dst [i] := wrd [i] ;
  1307. IF wrd [i] = 0C THEN
  1308. RETURN
  1309. END ;
  1310. INC (i)
  1311. END
  1312. END SaveWord ;
  1313. PROCEDURE NumToName (n : CARDINAL ; VAR dst : ARRAY OF CHAR) ;
  1314. VAR buf : ARRAY [0..9] OF CHAR ;
  1315. i, j : CARDINAL ;
  1316. BEGIN
  1317. IF n = 0 THEN
  1318. dst [0] := '0' ;
  1319. dst [1] := 0C ;
  1320. RETURN
  1321. END ;
  1322. i := 0 ;
  1323. WHILE n > 0 DO
  1324. IF i <= 9 THEN
  1325. buf [i] := CHR (ORD ('0') + (n MOD 10)) ;
  1326. INC (i)
  1327. END ;
  1328. n := n DIV 10
  1329. END ;
  1330. j := 0 ;
  1331. WHILE i > 0 DO
  1332. DEC (i) ;
  1333. IF j <= HIGH (dst) THEN
  1334. dst [j] := buf [i] ;
  1335. INC (j)
  1336. END
  1337. END ;
  1338. IF j <= HIGH (dst) THEN
  1339. dst [j] := 0C
  1340. END
  1341. END NumToName ;
  1342. PROCEDURE NewSym (name : ARRAY OF CHAR ; tag : CARDINAL ;
  1343. cls, size, elem, off : CARDINAL ; v : LONGINT ;
  1344. local : BOOLEAN) : CARDINAL ;
  1345. VAR e : SymEntry ;
  1346. BEGIN
  1347. IF symTop >= MaxSym THEN
  1348. Err (ECompOvf) ;
  1349. RETURN 0
  1350. END ;
  1351. CopyWord (name) ;
  1352. CopyStr (e.name, wrd) ;
  1353. e.tag := tag ;
  1354. e.cls := cls ;
  1355. e.size := size ;
  1356. e.elem := elem ;
  1357. e.off := off ;
  1358. e.lval := v ;
  1359. e.lo := 0 ;
  1360. e.hi := 0 ;
  1361. e.fldFirst := 0 ;
  1362. e.fldLast := 0 ;
  1363. e.arrIdx := 0 ;
  1364. e.parmFirst := 0 ;
  1365. e.parmCount := 0 ;
  1366. e.isKbd := FALSE ;
  1367. e.isVar := FALSE ;
  1368. e.level := lexnest ;
  1369. e.local := local ;
  1370. e.resvar := 0 ;
  1371. e.goPos := 0 ;
  1372. e.defnd := FALSE ;
  1373. e.fwd := FALSE ;
  1374. symtab [symTop] := e ;
  1375. INC (symTop) ;
  1376. RETURN symTop - 1
  1377. END NewSym ;
  1378. PROCEDURE Search (nm : ARRAY OF CHAR ; VAR idx : CARDINAL) : BOOLEAN ;
  1379. (* find nm among symbols visible at the current lexical level *)
  1380. VAR p : CARDINAL ;
  1381. BEGIN
  1382. CopyWord (nm) ;
  1383. p := symTop ;
  1384. WHILE p > 0 DO
  1385. DEC (p) ;
  1386. IF symtab [p].level <= lexnest THEN
  1387. IF NameEq (symtab [p].name, wrd) THEN
  1388. idx := p ;
  1389. RETURN TRUE
  1390. END
  1391. END
  1392. END ;
  1393. RETURN FALSE
  1394. END Search ;
  1395. PROCEDURE DupTest (nm : ARRAY OF CHAR) ;
  1396. (* A name may be declared twice only in the SAME scope. This used to reject
  1397. any name Search could see, so a parameter could not shadow a global - legal
  1398. ISO Pascal, and CALC.INC's `procedure IBMCh(var Ch: Char)' does exactly
  1399. that (`Ch' is a global). Same-level duplicates stay errors: two parameters
  1400. in one list, two locals, or two globals. *)
  1401. VAR i : CARDINAL ;
  1402. BEGIN
  1403. IF Search (nm, i) THEN
  1404. IF symtab [i].level = lexnest THEN
  1405. Err (EUnknown)
  1406. END
  1407. END
  1408. END DupTest ;
  1409. PROCEDURE HideLocals (from : CARDINAL) ;
  1410. (* Make every symbol from index `from' up invisible to everything outside the
  1411. procedure that declared it.
  1412. Search accepts a symbol when its level is <= lexnest, and every procedure
  1413. body is compiled at the same depth (lexnest 1), so a finished procedure's
  1414. parameters stayed visible to the NEXT procedure: a second `a : integer'
  1415. was a duplicate (err 41) and an unqualified `a' inside procedure two read
  1416. procedure one's argument. Level 0FFFFH fails `level <= lexnest' at every
  1417. depth a later procedure can be at, and by the time this runs the body that
  1418. could still legitimately see them is finished.
  1419. The symbols are relabelled, not popped: symtab[old].resvar holds an INDEX,
  1420. and a function's result variable is one of the entries being hidden. *)
  1421. VAR p : CARDINAL ;
  1422. BEGIN
  1423. p := from ;
  1424. WHILE p < symTop DO
  1425. symtab [p].level := 0FFFFH ;
  1426. INC (p)
  1427. END
  1428. END HideLocals ;
  1429. (* ---------------------------------------------------------------- *)
  1430. (* lexer *)
  1431. (* ---------------------------------------------------------------- *)
  1432. PROCEDURE InitKeys () ;
  1433. VAR i : CARDINAL ;
  1434. BEGIN
  1435. FOR i := 0 TO 42 DO
  1436. kTk [i] := 0 ;
  1437. kName [i] [0] := 0C
  1438. END ;
  1439. kName [1] := "PROGRAM" ; kTk [1] := TkProgram ;
  1440. kName [2] := "BEGIN" ; kTk [2] := TkBegin ;
  1441. kName [3] := "END" ; kTk [3] := TkEnd ;
  1442. kName [4] := "IF" ; kTk [4] := TkIf ;
  1443. kName [5] := "THEN" ; kTk [5] := TkThen ;
  1444. kName [6] := "ELSE" ; kTk [6] := TkElse ;
  1445. kName [7] := "WHILE" ; kTk [7] := TkWhile ;
  1446. kName [8] := "DO" ; kTk [8] := TkDo ;
  1447. kName [9] := "REPEAT" ; kTk [9] := TkRepeat ;
  1448. kName [10] := "UNTIL" ; kTk [10] := TkUntil ;
  1449. kName [11] := "FOR" ; kTk [11] := TkFor ;
  1450. kName [12] := "TO" ; kTk [12] := TkTo ;
  1451. kName [13] := "DOWNTO" ; kTk [13] := TkDownto ;
  1452. kName [14] := "CASE" ; kTk [14] := TkCase ;
  1453. kName [15] := "OF" ; kTk [15] := TkOf ;
  1454. kName [16] := "GOTO" ; kTk [16] := TkGoto ;
  1455. kName [17] := "EXIT" ; kTk [17] := TkExit ;
  1456. kName [18] := "WITH" ; kTk [18] := TkWith ;
  1457. kName [19] := "VAR" ; kTk [19] := TkVar ;
  1458. kName [20] := "CONST" ; kTk [20] := TkConst ;
  1459. kName [21] := "TYPE" ; kTk [21] := TkType ;
  1460. kName [22] := "LABEL" ; kTk [22] := TkLabel ;
  1461. kName [23] := "PROCEDURE" ; kTk [23] := TkProcedure ;
  1462. kName [24] := "FUNCTION" ; kTk [24] := TkFunction ;
  1463. kName [25] := "NIL" ; kTk [25] := TkNil ;
  1464. kName [26] := "AND" ; kTk [26] := TkAnd ;
  1465. kName [27] := "OR" ; kTk [27] := TkOr ;
  1466. kName [28] := "NOT" ; kTk [28] := TkNot ;
  1467. kName [29] := "DIV" ; kTk [29] := TkDiv ;
  1468. kName [30] := "MOD" ; kTk [30] := TkMod ;
  1469. kName [31] := "IN" ; kTk [31] := TkIn ;
  1470. kName [32] := "FILE" ; kTk [32] := TkFile ;
  1471. kName [33] := "TEXT" ; kTk [33] := TkText ;
  1472. kName [34] := "RECORD" ; kTk [34] := TkRecord ;
  1473. kName [35] := "ARRAY" ; kTk [35] := TkArray ;
  1474. kName [36] := "SET" ; kTk [36] := TkSet ;
  1475. kName [37] := "PACKED" ; kTk [37] := TkPacked ;
  1476. kName [38] := "FORWARD" ; kTk [38] := TkForward ;
  1477. kName [39] := "EXTERNAL" ; kTk [39] := TkExternal ;
  1478. kName [40] := "ABSOLUTE" ; kTk [40] := TkAbsolute ;
  1479. kName [41] := "OVERLAY" ; kTk [41] := TkOverlay ;
  1480. kName [42] := "STRING" ; kTk [42] := TkString
  1481. END InitKeys ;
  1482. PROCEDURE IsBlank (ch : CHAR) : BOOLEAN ;
  1483. BEGIN
  1484. RETURN (ch = ' ') OR (ORD (ch) = 09H) OR (ORD (ch) = 0DH) OR (ORD (ch) = 0AH) OR (ORD (ch) = 0CH)
  1485. END IsBlank ;
  1486. PROCEDURE Skip () ;
  1487. (* blanks, comments { } and (* *), compiler directives {$ } / (*$ *)
  1488. letter + sign toggles rng/chk. Include directives are already gone by the
  1489. time Skip runs: ExpandIncludes splices them into the buffer first, so the
  1490. {$I file} spelling never reaches here. {$I+}/{$I-} still do, and stay the
  1491. I/O-check toggle, exactly as TPSRC10 cdirec splits them on the sign. *)
  1492. VAR ch : CHAR ;
  1493. letter : CHAR ;
  1494. BEGIN
  1495. WHILE NOT abortFac DO
  1496. WHILE IsBlank (CurCh ()) DO
  1497. ch := GetCh ()
  1498. END ;
  1499. IF CurCh () = '{' THEN
  1500. ch := GetCh () ;
  1501. IF CurCh () = '$' THEN
  1502. ch := GetCh () ;
  1503. letter := Upper (GetCh ()) ;
  1504. IF CurCh () = '+' THEN
  1505. ch := GetCh () ;
  1506. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1507. IF letter = 'R' THEN dirs.rng := TRUE END
  1508. ELSIF CurCh () = '-' THEN
  1509. ch := GetCh () ;
  1510. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1511. IF letter = 'R' THEN dirs.rng := FALSE END
  1512. END
  1513. END ;
  1514. WHILE (CurCh () # '}') AND (CurCh () # 0C) DO
  1515. ch := GetCh ()
  1516. END ;
  1517. IF CurCh () = '}' THEN
  1518. ch := GetCh ()
  1519. END
  1520. ELSIF (CurCh () = '(') AND (PeekAhead (1) = '*') THEN
  1521. ch := GetCh () ;
  1522. ch := GetCh () ;
  1523. IF CurCh () = '$' THEN
  1524. ch := GetCh () ;
  1525. letter := Upper (GetCh ()) ;
  1526. IF CurCh () = '+' THEN
  1527. ch := GetCh () ;
  1528. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1529. IF letter = 'R' THEN dirs.rng := TRUE END
  1530. ELSIF CurCh () = '-' THEN
  1531. ch := GetCh () ;
  1532. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1533. IF letter = 'R' THEN dirs.rng := FALSE END
  1534. END
  1535. END ;
  1536. LOOP
  1537. IF (CurCh () = '*') AND (PeekAhead (1) = ')') THEN
  1538. ch := GetCh () ;
  1539. ch := GetCh () ;
  1540. EXIT
  1541. END ;
  1542. IF CurCh () = 0C THEN
  1543. EXIT
  1544. END ;
  1545. ch := GetCh ()
  1546. END
  1547. ELSE
  1548. RETURN
  1549. END
  1550. END
  1551. END Skip ;
  1552. PROCEDURE GetWord () ;
  1553. (* read identifier into wrd (uppercased); next char must be alpha *)
  1554. VAR i : CARDINAL ;
  1555. ch : CHAR ;
  1556. BEGIN
  1557. i := 0 ;
  1558. ch := GetCh () ;
  1559. LOOP
  1560. IF i > MaxName THEN
  1561. wrd [MaxName] := 0C ;
  1562. RETURN
  1563. END ;
  1564. wrd [i] := Upper (ch) ;
  1565. INC (i) ;
  1566. ch := CurCh () ;
  1567. IF NOT AlphaNum (ch) THEN
  1568. wrd [i] := 0C ;
  1569. RETURN
  1570. END ;
  1571. ch := GetCh ()
  1572. END
  1573. END GetWord ;
  1574. PROCEDURE WddTok () : CARDINAL ;
  1575. (* map wrd -> keyword token *)
  1576. VAR i : CARDINAL ;
  1577. BEGIN
  1578. i := 1 ;
  1579. WHILE i <= 42 DO
  1580. IF kName [i] [0] # 0C THEN
  1581. IF NameEq (wrd, kName [i]) THEN
  1582. RETURN kTk [i]
  1583. END
  1584. END ;
  1585. INC (i)
  1586. END ;
  1587. RETURN TkNone
  1588. END WddTok ;
  1589. PROCEDURE DeclaresProc () : BOOLEAN ;
  1590. (* Does the REST of the source declare a PROCEDURE or a FUNCTION?
  1591. Needed because the declaration part is compiled BEFORE the main statement
  1592. part, so a procedure's code lands between the program prologue and the
  1593. main body - and nothing jumps over it. A program with a procedure
  1594. therefore ran off the end of the prologue, straight into the first
  1595. procedure, which read its argument out of an uninitialised frame and
  1596. returned to address 0. Every Pascal program containing a procedure was
  1597. broken; `t13_proc` compiled and was never executed, so nothing saw it.
  1598. The jump that fixes it has to be emitted BEFORE the declaration part, but
  1599. whether one is needed is only known AFTER - so the only honest options are
  1600. to emit it unconditionally (3 dead bytes in every program, and every code
  1601. size in expected.tsv moves) or to know the answer in advance. This is the
  1602. second: it scans ahead and puts srcPos back.
  1603. That is safe because the whole program is already in `src` and `srcPos` is
  1604. a plain index into it - the same trick PeekKw and KwAhead use. The scan
  1605. looks for the keywords anywhere in the remainder rather than tracking the
  1606. nesting of `begin`s, which is deliberately loose: a program with no
  1607. procedures that merely mentions the word in a string literal would get a
  1608. 3-byte jump to the next instruction, which is harmless, whereas tracking
  1609. the main `begin` against a procedure's `begin` would be a second parser
  1610. to get wrong. *)
  1611. VAR save : CARDINAL ;
  1612. found : BOOLEAN ;
  1613. tk : CARDINAL ;
  1614. ch : CHAR ;
  1615. BEGIN
  1616. save := srcPos ;
  1617. found := FALSE ;
  1618. tk := TkNone ; (* so the answer is defined if src is empty *)
  1619. (* Step over delimiters as well as blanks. Stopping at the first
  1620. non-letter looked reasonable and was wrong: `var x : integer ;` is full
  1621. of ':' and ';', so the scan gave up inside the variable section and
  1622. never reached the PROCEDURE. The loop ends at the end of the source,
  1623. not at the first punctuation. *)
  1624. WHILE (NOT found) AND (srcPos < srcLen) DO
  1625. Skip () ;
  1626. IF Alpha (CurCh ()) THEN
  1627. GetWord () ;
  1628. tk := WddTok () ;
  1629. IF (tk = TkProcedure) OR (tk = TkFunction) THEN
  1630. found := TRUE
  1631. END
  1632. ELSE
  1633. ch := GetCh () (* a ':' or ';' - step over it *)
  1634. END
  1635. END ;
  1636. srcPos := save ;
  1637. RETURN (tk = TkProcedure) OR (tk = TkFunction)
  1638. END DeclaresProc ;
  1639. PROCEDURE KwAhead (word : ARRAY OF CHAR) : BOOLEAN ;
  1640. (* does the next token (past blanks/comments) equal the keyword 'word',
  1641. without consuming it? srcPos is saved and restored. *)
  1642. VAR save : CARDINAL ;
  1643. k : BOOLEAN ;
  1644. BEGIN
  1645. save := srcPos ;
  1646. Skip () ;
  1647. k := FALSE ;
  1648. IF Alpha (CurCh ()) THEN
  1649. GetWord () ;
  1650. k := NameEq (wrd, word)
  1651. END ;
  1652. srcPos := save ;
  1653. RETURN k
  1654. END KwAhead ;
  1655. PROCEDURE PeekKw (VAR tok : CARDINAL) ;
  1656. (* peek at the next keyword token without consuming it *)
  1657. VAR i : CARDINAL ;
  1658. BEGIN
  1659. tok := TkNone ;
  1660. i := 1 ;
  1661. WHILE i <= 42 DO
  1662. IF kName [i] [0] # 0C THEN
  1663. IF KwAhead (kName [i]) THEN
  1664. tok := kTk [i] ;
  1665. RETURN
  1666. END
  1667. END ;
  1668. INC (i)
  1669. END
  1670. END PeekKw ;
  1671. PROCEDURE MatchKey (VAR tok : CARDINAL) : BOOLEAN ;
  1672. (* skip; if next symbol is a word, read it into wrd and set its token.
  1673. Returns TRUE when a word was read (tok = TkNone for plain ids). *)
  1674. BEGIN
  1675. tok := TkNone ;
  1676. Skip () ;
  1677. IF NOT Alpha (CurCh ()) THEN
  1678. RETURN FALSE
  1679. END ;
  1680. GetWord () ;
  1681. tok := WddTok () ;
  1682. RETURN TRUE
  1683. END MatchKey ;
  1684. PROCEDURE MatchDelim (ch : CHAR) : BOOLEAN ;
  1685. BEGIN
  1686. Skip () ;
  1687. IF CurCh () = ch THEN
  1688. DropCh (GetCh ()) ;
  1689. RETURN TRUE
  1690. END ;
  1691. RETURN FALSE
  1692. END MatchDelim ;
  1693. PROCEDURE MatchAssign () : BOOLEAN ;
  1694. BEGIN
  1695. Skip () ;
  1696. IF (CurCh () = ':') AND (PeekAhead (1) = '=') THEN
  1697. DropCh (GetCh ()) ;
  1698. DropCh (GetCh ()) ;
  1699. RETURN TRUE
  1700. END ;
  1701. RETURN FALSE
  1702. END MatchAssign ;
  1703. PROCEDURE MatchRange () : BOOLEAN ;
  1704. BEGIN
  1705. Skip () ;
  1706. IF (CurCh () = '.') AND (PeekAhead (1) = '.') THEN
  1707. DropCh (GetCh ()) ;
  1708. DropCh (GetCh ()) ;
  1709. RETURN TRUE
  1710. END ;
  1711. RETURN FALSE
  1712. END MatchRange ;
  1713. PROCEDURE ExpectDelim (ch : CHAR ; n : CARDINAL) ;
  1714. BEGIN
  1715. Skip () ;
  1716. IF CurCh () = ch THEN
  1717. DropCh (GetCh ())
  1718. ELSE
  1719. Err (n)
  1720. END
  1721. END ExpectDelim ;
  1722. PROCEDURE HexVal (ch : CHAR) : CARDINAL ;
  1723. BEGIN
  1724. IF (ch >= '0') AND (ch <= '9') THEN
  1725. RETURN ORD (ch) - ORD ('0')
  1726. ELSIF (ch >= 'A') AND (ch <= 'F') THEN
  1727. RETURN ORD (ch) - ORD ('A') + 10
  1728. END ;
  1729. RETURN ORD (ch) - ORD ('a') + 10
  1730. END HexVal ;
  1731. PROCEDURE RdIntConst (VAR v : LONGINT) ;
  1732. (* bare integer constant; current char is digit or '$' *)
  1733. VAR acc : LONGINT ;
  1734. BEGIN
  1735. acc := 0 ;
  1736. IF CurCh () = '$' THEN
  1737. DropCh (GetCh ()) ;
  1738. WHILE IsHexCh (CurCh ()) DO
  1739. acc := acc * 16 + VAL (LONGINT, HexVal (CurCh ())) ;
  1740. DropCh (GetCh ())
  1741. END
  1742. ELSE
  1743. WHILE Digit (CurCh ()) DO
  1744. acc := acc * 10 + VAL (LONGINT, ORD (CurCh ()) - ORD ('0')) ;
  1745. DropCh (GetCh ())
  1746. END
  1747. END ;
  1748. v := acc
  1749. END RdIntConst ;
  1750. PROCEDURE StrNew (first : CARDINAL ; hasFirst : BOOLEAN ) : CARDINAL ;
  1751. (* Open a pool slot for a string literal, optionally pre-seeded with its
  1752. first character.
  1753. RdConst has to read the first character before it can tell a one-character
  1754. literal from a longer one - the "is the next character another quote?"
  1755. test only makes sense once something has been read - so the seeding has to
  1756. happen here and has to advance strTop. Leaving strTop alone and letting the
  1757. caller write the character by hand is a trap: strTop is the next FREE byte,
  1758. so the first StrPut lands on top of the seeded character and overwrites it.
  1759. (That bug shipped the literal 'hi' as 69 00 - 'i' then NUL.) *)
  1760. VAR x : CARDINAL ;
  1761. BEGIN
  1762. IF strCnt > HIGH (strOff) THEN
  1763. Err (ECompOvf) ; (* too many literals in one unit *)
  1764. RETURN 0
  1765. END ;
  1766. x := strCnt ;
  1767. strOff [x] := strTop ;
  1768. strLen [x] := 0 ;
  1769. INC (strCnt) ;
  1770. IF hasFirst THEN
  1771. strPool [strTop] := CHR (first) ;
  1772. INC (strTop) ;
  1773. strLen [x] := 1
  1774. END ;
  1775. rdStrX := x ;
  1776. RETURN x
  1777. END StrNew ;
  1778. PROCEDURE StrPut (x : CARDINAL ) ;
  1779. (* append the current source character to pool slot x *)
  1780. BEGIN
  1781. IF x > HIGH (strOff) THEN
  1782. RETURN
  1783. END ;
  1784. IF strTop > HIGH (strPool) THEN
  1785. Err (ECompOvf) ; (* literal longer than the pool *)
  1786. RETURN
  1787. END ;
  1788. strPool [strTop] := CurCh () ;
  1789. INC (strTop) ;
  1790. INC (strLen [x])
  1791. END StrPut ;
  1792. PROCEDURE RdConst (VAR v : LONGINT ; VAR cls : CARDINAL ;
  1793. VAR isStr : BOOLEAN) ;
  1794. (* scalar or string constant. A string literal's text is collected into the
  1795. pool and its slot index left in rdStrX; a single-character literal stays a
  1796. TScalar holding its character code, which is what "c := 'a'" wants. *)
  1797. CONST q = AposC ;
  1798. VAR ch : CHAR ;
  1799. idx : CARDINAL ;
  1800. BEGIN
  1801. isStr := FALSE ;
  1802. cls := TScalar ;
  1803. v := 0 ;
  1804. Skip () ;
  1805. IF CurCh () = '$' THEN
  1806. RdIntConst (v) ;
  1807. cls := TScalar
  1808. ELSIF Digit (CurCh ()) THEN
  1809. RdIntConst (v) ;
  1810. IF (CurCh () = '.') AND (Digit (PeekAhead (1))) THEN
  1811. cls := TReal ;
  1812. DropCh (GetCh ())
  1813. END ;
  1814. IF (CurCh () = 'E') OR (CurCh () = 'e') THEN
  1815. cls := TReal ;
  1816. DropCh (GetCh ())
  1817. END ;
  1818. IF cls = TReal THEN
  1819. WHILE AlphaNum (CurCh ()) OR (CurCh () = '.') OR (CurCh () = '-')
  1820. OR (CurCh () = '+') DO
  1821. DropCh (GetCh ())
  1822. END
  1823. END
  1824. ELSIF CurCh () = '^' THEN
  1825. (* TP3 caret character constant, unquoted: ^M is CR (13), ^[ is ESC
  1826. (27), ^@ is 0. The value is the upper-cased character minus 64, so
  1827. the +256-MOD-256 keeps ^@ and any control character from wrapping. *)
  1828. DropCh (GetCh ()) ;
  1829. IF CurCh () = 0C THEN
  1830. Err (EUnknown)
  1831. ELSE
  1832. ch := Upper (GetCh ()) ;
  1833. v := VAL (LONGINT, (ORD (ch) + 256 - 64) MOD 256) ;
  1834. cls := TScalar
  1835. END
  1836. ELSIF CurCh () = '#' THEN
  1837. (* TP3 decimal character constant: #27, #255. *)
  1838. DropCh (GetCh ()) ;
  1839. IF Digit (CurCh ()) THEN
  1840. RdIntConst (v) ;
  1841. cls := TScalar
  1842. ELSE
  1843. Err (EUnknown)
  1844. END
  1845. ELSIF Alpha (CurCh ()) THEN
  1846. (* TRUE / FALSE, or a NAMED constant - an enumerator (`[Constant,
  1847. Formula]'), or any earlier const. A constant expression may name a
  1848. constant, and set literals and `case' labels are full of enumerators. *)
  1849. GetWord () ;
  1850. IF NameEq (wrd, "TRUE") THEN
  1851. v := 1 ;
  1852. cls := TBool
  1853. ELSIF NameEq (wrd, "FALSE") THEN
  1854. v := 0 ;
  1855. cls := TBool
  1856. ELSIF Search (wrd, idx) AND (symtab [idx].tag = KConst) THEN
  1857. v := symtab [idx].lval ;
  1858. cls := symtab [idx].cls
  1859. ELSE
  1860. Err (EUnknown)
  1861. END
  1862. ELSIF ORD (CurCh ()) = q THEN
  1863. DropCh (GetCh ()) ;
  1864. IF ORD (CurCh ()) = q THEN
  1865. (* '' - the empty string. It used to be reported as the scalar 39,
  1866. so writeln('') printed a single quote mark. It is a string of
  1867. length zero, and an inline zero-length literal is exactly what the
  1868. runtime's JCXZ path is for. *)
  1869. DropCh (GetCh ()) ;
  1870. isStr := TRUE ;
  1871. cls := TString ;
  1872. v := 0 ;
  1873. rdStrX := StrNew (0, FALSE)
  1874. ELSIF (CurCh () = 0C) OR ((ORD (CurCh ()) = 0DH)) OR ((ORD (CurCh ()) = 0AH)) THEN
  1875. Err (EUnknown)
  1876. ELSE
  1877. v := VAL (LONGINT, ORD (GetCh ())) ;
  1878. cls := TScalar ;
  1879. IF ORD (CurCh ()) = q THEN
  1880. DropCh (GetCh ())
  1881. ELSE
  1882. isStr := TRUE ;
  1883. cls := TString ;
  1884. (* Scan to the closing quote. NB: the loop condition must test
  1885. the CURRENT character and only the current character. The
  1886. obvious-looking "while CurCh # quote" with a
  1887. "if PeekAhead(1) = quote then consume two" body is wrong:
  1888. consuming the quote moves the cursor past it, so the next
  1889. condition test sees the character AFTER the literal, is
  1890. satisfied, and the scan runs on to end-of-buffer - which
  1891. silently eats the rest of the program and makes every later
  1892. error point at end-of-file. Stop on the quote itself, and
  1893. treat a doubled quote as one embedded quote character.
  1894. The first character is already gone - it was read into v above -
  1895. so the pool slot is pre-seeded with it. *)
  1896. rdStrX := StrNew (VAL (CARDINAL, v), TRUE) ;
  1897. LOOP
  1898. IF ORD (CurCh ()) = q THEN
  1899. IF ORD (PeekAhead (1)) = q THEN
  1900. StrPut (rdStrX) ; (* '' inside *)
  1901. DropCh (GetCh ()) ; DropCh (GetCh ())
  1902. ELSE
  1903. EXIT (* closing quote *)
  1904. END
  1905. ELSIF (CurCh () = 0C) OR (ORD (CurCh ()) = 0DH) THEN
  1906. Err (EUnknown) ; (* unterminated *)
  1907. EXIT
  1908. ELSE
  1909. StrPut (rdStrX) ;
  1910. DropCh (GetCh ())
  1911. END
  1912. END ;
  1913. IF ORD (CurCh ()) = q THEN
  1914. DropCh (GetCh ())
  1915. END
  1916. END
  1917. END
  1918. ELSE
  1919. Err (EUnknown)
  1920. END
  1921. END RdConst ;
  1922. (* ---------------------------------------------------------------- *)
  1923. (* forward declarations *)
  1924. (* ---------------------------------------------------------------- *)
  1925. PROCEDURE ParseExpr (VAR r : ERes) ; FORWARD ;
  1926. PROCEDURE ParseAdd (VAR r : ERes) ; FORWARD ;
  1927. PROCEDURE ParseMul (VAR r : ERes) ; FORWARD ;
  1928. PROCEDURE ParseNeg (VAR r : ERes) ; FORWARD ;
  1929. PROCEDURE ParseAtom (VAR r : ERes) ; FORWARD ;
  1930. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ; FORWARD ;
  1931. PROCEDURE Statmnt () ; FORWARD ;
  1932. PROCEDURE ParseCall (idx : CARDINAL) ; FORWARD ;
  1933. PROCEDURE ParseCallArgs (idx : CARDINAL) ; FORWARD ;
  1934. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ; FORWARD ;
  1935. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ; FORWARD ;
  1936. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ; FORWARD ;
  1937. (* ---------------------------------------------------------------- *)
  1938. (* expressions (TPSRC9) *)
  1939. (* ---------------------------------------------------------------- *)
  1940. PROCEDURE VarSize (r : ERes) : CARDINAL ;
  1941. (* The width of a kind-1 value. An element (`b[i]') or a field (`r.f') has a
  1942. size of its own, which is NOT its variable's; when the parser has recorded
  1943. one, it wins. Otherwise the variable's declared size is the answer. *)
  1944. BEGIN
  1945. IF r.sz > 0 THEN
  1946. RETURN r.sz
  1947. END ;
  1948. RETURN symtab [r.idx].size
  1949. END VarSize ;
  1950. PROCEDURE LoadAtom (VAR r : ERes) ;
  1951. (* load value of r into AX (folding constants).
  1952. A string literal is refused here, and this is the single place that has to:
  1953. assignment, IF, WHILE, FOR, REPEAT, CASE, array subscripts and every
  1954. operator all reach their operand through LoadAtom, and none of them can use
  1955. a counted string where a 16-bit word is expected. Reporting it here rather
  1956. than in the parser means writeln('hi') still works - IoCall handles a
  1957. literal before it ever calls LoadAtom. *)
  1958. VAR emsz : CARDINAL ;
  1959. BEGIN
  1960. IF r.cls = TString THEN
  1961. Err (ENoLib) ; (* string value used as a number *)
  1962. r.kind := 2 ;
  1963. RETURN
  1964. END ;
  1965. IF r.cls = TSet THEN
  1966. (* A set is bytes, not a 16-bit value. It is legal as the right operand
  1967. of `in' (and later as a whole-value operand of `+'/`*'/'='/assignment),
  1968. all of which handle it BEFORE LoadAtom - but never as a number, which
  1969. would otherwise load its first two bytes as if it were an integer. *)
  1970. Err (ENoLib) ;
  1971. r.kind := 2 ;
  1972. RETURN
  1973. END ;
  1974. IF r.kind = 5 THEN
  1975. (* An element whose address ParseSub computed into DI (LEA DI,[base] /
  1976. ADD DI,AX): a string character, or an array element of one or two
  1977. bytes. Zeroing AH keeps a one-byte value a clean 16-bit char. The
  1978. read must happen HERE, before anything else is emitted: the caller
  1979. reaches this immediately after parsing the subscript, or - for a
  1980. binary operator - SaveLeft has already materialised it, so DI is
  1981. still the element's address. *)
  1982. IF VarSize (r) > 2 THEN
  1983. Err (ENoLib) ; (* a whole record/array as a value *)
  1984. r.kind := 2 ;
  1985. RETURN
  1986. END ;
  1987. IF VarSize (r) = 2 THEN
  1988. EmLdAxDi ()
  1989. ELSE
  1990. EmLdAlDi () ;
  1991. EmMovAh0 ()
  1992. END ;
  1993. r.kind := 2 ;
  1994. RETURN
  1995. END ;
  1996. IF r.kind = 0 THEN
  1997. EmMovAxi (W16 (r.imm)) ;
  1998. r.kind := 2
  1999. ELSIF r.kind = 1 THEN
  2000. IF symtab [r.idx].isVar THEN
  2001. (* A VAR parameter: [BP+off] holds the address, and the value is one
  2002. level down. r.boff is necessarily 0 - a by-reference parameter is
  2003. a scalar in this increment, so it has nothing to subscript. *)
  2004. IF r.boff # 0 THEN
  2005. Err (ENoLib) ;
  2006. r.kind := 2 ;
  2007. RETURN
  2008. END ;
  2009. EmLoadVarInd (symtab [r.idx].off, VarSize (r)) ;
  2010. r.kind := 2 ;
  2011. RETURN
  2012. END ;
  2013. IF (VarSize (r) > 2) AND NOT
  2014. ((r.cls = TChar) AND (symtab [r.idx].cls = TString)) THEN
  2015. Err (ENoLib)
  2016. ELSE
  2017. (* s[i] indexes one byte of a string, not the string, so its width is
  2018. one whatever the variable's declared width is. *)
  2019. emsz := VarSize (r) ;
  2020. IF (r.cls = TChar) AND (symtab [r.idx].cls = TString) THEN
  2021. emsz := 1
  2022. END ;
  2023. EmLoadVar (symtab [r.idx].local,
  2024. (symtab [r.idx].off + r.boff) MOD 10000H,
  2025. emsz) ;
  2026. IF emsz = 1 THEN
  2027. EmMovAh0 ()
  2028. END ;
  2029. r.kind := 2
  2030. END
  2031. END
  2032. END LoadAtom ;
  2033. PROCEDURE ParseSub (VAR r : ERes) ;
  2034. (* consume '[' expr ']' while present.
  2035. A CONSTANT index folds into the base offset boff, exactly as before. A
  2036. VARIABLE index on a STRING cannot fold - off+i is a run-time value - so it
  2037. is computed once here into DI and r.kind drops to 5, which is how LoadAtom,
  2038. Assignment and IoCall are told the element's address is in DI. Arrays
  2039. still accept only a constant index: a variable array subscript needs the
  2040. element-size scaling that a one-byte string element does not, and it is
  2041. item 2. *)
  2042. VAR t : ERes ;
  2043. ai, fi : CARDINAL ;
  2044. found : BOOLEAN ;
  2045. BEGIN
  2046. LOOP
  2047. Skip () ;
  2048. IF CurCh () = '.' THEN
  2049. (* FIELD selection: `r.f'. The field's offset adds to the record
  2050. base's, and the value's class and WIDTH become the field's - which
  2051. is the whole reason a width rides on the expression (VarSize). *)
  2052. IF r.kind = 5 THEN
  2053. (* the element is addressed through DI, not by idx+boff; its field
  2054. table would have to travel with the expression *)
  2055. Err (ENoLib) ;
  2056. RETURN
  2057. END ;
  2058. DropCh (GetCh ()) ;
  2059. Skip () ;
  2060. IF NOT Alpha (CurCh ()) THEN
  2061. Err (EUnknown) ;
  2062. RETURN
  2063. END ;
  2064. GetWord () ;
  2065. IF symtab [r.idx].fldFirst >= symtab [r.idx].fldLast THEN
  2066. Err (ESimpType) ; (* not a record *)
  2067. RETURN
  2068. END ;
  2069. fi := symtab [r.idx].fldFirst ;
  2070. found := FALSE ;
  2071. WHILE (fi < symtab [r.idx].fldLast) AND NOT found DO
  2072. IF NameEq (fields [fi].name, wrd) THEN
  2073. found := TRUE
  2074. ELSE
  2075. INC (fi)
  2076. END
  2077. END ;
  2078. IF NOT found THEN
  2079. Err (EUnknown) ;
  2080. RETURN
  2081. END ;
  2082. r.boff := W16 (VAL (LONGINT, r.boff)
  2083. + VAL (LONGINT, fields [fi].off)) ;
  2084. r.cls := fields [fi].cls ;
  2085. r.sz := fields [fi].size
  2086. ELSIF CurCh () = '[' THEN
  2087. DropCh (GetCh ()) ;
  2088. ParseExpr (t) ;
  2089. IF OK () THEN
  2090. IF symtab [r.idx].cls = TString THEN
  2091. (* s[i]: a STRING is a length byte at s[0] followed by the
  2092. characters, so index i selects the one byte at off+i. A second
  2093. subscript on a character is not a type. *)
  2094. IF r.cls = TChar THEN
  2095. Err (ESimpType) ;
  2096. RETURN
  2097. END ;
  2098. IF t.kind = 0 THEN
  2099. (* constant index: fold it into boff, as an array's does, and
  2100. r.cls drops to TChar so every consumer below - LoadAtom,
  2101. Assignment, IoCall - sees a one-byte value instead of the
  2102. whole string. *)
  2103. r.boff := W16 (VAL (LONGINT, r.boff) + t.imm)
  2104. ELSE
  2105. (* Variable index. Compute the element address once, now:
  2106. the index is evaluated into AX (LoadAtom is a no-op for a
  2107. kind-2 value and re-reads [DI] for a nested subscript), then
  2108. DI := base + AX. This is TP3's indstr/ialoop shape (TPSRC9
  2109. 1100-1111, 1200-1229), which likewise holds the address in
  2110. DI until the byte is loaded or stored; a register is what
  2111. lets a later LoadAtom read [DI] and a later assignment PUSH
  2112. DI across its right-hand side. *)
  2113. LoadAtom (t) ;
  2114. EmLeaDi (symtab [r.idx].local,
  2115. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  2116. EmAddDiAx () ;
  2117. r.kind := 5
  2118. END ;
  2119. r.cls := TChar ;
  2120. r.sz := 1
  2121. ELSIF symtab [r.idx].cls = TArray THEN
  2122. (* An array subscript. The element's address is
  2123. (index - lower bound) * element size from the array base, and
  2124. the value's width and class become the ELEMENT's - so a store
  2125. writes two bytes for an `array of Integer', not the whole
  2126. array. *)
  2127. IF symtab [r.idx].arrIdx = 0 THEN
  2128. Err (ESimpType) ;
  2129. RETURN
  2130. END ;
  2131. ai := symtab [r.idx].arrIdx - 1 ;
  2132. IF t.kind = 0 THEN
  2133. (* constant index: fold it into boff, as before *)
  2134. r.boff := W16 (VAL (LONGINT, r.boff)
  2135. + (t.imm - arrs [ai].lo [0])
  2136. * VAL (LONGINT, arrs [ai].elem)) ;
  2137. r.sz := arrs [ai].elem ;
  2138. r.cls := arrs [ai].ecls
  2139. ELSIF arrs [ai].n = 1 THEN
  2140. (* Run-time index, one dimension: AX := (i - lo) * elem,
  2141. then DI := base + AX. The element's address rides in DI
  2142. exactly as a string element's does, so LoadAtom,
  2143. Assignment, IoCall and SaveLeft already know the shape;
  2144. only the WIDTH is new (1 or 2 bytes, not always a char). *)
  2145. IF r.kind = 5 THEN
  2146. (* a second subscript on an element already addressed
  2147. through DI: 2-D run-time indexing is not implemented *)
  2148. Err (ENoLib) ;
  2149. RETURN
  2150. END ;
  2151. LoadAtom (t) ;
  2152. EmMovCxi (W16 (arrs [ai].lo [0])) ;
  2153. EmSubAxCx () ;
  2154. IF arrs [ai].elem # 1 THEN
  2155. EmMovCxi (arrs [ai].elem) ;
  2156. EmMulAxCx ()
  2157. END ;
  2158. EmLeaDi (symtab [r.idx].local,
  2159. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  2160. EmAddDiAx () ;
  2161. r.kind := 5 ;
  2162. r.sz := arrs [ai].elem ;
  2163. r.cls := arrs [ai].ecls
  2164. ELSE
  2165. (* two or more dimensions and a run-time index: the row
  2166. stride is (hi1 - lo1 + 1) * elem, which is the next
  2167. increment; loud, not a wrong address. *)
  2168. Err (ENoLib) ;
  2169. RETURN
  2170. END
  2171. ELSIF t.kind # 0 THEN
  2172. Err (ENoLib) ;
  2173. RETURN
  2174. ELSE
  2175. Err (ESimpType) ;
  2176. RETURN
  2177. END
  2178. END ;
  2179. ExpectDelim (']', ENoSemi)
  2180. ELSE
  2181. RETURN
  2182. END
  2183. END
  2184. END ParseSub ;
  2185. PROCEDURE ParseVar (VAR r : ERes) ;
  2186. (* name [ '[' constExpr ']' ]* ; a function name maps to its result var *)
  2187. VAR idx : CARDINAL ;
  2188. BEGIN
  2189. IF NOT Search (wrd, idx) THEN
  2190. Err (EUnknown) ;
  2191. RETURN
  2192. END ;
  2193. r.idx := idx ;
  2194. r.kind := 1 ;
  2195. r.boff := 0 ;
  2196. r.cls := symtab [idx].cls ;
  2197. IF symtab [idx].tag = KFunc THEN
  2198. idx := symtab [idx].resvar ;
  2199. r.idx := idx ;
  2200. r.cls := symtab [idx].cls
  2201. ELSIF (symtab [idx].tag # KVar) AND (symtab [idx].tag # KType) THEN
  2202. Err (EUnknown) ;
  2203. RETURN
  2204. END ;
  2205. IF r.cls = TSet THEN
  2206. (* a set value: carry where its bytes are so ParseCmp can fold `in' and
  2207. (later) compare. A set VARIABLE is still refused at its declaration,
  2208. so today this is a typed constant or an inline literal. *)
  2209. r.setoff := symtab [r.idx].off ;
  2210. r.setbase := symtab [r.idx].elem ;
  2211. r.setsize := symtab [r.idx].size
  2212. END ;
  2213. r.sz := symtab [r.idx].size ;
  2214. ParseSub (r)
  2215. END ParseVar ;
  2216. PROCEDURE ConstAdd (a, b : LONGINT) : LONGINT ;
  2217. BEGIN
  2218. RETURN VAL (LONGINT, W16 (a + b))
  2219. END ConstAdd ;
  2220. PROCEDURE ConstSub (a, b : LONGINT) : LONGINT ;
  2221. BEGIN
  2222. RETURN VAL (LONGINT, W16 (a - b))
  2223. END ConstSub ;
  2224. PROCEDURE ConstMul (a, b : LONGINT) : LONGINT ;
  2225. BEGIN
  2226. RETURN VAL (LONGINT, W16 (a * b))
  2227. END ConstMul ;
  2228. PROCEDURE EmXchgAxDx () ;
  2229. (* 92h = XCHG AX,DX. Named for what it EMITS, which is the point of the
  2230. whole naming convention: this used to be called EmMoveAxDx, which is what
  2231. somebody would expect the opcode to be, and it is not - 89 D8 is
  2232. MOV AX,DX, 92h is the exchange. Here the exchange is what is wanted, so
  2233. the name is the only thing that was wrong, and it was wrong in the exact
  2234. way this file's names are not allowed to be: reading as "a move" when it
  2235. is a swap. After EmIDivAxCx the remainder is in DX and `mod` wants it in
  2236. AX; an exchange gets it there in one byte where a move also would, so the
  2237. behaviour is identical either way and only the name lied. *)
  2238. BEGIN
  2239. Ebyte (92H)
  2240. END EmXchgAxDx ;
  2241. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ; FORWARD ;
  2242. PROCEDURE StrOperand (r : ERes) : BOOLEAN ; FORWARD ;
  2243. PROCEDURE BinOpEmit (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2244. (* binary operation at one precedence level; folds constant operands *)
  2245. VAR f : LONGINT ;
  2246. okc : BOOLEAN ;
  2247. BEGIN
  2248. IF StrOperand (left) OR StrOperand (right) THEN
  2249. (* A string OPERAND - a STRING or a CHAR, which is a one-character string
  2250. for this purpose - makes this a string operation, and `+' is the only
  2251. one ISO Modula-2 defines: every other binary operator reached here
  2252. (OR, and the multiplicative and additive numeric ops) has no meaning
  2253. over a STRING, and StrConcat rejects it.
  2254. The test is StrOperand and NOT `cls = TString' because of the two
  2255. CHAR operands. `'a' + 'b'' has no STRING in it at all, so a
  2256. TString-only test let it fall through to the integer path, where the
  2257. character codes were added and CHR(195) was printed - a silently
  2258. wrong program rather than an error (see t53_strcat_type). A CHAR
  2259. operand is still a string operand, which is also what makes `a + ch'
  2260. concatenate.
  2261. Handling it here, at the head of the one routine every binary
  2262. operator funnels through, is what keeps `a + b', `writeln(a + b)',
  2263. `(a + b) = c' and `s := a + b + c' all going through the same
  2264. emission. *)
  2265. StrConcat (op, left, right, res) ;
  2266. RETURN
  2267. END ;
  2268. IF op = TkAnd THEN
  2269. IF (left.kind = 0) AND (right.kind = 0) THEN
  2270. res.kind := 0 ;
  2271. res.imm := BitAnd (left.imm, right.imm) ;
  2272. res.cls := TBool ;
  2273. RETURN
  2274. END ;
  2275. LoadPair (left, right) ;
  2276. EmAndAxCx () ;
  2277. res.kind := 2 ; res.cls := TBool ;
  2278. RETURN
  2279. END ;
  2280. IF op = TkOr THEN
  2281. IF (left.kind = 0) AND (right.kind = 0) THEN
  2282. res.kind := 0 ;
  2283. res.imm := BitOr (left.imm, right.imm) ;
  2284. res.cls := TBool ;
  2285. RETURN
  2286. END ;
  2287. LoadPair (left, right) ;
  2288. EmOrAxCx () ;
  2289. res.kind := 2 ; res.cls := TBool ;
  2290. RETURN
  2291. END ;
  2292. IF (left.kind = 0) AND (right.kind = 0) THEN
  2293. okc := FALSE ;
  2294. CASE op OF
  2295. OpAdd : f := ConstAdd (left.imm, right.imm) ; okc := TRUE ;
  2296. | OpSub : f := ConstSub (left.imm, right.imm) ; okc := TRUE ;
  2297. | OpMul : f := ConstMul (left.imm, right.imm) ; okc := TRUE ;
  2298. | TkDiv : okc := (right.imm # 0) AND (right.imm > 0)
  2299. AND (left.imm >= 0) ;
  2300. IF okc THEN f := left.imm DIV right.imm END ;
  2301. | TkMod : okc := (right.imm # 0) AND (right.imm > 0)
  2302. AND (left.imm >= 0) ;
  2303. IF okc THEN f := left.imm MOD right.imm END ;
  2304. ELSE
  2305. okc := FALSE
  2306. END ;
  2307. IF okc THEN
  2308. res.kind := 0 ;
  2309. res.imm := VAL (LONGINT, W16 (f)) ;
  2310. res.cls := left.cls ;
  2311. RETURN
  2312. ELSIF op = TkDiv THEN
  2313. Err (EConstRange) ;
  2314. RETURN
  2315. END
  2316. END ;
  2317. LoadPair (left, right) ;
  2318. CASE op OF
  2319. OpAdd : EmAddAxCx ;
  2320. | OpSub : EmSubAxCx ;
  2321. | OpMul : EmMulAxCx ;
  2322. | TkDiv : EmIDivAxCx ;
  2323. | TkMod : EmIDivAxCx ; EmXchgAxDx ;
  2324. ELSE
  2325. Err (ETypeErr)
  2326. END ;
  2327. res.kind := 2 ;
  2328. res.cls := left.cls
  2329. END BinOpEmit ;
  2330. PROCEDURE ConstCmp (op : CARDINAL ; a, b : LONGINT ; VAR f : LONGINT)
  2331. : BOOLEAN ;
  2332. VAR a16, b16 : CARDINAL ;
  2333. BEGIN
  2334. a16 := W16 (a) ;
  2335. b16 := W16 (b) ;
  2336. f := 0 ;
  2337. CASE op OF
  2338. 1 : f := VAL (LONGINT, ORD (a16 = b16)) ;
  2339. | 2 : f := VAL (LONGINT, ORD (a16 # b16)) ;
  2340. | 3 : f := VAL (LONGINT, ORD (a16 < b16)) ;
  2341. | 4 : f := VAL (LONGINT, ORD (a16 >= b16)) ;
  2342. | 5 : f := VAL (LONGINT, ORD (a16 > b16)) ;
  2343. | 6 : f := VAL (LONGINT, ORD (a16 <= b16)) ;
  2344. ELSE
  2345. RETURN FALSE
  2346. END ;
  2347. RETURN TRUE
  2348. END ConstCmp ;
  2349. (* ---------------------------------------------------------------- *)
  2350. (* keeping an operand alive across the parse of the other one *)
  2351. (* ---------------------------------------------------------------- *)
  2352. PROCEDURE SaveLeft (VAR left : ERes) ;
  2353. (* Called the moment the operator has been recognised, i.e. *before* the
  2354. right-hand operand is parsed.
  2355. Every binary level in this parser has the shape
  2356. left := r ; ParseXxx (right) ; BinOpEmit (op, left, right, r) ;
  2357. so the right-hand operand's code is emitted between those two lines, and
  2358. the left-hand operand has to survive that. For kind 0 (a constant) and
  2359. kind 1 (a named variable) there is nothing to survive: LoadAtom re-emits
  2360. the MOV or the load at the operator site, and no code has been emitted
  2361. for the left yet. A kind-2 value is different - its code is already in
  2362. the image and its value exists only in AX, which the right-hand parse is
  2363. about to overwrite. The value had to be parked on the stack instead.
  2364. TPSRC9 does exactly this in the other order: addptr and mulptr CALL
  2365. pushres (which calls loadatom and sets flgpshax) *before* CALL mullevel,
  2366. so PUSH AX lands in the image ahead of the right-hand operand's code.
  2367. Without this, `(p > q) or (q > p)` emitted both comparisons and then
  2368. ORed the *second* comparison's result with itself - which is why it
  2369. printed FALSE for TRUE or FALSE. *)
  2370. BEGIN
  2371. IF left.kind = 2 THEN
  2372. EmPushAx () ;
  2373. left.kind := 4 (* 4 = on the top of the stack *)
  2374. ELSIF left.kind = 5 THEN
  2375. (* A string element whose address is in DI. This is the one place the
  2376. address must be spent BEFORE the right-hand operand is parsed: DI
  2377. cannot survive it, because the right operand may hold a subscript of
  2378. its own (which reuses DI) or call a routine (which may clobber it).
  2379. Reading [DI] now - which LoadAtom does, turning kind 5 into kind 2 -
  2380. and pushing the value is exactly what the kind-2 case above does
  2381. next, so the two branches converge on kind 4. A subscript on the
  2382. RIGHT is fine: it sets DI after this point and LoadPair reads it
  2383. immediately, with no parse in between. *)
  2384. LoadAtom (left) ; (* AL := [DI], AH := 0; kind := 2 *)
  2385. EmPushAx () ;
  2386. left.kind := 4
  2387. END
  2388. END SaveLeft ;
  2389. PROCEDURE LoadPair (VAR left, right : ERes) ;
  2390. (* Materialise both operands of a binary operator so that, once this
  2391. returns, AX holds the LEFT one and CX the RIGHT one - which is the state
  2392. EmAddAxCx/EmSubAxCx/EmMulAxCx/EmIDivAxCx/EmAndAxCx/EmOrAxCx/EmCmpAxCx
  2393. all expect (see EmXchgAxCx).
  2394. Three shapes, and only three:
  2395. left.kind = 4 SaveLeft pushed it before the right operand was
  2396. parsed, so the right value is in AX and the left one
  2397. is on the stack: load the right (a no-op for kind 2),
  2398. pop the left into CX, then swap.
  2399. right.kind = 2 The right value is in AX, and loading the left would
  2400. destroy it: push the right, load the left, then pop
  2401. the right straight into CX. No swap needed.
  2402. neither Both can still be materialised from scratch, and
  2403. neither is at risk, so this is the original sequence.
  2404. A kind-5 right-hand operand takes that last shape, and is safe there: the
  2405. only instruction emitted before its LoadAtom is the left's, and MOV AX,[var]
  2406. and MOV AX,imm do not touch DI, so [DI] still holds the element address.
  2407. Whichever shape is taken, exactly one push is matched by exactly one
  2408. pop. *)
  2409. BEGIN
  2410. IF left.kind = 4 THEN
  2411. LoadAtom (right) ;
  2412. EmPopCx () ;
  2413. EmXchgAxCx ()
  2414. ELSIF right.kind = 2 THEN
  2415. EmPushAx () ;
  2416. LoadAtom (left) ;
  2417. EmPopCx ()
  2418. ELSE
  2419. LoadAtom (left) ; EmPushAx () ;
  2420. LoadAtom (right) ; EmPopCx () ;
  2421. EmXchgAxCx ()
  2422. END
  2423. END LoadPair ;
  2424. PROCEDURE EmStrBlob (r : ERes) : CARDINAL ;
  2425. (* Emit a string literal's <len><chars> in the code stream behind a JMP and
  2426. return the image offset of the LENGTH byte. Shared by EmPushStrAddr (which
  2427. pushes that address) and EmPushStrSlot (which copies the bytes onto the
  2428. stack for a string value parameter). *)
  2429. VAR n, len, here : CARDINAL ;
  2430. BEGIN
  2431. len := strLen [r.strx] ;
  2432. IF len > 255 THEN
  2433. (* As in IoCall: the length is one byte, so a longer literal would wrap
  2434. and silently carry only its first (length MOD 256) characters.
  2435. TP3 strings are at most 255 characters. *)
  2436. Err (EConstRange) ;
  2437. RETURN 0
  2438. END ;
  2439. IF len + 1 <= 127 THEN
  2440. Ebyte (0EBH) ; Ebyte (VAL (BYTE, len + 1)) (* JMP rel8 over it *)
  2441. ELSE
  2442. Ebyte (0E9H) ; Eword (len + 1) (* JMP rel16 over it *)
  2443. END ;
  2444. here := pc ; (* the length byte: the literal's address *)
  2445. Ebyte (VAL (BYTE, len)) ;
  2446. n := 0 ;
  2447. WHILE n < len DO
  2448. Ebyte (VAL (BYTE, ORD (strPool [strOff [r.strx] + n]))) ;
  2449. INC (n)
  2450. END ;
  2451. RETURN here
  2452. END EmStrBlob ;
  2453. PROCEDURE EmPushStrAddr (r : ERes) ;
  2454. (* Push the ADDRESS of a whole-string operand - the argument shape cmpstr
  2455. takes, one per operand.
  2456. A string VARIABLE's value already is its address, so this is the same push
  2457. READ makes (EmPushVarAddr), through symtab's local/off.
  2458. A string LITERAL has no storage, and the image carries no initialised data
  2459. to put one in (globals are left to the loader's zero fill), so the
  2460. characters have to travel in the code stream and the operand is the address
  2461. of those bytes. TP3 does the same in TPSRC9 fullvar (993): it builds the
  2462. `JMP' opcode in AL and the length in AH (`MOV AL,#$EB' / `MOV.B AH,CH'),
  2463. emits that word, and takes the position immediately after it as varofs,
  2464. with varseg := CS - the instruction stream steps over the constant instead
  2465. of running into it.
  2466. The difference is one byte, and it is deliberate. TP3's constant is an
  2467. ARRAY [1..n] OF CHAR, and `estr2' (TPSRC10 85) emits it WITHOUT a length
  2468. byte because the length travelled on the stack instead. Every string in
  2469. THIS runtime - variable or literal - is a `string': a length byte and then
  2470. the characters, which is what rdstr writes and what cmpstr reads. So a
  2471. literal operand has to look the same, and the jump carries one extra byte:
  2472. <len><chars>, with the ADDRESS pushed being the length byte itself. The
  2473. jump still exists only to keep the CPU from walking into the characters.
  2474. Nothing is added to the data segment and no runtime entry is involved in
  2475. reading the literal; LEA AX,[that] is absolute into the code segment, which
  2476. is where a .COM's DS already is.
  2477. A 1-character literal is NOT a TString here: RdConst reports it as TScalar
  2478. (its character code), so `s = 'a'` compares a string with a character and
  2479. is a type error rather than a length-1 string compare. That is deliberate
  2480. - it is the same rule `c := 'a'` relies on - and the caller rejects it. *)
  2481. BEGIN
  2482. IF r.kind = 1 THEN
  2483. EmPushVarAddr (symtab [r.idx].local,
  2484. (symtab [r.idx].off + r.boff) MOD 10000H)
  2485. ELSIF r.kind = 3 THEN
  2486. EmPushVarAddr (FALSE, EmStrBlob (r)) (* the literal travels inline *)
  2487. ELSE
  2488. Err (ENoLib) (* a computed string is not a value *)
  2489. END
  2490. END EmPushStrAddr ;
  2491. PROCEDURE EmPushStrSlot (r : ERes ; reserve, copyN : CARDINAL) ;
  2492. (* Push a STRING VALUE argument's whole slot: reserve `reserve' bytes on the
  2493. stack and copy `copyN' of the source string's <len><chars> into them, so
  2494. that after the CALL the callee's BP+4 is the length byte and the characters
  2495. follow it.
  2496. <push the source address, then POP SI> ; local/global/literal alike
  2497. SUB SP,reserve ; MOV DI,SP ; MOV CX,copyN
  2498. loop: MOV AL,[SI] ; MOV [DI],AL ; INC SI ; INC DI ; LOOP loop
  2499. The address comes from EmPushStrAddr, which already knows how to form it for
  2500. a local ([BP+off]), a global (absolute) or a literal (inline blob) - so a
  2501. caller's LOCAL string can be passed too, not just a global.
  2502. A byte loop, not REP MOVSB, on purpose: MOVS/STOS address through ES, and a
  2503. .COM's ES happens to equal DS but nothing in this compiler establishes that
  2504. contract. Every access here is DS-relative, which is the one segment the
  2505. image already guarantees. `copyN' is at most `reserve' (a shorter actual
  2506. string than the formal leaves the tail of the slot untouched, harmless
  2507. because the length byte bounds every read). *)
  2508. BEGIN
  2509. EmPushStrAddr (r) ; (* push the source address *)
  2510. EmPopSi () ; (* SI := source *)
  2511. EmSubSp (reserve) ;
  2512. Ebyte (89H) ; Ebyte (0E7H) ; (* MOV DI,SP *)
  2513. EmMovCxi (copyN) ;
  2514. IF copyN > 0 THEN
  2515. Ebyte (8AH) ; Ebyte (04H) ; (* MOV AL,[SI] *)
  2516. Ebyte (88H) ; Ebyte (05H) ; (* MOV [DI],AL *)
  2517. Ebyte (46H) ; (* INC SI *)
  2518. Ebyte (47H) ; (* INC DI *)
  2519. Ebyte (0E2H) ; Ebyte (0F8H) (* LOOP -8: back to MOV AL,[SI] *)
  2520. END
  2521. END EmPushStrSlot ;
  2522. (* ---------------------------------------------------------------- *)
  2523. (* sets - type sizing, literals, compile-time membership *)
  2524. (* ---------------------------------------------------------------- *)
  2525. PROCEDURE SetRangeBits (VAR bytes : ARRAY OF CHAR ; size, base : CARDINAL ;
  2526. lo, hi : LONGINT) ;
  2527. (* Set the bits for every element in [lo, hi], using TP3's hybrid rule
  2528. (coeur-tp-ocr 4.7.2): element e is bit (e MOD 8) of byte
  2529. ((e DIV 8) - (base DIV 8)), and is IGNORED unless that byte is in
  2530. [0, size). A value that lands outside the used bytes is truncated away, as
  2531. TP3 does; one inside them but outside the DECLARED range still lands, which
  2532. is also TP3's behaviour. *)
  2533. VAR rel, first, last, bidx, bit, m, o : CARDINAL ;
  2534. BEGIN
  2535. IF (hi < 0) OR (lo > 255) THEN
  2536. RETURN
  2537. END ;
  2538. IF lo < 0 THEN first := 0 ELSE first := VAL (CARDINAL, lo) END ;
  2539. IF hi > 255 THEN last := 255 ELSE last := VAL (CARDINAL, hi) END ;
  2540. rel := first ;
  2541. WHILE rel <= last DO
  2542. IF rel >= base THEN
  2543. bidx := (rel - base) DIV 8 ;
  2544. IF bidx < size THEN
  2545. bit := (rel - base) MOD 8 ;
  2546. m := 1 ;
  2547. WHILE bit > 0 DO
  2548. m := m * 2 ; DEC (bit)
  2549. END ;
  2550. o := ORD (bytes [bidx]) ;
  2551. IF (o DIV m) MOD 2 = 0 THEN
  2552. bytes [bidx] := CHR (o + m)
  2553. END
  2554. END
  2555. END ;
  2556. INC (rel)
  2557. END
  2558. END SetRangeBits ;
  2559. PROCEDURE RdSetLiteral (base, size : CARDINAL ; VAR bytes : ARRAY OF CHAR) : BOOLEAN ;
  2560. (* Read a set constructor `[e, a..b, ...]' and fill `bytes' (already size
  2561. long). `[]' is the empty set. *)
  2562. VAR v, hi : LONGINT ; subcls : CARDINAL ; strf : BOOLEAN ; k : CARDINAL ;
  2563. BEGIN
  2564. k := 0 ;
  2565. WHILE k < size DO
  2566. bytes [k] := CHR (0) ;
  2567. INC (k)
  2568. END ;
  2569. ExpectDelim ('[', ENoSemi) ;
  2570. IF MatchDelim (']') THEN
  2571. RETURN OK () (* [] - the empty set *)
  2572. END ;
  2573. LOOP
  2574. RdConst (v, subcls, strf) ;
  2575. IF strf THEN
  2576. Err (ETypeErr) ;
  2577. RETURN FALSE
  2578. END ;
  2579. IF MatchRange () THEN
  2580. RdConst (hi, subcls, strf) ;
  2581. IF strf THEN
  2582. Err (ETypeErr) ;
  2583. RETURN FALSE
  2584. END
  2585. ELSE
  2586. hi := v
  2587. END ;
  2588. SetRangeBits (bytes, size, base, v, hi) ;
  2589. IF MatchDelim (',') THEN
  2590. (* another element *)
  2591. ELSE
  2592. EXIT
  2593. END
  2594. END ;
  2595. ExpectDelim (']', ENoSemi) ;
  2596. RETURN OK ()
  2597. END RdSetLiteral ;
  2598. PROCEDURE EmSetBlob (VAR bytes : ARRAY OF CHAR ; size : CARDINAL) : CARDINAL ;
  2599. (* Emit a set's bytes into the code stream behind a JMP over them - the same
  2600. trick EmPushStrAddr uses for a string literal - and return the image offset
  2601. of the first byte. Nothing goes in the data segment: a .COM's DS already
  2602. covers the code segment, which is why this port needs no `seg cs' where the
  2603. original did (see CALC-COMPILE.md's typed-constant storage decision). *)
  2604. VAR here, k : CARDINAL ;
  2605. BEGIN
  2606. IF size + 2 <= 127 THEN
  2607. Ebyte (0EBH) ; Ebyte (VAL (BYTE, size)) (* JMP rel8 over it *)
  2608. ELSE
  2609. Ebyte (0E9H) ; Eword (size) (* JMP rel16 over it *)
  2610. END ;
  2611. here := pc ;
  2612. k := 0 ;
  2613. WHILE k < size DO
  2614. Ebyte (VAL (BYTE, ORD (bytes [k]))) ;
  2615. INC (k)
  2616. END ;
  2617. RETURN here
  2618. END EmSetBlob ;
  2619. PROCEDURE FoldSetIn (left, right : ERes ; VAR res : ERes) ;
  2620. (* `e IN s' where e is a compile-time ordinal and s a set whose bytes are
  2621. already in the image: answer at compile time, exactly as TPSRC2's xsetin
  2622. answers at run time (AH > 255 -> FALSE, else test the bit). A run-time
  2623. element or a run-time set is still ENoLib - that is the next milestone, and
  2624. it must stay LOUD rather than silently answer wrong. *)
  2625. VAR off, base, size, rel, bidx, bit, m, o : CARDINAL ; isIn : BOOLEAN ;
  2626. BEGIN
  2627. res.kind := 0 ;
  2628. res.imm := 0 ;
  2629. res.cls := TBool ;
  2630. res.chr := FALSE ;
  2631. IF (left.kind # 0) OR (right.cls # TSet) THEN
  2632. Err (ENoLib) ;
  2633. RETURN
  2634. END ;
  2635. isIn := FALSE ;
  2636. IF (left.imm >= 0) AND (left.imm <= 255) THEN
  2637. off := right.setoff ; base := right.setbase ; size := right.setsize ;
  2638. rel := VAL (CARDINAL, left.imm) ;
  2639. IF rel >= base THEN
  2640. bidx := (rel - base) DIV 8 ;
  2641. IF bidx < size THEN
  2642. bit := (rel - base) MOD 8 ;
  2643. m := 1 ;
  2644. WHILE bit > 0 DO
  2645. m := m * 2 ; DEC (bit)
  2646. END ;
  2647. o := VAL (CARDINAL, cbuf [off + bidx]) ;
  2648. isIn := (o DIV m) MOD 2 # 0
  2649. END
  2650. END
  2651. END ;
  2652. res.imm := ORD (isIn)
  2653. END FoldSetIn ;
  2654. PROCEDURE RdSetBase (VAR baseCls : CARDINAL ; VAR lo, hi : LONGINT) ;
  2655. (* The base type of `set of ...': an ordinal range. `Char' and `byte' are
  2656. 0..255; a literal subrange `a..b' is read directly. A named or enumerated
  2657. base is ENoLib for now - `set of Attributes' waits for enums. *)
  2658. VAR idx, subcls : CARDINAL ; strf : BOOLEAN ;
  2659. BEGIN
  2660. baseCls := TScalar ;
  2661. Skip () ;
  2662. IF Alpha (CurCh ()) THEN
  2663. GetWord () ;
  2664. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  2665. IF symtab [idx].cls = TEnum THEN
  2666. lo := symtab [idx].lo ;
  2667. hi := symtab [idx].hi ;
  2668. baseCls := TEnum
  2669. ELSIF (symtab [idx].cls = TChar)
  2670. OR ((symtab [idx].cls = TScalar) AND (symtab [idx].size = 1)) THEN
  2671. lo := 0 ; hi := 255 ; baseCls := symtab [idx].cls
  2672. ELSE
  2673. Err (ENoLib)
  2674. END
  2675. ELSE
  2676. Err (EUnknown)
  2677. END
  2678. ELSE
  2679. RdConst (lo, subcls, strf) ;
  2680. IF NOT MatchRange () THEN
  2681. Err (ESimpType) ;
  2682. RETURN
  2683. END ;
  2684. RdConst (hi, subcls, strf) ;
  2685. IF (lo < 0) OR (hi > 255) OR (lo > hi) THEN
  2686. Err (EConstRange)
  2687. END
  2688. END
  2689. END RdSetBase ;
  2690. PROCEDURE NewScratchStr () : CARDINAL ;
  2691. (* Allocate a fresh 256-byte global STRING and return its symbol index.
  2692. A concatenation result needs STORAGE the emitted code can name. Making the
  2693. result a string VARIABLE (kind 1) is what keeps every downstream consumer
  2694. untouched: Assignment, IoCall and ParseCmp already handle kind 1, so `s :=
  2695. a + b', `writeln(a + b)' and `(a + b) = c' work with no code of their own.
  2696. One scratch PER `+' in the source, so a repeated or nested concatenation
  2697. never shares a destination - `a + b + c' is two occurrences and gets two
  2698. scratch strings, and the first result survives until the second consumes it.
  2699. (A loop reuses its site's scratch, which is correct because each execution
  2700. writes before it reads.) Recursion would break that, but this compiler
  2701. compiles no procedures yet - see the item list.
  2702. 256 bytes is the STRING type's own size, length byte plus 255 characters:
  2703. see ParseType's TkString arm and the predefined STRING in Inittur. The name
  2704. is a placeholder (nothing looks a scratch up by name) spelled with '@', as
  2705. tmpA/tmpB are, so it cannot collide with a Modula-2 identifier. *)
  2706. BEGIN
  2707. DropC (NewSym ("@@SC", KVar, TString, 256, 1, dc, 0, FALSE)) ;
  2708. dc := dc + 256 ;
  2709. RETURN symTop - 1
  2710. END NewScratchStr ;
  2711. PROCEDURE StrOperand (r : ERes) : BOOLEAN ;
  2712. (* Is r usable as one operand of `+'? A STRING, or a CHAR - which can appear
  2713. three ways: a quoted literal (cls TScalar with chr set), a CHAR variable
  2714. (cls TChar), and a string element s[i] (cls TChar, kind 5). A number is
  2715. not, and neither is a BOOLEAN. *)
  2716. BEGIN
  2717. RETURN (r.cls = TString) OR (r.cls = TChar) OR
  2718. ((r.cls = TScalar) AND r.chr)
  2719. END StrOperand ;
  2720. PROCEDURE EmPushStrOperand (r : ERes) ;
  2721. (* Push the ADDRESS of one concatenation operand, converting a CHAR to a
  2722. length-1 string first.
  2723. A STRING operand is pushed exactly as cmpstr pushes one (EmPushStrAddr):
  2724. a variable's value already IS its address, and a literal travels inline.
  2725. A CHAR operand has no such address, so it is materialised as a
  2726. `<length 1><character>' string in a fresh 2-byte scratch and the address of
  2727. THAT is pushed. This is TPSRC9's addch/addch2, which splice a character
  2728. into a concatenation by building a one-character string. The character is
  2729. loaded into AL (LoadAtom), the character is stored at [coff+1] and the
  2730. length 1 at [coff]. At most one operand of a concatenation is a CHAR -
  2731. StrConcat rejects char+char - so at most one such scratch is ever made. *)
  2732. VAR coff : CARDINAL ;
  2733. BEGIN
  2734. IF r.cls = TString THEN
  2735. EmPushStrAddr (r)
  2736. ELSE
  2737. coff := dc ;
  2738. dc := dc + 2 ;
  2739. LoadAtom (r) ; (* AX := the character *)
  2740. EmStoreVar (FALSE, (coff + 1) MOD 10000H, 1) ; (* [coff+1] := AL *)
  2741. EmMovAxi (1) ; (* AX := 1 *)
  2742. EmStoreVar (FALSE, coff MOD 10000H, 1) ; (* [coff] := AL = length *)
  2743. EmPushVarAddr (FALSE, coff MOD 10000H)
  2744. END
  2745. END EmPushStrOperand ;
  2746. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2747. (* `left + right' for strings: TPSRC2's xconcat, emitted as two runtime calls.
  2748. The layout is `<length byte><characters>' and `+' needs a place to build its
  2749. result, so this allocates one 256-byte global scratch (NewScratchStr) and
  2750. copies into it: first `dest := left' through the runtime's strstore, then
  2751. `dest := dest + right' through strcat, which appends. Using strstore for
  2752. the left operand and strcat for the right keeps the append logic in one
  2753. place and gives the compiler exactly one new entry to reach; it also means
  2754. the two calls have the same argument shape (source pushed first, destination
  2755. last, limit in CX), so the emission differs only in the entry named.
  2756. The limit is 255 - the scratch's 255 usable characters. An overflowing
  2757. result is a RUNTIME ERROR with exit code 16, TP3's `String too long', not a
  2758. truncation; see Runtime.EmitStrCat.
  2759. The operator rule: `+' concatenates, anything else over a STRING is a type
  2760. error, and char+char is ALSO a type error. ISO Modula-2 gives no meaning to
  2761. two characters summed, and inventing one (a two-character string?) would be
  2762. a guess this compiler does not make; TP3's own behaviour there is not
  2763. something the reference pins down. That char+char choice is the one place
  2764. this differs from a literal reading of the reference, and it is recorded
  2765. here and in v-TP3-STRCAT.md rather than left to be discovered.
  2766. The guard below is what ENFORCES that rule, and it only runs because
  2767. BinOpEmit's hook routes a CHAR operand here too. A hook that tested for a
  2768. STRING operand only would send `'a' + 'b'' to the integer path instead and
  2769. this test would never be reached - which is exactly what it did until
  2770. t53_strcat_type caught it. Three ways to fail it: a non-`+' operator over
  2771. a string operand, an operand that is neither a string nor a CHAR (a number),
  2772. and two CHARs with no STRING on either side. *)
  2773. VAR dest : CARDINAL ;
  2774. BEGIN
  2775. (* A placeholder for the paths below that bail out through Err. Err only
  2776. records the first error and does not unwind, so the caller goes on to use
  2777. res regardless: after `Err (ETypeErr)' in the guard, ParseAdd hands res
  2778. straight back to IoCall, to Assignment or to an enclosing concatenation.
  2779. The placeholder's SHAPE therefore matters. It must not claim to be a
  2780. STRING, because the string consumers reach symtab[res.idx] for any TString
  2781. (IoCall's `writeln' arm does) and idx is not a symbol here; and it must be
  2782. something LoadAtom can fold, because the numeric consumers will try. The
  2783. integer 0 is both. Leaving kind-2/TString here, as this once did, turned
  2784. `writeln('a' + 'b')' - two CHARs, a type error - into a compiler segfault
  2785. instead of an error message. *)
  2786. res.kind := 0 ;
  2787. res.imm := 0 ;
  2788. res.cls := TScalar ;
  2789. res.boff := 0 ;
  2790. res.chr := FALSE ;
  2791. IF (op # OpAdd) OR NOT StrOperand (left) OR NOT StrOperand (right) OR
  2792. ((left.cls # TString) AND (right.cls # TString)) THEN
  2793. Err (ETypeErr) ; (* a STRING on the wrong operator, a number,
  2794. or two CHARs *)
  2795. RETURN
  2796. END ;
  2797. dest := NewScratchStr () ;
  2798. (* dest := left *)
  2799. EmPushStrOperand (left) ;
  2800. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  2801. EmMovCxi (255) ;
  2802. DropC (EmCall (TU_StrStore)) ;
  2803. EmAddSp (4) ; (* pop the two addresses strstore took *)
  2804. (* dest := dest + right *)
  2805. EmPushStrOperand (right) ;
  2806. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  2807. EmMovCxi (255) ;
  2808. DropC (EmCall (TU_StrCat)) ;
  2809. EmAddSp (4) ;
  2810. res.kind := 1 ;
  2811. res.idx := dest ;
  2812. res.cls := TString ;
  2813. res.boff := 0 ;
  2814. res.chr := FALSE
  2815. END StrConcat ;
  2816. PROCEDURE ParseCmp (VAR r : ERes) ;
  2817. (* "=" | "<>" | "<" | "<=" | ">" | ">=" *)
  2818. VAR op : CARDINAL ;
  2819. left, right : ERes ;
  2820. f : LONGINT ;
  2821. BEGIN
  2822. ParseAdd (r) ;
  2823. LOOP
  2824. op := 0 ;
  2825. Skip () ;
  2826. IF CurCh () = '=' THEN
  2827. op := 1 ; DropCh (GetCh ())
  2828. ELSIF (CurCh () = '<') AND (PeekAhead (1) = '>') THEN
  2829. op := 2 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2830. ELSIF CurCh () = '<' THEN
  2831. IF PeekAhead (1) = '=' THEN
  2832. op := 6 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2833. ELSE
  2834. op := 3 ; DropCh (GetCh ())
  2835. END
  2836. ELSIF CurCh () = '>' THEN
  2837. IF PeekAhead (1) = '=' THEN
  2838. op := 5 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2839. ELSE
  2840. op := 4 ; DropCh (GetCh ())
  2841. END
  2842. END ;
  2843. IF op = 0 THEN
  2844. IF KwAhead ("IN") THEN
  2845. (* `e IN s' is at the comparison level in TP3 (TPSRC9 cmpin, 116).
  2846. Only the compile-time case is implemented; see FoldSetIn. *)
  2847. GetWord () ;
  2848. left := r ;
  2849. ParseAdd (right) ;
  2850. FoldSetIn (left, right, r) ;
  2851. RETURN
  2852. END ;
  2853. RETURN
  2854. END ;
  2855. left := r ;
  2856. SaveLeft (left) ;
  2857. ParseAdd (right) ;
  2858. IF (left.cls = TString) OR (right.cls = TString) THEN
  2859. (* A string comparison: cmpstr, the entry TPSRC9's vcompare (133)
  2860. reaches through TPSRC2's csteq/cstne/cstge/cstle/cstg/cstl
  2861. wrappers (890-925). It is intercepted BEFORE the constant-fold
  2862. arm, because a string literal is never a kind-0 constant and,
  2863. without this branch, both operands would fall through to LoadAtom,
  2864. which refuses a TString (ENoLib) - the symptom this arm cures.
  2865. cmpstr returns AX = -1/0/+1 (see Runtime.mod for why a value and
  2866. not flags), so the second half is exactly the numeric arm's: put
  2867. the sign in the flags and let the shared six-arm table answer.
  2868. EmOrAxAx is OR AX,AX rather than EmCmpAxi(0) on purpose: tests/
  2869. check_8086.py reads every `CMP AX,0000' in the program region as
  2870. an IF/WHILE/REPEAT test and requires a branch right after it, and
  2871. a comparison used as a VALUE (writeln(a = b)) is not one. *)
  2872. IF (left.cls # TString) OR (right.cls # TString) THEN
  2873. Err (ETypeErr) ; (* a string compared with a number/char *)
  2874. RETURN
  2875. END ;
  2876. EmPushStrAddr (left) ;
  2877. EmPushStrAddr (right) ;
  2878. DropC (EmCall (TU_CmpStr)) ;
  2879. EmAddSp (4) ;
  2880. EmOrAxAx () ;
  2881. EmRelSetcc (op) ;
  2882. r.kind := 2 ;
  2883. r.cls := TBool
  2884. ELSIF (left.kind = 0) AND (right.kind = 0) THEN
  2885. IF ConstCmp (op, left.imm, right.imm, f) THEN
  2886. r.kind := 0 ;
  2887. r.imm := f ;
  2888. r.cls := TBool
  2889. ELSE
  2890. r.kind := 0 ;
  2891. r.imm := 0 ;
  2892. r.cls := TBool
  2893. END
  2894. ELSE
  2895. LoadPair (left, right) ;
  2896. EmCmpAxCx () ;
  2897. EmRelSetcc (op) ;
  2898. r.kind := 2 ;
  2899. r.cls := TBool
  2900. END
  2901. END
  2902. END ParseCmp ;
  2903. PROCEDURE ParseAdd (VAR r : ERes) ;
  2904. VAR op : CARDINAL ;
  2905. left, right : ERes ;
  2906. BEGIN
  2907. ParseMul (r) ;
  2908. LOOP
  2909. op := 0 ;
  2910. Skip () ;
  2911. IF CurCh () = '+' THEN
  2912. op := OpAdd ; DropCh (GetCh ())
  2913. ELSIF CurCh () = '-' THEN
  2914. op := OpSub ; DropCh (GetCh ())
  2915. ELSIF KwAhead ("OR") THEN
  2916. GetWord () ;
  2917. op := TkOr
  2918. ELSE
  2919. RETURN
  2920. END ;
  2921. left := r ;
  2922. SaveLeft (left) ;
  2923. ParseMul (right) ;
  2924. BinOpEmit (op, left, right, r)
  2925. END
  2926. END ParseAdd ;
  2927. PROCEDURE ParseMul (VAR r : ERes) ;
  2928. VAR op : CARDINAL ;
  2929. left, right : ERes ;
  2930. BEGIN
  2931. ParseNeg (r) ;
  2932. LOOP
  2933. op := 0 ;
  2934. Skip () ;
  2935. IF CurCh () = '*' THEN
  2936. op := OpMul ; DropCh (GetCh ()) (* OpAdd here meant a*b -> a+b *)
  2937. ELSIF CurCh () = '/' THEN
  2938. op := 2 ; DropCh (GetCh ()) ; Err (ENoLib)
  2939. ELSIF KwAhead ("DIV") THEN
  2940. GetWord () ; op := TkDiv
  2941. ELSIF KwAhead ("MOD") THEN
  2942. GetWord () ; op := TkMod
  2943. ELSIF KwAhead ("AND") THEN
  2944. GetWord () ; op := TkAnd
  2945. ELSE
  2946. RETURN
  2947. END ;
  2948. IF op = 2 THEN
  2949. RETURN
  2950. END ;
  2951. left := r ;
  2952. SaveLeft (left) ;
  2953. ParseNeg (right) ;
  2954. BinOpEmit (op, left, right, r)
  2955. END
  2956. END ParseMul ;
  2957. PROCEDURE ParseNeg (VAR r : ERes) ;
  2958. BEGIN
  2959. Skip () ;
  2960. IF CurCh () = '+' THEN
  2961. DropCh (GetCh ()) ;
  2962. ParseNeg (r) ;
  2963. RETURN
  2964. ELSIF CurCh () = '-' THEN
  2965. DropCh (GetCh ()) ;
  2966. ParseNeg (r) ;
  2967. IF r.kind = 0 THEN
  2968. r.imm := VAL (LONGINT, W16 (0 - r.imm))
  2969. ELSE
  2970. LoadAtom (r) ;
  2971. EmNegAx () ;
  2972. r.kind := 2
  2973. END ;
  2974. RETURN
  2975. ELSIF KwAhead ("NOT") THEN
  2976. GetWord () ;
  2977. ParseNeg (r) ;
  2978. (* TPSRC9 neglevel branches on the operand's type before emitting
  2979. anything: CMP CL,#$0A (integer) -> NOT AX, CMP CL,#$0B (boolean)
  2980. -> XOR AL,#01, anything else -> error. This used to emit NOT AX
  2981. for both, so `not (a = a)' produced 0FFFEh and the runtime's
  2982. wrbool test ([BP+4] <> 0) read it as TRUE.
  2983. The integer constant fold stays: the 16 bits are the same either
  2984. way. A boolean constant must not go through BitNot - 0FFFFH-1 is
  2985. 0FFFEh, which wrbool also reads as TRUE - so it is loaded and
  2986. xor-ed, exactly as neglevel does it. *)
  2987. IF r.cls = TBool THEN
  2988. LoadAtom (r) ;
  2989. EmXorAl01 () ;
  2990. r.kind := 2
  2991. ELSIF r.cls = TScalar THEN
  2992. IF r.kind = 0 THEN
  2993. r.imm := BitNot (r.imm)
  2994. ELSE
  2995. LoadAtom (r) ;
  2996. EmNotAx () ;
  2997. r.kind := 2
  2998. END
  2999. ELSE
  3000. Err (ETypeErr)
  3001. END ;
  3002. RETURN
  3003. END ;
  3004. ParseAtom (r)
  3005. END ParseNeg ;
  3006. PROCEDURE ParseAtom (VAR r : ERes) ;
  3007. (* const | variable | func(params) | '(' expr ')' | '[' set ']' *)
  3008. VAR idx : CARDINAL ;
  3009. strf : BOOLEAN ;
  3010. quoted : BOOLEAN ;
  3011. ssize, sbase : CARDINAL ;
  3012. sbuf : ARRAY [0..31] OF CHAR ;
  3013. BEGIN
  3014. r.chr := FALSE ; (* default: not a quoted char literal *)
  3015. Skip () ;
  3016. IF CurCh () = '(' THEN
  3017. DropCh (GetCh ()) ;
  3018. ParseExpr (r) ;
  3019. ExpectDelim (')', ENoSemi) ;
  3020. RETURN
  3021. END ;
  3022. IF CurCh () = '[' THEN
  3023. (* An inline set literal. Full TP3 takes its type from context; here it
  3024. defaults to `set of Char' (0..255), which is what CALC writes
  3025. (`Ch in ['a'..'z']'), and its bytes are materialised in the code
  3026. stream. A typed/larger-base literal is a later milestone. *)
  3027. ssize := 32 ;
  3028. sbase := 0 ;
  3029. IF RdSetLiteral (sbase, ssize, sbuf) THEN
  3030. r.kind := 7 ;
  3031. r.cls := TSet ;
  3032. r.setoff := EmSetBlob (sbuf, ssize) ;
  3033. r.setbase := sbase ;
  3034. r.setsize := ssize
  3035. END ;
  3036. RETURN
  3037. END ;
  3038. IF (CurCh () = '$') OR (Digit (CurCh ())) OR (ORD (CurCh ()) = AposC)
  3039. OR (CurCh () = '^') OR (CurCh () = '#') THEN
  3040. (* remember that this was a quoted literal BEFORE RdConst consumes it:
  3041. RdConst reports a 1-character literal as TScalar (its char code),
  3042. which is right for "c := 'a'" but would make writeln('a') print 97.
  3043. Mark it so the writer picks the char entry, not the integer one. A
  3044. caret (^M) or decimal (#27) character constant is a character too. *)
  3045. quoted := (ORD (CurCh ()) = AposC) OR (CurCh () = '^')
  3046. OR (CurCh () = '#') ;
  3047. RdConst (r.imm, r.cls, strf) ;
  3048. r.chr := quoted AND (r.cls = TScalar) AND NOT strf ;
  3049. IF r.cls = TReal THEN
  3050. Err (ENoLib) ;
  3051. r.kind := 2 ;
  3052. RETURN
  3053. END ;
  3054. IF strf THEN
  3055. (* A string literal is legal here as a *value* - it is not rejected
  3056. at this point, because writeln('hi') needs it and IoCall is the
  3057. only place that knows how to emit one. Everywhere else the
  3058. literal has to end up as a machine word, and that is caught by
  3059. LoadAtom, which refuses a TString. *)
  3060. r.strx := rdStrX ;
  3061. r.kind := 3 ;
  3062. RETURN
  3063. END ;
  3064. r.kind := 0 ;
  3065. RETURN
  3066. END ;
  3067. IF NOT Alpha (CurCh ()) THEN
  3068. Err (EUnknown) ;
  3069. RETURN
  3070. END ;
  3071. GetWord () ;
  3072. IF NOT Search (wrd, idx) THEN
  3073. Err (EUnknown) ;
  3074. RETURN
  3075. END ;
  3076. IF symtab [idx].tag = KConst THEN
  3077. r.kind := 0 ;
  3078. r.imm := symtab [idx].lval ;
  3079. r.cls := symtab [idx].cls ;
  3080. RETURN
  3081. ELSIF symtab [idx].tag = KFunc THEN
  3082. ParseCall (idx) ;
  3083. r.kind := 2 ;
  3084. r.cls := symtab [idx].cls ;
  3085. RETURN
  3086. ELSIF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KType) THEN
  3087. (* ParseVar initialises boff to 0 and then ParseSub folds any constant
  3088. subscript into it. Do NOT reset boff here: doing so after ParseVar
  3089. returns threw away the subscript, so s[i] read/wrote off+0 (the
  3090. length byte) while still reporting itself as a char. This was
  3091. latent for arrays because an array cannot be declared yet, so no
  3092. fixture had ever exercised the fold. *)
  3093. ParseVar (r) ;
  3094. RETURN
  3095. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_KeyPressed) THEN
  3096. (* KeyPressed: a boolean FUNCTION with no argument, and TP3 lets it be
  3097. written without a parameter list (`until KeyPressed'). *)
  3098. EmCrtSeq (CrtKey) ;
  3099. r.kind := 2 ;
  3100. r.cls := TBool ;
  3101. r.chr := FALSE ;
  3102. RETURN
  3103. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_Length) THEN
  3104. (* LENGTH (s): the string's length byte, loaded inline. No runtime
  3105. entry, and no address is pushed - a string's value already carries its
  3106. length at [addr]. A literal is emitted inline (EmStrBlob) and the
  3107. byte is read from that image offset. *)
  3108. IF NOT MatchDelim ('(') THEN
  3109. Err (ENoSemi) ;
  3110. RETURN
  3111. END ;
  3112. ParseExpr (r) ;
  3113. ExpectDelim (')', ENoSemi) ;
  3114. IF NOT OK () THEN
  3115. RETURN
  3116. END ;
  3117. IF r.cls # TString THEN
  3118. Err (ETypeErr) ;
  3119. RETURN
  3120. END ;
  3121. IF r.kind = 1 THEN
  3122. EmLoadVar (symtab [r.idx].local,
  3123. (symtab [r.idx].off + r.boff) MOD 10000H, 1)
  3124. ELSIF r.kind = 3 THEN
  3125. EmLoadVar (FALSE, EmStrBlob (r), 1)
  3126. ELSE
  3127. Err (ENoLib) ;
  3128. RETURN
  3129. END ;
  3130. EmMovAh0 () ;
  3131. r.kind := 2 ;
  3132. r.cls := TScalar ;
  3133. r.chr := FALSE ;
  3134. RETURN
  3135. ELSE
  3136. Err (EUnknown)
  3137. END
  3138. END ParseAtom ;
  3139. PROCEDURE AddPend (kind, who, place : CARDINAL) ;
  3140. BEGIN
  3141. IF nPend < MaxPend THEN
  3142. pend [nPend].kind := kind ;
  3143. pend [nPend].who := who ;
  3144. pend [nPend].place := place ;
  3145. INC (nPend)
  3146. ELSE
  3147. Err (ECompOvf)
  3148. END
  3149. END AddPend ;
  3150. PROCEDURE ParmSlot (idx, k : CARDINAL) : CARDINAL ;
  3151. (* The stack slot of argument k (0-based) of procedure/function idx, from the
  3152. parameter list recorded on the symbol. Out of range means the source passed
  3153. more arguments than there are parameters: keep the old two-byte assumption
  3154. rather than inventing an arity error here. *)
  3155. VAR pi : CARDINAL ;
  3156. BEGIN
  3157. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3158. RETURN 2
  3159. END ;
  3160. pi := symtab [idx].parmFirst + k ;
  3161. RETURN ParamSlotBytes (symtab [pi])
  3162. END ParmSlot ;
  3163. PROCEDURE ParmIsVar (idx, k : CARDINAL) : BOOLEAN ;
  3164. (* Is argument k (0-based) of procedure/function idx declared VAR? Out of
  3165. range means the source passed more arguments than there are formals; treat
  3166. it as a value parameter, as ParmSlot already does. *)
  3167. VAR pi : CARDINAL ;
  3168. BEGIN
  3169. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3170. RETURN FALSE
  3171. END ;
  3172. pi := symtab [idx].parmFirst + k ;
  3173. RETURN symtab [pi].isVar
  3174. END ParmIsVar ;
  3175. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ;
  3176. (* emit the call to sym 'idx' and clean up `cleanup' bytes of arguments, which
  3177. is the SUM of their slot sizes - not 2 per argument once a slot can be
  3178. larger than a word. *)
  3179. VAR p : CARDINAL ;
  3180. BEGIN
  3181. IF symtab [idx].defnd THEN
  3182. DropC (EmCall (symtab [idx].goPos))
  3183. ELSE
  3184. p := EmCall (0) ;
  3185. AddPend (1, idx, p)
  3186. END ;
  3187. IF cleanup > 0 THEN
  3188. EmAddSp (cleanup)
  3189. END
  3190. END EmCallMost ;
  3191. PROCEDURE ParseCallArgs (idx : CARDINAL) ;
  3192. (* '(' already consumed: read args ')' then call.
  3193. Each argument is loaded and pushed the moment it has been parsed, which is
  3194. what TPSRC8 cproc/cprlp1/cprlp2 do - CALL exprsave, CALL epushax, one per
  3195. argument, then the CALL. A computed argument (kind 2) exists only in AX,
  3196. so parsing the argument after it would destroy it before the push loop
  3197. ever reached it: `p (a > b, x)' passed x twice.
  3198. Pushing in parse order is also the order the callee is laid out for: the
  3199. first argument goes on first and so ends up farthest from BP, and the LAST
  3200. declared parameter is the one at BP+4 (RESUME-TP3.md 3.11). *)
  3201. VAR arg : ERes ;
  3202. nArgs, cleanup, slot, nCopy : CARDINAL ;
  3203. BEGIN
  3204. nArgs := 0 ;
  3205. cleanup := 0 ;
  3206. IF CurCh () = ')' THEN
  3207. DropCh (GetCh ())
  3208. ELSE
  3209. LOOP
  3210. IF nArgs >= 16 THEN
  3211. Err (ECompOvf) ;
  3212. EXIT
  3213. END ;
  3214. ParseExpr (arg) ;
  3215. slot := ParmSlot (idx, nArgs) ;
  3216. IF ParmIsVar (idx, nArgs) THEN
  3217. (* VAR formal: push the actual's ADDRESS. Only a variable has
  3218. one; a constant or a computed value is refused rather than
  3219. quietly passed by value. An element with a constant index
  3220. (`s[i]') is a variable too: its address is off+boff, which
  3221. EmPushVarAddr forms directly. *)
  3222. IF arg.kind # 1 THEN
  3223. Err (ENoLib) ;
  3224. EXIT
  3225. END ;
  3226. IF symtab [arg.idx].isVar THEN
  3227. (* Passing a VAR parameter on: its slot already HOLDS the
  3228. address, so push that, not the address of the slot. *)
  3229. IF arg.boff # 0 THEN
  3230. Err (ENoLib) ;
  3231. EXIT
  3232. END ;
  3233. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  3234. EmPushAx ()
  3235. ELSE
  3236. EmPushVarAddr (symtab [arg.idx].local,
  3237. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  3238. END
  3239. ELSIF slot > 2 THEN
  3240. (* A STRING VALUE parameter: push its whole slot, copied.
  3241. `copyN' is at most the slot: an actual shorter than the formal
  3242. leaves the tail untouched, which is harmless because the length
  3243. byte bounds every read. *)
  3244. IF arg.cls # TString THEN
  3245. Err (ETypeErr) ;
  3246. EXIT
  3247. END ;
  3248. nCopy := slot ;
  3249. IF arg.kind = 1 THEN
  3250. IF VarSize (arg) < nCopy THEN
  3251. nCopy := VarSize (arg)
  3252. END
  3253. ELSIF arg.kind = 3 THEN
  3254. IF strLen [arg.strx] + 1 < nCopy THEN
  3255. nCopy := strLen [arg.strx] + 1
  3256. END
  3257. ELSE
  3258. Err (ENoLib) ; (* a computed string is not a value *)
  3259. EXIT
  3260. END ;
  3261. EmPushStrSlot (arg, slot, nCopy)
  3262. ELSE
  3263. LoadAtom (arg) ;
  3264. EmPushAx ()
  3265. END ;
  3266. cleanup := cleanup + slot ;
  3267. INC (nArgs) ;
  3268. IF NOT MatchDelim (',') THEN
  3269. EXIT
  3270. END
  3271. END ;
  3272. ExpectDelim (')', ENoSemi)
  3273. END ;
  3274. EmCallMost (idx, cleanup)
  3275. END ParseCallArgs ;
  3276. PROCEDURE ParseCall (idx : CARDINAL) ;
  3277. (* procedure/function call; '(' optional - same parse-then-push as above,
  3278. reached from ParseAtom when a FUNCTION is called in an expression *)
  3279. VAR arg : ERes ;
  3280. nArgs, cleanup, slot, nCopy : CARDINAL ;
  3281. BEGIN
  3282. nArgs := 0 ;
  3283. cleanup := 0 ;
  3284. IF MatchDelim ('(') THEN
  3285. IF CurCh () # ')' THEN
  3286. LOOP
  3287. IF nArgs >= 16 THEN
  3288. Err (ECompOvf) ;
  3289. EXIT
  3290. END ;
  3291. ParseExpr (arg) ;
  3292. slot := ParmSlot (idx, nArgs) ;
  3293. IF slot > 2 THEN
  3294. (* see ParseCallArgs: push the whole string slot *)
  3295. IF arg.cls # TString THEN
  3296. Err (ETypeErr) ;
  3297. EXIT
  3298. END ;
  3299. nCopy := slot ;
  3300. IF arg.kind = 1 THEN
  3301. IF VarSize (arg) < nCopy THEN
  3302. nCopy := VarSize (arg)
  3303. END
  3304. ELSIF arg.kind = 3 THEN
  3305. IF strLen [arg.strx] + 1 < nCopy THEN
  3306. nCopy := strLen [arg.strx] + 1
  3307. END
  3308. ELSE
  3309. Err (ENoLib) ;
  3310. EXIT
  3311. END ;
  3312. EmPushStrSlot (arg, slot, nCopy)
  3313. ELSE
  3314. LoadAtom (arg) ;
  3315. EmPushAx ()
  3316. END ;
  3317. cleanup := cleanup + slot ;
  3318. INC (nArgs) ;
  3319. IF NOT MatchDelim (',') THEN
  3320. EXIT
  3321. END
  3322. END ;
  3323. ExpectDelim (')', ENoSemi)
  3324. ELSE
  3325. DropCh (GetCh ())
  3326. END
  3327. END ;
  3328. EmCallMost (idx, cleanup)
  3329. END ParseCall ;
  3330. PROCEDURE ParseExpr (VAR r : ERes) ;
  3331. BEGIN
  3332. ParseCmp (r)
  3333. END ParseExpr ;
  3334. (* ---------------------------------------------------------------- *)
  3335. (* statements (TPSRC8) *)
  3336. (* ---------------------------------------------------------------- *)
  3337. PROCEDURE ParseLabelStmt () ;
  3338. (* numeric label definition 'n :' *)
  3339. VAR n : CARDINAL ;
  3340. nm : ARRAY [0..9] OF CHAR ;
  3341. idx : CARDINAL ;
  3342. i : CARDINAL ;
  3343. BEGIN
  3344. n := 0 ;
  3345. WHILE Digit (CurCh ()) DO
  3346. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  3347. DropCh (GetCh ())
  3348. END ;
  3349. ExpectDelim (':', ENoSemi) ;
  3350. NumToName (n, nm) ;
  3351. IF Search (nm, idx) THEN
  3352. IF symtab [idx].tag = KLabel THEN
  3353. symtab [idx].defnd := TRUE ;
  3354. symtab [idx].goPos := pc ;
  3355. i := 0 ;
  3356. WHILE i < nPend DO
  3357. IF (pend [i].kind = 0) AND (pend [i].who = idx) THEN
  3358. SetPatTgt (pend [i].place, pc) ;
  3359. pend [i].kind := 99
  3360. END ;
  3361. INC (i)
  3362. END
  3363. ELSE
  3364. Err (EUnknown)
  3365. END
  3366. ELSE
  3367. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  3368. symtab [idx].defnd := TRUE ;
  3369. symtab [idx].goPos := pc
  3370. END
  3371. END ParseLabelStmt ;
  3372. PROCEDURE Assignment (r : ERes) ;
  3373. (* ':=' already consumed by the caller; store expression into r *)
  3374. VAR src : ERes ;
  3375. k, n : CARDINAL ;
  3376. BEGIN
  3377. IF (r.kind # 1) AND (r.kind # 5) THEN
  3378. Err (EUnknown) ;
  3379. RETURN
  3380. END ;
  3381. IF (r.kind = 1) AND symtab [r.idx].isVar THEN
  3382. (* `varparam := expr': store through the address the slot holds. DI is
  3383. parked across the right-hand side because that expression may use DI
  3384. for a string element of its own. *)
  3385. IF r.boff # 0 THEN
  3386. Err (ENoLib) ;
  3387. RETURN
  3388. END ;
  3389. EmStoreVarIndPrep (symtab [r.idx].off) ;
  3390. ParseExpr (src) ;
  3391. LoadAtom (src) ;
  3392. EmPopDi () ;
  3393. EmStoreInd (VarSize (r)) ;
  3394. RETURN
  3395. END ;
  3396. IF (r.cls = TString) AND (VarSize (r) > 1) THEN
  3397. (* s := <string literal>. TPSRC8 asn2 sends a string through the scalar
  3398. store path, and estcpl's string arm emits `MOV CL,max_len' (max_len =
  3399. varsize-1) then `CALL strstore', which copies the source - length byte
  3400. and characters - into the destination and TRUNCATES a source longer
  3401. than max_len by rewriting the length byte (TPSRC2 strstore's
  3402. `CMP.B CL,AL / JBE stslenok / MOV.B [SI],AL'). Here the literal is
  3403. known at compile time, so its bytes become immediate stores instead of
  3404. a stack push and a block move. The variable that results is the same,
  3405. truncation included, and the tail past the new length is left as it
  3406. was, exactly as strstore leaves it. *)
  3407. ParseExpr (src) ;
  3408. IF (src.cls # TString) THEN
  3409. Err (ENoLib) ;
  3410. RETURN
  3411. END ;
  3412. IF src.kind # 3 THEN
  3413. (* s := <string variable>. TPSRC8 asnvar pushes the destination
  3414. address, then the expression (strload) pushes the source, and
  3415. estcpl emits MOV CL,max_len then CALL strstore, which copies
  3416. length byte + chars, TRUNCATING to max_len and leaving the
  3417. destination tail past the new length untouched. Here both
  3418. addresses are pushed - source first, so it sits at [BP+6] and the
  3419. destination at [BP+4] - the caller pops both, and the limit is a
  3420. full MOV CX,imm16 because this runtime reads it in CX outright. *)
  3421. IF src.kind # 1 THEN
  3422. Err (ENoLib) ; (* a computed string is not a value *)
  3423. RETURN
  3424. END ;
  3425. EmPushVarAddr (symtab [src.idx].local,
  3426. (symtab [src.idx].off + src.boff) MOD 10000H) ;
  3427. EmPushVarAddr (symtab [r.idx].local,
  3428. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  3429. EmMovCxi ((VarSize (r) - 1) MOD 10000H) ;
  3430. DropC (EmCall (TU_StrStore)) ;
  3431. EmAddSp (4) ;
  3432. RETURN
  3433. END ;
  3434. n := strLen [src.strx] ;
  3435. IF n > VarSize (r) - 1 THEN
  3436. n := VarSize (r) - 1
  3437. END ;
  3438. EmMovAxi (n) ;
  3439. EmStoreVar (symtab [r.idx].local,
  3440. (symtab [r.idx].off + r.boff) MOD 10000H, 1) ;
  3441. k := 0 ;
  3442. WHILE k < n DO
  3443. EmMovAxi (ORD (strPool [strOff [src.strx] + k])) ;
  3444. EmStoreVar (symtab [r.idx].local,
  3445. (symtab [r.idx].off + r.boff + 1 + k) MOD 10000H, 1) ;
  3446. INC (k)
  3447. END ;
  3448. RETURN
  3449. END ;
  3450. IF (r.kind = 5) OR (VarSize (r) > 2) THEN
  3451. IF r.kind = 5 THEN
  3452. (* An element addressed by DI: a string character (one byte) or an
  3453. array element (one or two). A wider element - a record - is
  3454. refused rather than stored as its first two bytes.
  3455. The destination address is in DI, and the right-hand side is
  3456. parsed next, so DI has to be saved first - the RHS may hold a
  3457. subscript of its own, which reuses DI, or call a routine that
  3458. clobbers it. This is TPSRC8 asnscal2/asnscal3 (758-760, 786-789),
  3459. which set flgpshdi around the expression for the same reason. *)
  3460. IF VarSize (r) > 2 THEN
  3461. Err (ENoLib) ;
  3462. RETURN
  3463. END ;
  3464. EmPushDi () ;
  3465. ParseExpr (src) ;
  3466. LoadAtom (src) ;
  3467. EmPopDi () ; (* DI := the destination again *)
  3468. EmStoreInd (VarSize (r)) ; (* [DI] := AL or AX *)
  3469. RETURN
  3470. END ;
  3471. (* A value wider than a word with no address to store through: an
  3472. assignment to a whole string/record/array is not a scalar store. *)
  3473. Err (ENoLib) ;
  3474. RETURN
  3475. END ;
  3476. ParseExpr (src) ;
  3477. LoadAtom (src) ;
  3478. EmStoreVar (symtab [r.idx].local,
  3479. (symtab [r.idx].off + r.boff) MOD 10000H,
  3480. VarSize (r))
  3481. END Assignment ;
  3482. PROCEDURE Compound () ;
  3483. (* BEGIN statement ';' ... END; END is consumed here *)
  3484. VAR tok : CARDINAL ;
  3485. BEGIN
  3486. LOOP
  3487. PeekKw (tok) ;
  3488. IF tok = TkEnd THEN
  3489. DropB (MatchKey (tok)) ;
  3490. RETURN
  3491. END ;
  3492. Statmnt () ;
  3493. IF NOT OK () THEN
  3494. RETURN
  3495. END ;
  3496. IF NOT MatchDelim (';') THEN
  3497. PeekKw (tok) ;
  3498. IF tok = TkEnd THEN
  3499. DropB (MatchKey (tok)) ;
  3500. RETURN
  3501. END ;
  3502. Err (ENoSemi) ;
  3503. RETURN
  3504. END
  3505. END
  3506. END Compound ;
  3507. PROCEDURE EmCrtSeq (which : CARDINAL) ;
  3508. (* The CRT byte sequences, in one parameterised helper. Every one is a fixed
  3509. BIOS call:
  3510. CrtClr - INT 10h AH=06 blank the whole window, then AH=02 home the cursor
  3511. CrtDl - DEC AX ; MOV DL,AL (a 1-based column -> 0-based)
  3512. CrtDh - DEC AX ; MOV DH,AL (a 1-based row)
  3513. CrtCaret - INT 10h AH=02, page 0, cursor at DH,DL
  3514. It takes a parameter on purpose: audit_helpers audits helpers with an EMPTY
  3515. parameter list byte-for-byte, and these multi-instruction sequences have no
  3516. single name grammar. Listed as COMP in NON_ONE_LINE, like SetBlob. *)
  3517. BEGIN
  3518. IF which = CrtClr THEN
  3519. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h *)
  3520. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  3521. Ebyte (0B9H) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV CX,0000h *)
  3522. Ebyte (0BAH) ; Ebyte (4FH) ; Ebyte (18H) ; (* MOV DX,184Fh *)
  3523. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h *)
  3524. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (02H) ; (* MOV AX,0200h *)
  3525. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3526. Ebyte (0BAH) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV DX,0000h *)
  3527. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3528. ELSIF which = CrtDl THEN
  3529. Ebyte (48H) ; (* DEC AX *)
  3530. Ebyte (88H) ; Ebyte (0C2H) (* MOV DL,AL *)
  3531. ELSIF which = CrtDh THEN
  3532. Ebyte (48H) ; (* DEC AX *)
  3533. Ebyte (88H) ; Ebyte (0C6H) (* MOV DH,AL *)
  3534. ELSIF which = CrtEol THEN
  3535. Ebyte (0B4H) ; Ebyte (03H) ; (* MOV AH,03h get cursor *)
  3536. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3537. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h -> DH,DL *)
  3538. Ebyte (89H) ; Ebyte (0D1H) ; (* MOV CX,DX upper-left *)
  3539. Ebyte (0B2H) ; Ebyte (4FH) ; (* MOV DL,4Fh col 79 *)
  3540. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h blank *)
  3541. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  3542. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3543. ELSIF which = CrtLow THEN
  3544. (* [crtAttr] := 7: the dim attribute ClrScr/ClrEol use from now on. The
  3545. runtime's console writer is INT 21h teletype, which has no attribute
  3546. channel, but the clear operations do - so this is where the setting is
  3547. observable, not a no-op. *)
  3548. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (07H)
  3549. ELSIF which = CrtNorm THEN
  3550. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (0FH)
  3551. ELSIF which = CrtKey THEN
  3552. (* KeyPressed: DOS AH=0Bh asks whether a character is waiting. AL is
  3553. 0FFh when one is, 0 when not; the boolean representation here is 0/1.
  3554. AND AX,1, not AND AL,1: the interrupt leaves AH = 0Bh, so the
  3555. comparison that follows (`CMP AX,0') would read 0B00h and call the
  3556. false case TRUE. bootcom happened to return AH=0 (it IRETs the
  3557. handler's whole AX) and hid this; hlt. No argument, no runtime
  3558. entry. *)
  3559. Ebyte (0B4H) ; Ebyte (0BH) ; (* MOV AH,0Bh *)
  3560. Ebyte (0CDH) ; Ebyte (21H) ; (* INT 21h *)
  3561. Ebyte (25H) ; Ebyte (01H) ; Ebyte (00H) (* AND AX,1 *)
  3562. ELSIF which = CrtDelay THEN
  3563. (* Delay(AX) milliseconds: TP3's xdelay, a calibrated busy loop. The
  3564. count 110 is TP3's default `delaycnt' for 1 ms (TPSRC1). AX = 0 does
  3565. nothing. *)
  3566. (* OR AX,AX, not CMP AX,0: check_8086 treats every `CMP AX,0000' in the
  3567. program region as one of the IF/WHILE/REPEAT tests and demands
  3568. Jcc+3;EJMP after it. This is neither. *)
  3569. Ebyte (0BH) ; Ebyte (0C0H) ; (* OR AX,AX *)
  3570. Ebyte (74H) ; Ebyte (08H) ; (* JZ past the loop *)
  3571. Ebyte (0B9H) ; Ebyte (6EH) ; Ebyte (00H) ; (* MOV CX,110 (1 ms) *)
  3572. Ebyte (0E2H) ; Ebyte (0FEH) ; (* LOOP -> itself *)
  3573. Ebyte (48H) ; (* DEC AX *)
  3574. Ebyte (75H) ; Ebyte (0F8H) (* JNZ -> MOV CX *)
  3575. ELSE
  3576. Ebyte (0B4H) ; Ebyte (02H) ; (* MOV AH,02h *)
  3577. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3578. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3579. END
  3580. END EmCrtSeq ;
  3581. PROCEDURE IoCall (idx : CARDINAL) ;
  3582. (* WRITE / WRITELN / READ / READLN / HALT.
  3583. TP3 (TPSRC8 pwriteln, pwrloop, prdtyped) does not pass a descriptor to
  3584. the runtime: it looks at each argument's class and emits a *different*
  3585. call per type, so the formatting is fixed at compile time. Mirrored
  3586. here - one call per argument, then a final call for the line break.
  3587. WRITE/WRITELN push the value; READ/READLN push the address, so the
  3588. runtime can store. As everywhere else in this compiler the caller
  3589. cleans the argument off the stack. *)
  3590. VAR arg : ERes ;
  3591. nArgs, ent, which, acls : CARDINAL ;
  3592. reading : BOOLEAN ;
  3593. pushed : BOOLEAN ;
  3594. skipArg : BOOLEAN ;
  3595. n : CARDINAL ;
  3596. dummy : ERes ;
  3597. BEGIN
  3598. which := symtab [idx].cls ; (* BI_* *)
  3599. IF which = BI_Halt THEN
  3600. IF MatchDelim ('(') THEN (* halt(0) - code ignored *)
  3601. ParseExpr (dummy) ;
  3602. ExpectDelim (')', ENoSemi)
  3603. END ;
  3604. DropC (EmCall (TU_Halt)) ;
  3605. RETURN
  3606. END ;
  3607. IF which = BI_ClrScr THEN
  3608. EmCrtSeq (CrtClr) ;
  3609. RETURN
  3610. END ;
  3611. IF which = BI_ClrEol THEN
  3612. (* clear from the cursor to the end of the line - a real INT 10h call,
  3613. not a no-op: AH=03 reads the cursor, CX := it, DL := 79, AH=06 blanks
  3614. that window. *)
  3615. EmCrtSeq (CrtEol) ;
  3616. RETURN
  3617. END ;
  3618. IF which = BI_GotoXY THEN
  3619. (* GotoXY (x, y): 1-based; evaluate x first and park it, then y, so the
  3620. code for y cannot clobber DL. *)
  3621. IF MatchDelim ('(') THEN
  3622. ParseExpr (dummy) ;
  3623. IF OK () THEN
  3624. LoadAtom (dummy) ;
  3625. EmPushAx ()
  3626. END ;
  3627. ExpectDelim (',', ENoSemi) ;
  3628. ParseExpr (dummy) ;
  3629. IF OK () THEN
  3630. LoadAtom (dummy) ;
  3631. EmCrtSeq (CrtDh)
  3632. END ;
  3633. ExpectDelim (')', ENoSemi) ;
  3634. EmPopAx () ;
  3635. EmCrtSeq (CrtDl) ;
  3636. EmCrtSeq (CrtCaret)
  3637. ELSE
  3638. Err (ENoSemi)
  3639. END ;
  3640. RETURN
  3641. END ;
  3642. IF which = BI_LowVideo THEN
  3643. (* set the attribute the CLEAR operations use to 7; see EmCrtSeq *)
  3644. EmCrtSeq (CrtLow) ;
  3645. RETURN
  3646. END ;
  3647. IF which = BI_NormVideo THEN
  3648. EmCrtSeq (CrtNorm) ;
  3649. RETURN
  3650. END ;
  3651. IF which = BI_Delay THEN
  3652. (* Delay(ms): a real busy loop (EmCrtSeq's CrtDelay), no INT, so it is
  3653. identical under qemu and Exec86. *)
  3654. IF MatchDelim ('(') THEN
  3655. ParseExpr (dummy) ;
  3656. IF OK () THEN
  3657. LoadAtom (dummy) ;
  3658. EmCrtSeq (CrtDelay)
  3659. END ;
  3660. ExpectDelim (')', ENoSemi)
  3661. ELSE
  3662. Err (ENoSemi)
  3663. END ;
  3664. RETURN
  3665. END ;
  3666. reading := (which = BI_Read) OR (which = BI_ReadLn) ;
  3667. nArgs := 0 ;
  3668. IF MatchDelim ('(') THEN
  3669. IF CurCh () # ')' THEN
  3670. LOOP
  3671. IF nArgs >= 16 THEN
  3672. Err (ECompOvf) ;
  3673. EXIT
  3674. END ;
  3675. ParseExpr (arg) ;
  3676. IF NOT OK () THEN
  3677. (* An argument that did not type-check has no value and arg.idx
  3678. is not a symbol. The string arm below dereferences
  3679. symtab[arg.idx] for ANY value whose class is TString - unlike
  3680. the string assign in Assignment, which can tell a failed
  3681. concat from a real one by its kind - so a `writeln' of a
  3682. rejected expression read symtab with whatever idx held
  3683. before and dereferenced it. That is exactly how
  3684. `writeln('a' + 'b')' - two CHARs, a type error since
  3685. v-TP3-STRCAT - segfaulted the compiler instead of reporting
  3686. the error. ParseSub guards its subscript the same way (see
  3687. `IF OK () THEN' before symtab[r.idx] there), and the
  3688. statement loop stops at the next iteration, so leaving the
  3689. rest of this WRITELN unparsed is harmless. *)
  3690. RETURN
  3691. END ;
  3692. (* One argument at a time: parse it, give it its own push or its
  3693. own runtime call, and only then read the next one. TPSRC8
  3694. pwrloop does exactly this, and it has to - a computed argument
  3695. exists only in AX, so parsing the argument after it, and the
  3696. call made for THIS one, are both free to destroy it. Reading
  3697. the whole list first and emitting afterwards printed the first
  3698. argument as the last argument's value, and pushed an argument
  3699. that an earlier inline string's call had already overwritten. *)
  3700. skipArg := FALSE ;
  3701. IF (nArgs = 0) AND ((arg.cls = TText) OR (arg.cls = TFile)) THEN
  3702. (* A leading FILE argument: `Read(Kbd, Ch)'. KBD is the console
  3703. keyboard and this runtime's read entries already read the
  3704. console, so the file is dropped and the rest of the argument
  3705. list is read exactly as without it. A real file is not
  3706. implemented yet - loud, rather than silently reading the file
  3707. variable as a data argument. *)
  3708. IF reading AND (arg.kind = 1) AND symtab [arg.idx].isKbd THEN
  3709. IF NOT MatchDelim (',') THEN
  3710. Err (ENoSemi) ;
  3711. RETURN
  3712. END ;
  3713. skipArg := TRUE
  3714. ELSE
  3715. Err (ENoLib) ;
  3716. RETURN
  3717. END
  3718. END ;
  3719. IF NOT skipArg THEN
  3720. pushed := TRUE ; (* default: value is on the stack -> call + pop *)
  3721. IF reading THEN
  3722. IF (arg.kind # 1) AND (arg.kind # 5) THEN
  3723. Err (ETypeErr) ; (* READ needs a variable *)
  3724. RETURN
  3725. END ;
  3726. acls := symtab [arg.idx].cls ;
  3727. (* s[i] is a CHAR variable, so read(s[i]) must read one byte at
  3728. off+boff, not the whole string at off. arg.cls is TChar
  3729. (set by ParseSub) while the symbol's own class is still
  3730. TString, which is exactly how the element is told from the
  3731. whole string; the address push has to carry boff. For a
  3732. plain variable arg.boff is 0, so nothing changes. *)
  3733. IF (acls = TString) AND (arg.cls = TChar) THEN
  3734. acls := TChar
  3735. END ;
  3736. IF arg.kind = 5 THEN
  3737. (* A variable index: ParseSub computed the element's address
  3738. into DI, and nothing has been emitted since, so that is
  3739. the address READ wants. A constant index folds into boff
  3740. and takes the LEA path below. *)
  3741. EmPushDi ()
  3742. ELSIF symtab [arg.idx].isVar THEN
  3743. (* A VAR parameter: its slot holds the address READ must
  3744. store through, not the address of the slot. *)
  3745. IF arg.boff # 0 THEN
  3746. Err (ENoLib) ;
  3747. RETURN
  3748. END ;
  3749. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  3750. EmPushAx ()
  3751. ELSE
  3752. EmPushVarAddr (symtab [arg.idx].local,
  3753. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  3754. END ;
  3755. IF acls = TString THEN
  3756. (* readln(s)/read(s) of a string variable: TPSRC8 prdstr
  3757. pushes the address, emits MOV CL,max_len and CALL
  3758. xrdstr. Here the limit is a full MOV CX,imm16 (this
  3759. runtime has no byte-register CH/CL setup), and rdstr
  3760. leaves the terminator pending so the readln wrapper can
  3761. consume the newline. *)
  3762. EmMovCxi ((VarSize (arg) - 1) MOD 10000H) ;
  3763. ent := TU_RdStr
  3764. ELSIF acls = TReal THEN
  3765. ent := TU_RdInt (* real reads: not yet *)
  3766. ELSIF acls = TBool THEN
  3767. (* TP3 refuses boolean I/O: TPSRC8 prderrtp is error 66,
  3768. "I/O not allowed here", and the runtime has no xrdbool
  3769. at all. rdbool stores a WORD, so one byte of an
  3770. accepted read would land on the variable AFTER b - the
  3771. exact overflow t37_readbyte pins for a byte. TP3's
  3772. answer to the whole class is the error; so is ours. *)
  3773. Err (EIoHere) ;
  3774. RETURN
  3775. ELSIF acls = TChar THEN
  3776. ent := TU_RdChar (* one byte, not a word *)
  3777. ELSIF acls = TScalar THEN
  3778. (* Dispatch on the SIZE, as TPSRC8 prdnum does:
  3779. `CMP varsize,#$01 / JA prdemit' keeps xrdint for
  3780. anything wider and falls through to `MOV AX,#xrdbyte'
  3781. for a one-byte variable. A BYTE is still TScalar (it
  3782. is *written* as an integer, as in TP3), but reading one
  3783. through rdint stored a word - and the second byte of
  3784. that word is the byte that FOLLOWS the variable. *)
  3785. IF VarSize (arg) = 1 THEN
  3786. ent := TU_RdByte
  3787. ELSE
  3788. ent := TU_RdInt
  3789. END
  3790. ELSE
  3791. Err (ETypeErr) ;
  3792. RETURN
  3793. END
  3794. ELSE
  3795. acls := arg.cls ;
  3796. IF (acls = TString) AND (arg.kind = 3) THEN
  3797. (* An inline string literal. TP3 TPSRC8 pwrinlin special-cases a
  3798. literal that is followed directly by ',' or ')' - i.e. an
  3799. argument, not an expression - and emits
  3800. CALL wrtinl <length byte> <characters...>
  3801. with no stack argument at all; wrtinl reads the length from the
  3802. return address and returns to just past the last character.
  3803. Mirrored exactly, so the literal costs only its own characters
  3804. in the code stream and nothing in the data segment. *)
  3805. IF strLen [arg.strx] > 255 THEN
  3806. (* The length is one byte, so a literal of 256 characters or
  3807. more would wrap: 300 characters emitted behind a length of
  3808. 44, and the runtime would print 44 of them and silently drop
  3809. the rest. TP3 strings are at most 255 characters, so refuse
  3810. rather than truncate. *)
  3811. Err (EConstRange) ;
  3812. RETURN
  3813. END ;
  3814. DropC (EmCall (TU_WrInl)) ;
  3815. Ebyte (VAL (BYTE, strLen [arg.strx])) ;
  3816. n := 0 ;
  3817. WHILE n < strLen [arg.strx] DO
  3818. Ebyte (VAL (BYTE, ORD (strPool [strOff [arg.strx] + n]))) ;
  3819. INC (n)
  3820. END ;
  3821. pushed := FALSE (* nothing was pushed for this one *)
  3822. ELSE
  3823. IF acls = TString THEN
  3824. (* A string *variable*. Its value IS its address, so it is
  3825. passed exactly the way READ passes an address: push it
  3826. and call the owner of the layout - wrstr - which reads
  3827. the length byte and prints that many characters. TPSRC8
  3828. pwrstr/pwrchk route a string argument to xwrtstr, and
  3829. xwrtstr reaches its argument through BP just like WrChar
  3830. does. The only difference from the inline-literal arm
  3831. above is where the bytes live: a literal's are in the
  3832. code stream (wrtinl) and a variable's are in the data
  3833. segment or the frame (wrstr). *)
  3834. EmPushVarAddr (symtab [arg.idx].local, symtab [arg.idx].off) ;
  3835. ent := TU_WrStr
  3836. ELSE
  3837. LoadAtom (arg) ;
  3838. EmPushAx () ;
  3839. IF arg.chr THEN
  3840. ent := TU_WrChar (* 'a' - one char, not 97 *)
  3841. ELSIF acls = TReal THEN
  3842. ent := TU_WrReal
  3843. ELSIF acls = TBool THEN
  3844. ent := TU_WrBool
  3845. ELSIF acls = TChar THEN
  3846. ent := TU_WrChar (* c : char - one char *)
  3847. ELSIF acls = TScalar THEN
  3848. ent := TU_WrInt
  3849. ELSE
  3850. Err (ETypeErr) ;
  3851. RETURN
  3852. END
  3853. END
  3854. END
  3855. END ;
  3856. IF pushed THEN
  3857. DropC (EmCall (ent)) ;
  3858. EmAddSp (2) (* one 16-bit argument *)
  3859. END ;
  3860. INC (nArgs)
  3861. END ;
  3862. IF NOT skipArg THEN
  3863. IF NOT MatchDelim (',') THEN
  3864. EXIT
  3865. END
  3866. END
  3867. END ;
  3868. IF NOT MatchDelim (')') THEN
  3869. Err (ENoSemi) ;
  3870. RETURN
  3871. END
  3872. ELSE
  3873. DropCh (GetCh ())
  3874. END
  3875. END ;
  3876. IF reading AND (nArgs = 0) THEN
  3877. (* readln with no variable: just skip to the next line *)
  3878. DropC (EmCall (TU_RdLn)) ;
  3879. RETURN
  3880. END ;
  3881. IF which = BI_WriteLn THEN
  3882. DropC (EmCall (TU_WrLn))
  3883. ELSIF which = BI_ReadLn THEN
  3884. DropC (EmCall (TU_RdLn))
  3885. END
  3886. END IoCall ;
  3887. PROCEDURE Statmnt () ;
  3888. VAR tok : CARDINAL ;
  3889. idx, i2 : CARDINAL ;
  3890. t, src : ERes ;
  3891. L1, zj, zj2, exj : CARDINAL ;
  3892. lo, hi, v : LONGINT ;
  3893. clso : CARDINAL ;
  3894. i : CARDINAL ;
  3895. k, nlbl, nlblJmp, bodyPc, skipJmp : CARDINAL ;
  3896. nm : ARRAY [0..MaxName] OF CHAR ;
  3897. strf : BOOLEAN ;
  3898. dow : BOOLEAN ;
  3899. BEGIN
  3900. Skip () ;
  3901. IF Digit (CurCh ()) THEN
  3902. ParseLabelStmt () ; (* consumed 'n' ':' *)
  3903. Statmnt () ; (* 'n : statement' - the statement follows
  3904. the label directly, with no ';' between *)
  3905. RETURN
  3906. END ;
  3907. IF NOT Alpha (CurCh ()) THEN
  3908. ExpectDelim (';', ENoSemi) ;
  3909. RETURN
  3910. END ;
  3911. DropB (MatchKey (tok)) ;
  3912. IF tok = TkBegin THEN
  3913. Compound ()
  3914. ELSIF tok = TkIf THEN
  3915. ParseExpr (t) ;
  3916. LoadAtom (t) ;
  3917. EmCmpAxi (0) ;
  3918. zj := EmJcc (84H, 0) ; (* JZ -> else/end *)
  3919. IF NOT (MatchKey (tok) AND (tok = TkThen)) THEN
  3920. Err (ENoSemi)
  3921. END ;
  3922. Statmnt () ;
  3923. (* Peek the ELSE, do not match it. `MatchKey (tok) AND (tok = TkElse)`
  3924. consumes whatever the next keyword is even when the AND fails, so an
  3925. `if` that was the LAST statement of a BEGIN..END block ate the block's
  3926. own END: Compound then found neither ';' nor END and raised ENoSemi.
  3927. Any `if` as the last statement of a compound was unparseable - not
  3928. in a loop, not anywhere - and no fixture had one, so nothing noticed.
  3929. The visible symptom was a parse error at the statement AFTER the
  3930. block, which points at entirely the wrong piece of source. *)
  3931. PeekKw (tok) ;
  3932. IF tok = TkElse THEN
  3933. DropB (MatchKey (tok)) ;
  3934. exj := EmJmpNear (0) ;
  3935. SetPatTgt (zj, pc) ;
  3936. Statmnt () ;
  3937. SetPatTgt (exj, pc)
  3938. ELSE
  3939. SetPatTgt (zj, pc)
  3940. END
  3941. ELSIF tok = TkWhile THEN
  3942. L1 := pc ;
  3943. ParseExpr (t) ;
  3944. LoadAtom (t) ;
  3945. EmCmpAxi (0) ;
  3946. zj := EmJcc (84H, 0) ; (* JZ -> end *)
  3947. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  3948. Err (ENoSemi)
  3949. END ;
  3950. brkSave [brkN] := exitCnt ;
  3951. loopTy [brkN] := 1 ;
  3952. INC (brkN) ;
  3953. Statmnt () ;
  3954. DEC (brkN) ;
  3955. i := brkSave [brkN] ;
  3956. WHILE i < exitCnt DO
  3957. SetPatTgt (exitPatch [i], pc) ;
  3958. INC (i)
  3959. END ;
  3960. exitCnt := brkSave [brkN] ;
  3961. DropC (EmJmpNear (L1)) ;
  3962. SetPatTgt (zj, pc)
  3963. ELSIF tok = TkRepeat THEN
  3964. L1 := pc ;
  3965. brkSave [brkN] := exitCnt ;
  3966. loopTy [brkN] := 1 ;
  3967. INC (brkN) ;
  3968. (* The body is a STATEMENT SEQUENCE, not one statement: `repeat a; b
  3969. until c'. This used to call Statmnt once and then demand UNTIL, so
  3970. any body with a second statement was ENoSemi at the first ';'. t12's
  3971. two bodies are single statements and never saw it; CALC's `Flash' does
  3972. (GotoXY; Blink := not Blink; if ...; Write; Delay). Same shape as
  3973. Compound, stopping at UNTIL instead of END. *)
  3974. LOOP
  3975. PeekKw (tok) ;
  3976. IF tok = TkUntil THEN
  3977. DropB (MatchKey (tok)) ;
  3978. EXIT
  3979. END ;
  3980. Statmnt () ;
  3981. IF NOT OK () THEN
  3982. RETURN
  3983. END ;
  3984. IF NOT MatchDelim (';') THEN
  3985. PeekKw (tok) ;
  3986. IF tok = TkUntil THEN
  3987. DropB (MatchKey (tok)) ;
  3988. EXIT
  3989. END ;
  3990. Err (ENoSemi) ;
  3991. RETURN
  3992. END
  3993. END ;
  3994. ParseExpr (t) ;
  3995. LoadAtom (t) ;
  3996. EmCmpAxi (0) ;
  3997. (* UNTIL exits when the condition is TRUE, so the body runs again when
  3998. it is FALSE. The condition is a 0/1 in AX and EmCmpAxi (0) has just
  3999. compared it with 0, so ZF=1 means "condition false" -- which is
  4000. exactly the case that loops, hence JZ.
  4001. This was JNZ, which compiled repeat-until as while-until: the body
  4002. ran once, the condition was tested, and it stopped. t12_repeat is
  4003. `i:=0; repeat i:=i+1 until i>5' and it printed 1.
  4004. No patch slot: L1 is backwards and already known, so EmJcc returns
  4005. 0 and there is nothing to SetPatTgt. *)
  4006. DropC (EmJcc (84H, L1)) ; (* JZ -> body again *)
  4007. DEC (brkN) ;
  4008. i := brkSave [brkN] ;
  4009. WHILE i < exitCnt DO
  4010. SetPatTgt (exitPatch [i], pc) ;
  4011. INC (i)
  4012. END ;
  4013. exitCnt := brkSave [brkN]
  4014. ELSIF tok = TkFor THEN
  4015. (* control variable *)
  4016. Skip () ; (* after the FOR keyword: skip blanks *)
  4017. IF NOT Alpha (CurCh ()) THEN
  4018. Err (EUnknown) ;
  4019. RETURN
  4020. END ;
  4021. GetWord () ;
  4022. IF NOT Search (wrd, idx) THEN
  4023. Err (EUnknown) ;
  4024. RETURN
  4025. END ;
  4026. IF symtab [idx].size > 2 THEN
  4027. Err (ENoLib) ;
  4028. RETURN
  4029. END ;
  4030. IF NOT MatchAssign () THEN
  4031. Err (ENoSemi)
  4032. END ;
  4033. ParseExpr (src) ;
  4034. LoadAtom (src) ;
  4035. EmStoreVar (symtab [idx].local, symtab [idx].off,
  4036. symtab [idx].size) ;
  4037. IF NOT MatchKey (tok) THEN
  4038. Err (ESimpType) ;
  4039. RETURN
  4040. END ;
  4041. IF (tok = TkTo) OR (tok = TkDownto) THEN
  4042. dow := (tok = TkDownto)
  4043. ELSE
  4044. Err (ESimpType) ;
  4045. RETURN
  4046. END ;
  4047. ParseExpr (t) ;
  4048. LoadAtom (t) ;
  4049. EmPushAx () ; (* loop bound on the stack *)
  4050. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  4051. Err (ENoSemi)
  4052. END ;
  4053. brkSave [brkN] := exitCnt ;
  4054. loopTy [brkN] := 2 ;
  4055. INC (brkN) ;
  4056. L1 := pc ; (* Ltest: the test comes FIRST *)
  4057. (* The test is emitted before the body, not after it. It used to be
  4058. emitted after, which is a post-test loop and runs the body one time
  4059. too many: with `for i := 1 to 5`, the sequence of i at the test is
  4060. 1,2,3,4,5,6 - the test at i=5 is `5 > 5`, which is false, so the
  4061. body ran a sixth time with i=6. `for i := 1 to 5 do s := s + i`
  4062. printed 21. The size was right and the shape was right; only the
  4063. order was wrong, and no byte check can see an order.
  4064. The bound stays on the stack for the whole loop, so EmMovCxSp has to
  4065. re-read it every iteration - which is also what makes the bound a
  4066. *variable* rather than a constant. [SP] cannot be encoded on the
  4067. 8086, so EmMovCxSp is POP CX ; PUSH CX, an observational no-op that
  4068. leaves the bound in place. *)
  4069. EmMovCxSp () ;
  4070. EmLoadVar (symtab [idx].local, symtab [idx].off,
  4071. symtab [idx].size) ;
  4072. EmCmpAxCx () ;
  4073. IF dow THEN
  4074. zj := EmJcc (8CH, 0) (* JL -> done *)
  4075. ELSE
  4076. zj := EmJcc (8FH, 0) (* JG -> done *)
  4077. END ;
  4078. Statmnt () ;
  4079. DEC (brkN) ;
  4080. (* A FOR's exits are NOT patched here, even though `done` is not known
  4081. yet. For a WHILE or REPEAT, "just after the body" is a correct
  4082. target: the jump back to the test re-evaluates the condition and
  4083. leaves. For a FOR there is a STEP between the body and `done`, so
  4084. an EXIT that jumped here would increment the control variable and
  4085. jump back to the test - and if the incremented value still satisfied
  4086. the bound, it would run the body AGAIN. `exit` did not exit.
  4087. The fix needs no new bookkeeping: `brkSave [brkN] .. exitCnt` still
  4088. names exactly this loop's exits, because Statmnt may have added more
  4089. and nothing has reset exitCnt. So they are patched at `done`, below.
  4090. A WHILE nested inside the FOR saves and restores its own range and
  4091. leaves this one intact. *)
  4092. (* step *)
  4093. EmLoadVar (symtab [idx].local, symtab [idx].off,
  4094. symtab [idx].size) ;
  4095. IF dow THEN
  4096. EmDecAx ()
  4097. ELSE
  4098. EmIncAx ()
  4099. END ;
  4100. EmStoreVar (symtab [idx].local, symtab [idx].off,
  4101. symtab [idx].size) ;
  4102. DropC (EmJmpNear (L1)) ;
  4103. SetPatTgt (zj, pc) ; (* done: *)
  4104. (* A WHILE loop here, not a FOR over the exit range. The range is
  4105. usually EMPTY - most loops have no `exit` - and `exitCnt` is a
  4106. CARDINAL, so `TO exitCnt - 1` with exitCnt = 0 is `TO 65535`: the
  4107. loop does not terminate, it wraps, and it walks exitPatch [0..65535]
  4108. off the end of a 64-element array. `for i := 1 to 10 do i := i` has
  4109. no exit, so this is the ORDINARY case, and it faulted with
  4110. "invalid address referenced" on every FOR loop without an exit. *)
  4111. i := brkSave [brkN] ;
  4112. WHILE i < exitCnt DO
  4113. SetPatTgt (exitPatch [i], pc) ;
  4114. INC (i)
  4115. END ;
  4116. exitCnt := brkSave [brkN] ;
  4117. EmAddSp (2) (* drop the loop bound *)
  4118. ELSIF tok = TkCase THEN
  4119. ParseExpr (t) ;
  4120. LoadAtom (t) ;
  4121. EmPushAx () ; (* selector on the stack *)
  4122. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4123. Err (ENoSemi)
  4124. END ;
  4125. caseN := 0 ;
  4126. LOOP
  4127. Skip () ;
  4128. IF MatchDelim (';') THEN
  4129. Skip ()
  4130. END ;
  4131. PeekKw (tok) ;
  4132. IF (tok = TkEnd) OR (tok = TkElse) THEN
  4133. EXIT
  4134. END ;
  4135. (* Case labels: `v' | `lo..hi', comma-separated, all selecting the
  4136. same statement (CALC's `'G', 'I', 'O', 'Q':'). Read the whole list
  4137. first; the emission then knows whether this is the one-label path
  4138. or a list. *)
  4139. nlbl := 0 ;
  4140. LOOP
  4141. IF Alpha (CurCh ()) THEN
  4142. GetWord () ;
  4143. IF Search (wrd, i2) AND (symtab [i2].tag = KConst) THEN
  4144. lo := symtab [i2].lval
  4145. ELSE
  4146. Err (EUnknown) ;
  4147. RETURN
  4148. END
  4149. ELSE
  4150. RdConst (lo, clso, strf)
  4151. END ;
  4152. IF MatchRange () THEN
  4153. RdConst (hi, clso, strf)
  4154. ELSE
  4155. hi := lo
  4156. END ;
  4157. IF nlbl >= 32 THEN
  4158. Err (ECompOvf) ;
  4159. RETURN
  4160. END ;
  4161. lblLo [nlbl] := lo ;
  4162. lblHi [nlbl] := hi ;
  4163. INC (nlbl) ;
  4164. IF MatchDelim (',') THEN
  4165. Skip ()
  4166. ELSE
  4167. EXIT
  4168. END
  4169. END ;
  4170. Skip () ;
  4171. ExpectDelim (':', ENoSemi) ;
  4172. IF NOT OK () THEN
  4173. RETURN
  4174. END ;
  4175. EmMovAxSp () ;
  4176. IF nlbl = 1 THEN
  4177. (* One label: the original bytes, except that a RANGE is now a
  4178. real range. It used to compare AX with lo and then with hi,
  4179. both demanding equality, so `1..5' matched NOTHING unless
  4180. lo = hi - a silently wrong answer, not an error. *)
  4181. lo := lblLo [0] ;
  4182. hi := lblHi [0] ;
  4183. IF hi = lo THEN
  4184. EmCmpAxi (W16 (lo)) ;
  4185. zj := EmJcc (85H, 0) ; (* JNZ -> next arm *)
  4186. zj2 := 0
  4187. ELSE
  4188. EmCmpAxi (W16 (lo)) ;
  4189. zj := EmJcc (8CH, 0) ; (* JL -> next arm *)
  4190. EmCmpAxi (W16 (hi)) ;
  4191. zj2 := EmJcc (8FH, 0) (* JG -> next arm *)
  4192. END ;
  4193. Statmnt () ;
  4194. IF caseN >= 64 THEN
  4195. Err (ECompOvf) ;
  4196. RETURN
  4197. END ;
  4198. caseJmp [caseN] := EmJmpNear (0) ;
  4199. INC (caseN) ;
  4200. SetPatTgt (zj, pc) ;
  4201. IF zj2 # 0 THEN
  4202. SetPatTgt (zj2, pc)
  4203. END
  4204. ELSE
  4205. (* A list. A single label branches INTO the statement; a range
  4206. first sends AX below lo to the next label, then `<= hi' to the
  4207. body. The body jumps are patched once the body's address is
  4208. known, and the no-match EJMP skips the body to the next arm. *)
  4209. nlblJmp := 0 ;
  4210. FOR k := 0 TO nlbl - 1 DO
  4211. IF lblHi [k] = lblLo [k] THEN
  4212. EmCmpAxi (W16 (lblLo [k])) ;
  4213. lblJmp [nlblJmp] := EmJcc (84H, 0) ; (* JZ -> body *)
  4214. INC (nlblJmp)
  4215. ELSE
  4216. (* `lo <= AX <= hi', built from the two conditions this
  4217. compiler declares for a branch (L and G): below lo skips
  4218. the label, above hi skips it, otherwise an unconditional
  4219. jump enters the body. JLE would be shorter and is legal
  4220. 8086, but check_8086's declared condition set is exactly
  4221. Z/NZ/L/G (the four the parser's comparisons use), and a
  4222. new condition in CASE would rightly be reported there. *)
  4223. EmCmpAxi (W16 (lblLo [k])) ;
  4224. zj := EmJcc (8CH, 0) ; (* JL -> next label *)
  4225. EmCmpAxi (W16 (lblHi [k])) ;
  4226. zj2 := EmJcc (8FH, 0) ; (* JG -> next label *)
  4227. lblJmp [nlblJmp] := EmJmpNear (0) ; (* in range -> body *)
  4228. INC (nlblJmp) ;
  4229. SetPatTgt (zj, pc) ;
  4230. SetPatTgt (zj2, pc)
  4231. END
  4232. END ;
  4233. skipJmp := EmJmpNear (0) ;
  4234. bodyPc := pc ;
  4235. FOR k := 0 TO nlblJmp - 1 DO
  4236. SetPatTgt (lblJmp [k], bodyPc)
  4237. END ;
  4238. Statmnt () ;
  4239. IF caseN >= 64 THEN
  4240. Err (ECompOvf) ;
  4241. RETURN
  4242. END ;
  4243. caseJmp [caseN] := EmJmpNear (0) ;
  4244. INC (caseN) ;
  4245. SetPatTgt (skipJmp, pc)
  4246. END
  4247. END ;
  4248. IF tok = TkElse THEN
  4249. DropB (MatchKey (tok)) ;
  4250. Statmnt () ;
  4251. IF NOT (MatchKey (tok) AND (tok = TkEnd)) THEN
  4252. Err (ENoSemi)
  4253. END
  4254. ELSE
  4255. DropB (MatchKey (tok))
  4256. END ;
  4257. EmAddSp (2) ;
  4258. FOR i := 0 TO caseN - 1 DO
  4259. SetPatTgt (caseJmp [i], pc)
  4260. END
  4261. ELSIF tok = TkGoto THEN
  4262. v := 0 ;
  4263. Skip () ; (* after the GOTO keyword: skip blanks *)
  4264. IF Digit (CurCh ()) THEN
  4265. RdIntConst (v) ;
  4266. NumToName (W16 (v), nm) ;
  4267. IF Search (nm, idx) THEN
  4268. IF symtab [idx].tag = KLabel THEN
  4269. IF symtab [idx].defnd THEN
  4270. DropC (EmJmpNear (symtab [idx].goPos))
  4271. ELSE
  4272. zj := EmJmpNear (0) ;
  4273. AddPend (0, idx, zj)
  4274. END
  4275. ELSE
  4276. Err (EUnknown)
  4277. END
  4278. ELSE
  4279. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  4280. zj := EmJmpNear (0) ;
  4281. AddPend (0, idx, zj)
  4282. END
  4283. ELSE
  4284. Err (EUnknown)
  4285. END
  4286. ELSIF tok = TkExit THEN
  4287. IF brkN = 0 THEN
  4288. Err (EUnknown)
  4289. ELSE
  4290. (* No EmAddSp (2) here, even inside a FOR. The FOR's `done` label
  4291. drops the bound, so an EXIT that jumped to `done` would drop it a
  4292. second time - 4 bytes off a stack that only had 2 to give, which
  4293. silently corrupts the caller's frame. It used to do exactly
  4294. that, and it was doubly wrong: the exits were patched to the STEP
  4295. rather than to `done`, so the EXIT also incremented the control
  4296. variable and jumped back into the test. *)
  4297. zj := EmJmpNear (0) ;
  4298. IF exitCnt < 64 THEN
  4299. exitPatch [exitCnt] := zj ;
  4300. INC (exitCnt)
  4301. END
  4302. END
  4303. ELSIF tok = TkWith THEN
  4304. Err (ENoLib)
  4305. ELSE
  4306. (* identifier statement: assignment or call *)
  4307. IF NOT Search (wrd, idx) THEN
  4308. Err (EUnknown) ;
  4309. RETURN
  4310. END ;
  4311. IF symtab [idx].tag = KBuiltin THEN
  4312. IoCall (idx) ;
  4313. RETURN
  4314. END ;
  4315. IF symtab [idx].tag = KProc THEN
  4316. IF MatchDelim ('(') THEN
  4317. ParseCallArgs (idx)
  4318. ELSE
  4319. ParseCall (idx)
  4320. END ;
  4321. RETURN
  4322. END ;
  4323. IF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KFunc) THEN
  4324. t.idx := idx ;
  4325. t.kind := 1 ;
  4326. t.boff := 0 ;
  4327. t.cls := symtab [idx].cls ;
  4328. IF symtab [idx].tag = KFunc THEN
  4329. t.idx := symtab [idx].resvar ;
  4330. t.cls := symtab [t.idx].cls
  4331. END ;
  4332. t.sz := symtab [t.idx].size ; (* ParseSub may narrow it further *)
  4333. ParseSub (t) ;
  4334. IF MatchAssign () THEN
  4335. Assignment (t) ;
  4336. RETURN
  4337. END ;
  4338. Err (ENoSemi) ;
  4339. RETURN
  4340. END ;
  4341. Err (ENoSemi)
  4342. END
  4343. END Statmnt ;
  4344. (* ---------------------------------------------------------------- *)
  4345. (* types and declarations (TPSRC7) *)
  4346. (* ---------------------------------------------------------------- *)
  4347. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ;
  4348. VAR tok : CARDINAL ;
  4349. idx : CARDINAL ;
  4350. lo, hi : LONGINT ;
  4351. s2, e2 : CARDINAL ;
  4352. subcls : CARDINAL ;
  4353. strf : BOOLEAN ;
  4354. consumed : BOOLEAN ;
  4355. running, groupFirst, i, an : CARDINAL ;
  4356. alo, ahi : ARRAY [0..3] OF LONGINT ;
  4357. ecls2 : CARDINAL ;
  4358. BEGIN
  4359. cls := TNone ; size := 0 ; elem := 0 ;
  4360. consumed := FALSE ;
  4361. newArrIdx := 0 ;
  4362. Skip () ; (* after ':' / '=' : skip blanks *)
  4363. IF CurCh () = '(' THEN
  4364. (* An enumeration: `(Constant, Formula, Txt, ...)'. Each enumerator
  4365. becomes a constant with its ordinal position as its value, and the
  4366. TYPE is 1 byte (TP3 uses one below 256 values) with bounds 0..n-1,
  4367. which DefType records so `set of Attributes' can size its base.
  4368. Enumerators are TScalar, not TEnum: they behave as ordinals; only the
  4369. TYPE carries the enum identity and its bounds. *)
  4370. DropCh (GetCh ()) ;
  4371. lo := 0 ;
  4372. hi := -1 ;
  4373. LOOP
  4374. Skip () ;
  4375. IF NOT Alpha (CurCh ()) THEN
  4376. Err (EUnknown) ;
  4377. RETURN
  4378. END ;
  4379. GetWord () ;
  4380. DupTest (wrd) ;
  4381. DropC (NewSym (wrd, KConst, TScalar, 1, 1, 0, hi + 1, FALSE)) ;
  4382. hi := hi + 1 ;
  4383. IF MatchDelim (',') THEN
  4384. (* another enumerator *)
  4385. ELSE
  4386. EXIT
  4387. END
  4388. END ;
  4389. ExpectDelim (')', ENoSemi) ;
  4390. enumLo := lo ;
  4391. enumHi := hi ;
  4392. cls := TEnum ;
  4393. size := 1 ;
  4394. elem := 1 ;
  4395. RETURN
  4396. END ;
  4397. IF Alpha (CurCh ()) THEN
  4398. DropB (MatchKey (tok)) ;
  4399. consumed := TRUE
  4400. ELSE
  4401. tok := TkNone
  4402. END ;
  4403. IF tok = TkArray THEN
  4404. (* array [range, range, ...] of T. Several ranges are allowed; the LAST
  4405. varies fastest (row-major), so `Sheet[fx,fy]' strides the first range
  4406. by the second's count (RESUME-TP3.md §2). The shape is kept in the
  4407. array table; the symbol carries a pointer to it (SymEntry.arrIdx) so
  4408. indexing can scale by the element size and subtract each lower bound. *)
  4409. ExpectDelim ('[', ENoSemi) ;
  4410. an := 0 ;
  4411. LOOP
  4412. RdConst (lo, subcls, strf) ;
  4413. IF NOT MatchRange () THEN
  4414. Err (ESimpType) ;
  4415. RETURN
  4416. END ;
  4417. RdConst (hi, subcls, strf) ;
  4418. IF an < 4 THEN
  4419. alo [an] := lo ;
  4420. ahi [an] := hi ;
  4421. INC (an)
  4422. END ;
  4423. IF MatchDelim (',') THEN
  4424. (* another range *)
  4425. ELSE
  4426. EXIT
  4427. END
  4428. END ;
  4429. ExpectDelim (']', ENoSemi) ;
  4430. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4431. Err (ENoSemi) ;
  4432. RETURN
  4433. END ;
  4434. ParseType (cls, s2, e2) ;
  4435. ecls2 := cls ;
  4436. cls := TArray ;
  4437. elem := s2 ;
  4438. size := s2 ;
  4439. i := 0 ;
  4440. WHILE i < an DO
  4441. size := size * W16 (VAL (LONGINT, W16 (ahi [i]))
  4442. - VAL (LONGINT, W16 (alo [i])) + 1) ;
  4443. INC (i)
  4444. END ;
  4445. (* register the shape so indexing can scale by element size and subtract
  4446. each lower bound; the symbol points at this slot *)
  4447. IF arrTop < MaxArrs THEN
  4448. arrs [arrTop].n := an ;
  4449. arrs [arrTop].elem := s2 ;
  4450. arrs [arrTop].ecls := ecls2 ;
  4451. i := 0 ;
  4452. WHILE i < an DO
  4453. arrs [arrTop].lo [i] := alo [i] ;
  4454. arrs [arrTop].hi [i] := ahi [i] ;
  4455. INC (i)
  4456. END ;
  4457. newArrIdx := arrTop + 1 ;
  4458. INC (arrTop)
  4459. ELSE
  4460. Err (ECompOvf)
  4461. END
  4462. ELSIF tok = TkString THEN
  4463. cls := TString ;
  4464. size := 256 ;
  4465. elem := 1 ;
  4466. IF MatchDelim ('[') THEN
  4467. RdConst (hi, subcls, strf) ;
  4468. ExpectDelim (']', ENoSemi) ;
  4469. size := W16 (hi) + 1
  4470. END
  4471. ELSIF tok = TkSet THEN
  4472. (* set of <ordinal>. TP3's hybrid layout (coeur-tp-ocr 4.7.2): only the
  4473. whole BYTES covering the base range are stored, so `set of Char' is 32
  4474. bytes and `set of 12..17' is 2. `elem' carries the origin - the first
  4475. element of the first byte, a multiple of 8 - which is all the
  4476. membership and constructor arithmetic needs. *)
  4477. PeekKw (tok) ;
  4478. IF tok = TkOf THEN
  4479. DropB (MatchKey (tok)) ;
  4480. RdSetBase (subcls, lo, hi) ;
  4481. IF OK () THEN
  4482. cls := TSet ;
  4483. elem := (VAL (CARDINAL, lo) DIV 8) * 8 ;
  4484. size := (VAL (CARDINAL, hi) DIV 8)
  4485. - (VAL (CARDINAL, lo) DIV 8) + 1
  4486. END
  4487. ELSE
  4488. Err (ENoSemi)
  4489. END
  4490. ELSIF tok = TkRecord THEN
  4491. (* record fieldList end, fields NON-COMPACTED and juxtaposed
  4492. (RESUME-TP3.md §2). Each name in a `a, b : T' group is a field of its
  4493. own at the running offset; the field table is where `x.f' looks, keyed
  4494. per record so field names need not be globally unique.
  4495. recFldFirst/recFldLast hand the range to DefType, or to the enclosing
  4496. record's field entry when records nest. *)
  4497. recFldFirst := fldTop ;
  4498. running := 0 ;
  4499. LOOP
  4500. PeekKw (tok) ;
  4501. IF tok = TkEnd THEN
  4502. DropB (MatchKey (tok)) ;
  4503. EXIT
  4504. END ;
  4505. IF CurCh () = 0C THEN
  4506. Err (EUnknown) ;
  4507. EXIT
  4508. END ;
  4509. (* the group's names, then ONE `: type' *)
  4510. groupFirst := fldTop ;
  4511. LOOP
  4512. Skip () ;
  4513. IF NOT Alpha (CurCh ()) THEN
  4514. Err (EUnknown) ;
  4515. RETURN
  4516. END ;
  4517. GetWord () ;
  4518. IF fldTop < MaxFields THEN
  4519. CopyStr (fields [fldTop].name, wrd) ;
  4520. fields [fldTop].off := 0 ;
  4521. INC (fldTop)
  4522. ELSE
  4523. Err (ECompOvf)
  4524. END ;
  4525. IF NOT MatchDelim (',') THEN
  4526. EXIT
  4527. END
  4528. END ;
  4529. ExpectDelim (':', ENoSemi) ;
  4530. ParseType (subcls, s2, e2) ;
  4531. IF NOT OK () THEN
  4532. RETURN
  4533. END ;
  4534. (* every name in the group gets the type and its own slot *)
  4535. i := groupFirst ;
  4536. WHILE i < fldTop DO
  4537. fields [i].cls := subcls ;
  4538. fields [i].size := s2 ;
  4539. fields [i].elem := e2 ;
  4540. fields [i].off := running ;
  4541. fields [i].lo := enumLo ;
  4542. fields [i].hi := enumHi ;
  4543. running := running + s2 ;
  4544. INC (i)
  4545. END ;
  4546. IF NOT MatchDelim (';') THEN
  4547. Err (ENoSemi) ;
  4548. RETURN
  4549. END
  4550. END ;
  4551. recFldLast := fldTop ;
  4552. cls := TRecord ;
  4553. size := running ;
  4554. elem := running
  4555. ELSIF tok = TkText THEN
  4556. (* A TEXT file variable. We do our own unbuffered INT 21h I/O, so the
  4557. file variable is just our control block (see FileVarSize) and the
  4558. element is one byte; TP3 keeps a 128-byte buffer in its own, which is
  4559. a divergence we do not need. *)
  4560. cls := TText ;
  4561. size := FileVarSize ;
  4562. elem := 1
  4563. ELSIF tok = TkFile THEN
  4564. (* file of T. The element type is parsed for its SIZE, which is what a
  4565. Read/Write moves per record; the variable itself is the control
  4566. block. *)
  4567. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4568. Err (ENoSemi) ;
  4569. RETURN
  4570. END ;
  4571. ParseType (subcls, s2, e2) ;
  4572. IF OK () THEN
  4573. cls := TFile ;
  4574. size := FileVarSize ;
  4575. elem := s2
  4576. END
  4577. ELSE
  4578. IF consumed THEN
  4579. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  4580. cls := symtab [idx].cls ;
  4581. size := symtab [idx].size ;
  4582. (* The type's ELEMENT size, not its total size. They are equal for
  4583. a record, but not for an array (`Letters' is 6 bytes of 3
  4584. Integers) or a file. A named array typed constant used to get
  4585. typElem = 6, wrote six bytes per element and wrapped the
  4586. little-endian divider to zero: SIGFPE in DefConst. *)
  4587. elem := symtab [idx].elem ;
  4588. enumLo := symtab [idx].lo ;
  4589. enumHi := symtab [idx].hi ;
  4590. recFldFirst := symtab [idx].fldFirst ;
  4591. recFldLast := symtab [idx].fldLast ;
  4592. newArrIdx := symtab [idx].arrIdx
  4593. ELSE
  4594. Err (EUnknown)
  4595. END
  4596. ELSE
  4597. (* subrange lo .. hi. TP3 sizes it by its bounds: ONE byte when both
  4598. are inside 0..255, else two (RESUME-TP3.md §2). `0..20' and
  4599. `'A'..'G'' are one byte - which is what makes CellRec 80 and not
  4600. 82, and `Sheet' 147*80. The bounds are kept for `set of T'. *)
  4601. RdConst (lo, subcls, strf) ;
  4602. IF NOT MatchRange () THEN
  4603. Err (ESimpType) ;
  4604. RETURN
  4605. END ;
  4606. RdConst (hi, subcls, strf) ;
  4607. cls := TScalar ;
  4608. IF (lo >= 0) AND (hi <= 255) AND (lo <= hi) THEN
  4609. size := 1
  4610. ELSE
  4611. size := 2
  4612. END ;
  4613. elem := size ;
  4614. enumLo := lo ;
  4615. enumHi := hi
  4616. END
  4617. END
  4618. END ParseType ;
  4619. PROCEDURE DefVar () ;
  4620. (* 'name' (',' name)* ':' type [ABSOLUTE addr] ; group repeated until a
  4621. declaration keyword appears *)
  4622. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4623. cls, size, elem : CARDINAL ;
  4624. tok : CARDINAL ;
  4625. v : LONGINT ;
  4626. off : CARDINAL ;
  4627. first, i : CARDINAL ;
  4628. BEGIN
  4629. LOOP
  4630. Skip () ; (* after the VAR keyword: skip blanks *)
  4631. IF NOT Alpha (CurCh ()) THEN
  4632. Err (EUnknown) ;
  4633. RETURN
  4634. END ;
  4635. (* A group is `name (, name)* : type' - TPSRC7 rdvarlst/rdvloop collects
  4636. the whole comma-separated list of names FIRST (`CALL ccomma / JZ
  4637. rdvloop'), then reads one `: type' with ecolon/rdvartp, then vardef2
  4638. gives every name in the list that one type. The names are created as
  4639. placeholders here and filled in once the type is known, which is the
  4640. same shape as TP3 reserving a symtab slot per name and storing the
  4641. type pointer into each afterwards. *)
  4642. first := symTop ;
  4643. LOOP
  4644. Skip () ; (* GetWord does not skip blanks, and the cursor
  4645. sits on the space after the ',' *)
  4646. IF NOT Alpha (CurCh ()) THEN
  4647. Err (EUnknown) ;
  4648. RETURN
  4649. END ;
  4650. GetWord () ;
  4651. SaveWord (nm) ;
  4652. DupTest (nm) ;
  4653. DropC (NewSym (nm, KVar, TNone, 0, 0, 0, 0, lexnest # 0)) ;
  4654. IF NOT MatchDelim (',') THEN
  4655. EXIT
  4656. END
  4657. END ;
  4658. ExpectDelim (':', ENoSemi) ;
  4659. ParseType (cls, size, elem) ;
  4660. IF OK () THEN
  4661. IF lexnest = 0 THEN
  4662. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  4663. AND (cls # TArray) AND (cls # TFile) AND (cls # TText) THEN
  4664. (* Still the catch-all for a type whose storage this compiler does
  4665. not lay out yet (an ARRAY at its point of use, a RECORD, ...).
  4666. A STRING is the exception now: its layout is length byte +
  4667. characters, and the rest of the compiler knows it - see
  4668. Assignment and IoCall. *)
  4669. Err (ENoLib) ;
  4670. RETURN
  4671. END ;
  4672. PeekKw (tok) ;
  4673. IF tok = TkAbsolute THEN
  4674. DropB (MatchKey (tok)) ;
  4675. IF (CurCh () = '$') OR (Digit (CurCh ())) THEN
  4676. RdIntConst (v) ;
  4677. off := W16 (v)
  4678. ELSE
  4679. Err (EUnknown) ;
  4680. off := 0
  4681. END ;
  4682. (* TP3's absolute path (vdstore) leaves the offset fixed, so
  4683. every name in the group aliases the same address. *)
  4684. i := first ;
  4685. WHILE i < symTop DO
  4686. symtab [i].cls := cls ; symtab [i].size := size ;
  4687. symtab [i].elem := elem ; symtab [i].off := off ;
  4688. symtab [i].fldFirst := recFldFirst ;
  4689. symtab [i].fldLast := recFldLast ;
  4690. symtab [i].arrIdx := newArrIdx ;
  4691. INC (i)
  4692. END
  4693. ELSE
  4694. i := first ;
  4695. WHILE i < symTop DO
  4696. symtab [i].cls := cls ; symtab [i].size := size ;
  4697. symtab [i].elem := elem ; symtab [i].off := dc ;
  4698. symtab [i].fldFirst := recFldFirst ;
  4699. symtab [i].fldLast := recFldLast ;
  4700. symtab [i].arrIdx := newArrIdx ;
  4701. dc := dc + size ;
  4702. INC (i)
  4703. END
  4704. END ;
  4705. varspc := varspc + size * (symTop - first)
  4706. ELSE
  4707. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  4708. AND (cls # TArray) AND (cls # TFile) AND (cls # TText) THEN
  4709. Err (ENoLib) ;
  4710. RETURN
  4711. END ;
  4712. (* A local occupies [off, off+size-1] and lives BELOW the saved BP,
  4713. because BP-relative locals grow down from the top of the frame
  4714. while a STRING grows UP from its base (length byte, then chars).
  4715. Top-anchored packing keeps both true at once: locFree is the
  4716. highest still-free byte (-1 at the top), the new symbol's base
  4717. is placed so that its LAST byte lands on that byte, and locFree
  4718. then drops by the whole size. So the first INTEGER (size 2) is
  4719. at -2 and the second at -4, byte for byte what the old
  4720. pre-decrement rule produced, while a string[5] local (size 6) is
  4721. at -6..-1 instead of the old -2..+3 - which straddled the saved
  4722. BP at [BP] and the return address at [BP+2] and made `readln(s)'
  4723. into a local store characters over its own return address.
  4724. Each name in the group gets its own slot. *)
  4725. i := first ;
  4726. WHILE i < symTop DO
  4727. symtab [i].cls := cls ; symtab [i].size := size ;
  4728. symtab [i].elem := elem ;
  4729. symtab [i].fldFirst := recFldFirst ;
  4730. symtab [i].fldLast := recFldLast ;
  4731. symtab [i].arrIdx := newArrIdx ;
  4732. symtab [i].off := (locFree - size + 1) MOD 10000H ;
  4733. locFree := (locFree - size) MOD 10000H ;
  4734. INC (i)
  4735. END ;
  4736. locBytes := locBytes + size * (symTop - first)
  4737. END
  4738. END ;
  4739. IF MatchDelim (',') THEN
  4740. (* The older `name : type, name : type' spelling: another group
  4741. follows without a semicolon. TP3's grammar is names-then-one-type
  4742. with ',' inside a group and ';' between groups (TPSRC7 rdvarlst /
  4743. rdvloop then ecolon/rdvartp), and both spellings reach the same
  4744. symbols, so both separators are accepted here. *)
  4745. ELSIF MatchDelim (';') THEN
  4746. PeekKw (tok) ;
  4747. IF tok # TkNone THEN
  4748. RETURN
  4749. END
  4750. ELSE
  4751. Err (ENoSemi) ;
  4752. RETURN
  4753. END
  4754. END
  4755. END DefVar ;
  4756. PROCEDURE DefConst () ;
  4757. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4758. v : LONGINT ;
  4759. cls, typCls, typSize, typElem, soff, ci : CARDINAL ;
  4760. isStr : BOOLEAN ;
  4761. tok : CARDINAL ;
  4762. typed, setTyped, arrTyped : BOOLEAN ;
  4763. nb, k, divi, w : CARDINAL ;
  4764. BEGIN
  4765. LOOP
  4766. PeekKw (tok) ;
  4767. IF tok # TkNone THEN
  4768. RETURN
  4769. END ;
  4770. Skip () ; (* after the CONST keyword: skip blanks *)
  4771. IF NOT Alpha (CurCh ()) THEN
  4772. Err (EUnknown) ;
  4773. RETURN
  4774. END ;
  4775. GetWord () ;
  4776. SaveWord (nm) ;
  4777. DupTest (nm) ;
  4778. (* Two spellings: a plain constant `name = value', and a TYPED constant
  4779. `name : Type = value', which TP3 3.0 added (TPSRC7's constant reader
  4780. takes the type first and the value second). For a SCALAR type the
  4781. value still folds to an immediate, so the declared type is simply
  4782. recorded as the symbol's class - `FXMax : Char = 'G'' is a TChar
  4783. constant holding 71, and `writeln (FXMax)' prints G rather than 71.
  4784. A SET typed constant (`Numbers : set of Char = ['0'..'9']') is a value
  4785. with a layout, so it cannot fold: its bytes are emitted code-resident
  4786. and the name becomes an addressable value. See the storage decision
  4787. in CALC-COMPILE.md. An ARRAY or RECORD typed constant is still
  4788. refused loudly - those layouts come later. *)
  4789. typed := FALSE ;
  4790. setTyped := FALSE ;
  4791. arrTyped := FALSE ;
  4792. Skip () ;
  4793. IF CurCh () = ':' THEN
  4794. DropCh (GetCh ()) ;
  4795. ParseType (typCls, typSize, typElem) ;
  4796. IF OK () THEN
  4797. IF typCls = TSet THEN
  4798. setTyped := TRUE
  4799. ELSIF typCls = TArray THEN
  4800. arrTyped := TRUE
  4801. ELSIF typSize > 2 THEN
  4802. Err (ENoLib)
  4803. ELSE
  4804. typed := TRUE
  4805. END
  4806. END
  4807. END ;
  4808. IF OK () AND setTyped THEN
  4809. ExpectDelim ('=', ENoSemi) ;
  4810. IF RdSetLiteral (typElem, typSize, constBlob) THEN
  4811. soff := EmSetBlob (constBlob, typSize) ;
  4812. DropC (NewSym (nm, KVar, TSet, typSize, typElem, soff, 0, FALSE))
  4813. END
  4814. ELSIF OK () AND arrTyped THEN
  4815. (* array typed constant: `(v1, v2, ...)' in element order, each value
  4816. written little-endian in typElem bytes. CALC's is XPOS (seven
  4817. Integers, 14 bytes). An element that is a STRING (CALC.INC's
  4818. StandardfunctionNames) is a later increment, and is refused here. *)
  4819. ExpectDelim ('=', ENoSemi) ;
  4820. ExpectDelim ('(', ENoSemi) ;
  4821. nb := 0 ;
  4822. LOOP
  4823. RdConst (v, cls, isStr) ;
  4824. IF isStr OR (nb + typElem > 512) THEN
  4825. Err (ENoLib) ;
  4826. EXIT
  4827. END ;
  4828. w := VAL (CARDINAL, W16 (v)) ;
  4829. divi := 1 ;
  4830. k := 0 ;
  4831. WHILE k < typElem DO
  4832. constBlob [nb] := CHR ((w DIV divi) MOD 256) ;
  4833. divi := divi * 256 ;
  4834. INC (nb) ;
  4835. INC (k)
  4836. END ;
  4837. IF MatchDelim (',') THEN
  4838. (* another element *)
  4839. ELSE
  4840. EXIT
  4841. END
  4842. END ;
  4843. ExpectDelim (')', ENoSemi) ;
  4844. IF OK () THEN
  4845. soff := EmSetBlob (constBlob, typSize) ;
  4846. ci := NewSym (nm, KVar, TArray, typSize, typElem, soff, 0, FALSE) ;
  4847. symtab [ci].arrIdx := newArrIdx
  4848. END
  4849. ELSIF OK () THEN
  4850. ExpectDelim ('=', ENoSemi) ;
  4851. RdConst (v, cls, isStr) ;
  4852. IF isStr THEN
  4853. Err (ENoLib)
  4854. END ;
  4855. IF OK () THEN
  4856. IF typed THEN
  4857. cls := typCls
  4858. END ;
  4859. DropC (NewSym (nm, KConst, cls, 0, 0, 0, v, FALSE))
  4860. END
  4861. END ;
  4862. IF NOT MatchDelim (';') THEN
  4863. Err (ENoSemi) ;
  4864. RETURN
  4865. END
  4866. END
  4867. END DefConst ;
  4868. PROCEDURE DefLabelPart () ;
  4869. VAR nm : ARRAY [0..9] OF CHAR ;
  4870. n : CARDINAL ;
  4871. BEGIN
  4872. LOOP
  4873. Skip () ;
  4874. IF NOT Digit (CurCh ()) THEN
  4875. Err (EUnknown) ;
  4876. RETURN
  4877. END ;
  4878. n := 0 ;
  4879. WHILE Digit (CurCh ()) DO
  4880. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  4881. DropCh (GetCh ())
  4882. END ;
  4883. NumToName (n, nm) ;
  4884. IF NOT Search (nm, n) THEN
  4885. DropC (NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE))
  4886. END ;
  4887. IF NOT MatchDelim (',') THEN
  4888. IF MatchDelim (';') THEN
  4889. RETURN
  4890. END ;
  4891. Err (ENoSemi) ;
  4892. RETURN
  4893. END
  4894. END
  4895. END DefLabelPart ;
  4896. PROCEDURE IfMatchSemi () ;
  4897. BEGIN
  4898. IF NOT MatchDelim (';') THEN
  4899. Err (ENoSemi)
  4900. END
  4901. END IfMatchSemi ;
  4902. PROCEDURE SymEpi () ;
  4903. (* function result: AX := result var *)
  4904. BEGIN
  4905. IF curIsFunc THEN
  4906. IF OK () THEN
  4907. EmLoadVar (TRUE, symtab [resultVar].off, symtab [resultVar].size)
  4908. END
  4909. END
  4910. END SymEpi ;
  4911. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ;
  4912. (* How many bytes a value parameter occupies in the callee's stack frame.
  4913. TP3's `tstscal' (TPSRC7 1243): a scalar-like parameter is AT LEAST two
  4914. bytes on the stack even when its type is one byte; anything larger spends
  4915. its own size. Generalised here so step 2 can put a string's 71 bytes on
  4916. the stack without changing what a scalar does today. *)
  4917. BEGIN
  4918. IF (cls = TScalar) OR (cls = TChar) OR (cls = TBool) OR (cls = TEnum) THEN
  4919. RETURN 2
  4920. END ;
  4921. RETURN size
  4922. END SlotSize ;
  4923. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ;
  4924. (* The bytes a parameter occupies in the frame. A VAR parameter's slot is the
  4925. ADDRESS, always two bytes, whatever its type: `size' stays the type's width
  4926. so loads and stores know whether they read one byte or two. *)
  4927. BEGIN
  4928. IF e.isVar THEN
  4929. RETURN 2
  4930. END ;
  4931. RETURN SlotSize (e.cls, e.size)
  4932. END ParamSlotBytes ;
  4933. PROCEDURE ProcFunc () ;
  4934. (* PROCEDURE name (params) ; body | FUNCTION name (params) : type ; body *)
  4935. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4936. idx, old : CARDINAL ;
  4937. tok, tok2 : CARDINAL ;
  4938. parmNm : ARRAY [0..MaxName] OF CHAR ;
  4939. cls, size, elem : CARDINAL ;
  4940. isFunc, groupVar : BOOLEAN ;
  4941. saveNest, saveLoc, saveRes, saveF : CARDINAL ;
  4942. saveLB, savePO : CARDINAL ;
  4943. nestMark : CARDINAL ; (* symTop just inside this procedure *)
  4944. i, first : CARDINAL ;
  4945. BEGIN
  4946. isFunc := curIsFunc ;
  4947. Skip () ; (* after the PROCEDURE/FUNCTION keyword *)
  4948. IF NOT Alpha (CurCh ()) THEN
  4949. Err (EUnknown) ;
  4950. RETURN
  4951. END ;
  4952. GetWord () ;
  4953. SaveWord (nm) ;
  4954. IF Search (nm, idx) AND (symtab [idx].tag = KProc)
  4955. AND (symtab [idx].fwd) THEN
  4956. old := idx
  4957. ELSIF Search (nm, idx) THEN
  4958. Err (EUnknown) ;
  4959. RETURN
  4960. ELSE
  4961. old := NewSym (nm, KProc, TNone, 0, 0, 0, 0, FALSE)
  4962. END ;
  4963. IF isFunc THEN
  4964. symtab [old].tag := KFunc
  4965. END ;
  4966. saveNest := lexnest ;
  4967. saveLoc := locFree ;
  4968. saveRes := resultVar ;
  4969. saveF := VAL (CARDINAL, ORD (curIsFunc)) ;
  4970. saveLB := locBytes ;
  4971. savePO := parmOff ;
  4972. INC (lexnest) ;
  4973. nestMark := symTop ; (* after the proc's own name, before its params *)
  4974. locFree := 0FFFFH ;
  4975. locBytes := 0 ;
  4976. parmOff := 4 ;
  4977. IF MatchDelim ('(') THEN
  4978. IF CurCh () # ')' THEN
  4979. LOOP
  4980. (* PeekKw, not MatchKey: MatchKey CONSUMES the word it reads, so
  4981. using it to test for VAR would eat the parameter's name. *)
  4982. PeekKw (tok) ;
  4983. groupVar := FALSE ;
  4984. IF tok = TkVar THEN
  4985. (* A by-reference parameter: the slot will hold an ADDRESS.
  4986. `size' still carries the type's own width, because the
  4987. callee's loads and stores must know whether they move one
  4988. byte or two. *)
  4989. DropB (MatchKey (tok)) ;
  4990. groupVar := TRUE
  4991. END ;
  4992. first := symTop ;
  4993. LOOP
  4994. Skip () ; (* blanks before the parameter name *)
  4995. IF NOT Alpha (CurCh ()) THEN
  4996. Err (EUnknown) ;
  4997. RETURN
  4998. END ;
  4999. GetWord () ;
  5000. SaveWord (parmNm) ;
  5001. DupTest (parmNm) ;
  5002. DropC (NewSym (parmNm, KVar, TNone, 0, 0, 0, 0, TRUE)) ;
  5003. IF NOT MatchDelim (',') THEN
  5004. EXIT
  5005. END
  5006. END ;
  5007. ExpectDelim (':', ENoSemi) ; (* formal is 'name : type' *)
  5008. ParseType (cls, size, elem) ;
  5009. IF groupVar AND ((size > 2) OR (cls = TString)) THEN
  5010. (* A VAR parameter of a record, array or string would need the
  5011. callee to address through a larger object (or a counted
  5012. string) than the scalar [BX] paths below; refusing is the
  5013. honest answer, not quietly passing it by value. *)
  5014. Err (ENoLib) ;
  5015. RETURN
  5016. END ;
  5017. IF (size > 2) AND (cls # TString) THEN
  5018. (* A string VALUE parameter is a whole-slot copy (n+1 bytes on
  5019. the stack); any other type wider than a word - a record, an
  5020. array, a set - is still refused. *)
  5021. Err (ENoLib) ;
  5022. RETURN
  5023. END ;
  5024. i := first ;
  5025. WHILE i < symTop DO
  5026. symtab [i].cls := cls ; symtab [i].size := size ;
  5027. symtab [i].elem := elem ;
  5028. symtab [i].off := parmOff ;
  5029. symtab [i].isVar := groupVar ;
  5030. IF groupVar THEN
  5031. parmOff := parmOff + 2 (* the address, whatever the type *)
  5032. ELSE
  5033. parmOff := parmOff + SlotSize (cls, size)
  5034. END ;
  5035. INC (i)
  5036. END ;
  5037. IF MatchDelim (')') THEN
  5038. EXIT
  5039. END ;
  5040. IF MatchDelim (';') THEN
  5041. (* next group *)
  5042. ELSIF MatchDelim (',') THEN
  5043. (* the older `name : type, name : type' spelling *)
  5044. ELSE
  5045. Err (ENoSemi) ;
  5046. EXIT
  5047. END
  5048. END
  5049. ELSE
  5050. DropCh (GetCh ())
  5051. END
  5052. END ;
  5053. (* TP3 lays a parameter list out BACKWARDS from BP+4: the LAST declared
  5054. parameter sits at BP+4 and each earlier one is 2 bytes farther from BP
  5055. (RESUME-TP3.md 3.11 - "le dernier paramètre déclaré est le plus proche
  5056. (BP+4)" - and the Code Generation Internals stack frame, "BP+4: last
  5057. parameter"). This is the other half of pushing the arguments as they
  5058. are parsed: the first argument is pushed first and so ends up farthest
  5059. from BP, which has to be the FIRST declared parameter's slot.
  5060. During the loop the offsets were provisional, in declaration order
  5061. (parmOff starts at 4 and grows by each parameter's SLOT size), so
  5062. parameter k sat at 4 + sum of the slots before it. For slot sizes s and
  5063. frame total T, the parameter's final base is
  5064. 4 + (T - prefix - s) = 8 + T - off - s, which sends the FIRST declared
  5065. parameter to the far end and the LAST to BP+4. With every slot 2 -
  5066. every scalar, which is all this compiler accepts today - that reduces
  5067. exactly to the old `parmOff + 2 - off`, so no existing frame moves.
  5068. A slot larger than 2 (a string's 71 bytes) falls out of the same
  5069. formula, and a VAR parameter is exactly 2 even when its TYPE is one
  5070. byte: ParamSlotBytes carries that rule.
  5071. The range is exactly the parameters: the only symbol created while the
  5072. list is read is the parameter itself (NewSym inside the loop),
  5073. ParseType creates no symbols, the procedure's own name predates
  5074. nestMark, and a function's result variable is created after this point. *)
  5075. i := nestMark ;
  5076. WHILE i < symTop DO
  5077. symtab [i].off := 8 + (parmOff - 4) - symtab [i].off
  5078. - ParamSlotBytes (symtab [i]) ;
  5079. INC (i)
  5080. END ;
  5081. (* Record the parameter list on the procedure symbol: a call site has to
  5082. know each argument's SLOT size to push and clean up the right number of
  5083. bytes. Only when this definition actually read a list - a FORWARD's
  5084. list is kept, and the later `function Expression;' that repeats only the
  5085. name must not wipe it. *)
  5086. IF symTop > nestMark THEN
  5087. symtab [old].parmFirst := nestMark ;
  5088. symtab [old].parmCount := symTop - nestMark
  5089. END ;
  5090. IF isFunc THEN
  5091. IF MatchDelim (':') THEN
  5092. ParseType (cls, size, elem)
  5093. ELSE
  5094. cls := TScalar ;
  5095. size := 2 ;
  5096. elem := 2
  5097. END ;
  5098. IF size > 2 THEN
  5099. Err (ENoLib) ;
  5100. RETURN
  5101. END ;
  5102. symtab [old].cls := cls ;
  5103. symtab [old].size := size ;
  5104. resultVar := NewSym (nm, KVar, cls, size, elem,
  5105. (locFree - size + 1) MOD 10000H, 0, TRUE) ;
  5106. symtab [old].resvar := resultVar ;
  5107. locFree := (locFree - size) MOD 10000H ;
  5108. locBytes := locBytes + size
  5109. END ;
  5110. IfMatchSemi () ;
  5111. PeekKw (tok2) ;
  5112. IF (tok2 = TkForward) OR (tok2 = TkExternal) THEN
  5113. DropB (MatchKey (tok2)) ;
  5114. symtab [old].fwd := TRUE ;
  5115. symtab [old].defnd := (tok2 = TkExternal) ;
  5116. IfMatchSemi () ;
  5117. HideLocals (nestMark) ; (* a FORWARD's parameters are not the
  5118. caller's to see either *)
  5119. lexnest := saveNest ;
  5120. locFree := saveLoc ;
  5121. resultVar := saveRes ;
  5122. curIsFunc := (saveF # 0) ;
  5123. locBytes := saveLB ;
  5124. parmOff := savePO ;
  5125. RETURN
  5126. END ;
  5127. (* body *)
  5128. symtab [old].goPos := pc ;
  5129. symtab [old].defnd := TRUE ;
  5130. EmPushBp () ;
  5131. EmMovBpSp () ;
  5132. DefPart () ; (* nested declarations; stops at BEGIN *)
  5133. IF locBytes > 0 THEN
  5134. EmSubSp (locBytes)
  5135. END ;
  5136. DropC (EmCall (TU_StackChk)) ;
  5137. Statmnt () ; (* body *)
  5138. IF OK () THEN
  5139. SymEpi () ;
  5140. EmLeave () ;
  5141. EmRet ()
  5142. END ;
  5143. (* patch pending forward calls to this proc *)
  5144. i := 0 ;
  5145. WHILE i < nPend DO
  5146. IF (pend [i].kind = 1) AND (pend [i].who = old) THEN
  5147. SetPatTgt (pend [i].place, symtab [old].goPos) ;
  5148. pend [i].kind := 99
  5149. END ;
  5150. INC (i)
  5151. END ;
  5152. HideLocals (nestMark) ; (* parameters and locals stop here *)
  5153. lexnest := saveNest ;
  5154. locFree := saveLoc ;
  5155. resultVar := saveRes ;
  5156. curIsFunc := (saveF # 0) ;
  5157. locBytes := saveLB ;
  5158. parmOff := savePO
  5159. END ProcFunc ;
  5160. PROCEDURE DefType () ;
  5161. (* 'name' '=' typeDef ; ... until a declaration keyword appears *)
  5162. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  5163. cls, size, elem, tidx : CARDINAL ;
  5164. tok : CARDINAL ;
  5165. BEGIN
  5166. LOOP
  5167. PeekKw (tok) ;
  5168. IF tok # TkNone THEN
  5169. RETURN
  5170. END ;
  5171. Skip () ; (* after the TYPE keyword: skip blanks *)
  5172. IF NOT Alpha (CurCh ()) THEN
  5173. Err (EUnknown) ;
  5174. RETURN
  5175. END ;
  5176. GetWord () ;
  5177. SaveWord (nm) ;
  5178. DupTest (nm) ;
  5179. ExpectDelim ('=', ENoSemi) ;
  5180. ParseType (cls, size, elem) ;
  5181. IF NOT OK () THEN
  5182. RETURN
  5183. END ;
  5184. tidx := NewSym (nm, KType, cls, size, elem, 0, 0, FALSE) ;
  5185. IF cls = TEnum THEN
  5186. (* the enumeration's bounds, set by ParseType, belong to the type - so
  5187. `set of Attributes' can size its base (0..n-1, one byte) *)
  5188. symtab [tidx].lo := enumLo ;
  5189. symtab [tidx].hi := enumHi
  5190. END ;
  5191. IF cls = TRecord THEN
  5192. (* and a record's fields live in the field table; the type records
  5193. which range is its own *)
  5194. symtab [tidx].fldFirst := recFldFirst ;
  5195. symtab [tidx].fldLast := recFldLast
  5196. END ;
  5197. IF cls = TArray THEN
  5198. symtab [tidx].arrIdx := newArrIdx
  5199. END ;
  5200. DropC (tidx) ;
  5201. IF NOT MatchDelim (';') THEN
  5202. Err (ENoSemi) ;
  5203. RETURN
  5204. END
  5205. END
  5206. END DefType ;
  5207. PROCEDURE DefPart () ;
  5208. (* LABEL / CONST / TYPE / VAR / OVERLAY / PROC / FUNCTION / BEGIN *)
  5209. VAR tok : CARDINAL ;
  5210. BEGIN
  5211. LOOP
  5212. IF MatchDelim (';') THEN
  5213. (* separator between declarations *)
  5214. ELSE
  5215. PeekKw (tok) ;
  5216. IF tok = TkBegin THEN
  5217. RETURN
  5218. END ;
  5219. IF NOT MatchKey (tok) THEN
  5220. Err (EUnknown) ;
  5221. RETURN
  5222. END ;
  5223. CASE tok OF
  5224. TkLabel : DefLabelPart () ;
  5225. | TkConst : DefConst () ;
  5226. | TkType : DefType () ;
  5227. | TkVar : DefVar () ;
  5228. | TkOverlay :
  5229. LOOP
  5230. Skip () ;
  5231. IF CurCh () = ';' THEN
  5232. DropCh (GetCh ()) ;
  5233. EXIT
  5234. END ;
  5235. IF CurCh () = 0C THEN
  5236. Err (ENoSemi) ;
  5237. EXIT
  5238. END ;
  5239. DropCh (GetCh ())
  5240. END ;
  5241. | TkProcedure : curIsFunc := FALSE ; ProcFunc () ;
  5242. | TkFunction : curIsFunc := TRUE ; ProcFunc () ;
  5243. ELSE
  5244. Err (EUnknown) ;
  5245. RETURN
  5246. END ;
  5247. IF NOT OK () THEN
  5248. RETURN
  5249. END
  5250. END
  5251. END
  5252. END DefPart ;
  5253. (* ---------------------------------------------------------------- *)
  5254. (* driver (TPSRC7 compile) *)
  5255. (* ---------------------------------------------------------------- *)
  5256. PROCEDURE DefBuiltins () ;
  5257. (* The standard procedures. Without these, WRITELN is absent from the
  5258. symbol table, Statmnt's identifier branch fails its Search and every
  5259. program that prints anything dies with EUnknown (41) on the '(' after the
  5260. call name - the single remaining cause of failure in the fixture matrix.
  5261. Tagged KBuiltin (not KProc) because these are not called generically:
  5262. WRITE/WRITELN/READ/READLN need TP3's per-argument type dispatch
  5263. (IoCall), and HALT takes no argument at all. defnd is TRUE because the
  5264. entry point is known - there is no forward reference to patch. *)
  5265. VAR i : CARDINAL ;
  5266. BEGIN
  5267. i := NewSym ("WRITE" , KBuiltin, BI_Write , 0, 0, 0, 0, FALSE) ;
  5268. symtab [i].defnd := TRUE ;
  5269. symtab [i].goPos := TU_WrInt ;
  5270. i := NewSym ("WRITELN", KBuiltin, BI_WriteLn, 0, 0, 0, 0, FALSE) ;
  5271. symtab [i].defnd := TRUE ;
  5272. symtab [i].goPos := TU_WrInt ;
  5273. i := NewSym ("READ" , KBuiltin, BI_Read , 0, 0, 0, 0, FALSE) ;
  5274. symtab [i].defnd := TRUE ;
  5275. symtab [i].goPos := TU_RdInt ;
  5276. i := NewSym ("READLN" , KBuiltin, BI_ReadLn , 0, 0, 0, 0, FALSE) ;
  5277. symtab [i].defnd := TRUE ;
  5278. symtab [i].goPos := TU_RdInt ;
  5279. i := NewSym ("HALT" , KBuiltin, BI_Halt , 0, 0, 0, 0, FALSE) ;
  5280. symtab [i].defnd := TRUE ;
  5281. symtab [i].goPos := TU_Halt ;
  5282. i := NewSym ("LENGTH" , KBuiltin, BI_Length , 0, 0, 0, 0, FALSE) ;
  5283. symtab [i].defnd := TRUE ;
  5284. symtab [i].goPos := 0 ; (* inline: the length byte, no entry *)
  5285. (* The CRT identifiers. ClrScr and GotoXY emit real INT 10h code; the other
  5286. four are registered so they are recognised, and IoCall refuses them with
  5287. ENoLib - loud, not inert. *)
  5288. i := NewSym ("CLRSCR" , KBuiltin, BI_ClrScr , 0, 0, 0, 0, FALSE) ;
  5289. symtab [i].defnd := TRUE ;
  5290. i := NewSym ("GOTOXY" , KBuiltin, BI_GotoXY , 0, 0, 0, 0, FALSE) ;
  5291. symtab [i].defnd := TRUE ;
  5292. i := NewSym ("LOWVIDEO", KBuiltin, BI_LowVideo, 0, 0, 0, 0, FALSE) ;
  5293. symtab [i].defnd := TRUE ;
  5294. i := NewSym ("NORMVIDEO", KBuiltin, BI_NormVideo, 0, 0, 0, 0, FALSE) ;
  5295. symtab [i].defnd := TRUE ;
  5296. i := NewSym ("CLREOL" , KBuiltin, BI_ClrEol , 0, 0, 0, 0, FALSE) ;
  5297. symtab [i].defnd := TRUE ;
  5298. i := NewSym ("DELAY" , KBuiltin, BI_Delay , 0, 0, 0, 0, FALSE) ;
  5299. symtab [i].defnd := TRUE ;
  5300. i := NewSym ("KEYPRESSED", KBuiltin, BI_KeyPressed, 0, 0, 0, 0, FALSE) ;
  5301. symtab [i].defnd := TRUE ;
  5302. (* KBD: the console keyboard as a TEXT file. This runtime's read entries
  5303. already read the console, so `Read(Kbd, Ch)' drops the file argument and
  5304. reads a character exactly as `Read(Ch)' does. *)
  5305. i := NewSym ("KBD", KVar, TText, FileVarSize, 1, 0, 0, FALSE) ;
  5306. symtab [i].isKbd := TRUE
  5307. END DefBuiltins ;
  5308. PROCEDURE Inittur () ;
  5309. (* reset compiler state and define the standard types *)
  5310. VAR i, rt : CARDINAL ;
  5311. BEGIN
  5312. abortFac := FALSE ;
  5313. errNum := 0 ;
  5314. txerrPos := 0 ;
  5315. srcPos := 0 ;
  5316. srcLen := Length () ;
  5317. inclActive := FALSE ;
  5318. inclEnd := 0 ;
  5319. (* The image layout is
  5320. [JMP rel16][runtime][program header][program code]
  5321. The runtime is copied to the front, which is what the original does:
  5322. TPSRC7 "copyrt" runs REPZ MOVSB with SI=DI=0 and then "MOV pc,#$2D7C".
  5323. Because the runtime sits at (near) offset 0, every address the compiler
  5324. emits is already image-absolute - the data symbols' offsets, the TU_*
  5325. call targets and the rel16 displacements all need no relocation pass.
  5326. (The base shift would in fact cancel in EmCall's arithmetic, since both
  5327. sides of a CALL move together; making the offsets absolute just means
  5328. the linker has nothing to do but copy bytes.)
  5329. The JMP is new, and it is not cosmetic. A DOS .COM is entered at
  5330. CS:0100, i.e. FILE offset 0, and for a long time offset 0 held the
  5331. runtime's first bytes - so a .COM built by this compiler started by
  5332. executing initmem with AX holding whatever the loader left in it. Every
  5333. test up to that point checked bytes and never ran the thing, so it could
  5334. not see this. The jump is the program's entry and the runtime is
  5335. ordinary data to it; keeping the runtime at the front is what preserves
  5336. the no-relocation property, so the jump goes in front of the runtime
  5337. rather than the runtime being moved behind the program.
  5338. dc is put a fixed 4 KiB above the end of the program so that data cannot
  5339. collide with code in a single 64 KiB .COM segment. LIMITATION: a
  5340. program whose code exceeds 4 KiB overruns its own data area. TP3 had
  5341. overlay segments for this; we do not, and the check belongs where the
  5342. limit is documented rather than as a silent truncation. *)
  5343. RT_Build (EntSize) ;
  5344. rt := RT_Size () ;
  5345. IF rt >= MaxCode THEN
  5346. Err (EMemOvf) ; (* cannot happen: rt is 436 *)
  5347. RETURN
  5348. END ;
  5349. (* The entry jump, at image offset 0. See the layout note above: a DOS
  5350. .COM is entered at CS:0100, which is file offset 0, so whatever sits
  5351. at offset 0 is the program's first executed instruction. *)
  5352. (* The jump's three bytes are written out longhand rather than through
  5353. Eword, because Eword writes at pc and advances it, and pc is stale at
  5354. this point -- the operand landed wherever the last compile left pc. *)
  5355. cbuf [0] := 0E9H ; (* JMP rel16 *)
  5356. entRel := 1 ;
  5357. cbuf [entRel] := 0 ;
  5358. cbuf [entRel + 1] := 0 ;
  5359. i := EntSize ;
  5360. WHILE i - EntSize < rt DO
  5361. cbuf [i] := RT_Byte (i - EntSize) ;
  5362. INC (i)
  5363. END ;
  5364. pc := rt + EntSize ;
  5365. rtSz := rt + EntSize ;
  5366. dataBase := rtSz + 1000H ;
  5367. dc := dataBase ;
  5368. imgReady := TRUE ;
  5369. strTop := 0 ;
  5370. strCnt := 0 ;
  5371. rdStrX := 0 ;
  5372. varspc := 0 ;
  5373. symTop := 0 ;
  5374. nPatch := 0 ;
  5375. nPend := 0 ;
  5376. exitCnt := 0 ;
  5377. brkN := 0 ;
  5378. caseN := 0 ;
  5379. lexnest := 0 ;
  5380. curIsFunc := FALSE ;
  5381. resultVar := 0 ;
  5382. locFree := 0FFFFH ;
  5383. locBytes := 0 ;
  5384. parmOff := 4 ;
  5385. dirs.rng := TRUE ;
  5386. dirs.chk := TRUE ;
  5387. InitKeys () ;
  5388. DropC (NewSym ("INTEGER", KType, TScalar, 2, 2, 0, 0, FALSE)) ;
  5389. DropC (NewSym ("BYTE" , KType, TScalar, 1, 1, 0, 0, FALSE)) ;
  5390. DropC (NewSym ("CHAR" , KType, TChar, 1, 1, 0, 0, FALSE)) ;
  5391. DropC (NewSym ("BOOLEAN", KType, TBool , 1, 1, 0, 0, FALSE)) ;
  5392. DropC (NewSym ("REAL" , KType, TReal , 6, 6, 0, 0, FALSE)) ;
  5393. DropC (NewSym ("STRING" , KType, TString, 256, 1, 0, 0, FALSE)) ;
  5394. DropC (NewSym ("TRUE" , KConst, TBool, 1, 1, 0, 1, FALSE)) ;
  5395. DropC (NewSym ("FALSE" , KConst, TBool, 1, 1, 0, 0, FALSE)) ;
  5396. DefBuiltins () ;
  5397. tmpA := NewSym ("@@T1", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  5398. dc := dc + 2 ;
  5399. tmpB := NewSym ("@@T2", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  5400. dc := dc + 2 ;
  5401. (* The text attribute LowVideo/NormVideo set (default 7, written by the
  5402. prologue). One byte, and its address is baked into the clear sequences. *)
  5403. crtAttrOff := dc ;
  5404. DropC (NewSym ("@@ATTR", KVar, TScalar, 1, 1, dc, 0, FALSE)) ;
  5405. dc := dc + 1 ;
  5406. (* Runtime entry offsets, derived from the blob rather than assumed. This
  5407. has to happen after RT_Build, since RT_Entry only knows where the code
  5408. landed once the blob is assembled.
  5409. RT_Entry returns an IMAGE-ABSOLUTE address, already biased by the base
  5410. RT_Build was given, so nothing here has to know where the runtime
  5411. landed. It used to return a blob-relative offset, and the bias was
  5412. applied here instead - three bytes' worth, for the entry jump. With
  5413. that line missing, every CALL landed three bytes short, in the middle of
  5414. a neighbouring runtime entry, and a CALL into the middle of wrtin's
  5415. `INT 21h' behaves perfectly plausibly: the program runs, prints nothing
  5416. and hangs. Only running it finds that. *)
  5417. IF (RT_Entry (13) = 0) OR (RT_Entry (11) = 0) OR (RT_Entry (3) = 0) THEN
  5418. (* RT_Entry returns 0 for an unknown selector. initmem sits at 0
  5419. legitimately, so it cannot appear in this test - but wrtinl, rdln
  5420. and wrint never can, so catching them is enough to catch a runtime
  5421. that failed to build or a selector that went stale. This test is on
  5422. 0 is not a usable address here, since RT_Entry returns an
  5423. image-absolute address and the base is EntSize. *)
  5424. Err (EMemOvf)
  5425. END ;
  5426. TU_InitMem := RT_Entry (0) ;
  5427. TU_ProgEnd := RT_Entry (1) ;
  5428. TU_StackChk := RT_Entry (2) ;
  5429. TU_WrInt := RT_Entry (3) ;
  5430. TU_WrChar := RT_Entry (4) ;
  5431. TU_WrBool := RT_Entry (5) ;
  5432. TU_WrReal := RT_Entry (6) ;
  5433. TU_WrLn := RT_Entry (7) ;
  5434. TU_RdInt := RT_Entry (8) ;
  5435. TU_RdChar := RT_Entry (9) ;
  5436. TU_RdBool := RT_Entry (10) ;
  5437. TU_RdLn := RT_Entry (11) ;
  5438. TU_Halt := RT_Entry (12) ;
  5439. TU_WrInl := RT_Entry (13) ; (* inline string literal *)
  5440. TU_RdByte := RT_Entry (14) ; (* a BYTE read stores one byte *)
  5441. TU_WrStr := RT_Entry (15) ; (* a string variable is written through
  5442. the address on the stack *)
  5443. TU_RdStr := RT_Entry (16) ; (* readln(s)/read(s): TPSRC8 prdstr,
  5444. TPSRC4 xrdstr *)
  5445. TU_StrStore := RT_Entry (17) ; (* s := t: TPSRC8 asnvar, TPSRC2 strstore *)
  5446. TU_CmpStr := RT_Entry (18) ; (* string compare: TPSRC9 vcompare,
  5447. TPSRC2 cmpstr *)
  5448. TU_StrCat := RT_Entry (19) ; (* string concatenation: TPSRC2 xconcat *)
  5449. END Inittur ;
  5450. PROCEDURE HeadWord (VAR slot : CARDINAL) ;
  5451. BEGIN
  5452. slot := pc ;
  5453. Eword (0)
  5454. END HeadWord ;
  5455. PROCEDURE Compile (VAR errNo, errPos : CARDINAL) : BOOLEAN ;
  5456. VAR tok : CARDINAL ;
  5457. overProc : CARDINAL ;
  5458. hasProc : BOOLEAN ;
  5459. BEGIN
  5460. Inittur () ;
  5461. IF OK () THEN
  5462. (* Resolve every {$I} first: the parser (and DeclaresProc's lookahead)
  5463. must see one finished buffer. See ExpandIncludes. *)
  5464. ExpandIncludes ()
  5465. END ;
  5466. IF OK () THEN
  5467. (* program prologue: header words, CALL initmem, MOV BP,SP *)
  5468. HeadWord (hdrFlag) ;
  5469. HeadWord (hdrCS) ;
  5470. HeadWord (hdrDS) ;
  5471. HeadWord (hdrHeap) ;
  5472. HeadWord (hdrMax) ;
  5473. Eword (16) ; (* max open files *)
  5474. Eword (0) ; (* input buffer word *)
  5475. Eword (0) ; (* output buffer word *)
  5476. (* Here, and not one line earlier, is the first instruction of the
  5477. program: everything above is the header, which is DATA. The entry
  5478. jump has to land exactly here. Recorded rather than assumed, so that
  5479. a header that grows a word moves the target with it. *)
  5480. prologAt := pc ;
  5481. (* TU_InitMem takes the header offset in AX, not on the stack, so the
  5482. AX load has to precede the call. Previously the prologue called
  5483. offset 8 - which in this layout is the hdrMax word - and that was
  5484. coherent only because the runtime was not there. Now it is the
  5485. real header. *)
  5486. EmMovAxi ((rtSz + LoadBias) MOD 10000H) ;
  5487. DropC (EmCall (TU_InitMem)) ;
  5488. EmMovBpSp () ;
  5489. (* [@@ATTR] := 7 - the default text attribute, before any LowVideo or
  5490. NormVideo runs. The data area is zero-filled, and attribute 0 would
  5491. make every clear black-on-black. Through EmCrtSeq, not raw Ebyte:
  5492. Compile is not a one-line emitter, and the helper audit rightly
  5493. refuses to let a byte-emitting statement hide inside it. *)
  5494. EmCrtSeq (CrtLow) ;
  5495. IF MatchKey (tok) AND (tok = TkProgram) THEN
  5496. (* MatchKey stops right after "PROGRAM", so the optional program
  5497. name normally follows blanks. Skip them before testing for the
  5498. name: otherwise Alpha sees the blank, the name is never consumed
  5499. and IfMatchSemi reports ENoSemi at the name. *)
  5500. Skip () ;
  5501. IF Alpha (CurCh ()) THEN
  5502. GetWord ()
  5503. END ;
  5504. IF MatchDelim ('(') THEN
  5505. WHILE NOT MatchDelim (')') DO
  5506. IF Alpha (CurCh ()) THEN
  5507. GetWord ()
  5508. END ;
  5509. IF CurCh () = ',' THEN
  5510. DropCh (GetCh ())
  5511. END
  5512. END
  5513. END ;
  5514. IfMatchSemi ()
  5515. END ;
  5516. IF OK () THEN
  5517. (* Jump over the procedure bodies, if there are any. DefPart
  5518. compiles them HERE, between the prologue and the main statement
  5519. part, and there was no jump - so a program with a procedure fell
  5520. off the end of the prologue into the first procedure. See
  5521. DeclaresProc for why the condition is asked before DefPart runs
  5522. and not after. *)
  5523. hasProc := DeclaresProc () ;
  5524. IF hasProc THEN
  5525. overProc := EmJmpNear (0)
  5526. END ;
  5527. DefPart () ;
  5528. IF OK () THEN
  5529. (* A separate flag, NOT `overProc # 0`. EmJmpNear returns a
  5530. patch SLOT, and slot 0 is a perfectly ordinary slot - the
  5531. first forward jump in a program is slot 0. So a zero test
  5532. cannot tell "no forward jump" from "forward jump in slot 0",
  5533. it just skips the first patch, and the jump keeps its
  5534. placeholder target of 0. The program then jumped to image
  5535. offset 0, i.e. back to the entry jump, and ran the runtime
  5536. and the whole program again, forever. The slot is only
  5537. valid together with a boolean saying a slot was taken. *)
  5538. IF hasProc THEN
  5539. SetPatTgt (overProc, pc)
  5540. END ;
  5541. IF MatchKey (tok) AND (tok = TkBegin) THEN
  5542. Compound () ;
  5543. IF OK () THEN
  5544. EmXorAxAx () ;
  5545. DropC (EmCall (TU_ProgEnd)) ;
  5546. ResolvePatches () ;
  5547. (* Program-only sizes. The runtime is not part of the
  5548. program's code, and the fixture table has always meant
  5549. "the program's own code", so subtract it here rather
  5550. than making every expectation in expected.tsv wrong. *)
  5551. codeSz := pc - rtSz ;
  5552. dataSz := dc - dataBase ;
  5553. (* Header words. The layout is ours (the original's is
  5554. bigger and serves a real overlay loader), but
  5555. Runtime.EmitInitMem reads +4 and +8, so hdrDS and
  5556. hdrHeap must be the data base and the data end. *)
  5557. (* The entry jump's displacement. A .COM is entered at
  5558. CS:0100 = file offset 0, so the jump is the only thing
  5559. that decides where execution starts, and it has to land
  5560. on the START of the program code - the prologue, which is
  5561. at rtSz - not on pc, which is the END of it. (Patching
  5562. pc - EntSize, i.e. the end, lands one byte past the last
  5563. instruction, in the zero-filled code/data gap, where the
  5564. CPU slides through `ADD [BX+SI],AL' until it faults.)
  5565. The displacement is measured from the END of the jump,
  5566. and both addresses are image-absolute, so the load
  5567. segment cancels. *)
  5568. (* The entry jump's displacement. A .COM is entered at
  5569. CS:0100 = file offset 0, so this jump is the only thing
  5570. that decides where execution starts.
  5571. The target is prologAt - where the prologue ACTUALLY
  5572. began, recorded before the header words were emitted,
  5573. and the header is 16 bytes long, so this is rtSz + 16 and
  5574. NOT rtSz. Landing on rtSz lands on the HEADER, which is
  5575. data, and the CPU then decodes sixteen bytes of it as
  5576. instructions. That failure is spectacularly
  5577. non-deterministic across programs: 01 00 is
  5578. `ADD [BX+SI],AX' and is harmless, so writeln('hi') ran
  5579. fine by sliding through the header into the prologue,
  5580. while t07's hdrHeap word 90 12 decodes as a LOCK-prefixed
  5581. ADD whose displacement crosses a page and faults, and the
  5582. program hung with no output at all. Both looked like
  5583. "the jump is in the right area". Recording the position
  5584. rather than assuming it means a future header that grows
  5585. a word cannot silently reintroduce this. *)
  5586. PatchWord (entRel, (prologAt - EntSize) MOD 10000H) ;
  5587. PatchWord (hdrFlag, 1) ;
  5588. (* Every OFFSET field in the header is a segment offset,
  5589. i.e. an image offset plus LoadBias - one convention for
  5590. the whole structure, so that nobody has to remember
  5591. which of these five words is numbered which way.
  5592. hdrFlag 1 set, so a loader can recognise the header
  5593. hdrCS end of the generated code
  5594. hdrDS first byte of the data area <- read by initmem
  5595. hdrHeap one past the last <- read by initmem
  5596. hdrMax 0 (no overlay loader yet)
  5597. hdrDS and hdrHeap are the two that are CONSUMED, and
  5598. omitting the bias there is a silent no-op: initmem would
  5599. clear a range starting 0100h below the data, off the
  5600. front of the image, and never reach the globals at the
  5601. end. Nothing crashes, and the globals keep whatever the
  5602. loader left in them. *)
  5603. PatchWord (hdrCS, pc + LoadBias) ;
  5604. PatchWord (hdrDS, dataBase + LoadBias) ;
  5605. PatchWord (hdrHeap, dc + LoadBias) ;
  5606. PatchWord (hdrMax, 0)
  5607. END
  5608. ELSE
  5609. Err (EUnknown)
  5610. END
  5611. END
  5612. END
  5613. END ;
  5614. IF NOT MatchDelim ('.') THEN
  5615. Err (EPointExp)
  5616. END ;
  5617. IF abortFac THEN
  5618. errNo := errNum ; (* was "errNo := errNo": a self-assignment,
  5619. because the formal shadowed the module
  5620. variable, so the error code always
  5621. reached the caller as 0 *)
  5622. errPos := txerrPos ;
  5623. RETURN FALSE
  5624. END ;
  5625. errNo := 0 ;
  5626. errPos := 0 ;
  5627. RETURN TRUE
  5628. END Compile ;
  5629. PROCEDURE CodeBytes () : CARDINAL ;
  5630. BEGIN
  5631. RETURN codeSz
  5632. END CodeBytes ;
  5633. PROCEDURE DataBytes () : CARDINAL ;
  5634. BEGIN
  5635. RETURN dataSz
  5636. END DataBytes ;
  5637. PROCEDURE ImageBytes () : CARDINAL ;
  5638. (* Total linked image size: rtSz (the runtime) + CodeBytes (the program).
  5639. The program is NOT padded out to the data base here - the linker does
  5640. that, and only it knows the .COM's final size. *)
  5641. BEGIN
  5642. RETURN rtSz + codeSz
  5643. END ImageBytes ;
  5644. PROCEDURE DataBase () : CARDINAL ;
  5645. (* image-absolute offset at which the data area begins (rtSz + 1000H). The
  5646. linker must place the program's data here and zero-fill from the end of
  5647. the code up to it. *)
  5648. BEGIN
  5649. RETURN dataBase
  5650. END DataBase ;
  5651. PROCEDURE ImageByteAt (i : CARDINAL) : BYTE ;
  5652. (* i-th byte of the WHOLE image, runtime included, so a test can check the
  5653. real thing a .COM would contain. Returns 0 past the end. *)
  5654. BEGIN
  5655. IF i >= rtSz + codeSz THEN
  5656. RETURN 0
  5657. END ;
  5658. RETURN cbuf [i]
  5659. END ImageByteAt ;
  5660. PROCEDURE CodeByteAt (i : CARDINAL) : BYTE ;
  5661. (* i-th byte of the emitted image, for test harnesses that need to check
  5662. the generated 8086 code rather than just its size. Returns 0 past the
  5663. end of the image. *)
  5664. BEGIN
  5665. IF i >= codeSz THEN
  5666. RETURN 0
  5667. END ;
  5668. RETURN cbuf [i]
  5669. END CodeByteAt ;
  5670. END Compiler.