Compiler.mod 143 KB

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