Compiler.mod 134 KB

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