Compiler.mod 180 KB

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