Compiler.mod 111 KB

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