Compiler.mod 238 KB

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