Compiler.mod 257 KB

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