Compiler.mod 314 KB

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