Compiler.mod 198 KB

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