Compiler.mod 127 KB

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