Compiler.mod 309 KB

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