Compiler.mod 332 KB

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