Compiler.mod 124 KB

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