Compiler.mod 178 KB

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