Compiler.mod 167 KB

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