Compiler.mod 137 KB

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