Compiler.mod 288 KB

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