Compiler.mod 220 KB

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