Compiler.mod 158 KB

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