Compiler.mod 206 KB

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