Compiler.mod 149 KB

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