Compiler.mod 209 KB

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