Compiler.mod 188 KB

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