Compiler.mod 107 KB

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