Compiler.mod 131 KB

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