Compiler.mod 184 KB

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