Compiler.mod 125 KB

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