Compiler.mod 210 KB

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