Compiler.mod 277 KB

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