Compiler.mod 285 KB

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