Compiler.mod 117 KB

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