Compiler.mod 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875
  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. MaxSym = 3000 ;
  66. MaxPatch = 2000 ;
  67. MaxPend = 400 ;
  68. MaxFields = 2000 ; (* record fields, in a table of their own: a
  69. field is scoped to its record, not global *)
  70. MaxArrs = 1000 ; (* array SHAPES, likewise: a symbol points at
  71. one, and 2-D indexing needs both ranges *)
  72. FileVarSize = 4 ; (* a file variable is our control block: the DOS
  73. handle (word) and a mode word (0 closed, 1
  74. read, 2 write). TP3 keeps a buffer here too;
  75. we do unbuffered INT 21h I/O. *)
  76. (* type codes (TP3 vartp) *)
  77. TNone = 0 ; TArray = 1 ; TRecord = 2 ; TSet = 3 ;
  78. TPtr = 4 ; TFile = 5 ; TText = 6 ; TUntyp = 7 ;
  79. TString = 8 ; TReal = 9 ; TScalar = 10 ; TBool = 11 ;
  80. (* CHAR needs a class of its own. It used to be registered as TScalar,
  81. which made a CHAR variable indistinguishable from an INTEGER one: the
  82. class is all IoCall has to dispatch on, so `write(c)` called wrint (the
  83. value 65 became the *address* 65 and it printed whatever lived at 0x41)
  84. and `readln(c)` called rdint (which stores a 16-bit result, so it wrote
  85. two bytes into a one-byte variable). TP3 TPSRC8 prdtyped/pwriteln
  86. dispatches on the type identifier for exactly this reason. BYTE stays
  87. TScalar: a BYTE is written as an integer, as in TP3 - but a READ of one
  88. is dispatched on the variable's size instead (TPSRC8 prdnum
  89. `CMP varsize,#$01 / JA -> rdint, else rdbyte'), so the one thing class
  90. alone cannot tell apart is told apart where the size is in hand. *)
  91. TChar = 12 ;
  92. TEnum = 13 ; (* an enumeration type: ordinal, size 1 (TP3 uses 1
  93. byte below 256 values), bounds in SymEntry.lo/hi *)
  94. (* symbol kinds *)
  95. KLabel = 100H ; KConst = 200H ; KType = 300H ;
  96. KVar = 400H ; KProc = 500H ; KFunc = 600H ;
  97. KBuiltin = 700H ; (* standard procedure, see BI_* below *)
  98. (* which standard procedure a KBuiltin symbol denotes *)
  99. BI_Write = 0 ; BI_WriteLn = 1 ; BI_Read = 2 ;
  100. BI_ReadLn = 3 ; BI_Halt = 4 ; BI_Length = 5 ;
  101. (* CRT identifiers. There is no unit system, so these are builtins. They
  102. are statements (except Length), dispatched in IoCall; each one that is
  103. not implemented yet is a loud ENoLib, never a silent no-op. *)
  104. BI_ClrScr = 6 ; BI_GotoXY = 7 ; BI_LowVideo = 8 ;
  105. BI_NormVideo = 9 ; BI_ClrEol = 10 ; BI_Delay = 11 ;
  106. BI_KeyPressed = 12 ;
  107. (* the sub-codes EmCrtSeq takes *)
  108. CrtClr = 0 ; CrtDl = 1 ; CrtDh = 2 ; CrtCaret = 3 ; CrtEol = 4 ;
  109. CrtLow = 5 ; CrtNorm = 6 ; CrtDelay = 7 ; CrtKey = 8 ;
  110. (* keyword tokens *)
  111. TkNone = 0 ; TkProgram = 1 ; TkBegin = 2 ; TkEnd = 3 ;
  112. TkIf = 4 ; TkThen = 5 ; TkElse = 6 ; TkWhile = 7 ;
  113. TkDo = 8 ; TkRepeat = 9 ; TkUntil = 10 ; TkFor = 11 ;
  114. TkTo = 12 ; TkDownto = 13 ; TkCase = 14 ; TkOf = 15 ;
  115. TkGoto = 16 ; TkExit = 17 ; TkWith = 18 ; TkVar = 19 ;
  116. TkConst= 20 ; TkType = 21 ; TkLabel = 22 ; TkProcedure = 23 ;
  117. TkFunction = 24 ; TkNil = 25 ; TkAnd = 26 ; TkOr = 27 ;
  118. TkNot = 28 ; TkDiv = 29 ; TkMod = 30 ; TkIn = 31 ;
  119. TkFile = 32 ; TkText = 33 ; TkRecord = 34 ; TkArray = 35 ;
  120. TkSet = 36 ; TkPacked = 37 ; TkForward = 38 ; TkExternal = 39 ;
  121. TkAbsolute = 40 ; TkOverlay = 41 ; TkString = 42 ;
  122. (* Codes for the SYMBOL operators, as BinOpEmit numbers them. The word
  123. operators carry their own Tk* token and need no code here.
  124. These are named, not bare numbers, because every precedence level's
  125. parser picks its own code out of the same set and BinOpEmit cannot see
  126. which level called it. ParseAdd chose 1 for '+' and ParseMul chose 1
  127. for '*', so every multiplication dispatched to EmAddAxCx and a * b
  128. compiled to a + b. Only the constant-folding path was right, which is
  129. why n * n with n a CONST was correct and a * b with a a variable was
  130. not. *)
  131. OpAdd = 1 ; OpSub = 2 ; OpMul = 3 ;
  132. (* TP3 error numbers *)
  133. ENoSemi = 1 ; EPointExp = 10 ; ESimpType = 30 ;
  134. EUnknown = 41 ; EConstRange = 45 ; EMemOvf = 98 ;
  135. ECompOvf = 99 ; ENoLib = 102 ; ETypeErr = 56 ;
  136. EIoHere = 66 ; (* I/O not allowed here - TPSRC8 prderrtp *)
  137. EFileNF = 90 ; (* File not found - TPSRC10 cdincl, errb *)
  138. EInclNest = 96 ; (* Illegal nesting of include files - TPSRC10 cdincl *)
  139. AposC = 39 ; (* ORD ("'") - avoids quote-in-quote *)
  140. (* ---------------------------------------------------------------- *)
  141. (* types *)
  142. (* ---------------------------------------------------------------- *)
  143. TYPE
  144. SymEntry =
  145. RECORD
  146. name : ARRAY [0..MaxName] OF CHAR ;
  147. tag : CARDINAL ;
  148. cls : CARDINAL ;
  149. size : CARDINAL ;
  150. elem : CARDINAL ;
  151. off : CARDINAL ;
  152. lval : LONGINT ;
  153. lo, hi : LONGINT ; (* an ORDINAL type's bounds: an enumeration
  154. (0..n-1) or a subrange. Needed so
  155. `set of T' can size its base. *)
  156. fldFirst, fldLast : CARDINAL ; (* a RECORD type's field range in the
  157. field table (0,0 when not a record) *)
  158. arrIdx : CARDINAL ; (* an ARRAY type's shape in ArrRec (0 = no) *)
  159. parmFirst, parmCount : CARDINAL ; (* a PROCEDURE/FUNCTION's parameters:
  160. symtab indices, in declaration order *)
  161. isKbd : BOOLEAN ; (* the predefined KBD file: reads are console *)
  162. isVar : BOOLEAN ; (* a VAR parameter: the slot holds an address *)
  163. level : CARDINAL ;
  164. local : BOOLEAN ;
  165. resvar : CARDINAL ;
  166. goPos : CARDINAL ;
  167. defnd : BOOLEAN ;
  168. fwd : BOOLEAN ;
  169. END ;
  170. PatchRec =
  171. RECORD
  172. place : CARDINAL ;
  173. target : CARDINAL ;
  174. filled : BOOLEAN ;
  175. END ;
  176. PendRec =
  177. RECORD
  178. kind : CARDINAL ; (* 0 goto, 1 call *)
  179. who : CARDINAL ;
  180. place : CARDINAL ; (* patch slot index *)
  181. END ;
  182. ERes =
  183. RECORD
  184. cls : CARDINAL ;
  185. kind : CARDINAL ; (* 0 const, 1 var, 2 value in AX,
  186. 3 string literal (cls = TString),
  187. 4 value on the stack (SaveLeft),
  188. 5 string element, address in DI,
  189. 7 set value (cls = TSet) *)
  190. imm : LONGINT ;
  191. idx : CARDINAL ;
  192. boff : CARDINAL ; (* constant fold-in for subscripts *)
  193. chr : BOOLEAN ; (* single-quoted literal, e.g. 'a' *)
  194. strx : CARDINAL ; (* string literal: index into strPool *)
  195. setoff : CARDINAL ; (* SET value: image offset of the bytes *)
  196. setbase : CARDINAL ; (* ... the first byte's first element,
  197. a multiple of 8 (TP3's hybrid origin) *)
  198. setsize : CARDINAL ; (* ... and how many bytes there are *)
  199. sz : CARDINAL ; (* width of a kind-1 value: an element or
  200. field's size, not its variable's *)
  201. END ;
  202. DirRec = RECORD rng, chk : BOOLEAN END ;
  203. FldRec =
  204. RECORD
  205. name : ARRAY [0..MaxName] OF CHAR ;
  206. cls : CARDINAL ;
  207. size : CARDINAL ;
  208. elem : CARDINAL ;
  209. off : CARDINAL ; (* byte offset within the record *)
  210. lo, hi : LONGINT ; (* bounds, for a subrange/enum field *)
  211. END ;
  212. ArrRec =
  213. RECORD
  214. n : CARDINAL ; (* number of ranges (1 for array[1..5]) *)
  215. lo, hi : ARRAY [0..3] OF LONGINT ;
  216. elem : CARDINAL ; (* element size in bytes *)
  217. ecls : CARDINAL ; (* element CLASS, for a subscripted value *)
  218. END ;
  219. (* ---------------------------------------------------------------- *)
  220. (* state *)
  221. (* ---------------------------------------------------------------- *)
  222. VAR
  223. srcPos, srcLen : CARDINAL ;
  224. (* Include state. srcName is the path the buffer was loaded from, set by
  225. SetSource; only its directory is used, because a {$I file} directive
  226. names the file relative to the INCLUDING file. Includes are expanded by
  227. ExpandIncludes BEFORE parsing, so inclEnd is the end of the include
  228. region currently being scanned and inclActive says one is open - a
  229. nested {$I} inside that region is error 96, since TP3 permits only one
  230. level. incBuf holds one whole include file while it is spliced. *)
  231. srcName : ARRAY [0..255] OF CHAR ; inclName : ARRAY [0..127] OF CHAR ;
  232. inclPath : ARRAY [0..383] OF CHAR ;
  233. inclEnd : CARDINAL ;
  234. inclActive : BOOLEAN ;
  235. incBuf : ARRAY [0..TextLimit] OF CHAR ;
  236. enumLo, enumHi : LONGINT ; (* bounds of the enumeration ParseType just read,
  237. handed to DefType which owns the type NAME *)
  238. fields : ARRAY [0..MaxFields - 1] OF FldRec ;
  239. fldTop : CARDINAL ; (* next free field-table slot *)
  240. recFldFirst, recFldLast : CARDINAL ; (* field range ParseType just built *)
  241. arrs : ARRAY [0..MaxArrs - 1] OF ArrRec ;
  242. arrTop : CARDINAL ; (* next free array-shape slot *)
  243. newArrIdx : CARDINAL ; (* ArrRec index+1 for the type just parsed *)
  244. constBlob : ARRAY [0..511] OF CHAR ; (* bytes of a set/array typed constant
  245. while it is being built *)
  246. wrd : ARRAY [0..MaxName] OF CHAR ;
  247. (* String-literal pool.
  248. TP3 does not put a literal in the data segment at all: it emits the
  249. literal *inline in the code stream* as <length byte><characters>, and
  250. the runtime entry "wrtinl" reads the length from the return address and
  251. returns to just past the last character (TPSRC4 xwrtinl, TPSRC10
  252. estring). So nothing here ends up in the image as data - the pool only
  253. has to survive from the moment the literal is scanned until IoCall
  254. decides to emit it, because by then the parser has moved on. *)
  255. strPool : ARRAY [0..4095] OF CHAR ;
  256. strOff : ARRAY [0..255] OF CARDINAL ;
  257. strLen : ARRAY [0..255] OF CARDINAL ;
  258. strTop : CARDINAL ; (* next free byte in strPool *)
  259. strCnt : CARDINAL ; (* literals collected so far *)
  260. rdStrX : CARDINAL ; (* pool index of the literal RdConst just read *)
  261. symtab : ARRAY [0..MaxSym - 1] OF SymEntry ;
  262. symTop : CARDINAL ;
  263. patches : ARRAY [0..MaxPatch - 1] OF PatchRec ;
  264. nPatch : CARDINAL ;
  265. pend : ARRAY [0..MaxPend - 1] OF PendRec ;
  266. nPend : CARDINAL ;
  267. exitPatch : ARRAY [0..63] OF CARDINAL ;
  268. exitCnt : CARDINAL ;
  269. brkSave : ARRAY [0..15] OF CARDINAL ;
  270. loopTy : ARRAY [0..15] OF CARDINAL ; (* 1 while/repeat, 2 for *)
  271. brkN : CARDINAL ;
  272. caseJmp : ARRAY [0..63] OF CARDINAL ;
  273. caseN : CARDINAL ;
  274. pc, dc : CARDINAL ;
  275. varspc : CARDINAL ;
  276. cbuf : ARRAY [0..MaxCode - 1] OF BYTE ;
  277. codeSz, dataSz : CARDINAL ;
  278. (* Image layout, all image-absolute. rtSz is where the runtime ends and
  279. the program header begins; dataBase is where the data area begins
  280. (rtSz + 1000H, a fixed 4 KiB above the code). codeSz and dataSz are
  281. PROGRAM sizes - the runtime is excluded - so the numbers the fixture
  282. table pins keep meaning what they meant before the runtime was
  283. prepended. *)
  284. rtSz, dataBase : CARDINAL ;
  285. (* TRUE once Compile has computed rtSz/dataBase, i.e. once the code window
  286. has been measured. Ebyte refuses to write past dataBase (the 4 KiB code
  287. window) and needs to know the window is real before it can: dataBase is
  288. 0 until it is set, and `pc >= 0' would abort on the very first byte. *)
  289. imgReady : BOOLEAN ;
  290. (* Image offset of the entry jump's rel16 operand, patched at the end of
  291. Compile. The jump is at image offset 0, so its displacement is simply
  292. the program code's end - 3. *)
  293. entRel, prologAt : CARDINAL ;
  294. (* Runtime entry offsets as IMAGE-ABSOLUTE addresses, which is what
  295. EmCall and EmJmp want. They are derived from Runtime.RT_Entry in
  296. Inittur (after RT_Build, since RT_Entry only knows where the code
  297. landed once the blob is assembled) rather than written down, so a moved
  298. entry cannot leave the compiler calling the old address. Not a CONST
  299. block because RT_Entry is a function.
  300. Standard-procedure entries: TP3 does NOT pass a descriptor -
  301. TPSRC8 pwriteln/pwrloop inspects each argument's class in CL and emits
  302. a *different* call per type, so the type is fixed at compile time and
  303. the runtime needs only the value. Mirrored here. *)
  304. TU_InitMem : CARDINAL ;
  305. TU_ProgEnd : CARDINAL ;
  306. TU_StackChk : CARDINAL ;
  307. TU_WrInt : CARDINAL ; TU_WrChar : CARDINAL ; TU_WrBool : CARDINAL ;
  308. TU_WrReal : CARDINAL ; TU_WrLn : CARDINAL ;
  309. TU_RdInt : CARDINAL ; TU_RdChar : CARDINAL ; TU_RdBool : CARDINAL ;
  310. TU_RdLn : CARDINAL ; TU_Halt : CARDINAL ;
  311. TU_RdByte : CARDINAL ; (* one-byte variable reads; see IoCall *)
  312. TU_WrInl : CARDINAL ; (* inline string literal; NO stack argument *)
  313. TU_WrStr : CARDINAL ; (* string variable; address is the stack argument *)
  314. TU_RdStr : CARDINAL ; (* readln(s)/read(s); address on the stack, limit
  315. in CX *)
  316. TU_StrStore : CARDINAL ; (* s := t; dest and source addresses on the stack,
  317. limit in CX *)
  318. TU_CmpStr : CARDINAL ; (* string comparison; two addresses on the stack,
  319. signed -1/0/+1 in AX *)
  320. TU_StrCat : CARDINAL ; (* string concatenation; dest and source addresses
  321. on the stack, limit in CX; exit code 16 if the
  322. result would be too long *)
  323. abortFac : BOOLEAN ;
  324. errNum : CARDINAL ; (* NOT "errNo": Compile's formal of that
  325. name would shadow it, and the caller's
  326. errNo would never be filled in *)
  327. txerrPos : CARDINAL ;
  328. lexnest : CARDINAL ;
  329. curIsFunc : BOOLEAN ;
  330. resultVar : CARDINAL ;
  331. locFree : CARDINAL ; (* next local slot (BP-relative, 8-bit) *)
  332. locBytes : CARDINAL ; (* frame size for SUB SP *)
  333. parmOff : CARDINAL ; (* provisional parameter slot, in declaration
  334. order; remapped to TP3's BP+4 rule when the
  335. list has been read (see ProcFunc) *)
  336. dirs : DirRec ;
  337. tmpA, tmpB : CARDINAL ; (* global scratch word addresses *)
  338. crtAttrOff : CARDINAL ; (* image offset of the text attribute byte that
  339. LowVideo/NormVideo set and ClrScr/ClrEol use *)
  340. hdrFlag, hdrCS, hdrDS, hdrHeap, hdrMax : CARDINAL ;
  341. kName : ARRAY [0..42] OF ARRAY [0..15] OF CHAR ;
  342. kTk : ARRAY [0..42] OF CARDINAL ;
  343. (* ---------------------------------------------------------------- *)
  344. (* small char helpers *)
  345. (* ---------------------------------------------------------------- *)
  346. PROCEDURE CurCh () : CHAR ;
  347. BEGIN
  348. IF srcPos >= srcLen THEN
  349. RETURN 0C
  350. END ;
  351. RETURN CharAt (srcPos)
  352. END CurCh ;
  353. PROCEDURE GetCh () : CHAR ;
  354. VAR ch : CHAR ;
  355. BEGIN
  356. ch := CurCh () ;
  357. IF srcPos < srcLen THEN
  358. INC (srcPos)
  359. END ;
  360. RETURN ch
  361. END GetCh ;
  362. PROCEDURE PeekAhead (k : CARDINAL) : CHAR ;
  363. BEGIN
  364. IF srcPos + k >= srcLen THEN
  365. RETURN 0C
  366. END ;
  367. RETURN CharAt (srcPos + k)
  368. END PeekAhead ;
  369. PROCEDURE Digit (ch : CHAR) : BOOLEAN ;
  370. BEGIN
  371. RETURN (ch >= '0') AND (ch <= '9')
  372. END Digit ;
  373. PROCEDURE Alpha (ch : CHAR) : BOOLEAN ;
  374. BEGIN
  375. RETURN ((ch >= 'A') AND (ch <= 'Z')) OR ((ch >= 'a') AND (ch <= 'z'))
  376. OR (ch = '_')
  377. END Alpha ;
  378. PROCEDURE AlphaNum (ch : CHAR) : BOOLEAN ;
  379. BEGIN
  380. RETURN (Alpha (ch)) OR (Digit (ch))
  381. END AlphaNum ;
  382. PROCEDURE IsHexCh (ch : CHAR) : BOOLEAN ;
  383. BEGIN
  384. RETURN (Digit (ch)) OR ((ch >= 'A') AND (ch <= 'F'))
  385. OR ((ch >= 'a') AND (ch <= 'f'))
  386. END IsHexCh ;
  387. PROCEDURE Upper (ch : CHAR) : CHAR ;
  388. BEGIN
  389. IF (ch >= 'a') AND (ch <= 'z') THEN
  390. RETURN CHR (ORD (ch) - ORD ('a') + ORD ('A'))
  391. END ;
  392. RETURN ch
  393. END Upper ;
  394. PROCEDURE W16 (x : LONGINT) : CARDINAL ;
  395. (* fold x modulo 10000H, handling negatives (no negative MOD) *)
  396. VAR m : CARDINAL ;
  397. BEGIN
  398. IF x >= 0 THEN
  399. RETURN VAL (CARDINAL, x MOD 10000H)
  400. END ;
  401. m := VAL (CARDINAL, (0 - x) MOD 10000H) ;
  402. RETURN (10000H - m) MOD 10000H
  403. END W16 ;
  404. PROCEDURE DropCh (v : CHAR) ;
  405. BEGIN
  406. END DropCh ;
  407. PROCEDURE DropB (v : BOOLEAN) ;
  408. BEGIN
  409. END DropB ;
  410. PROCEDURE DropC (v : CARDINAL) ;
  411. BEGIN
  412. END DropC ;
  413. PROCEDURE BitAnd (a, b : LONGINT) : LONGINT ;
  414. BEGIN
  415. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  416. * VAL (BITSET, W16 (b))))
  417. END BitAnd ;
  418. PROCEDURE BitOr (a, b : LONGINT) : LONGINT ;
  419. BEGIN
  420. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, W16 (a))
  421. + VAL (BITSET, W16 (b))))
  422. END BitOr ;
  423. PROCEDURE BitNot (a : LONGINT) : LONGINT ;
  424. BEGIN
  425. RETURN VAL (LONGINT, CARDINAL (VAL (BITSET, 0FFFFH)
  426. - VAL (BITSET, W16 (a))))
  427. END BitNot ;
  428. (* ---------------------------------------------------------------- *)
  429. (* errors *)
  430. (* ---------------------------------------------------------------- *)
  431. PROCEDURE Err (n : CARDINAL) ;
  432. BEGIN
  433. IF NOT abortFac THEN
  434. abortFac := TRUE ;
  435. errNum := n ;
  436. txerrPos := srcPos
  437. END
  438. END Err ;
  439. PROCEDURE OK () : BOOLEAN ;
  440. BEGIN
  441. RETURN NOT abortFac
  442. END OK ;
  443. (* ---------------------------------------------------------------- *)
  444. (* {$I file} include *)
  445. (* ---------------------------------------------------------------- *)
  446. PROCEDURE SetSource (path : ARRAY OF CHAR) ;
  447. (* remember the path the buffer was loaded from; MakeIncludePath keeps only its
  448. directory *)
  449. VAR i : CARDINAL ;
  450. BEGIN
  451. i := 0 ;
  452. WHILE (i < 255) AND (i <= HIGH (path)) AND (path [i] # 0C) DO
  453. srcName [i] := path [i] ;
  454. INC (i)
  455. END ;
  456. srcName [i] := 0C
  457. END SetSource ;
  458. PROCEDURE ReadWholeFile (path : ARRAY OF CHAR ; VAR n : CARDINAL) : BOOLEAN ;
  459. (* Read path into incBuf with the same CR/LF normalisation as LoadWorkFile,
  460. and report its length in n. FALSE if it could not be opened. ^Z ends the
  461. text, as it does for every other reader here. *)
  462. VAR fd : INTEGER ;
  463. k : LONGINT ;
  464. b : BYTE ;
  465. ch : CHAR ;
  466. prevCR, emit : BOOLEAN ;
  467. BEGIN
  468. n := 0 ;
  469. fd := open (ADR (path), 0, 0) ;
  470. IF fd < 0 THEN
  471. RETURN FALSE
  472. END ;
  473. prevCR := FALSE ;
  474. LOOP
  475. k := read (fd, ADR (b), 1) ;
  476. IF k # 1 THEN EXIT END ;
  477. IF b = 26 THEN EXIT END ; (* ^Z *)
  478. emit := TRUE ;
  479. IF b = 10 THEN
  480. IF prevCR THEN
  481. emit := FALSE
  482. ELSE
  483. ch := CHR (13) (* lone LF -> CR *)
  484. END ;
  485. prevCR := FALSE
  486. ELSIF b = 13 THEN
  487. ch := CHR (13) ;
  488. prevCR := TRUE
  489. ELSE
  490. ch := CHR (ORD (b)) ;
  491. prevCR := FALSE
  492. END ;
  493. IF emit AND (n <= TextLimit) THEN
  494. incBuf [n] := ch ;
  495. INC (n)
  496. END
  497. END ;
  498. k := close (fd) ;
  499. RETURN TRUE
  500. END ReadWholeFile ;
  501. PROCEDURE MakeIncludePath () ;
  502. (* inclPath := directory (srcName) + inclName, defaulting the extension to
  503. .PAS when the name has none (TPSRC10 kpasext). *)
  504. VAR i, j, last : CARDINAL ; dot : BOOLEAN ;
  505. BEGIN
  506. dot := FALSE ;
  507. i := 0 ;
  508. WHILE (i < 127) AND (inclName [i] # 0C) DO
  509. IF inclName [i] = '.' THEN dot := TRUE END ;
  510. INC (i)
  511. END ;
  512. IF (NOT dot) AND (i <= 123) THEN
  513. inclName [i] := '.' ;
  514. inclName [i + 1] := 'P' ;
  515. inclName [i + 2] := 'A' ;
  516. inclName [i + 3] := 'S' ;
  517. inclName [i + 4] := 0C
  518. END ;
  519. last := 0 ;
  520. i := 0 ;
  521. WHILE (i < 256) AND (srcName [i] # 0C) DO
  522. IF srcName [i] = '/' THEN last := i + 1 END ;
  523. INC (i)
  524. END ;
  525. j := 0 ;
  526. WHILE j < last DO
  527. inclPath [j] := srcName [j] ;
  528. INC (j)
  529. END ;
  530. i := 0 ;
  531. WHILE (i < 127) AND (inclName [i] # 0C) DO
  532. inclPath [j] := inclName [i] ;
  533. INC (j) ;
  534. INC (i)
  535. END ;
  536. inclPath [j] := 0C
  537. END MakeIncludePath ;
  538. PROCEDURE ExpandIncludes () ;
  539. (* Replace every {$I name} directive in the buffer with the named file's text,
  540. BEFORE parsing.
  541. This is a pre-pass, and it has to be. Skip is called by lookahead routines
  542. (DeclaresProc, PeekKw, KwAhead) that SAVE AND RESTORE srcPos; an include
  543. performed inside Skip would run once during the lookahead and once for real,
  544. and the second pass would see the first splice's text and report error 96.
  545. A splice also grows the buffer, which a rewind cannot undo. So the whole
  546. expansion is done here, in one forward scan with no lookahead, and the
  547. parser only ever sees the finished text.
  548. The scan has to recognise exactly what the lexer does, or it would expand a
  549. directive that the lexer would have read as a string or a comment: a quoted
  550. literal is skipped, then star-paren comments (which is why {$I} written
  551. inside one is inert - t56_include.inc relies on that), then brace comments,
  552. and only then a brace directive.
  553. Divergence from the original: TP3 STREAMS the include file line by line and
  554. switches back to the outer file at EOF (TPSRC10 fileline/getincl/fileeof);
  555. we hold the whole source in TextBuf and address it by index, so the include
  556. is spliced in place. A nested {$I} therefore cannot switch back on its own
  557. - which TP3 also refuses, and that is the error 96 reported here. *)
  558. VAR i, d0, d1, k, ni, n : CARDINAL ;
  559. c, letter : CHAR ;
  560. isInc : BOOLEAN ;
  561. BEGIN
  562. i := 0 ;
  563. inclActive := FALSE ;
  564. inclEnd := 0 ;
  565. WHILE (i < Length ()) AND OK () DO
  566. c := CharAt (i) ;
  567. IF c = "'" THEN
  568. INC (i) ;
  569. WHILE (i < Length ()) AND (CharAt (i) # "'") DO INC (i) END ;
  570. IF i < Length () THEN INC (i) END
  571. ELSIF (c = '(') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '*') THEN
  572. INC (i, 2) ;
  573. WHILE (i < Length ()) AND NOT ((CharAt (i) = '*')
  574. AND (i + 1 < Length ()) AND (CharAt (i + 1) = ')')) DO
  575. INC (i)
  576. END ;
  577. IF i < Length () THEN INC (i, 2) END
  578. ELSIF (c = '{') AND (i + 1 < Length ()) AND (CharAt (i + 1) = '$') THEN
  579. d0 := i ;
  580. d1 := i + 2 ;
  581. WHILE (d1 < Length ()) AND (CharAt (d1) # '}') DO INC (d1) END ;
  582. IF i + 2 < Length () THEN
  583. letter := Upper (CharAt (i + 2))
  584. ELSE
  585. letter := 0C
  586. END ;
  587. isInc := FALSE ;
  588. IF letter = 'I' THEN
  589. k := i + 3 ;
  590. WHILE (k < d1) AND ((CharAt (k) = ' ') OR (CharAt (k) = CHR (9))) DO
  591. INC (k)
  592. END ;
  593. IF (k >= d1) OR ((CharAt (k) # '+') AND (CharAt (k) # '-')) THEN
  594. isInc := TRUE
  595. END
  596. END ;
  597. IF isInc THEN
  598. IF inclActive AND (d0 < inclEnd) THEN
  599. srcPos := d0 ;
  600. Err (EInclNest) ; (* 96 *)
  601. RETURN
  602. END ;
  603. ni := 0 ;
  604. WHILE (k < d1) AND (ni < 127) DO
  605. inclName [ni] := CharAt (k) ;
  606. INC (k) ;
  607. INC (ni)
  608. END ;
  609. WHILE (ni > 0) AND ((inclName [ni - 1] = ' ')
  610. OR (inclName [ni - 1] = CHR (9))) DO
  611. DEC (ni)
  612. END ;
  613. inclName [ni] := 0C ;
  614. MakeIncludePath () ;
  615. IF NOT ReadWholeFile (inclPath, n) THEN
  616. srcPos := d0 ;
  617. Err (EFileNF) ; (* 90 *)
  618. RETURN
  619. END ;
  620. DeleteFromTo (d0, d1 - d0 + 1) ;
  621. IF NOT InsertStr (d0, incBuf, n) THEN
  622. srcPos := d0 ;
  623. Err (EMemOvf) ;
  624. RETURN
  625. END ;
  626. inclEnd := d0 + n ;
  627. inclActive := TRUE ;
  628. i := d0 (* scan the new text too *)
  629. ELSE
  630. i := d1 + 1 (* ordinary directive: leave it *)
  631. END
  632. ELSIF c = '{' THEN
  633. INC (i) ;
  634. WHILE (i < Length ()) AND (CharAt (i) # '}') DO INC (i) END ;
  635. IF i < Length () THEN INC (i) END
  636. ELSE
  637. INC (i)
  638. END
  639. END ;
  640. srcLen := Length () ;
  641. srcPos := 0
  642. END ExpandIncludes ;
  643. (* ---------------------------------------------------------------- *)
  644. (* emission : ebyte / eword / ecall / ejump *)
  645. (* ---------------------------------------------------------------- *)
  646. PROCEDURE Ebyte (b : BYTE) ;
  647. BEGIN
  648. IF (pc >= MaxCode) OR (imgReady AND (pc >= dataBase)) THEN
  649. (* The image buffer bound, and the code window. dataBase is a fixed
  650. 4 KiB above the end of the runtime, so a program whose code reaches
  651. it has grown into its own data area - the two cannot share a 64 KiB
  652. .COM segment. Reported as TP3's error 98 (memory overflow) rather
  653. than a silent truncation; see the layout note in Compile and
  654. SUMMARY.md "Known limit". *)
  655. Err (EMemOvf)
  656. ELSE
  657. cbuf [pc] := b ;
  658. INC (pc)
  659. END
  660. END Ebyte ;
  661. PROCEDURE Eword (w : CARDINAL) ;
  662. BEGIN
  663. Ebyte (VAL (BYTE, w MOD 100H)) ;
  664. Ebyte (VAL (BYTE, (w DIV 100H) MOD 100H))
  665. END Eword ;
  666. PROCEDURE PatchWord (at, w : CARDINAL) ;
  667. (* Store a 16-bit word into cbuf at an absolute offset.
  668. A helper, because writing this inline got it wrong in all four header
  669. words: the low byte was (w DIV 16) MOD 100H, which is a NIBBLE shift, not
  670. the byte shift (w MOD 100H). So 1181h - the data base - was stored as
  671. 0118h = 280. It was invisible for as long as nothing read those words,
  672. which is exactly what "write it inline once and trust it" buys you. *)
  673. BEGIN
  674. cbuf [at] := VAL (BYTE, w MOD 100H) ;
  675. cbuf [at + 1] := VAL (BYTE, (w DIV 100H) MOD 100H)
  676. END PatchWord ;
  677. PROCEDURE AddPatch (place, target : CARDINAL) ;
  678. BEGIN
  679. IF nPatch < MaxPatch THEN
  680. patches [nPatch].place := place ;
  681. patches [nPatch].target := target ;
  682. patches [nPatch].filled := FALSE ;
  683. INC (nPatch)
  684. ELSE
  685. Err (ECompOvf)
  686. END
  687. END AddPatch ;
  688. PROCEDURE SetPatTgt (idx, t : CARDINAL) ;
  689. BEGIN
  690. IF idx < nPatch THEN
  691. patches [idx].target := t
  692. END
  693. END SetPatTgt ;
  694. PROCEDURE EmCall (target : CARDINAL) : CARDINAL ;
  695. (* E8 rel16 near call; target = 0 => forward (patched later).
  696. Returns the patch slot, or 0 when resolved directly. *)
  697. VAR rel, p : CARDINAL ;
  698. BEGIN
  699. Ebyte (0E8H) ;
  700. IF target = 0 THEN
  701. Eword (0) ;
  702. p := nPatch ;
  703. AddPatch (pc - 2, 0) ;
  704. RETURN p
  705. END ;
  706. (* rel16 is measured from the END of the instruction. Here pc already
  707. points past the opcode(s) and at the displacement field, so the
  708. instruction ends at pc+2 - the same convention ResolvePatches uses
  709. with "place + 2". Omitting the +2 lands every direct call/jump 2 bytes
  710. past its target. *)
  711. rel := (target + 10000H - (pc + 2)) MOD 10000H ;
  712. Eword (rel) ;
  713. RETURN 0
  714. END EmCall ;
  715. PROCEDURE EmJmpNear (target : CARDINAL) : CARDINAL ;
  716. (* E9 rel16; target = 0 => forward. Returns patch slot or 0. *)
  717. VAR rel, p : CARDINAL ;
  718. BEGIN
  719. Ebyte (0E9H) ;
  720. IF target = 0 THEN
  721. Eword (0) ;
  722. p := nPatch ;
  723. AddPatch (pc - 2, 0) ;
  724. RETURN p
  725. END ;
  726. rel := (target + 10000H - (pc + 2)) MOD 10000H ; (* see EmCall *)
  727. Eword (rel) ;
  728. RETURN 0
  729. END EmJmpNear ;
  730. PROCEDURE JccShort (cc : BYTE) : BYTE ;
  731. (* The 8086 SHORT Jcc opcode for a condition nibble. 70h..7Fh is exactly
  732. 70h + nibble: 70 JO 71 JNO 72 JB 73 JAE 74 JE 75 JNE 76 JBE 77 JA
  733. 78 JS 79 JNS 7A JP 7B JNP 7C JL 7D JGE 7E JLE 7F JG.
  734. So 70H + cc is the same condition the 386-only `0F 8x rel16' (for a Jcc) or
  735. `0F 9x' (for a SETcc) encoded, which is what lets the seven EmJcc sites and
  736. the six EmSetcc arms go on passing the low byte they always passed. *)
  737. VAR n : CARDINAL ;
  738. BEGIN
  739. n := VAL (CARDINAL, cc) MOD 10H ;
  740. RETURN VAL (BYTE, 70H + n)
  741. END JccShort ;
  742. PROCEDURE JccShortInv (cc : BYTE) : BYTE ;
  743. (* The same, for a jump that is taken when the condition does NOT hold.
  744. EmJcc needs this one and EmSetcc needs the other, and the difference is the
  745. whole bug, so it is worth being explicit about where it comes from: the low
  746. bit of a Jcc code IS the negation bit. 4/5, C/D, E/F, 2/3, 6/7, A/9, B/8 and
  747. 0/1 are the eight (condition, its negation) pairs, so negating a condition is
  748. `n XOR 1' and nothing more - `JE' and `JNE' are 0x74 and 0x75.
  749. Gm2 under -fiso has no XOR on integers at all: BITAND and BAND are both
  750. syntax errors, and arithmetic on a BYTE operand is rejected too, which is
  751. why every operand here goes through VAL. n + 1 - 2*(n MOD 2) is XOR 1 for a
  752. four-bit n and it lives in one named place rather than open-coded, because
  753. an open-coded negation at two call sites is how they end up disagreeing. *)
  754. VAR n : CARDINAL ;
  755. BEGIN
  756. n := VAL (CARDINAL, cc) MOD 10H ;
  757. RETURN VAL (BYTE, 70H + n + 1 - 2 * (n MOD 2))
  758. END JccShortInv ;
  759. PROCEDURE EmJcc (cc : BYTE ; target : CARDINAL) : CARDINAL ;
  760. (* A conditional branch, 8086 style. `cc' is the condition nibble, and it is
  761. exactly the low byte of the `0F 8x rel16' this used to emit.
  762. That was a real fault and nothing in the build could see it: `0F' is a
  763. 386-and-later opcode prefix and the 8086 has none, so EVERY conditional
  764. branch in EVERY compiled program was an illegal instruction on the machine
  765. TP3 targets. FCML decoded it happily, because FCML's -m16 mode is 386 --
  766. and FCML is this project's independent disassembler, so the one tool that
  767. could have objected was the one guaranteed to agree. qemu-system-i386 has
  768. no 8086 model either; its lowest is 486. So the compile succeeded, the
  769. .COM linked, the layout checked, the golden held and all 30 fixtures ran to
  770. the right answers, all at once, with the bug in.
  771. TPSRC8 lays IF, WHILE and REPEAT out as
  772. MOV AL,brnchop ; MOV AH,#$03 ; CALL eword ; PUSH pc ; CALL ejump
  773. i.e. a SHORT Jcc of displacement 3, stepping over a 3-byte EJMP. That is
  774. the shape here too, and EmJmpNear already owns the displacement arithmetic
  775. and the patch slot, so it is three lines and there is no second copy of
  776. that rule.
  777. The one thing that is NOT the same as TPSRC8, and cost a round of "every
  778. conditional is inverted" (t09_if printed pos/nonpos/lt for a program that
  779. must print nonpos/pos/ge): TP3's brnchop is the branch taken when the
  780. condition is TRUE, and TP3 steps over the EJMP when it is taken. Here `cc'
  781. is the branch taken when the condition is FALSE -- IF's `EmJcc (84H)' is
  782. JZ, patched to the ELSE, so it must fire when the test failed. EmJcc jumps
  783. to the target, it does not step over it, so stepping over an EJMP and then
  784. falling into the destination is the wrong way round: the byte has to be
  785. JccShortInv, not JccShort. The control flow that comes out is identical to
  786. the `0F 8x' form this replaces; only which of the pair is spelled differs.
  787. The flags survive, and the FOR test needs them to: it emits CMP and then
  788. Jcc with nothing in between, so anything that wrote a flag here would
  789. break the loop. Jcc and EJMP both leave the flags alone. *)
  790. BEGIN
  791. Ebyte (JccShortInv (cc)) ; (* Jcc_s, taken when cc does NOT hold *)
  792. Ebyte (03H) ; (* rel8: step over the 3-byte EJMP *)
  793. RETURN EmJmpNear (target) (* target = 0 => forward, see above *)
  794. END EmJcc ;
  795. PROCEDURE ResolvePatches () ;
  796. VAR i : CARDINAL ;
  797. rel : CARDINAL ;
  798. BEGIN
  799. i := 0 ;
  800. WHILE i < nPatch DO
  801. IF NOT patches [i].filled THEN
  802. rel := (patches [i].target + 10000H - (patches [i].place + 2))
  803. MOD 10000H ;
  804. cbuf [patches [i].place] := VAL (BYTE, rel MOD 100H) ;
  805. cbuf [patches [i].place + 1] := VAL (BYTE, (rel DIV 100H) MOD 100H) ;
  806. patches [i].filled := TRUE
  807. END ;
  808. INC (i)
  809. END
  810. END ResolvePatches ;
  811. (* 1-byte const emitters *)
  812. PROCEDURE EmMovAxi (imm : CARDINAL) ;
  813. BEGIN
  814. Ebyte (0B8H) ; Eword (imm)
  815. END EmMovAxi ;
  816. PROCEDURE EmMovCxi (imm : CARDINAL) ;
  817. BEGIN
  818. Ebyte (0B9H) ; Eword (imm)
  819. END EmMovCxi ;
  820. PROCEDURE EmMovBpSp () ;
  821. BEGIN
  822. Ebyte (8BH) ; Ebyte (0ECH)
  823. END EmMovBpSp ;
  824. PROCEDURE EmMovAh0 () ;
  825. BEGIN
  826. Ebyte (0B4H) ; Ebyte (0H)
  827. END EmMovAh0 ;
  828. PROCEDURE EmMovAxSp () ;
  829. (* Read the top of the stack into AX, leaving the stack unchanged.
  830. The obvious encoding, MOV AX,[SP], DOES NOT EXIST on the 8086. There is
  831. no encoding of [SP] as a memory operand: SIB bytes, which is how [ESP]
  832. would be written, did not exist until the 386, and mod=00 / rm=100 is
  833. [SI], not [SP]. The first version of this emitted 8B 44 24 00 - mod=01,
  834. rm=100, SIB=24h, disp8=0 - which is correct only on a 386 and above. Two
  835. of this project's oracles agree that it is wrong: fcml in 16-bit mode
  836. decodes it as MOV AX,[SI+0x24h], and so does qemu executing it, because
  837. qemu follows the CPU's rules for the encoding it is given rather than
  838. guessing. It was not the encoder's fault that the bytes were well formed;
  839. they were, and they read SI+24h.
  840. The observable effect was that CASE compiled to no branches at all: each
  841. label test loaded a garbage address, every comparison failed, and the
  842. program fell straight past the whole statement and exited without printing.
  843. A CASE fixture caught it. Nothing else could have - the encoding is
  844. valid, the size is right, and the byte-level checks have no way to know
  845. what register was meant.
  846. So: POP then PUSH the same value. Two bytes, no SIB, correct on every
  847. 8086, and observationally identical to peeking - the stack pointer ends
  848. where it started, holding the same value. *)
  849. BEGIN
  850. Ebyte (58H) ; (* POP AX *)
  851. Ebyte (50H) (* PUSH AX *)
  852. END EmMovAxSp ;
  853. PROCEDURE EmMovCxSp () ;
  854. (* The same, for CX - the FOR loop's bound, pushed by the FOR statement and
  855. re-read on every iteration. This one was emitting 8B 0C and nothing else,
  856. which is MOV CX,[SI] with the SIB slot missing: the *next* instruction was
  857. consumed as the SIB byte and the displacement. Same root cause, same fix,
  858. and it had not been noticed only because no FOR fixture is executed yet. *)
  859. BEGIN
  860. Ebyte (59H) ; (* POP CX *)
  861. Ebyte (51H) (* PUSH CX *)
  862. END EmMovCxSp ;
  863. PROCEDURE EmPushAx () ;
  864. BEGIN
  865. Ebyte (50H)
  866. END EmPushAx ;
  867. PROCEDURE EmPopCx () ;
  868. BEGIN
  869. Ebyte (59H)
  870. END EmPopCx ;
  871. PROCEDURE EmPopDx () ;
  872. BEGIN
  873. Ebyte (5AH)
  874. END EmPopDx ;
  875. PROCEDURE EmPopSi () ;
  876. BEGIN
  877. Ebyte (5EH) (* POP SI *)
  878. END EmPopSi ;
  879. PROCEDURE EmPopAx () ;
  880. BEGIN
  881. Ebyte (58H) (* POP AX *)
  882. END EmPopAx ;
  883. (* 91 = XCHG AX,CX, and NOT 93. LoadPair hands the operator the left
  884. operand in CX and the right in AX (in the original, and still the
  885. commonest, shape: it pushes the left, loads the right, then pops the
  886. left into CX), so the exchange is what puts LEFT in AX for the
  887. operation to act on.
  888. Without it, `a - b` computes `b - a`; with the wrong register, `a + b`
  889. computes `AX' + a` where AX' is whatever BX happened to hold.
  890. This emitted 93H = XCHG BX,AX for its entire life, which is the same class
  891. of mistake as MovSiBx = 89 DC in Runtime.mod: the right opcode, the wrong
  892. ModRM, decoding cleanly. Byte counts were right, the compile matrix was
  893. green, and no exec fixture did arithmetic on two variables - the first one
  894. to do so, `c := a + b` with a=7 b=5, printed 263 = 0100h+7, where 0100h
  895. was the caller's leftover BX. The name was the only thing wrong, and
  896. nothing read the name: audit_helpers.py swept Runtime.mod and not
  897. Compiler.mod, which is where most of these emitters live. It does both
  898. modules now. *)
  899. PROCEDURE EmXchgAxCx () ;
  900. BEGIN
  901. Ebyte (91H)
  902. END EmXchgAxCx ;
  903. PROCEDURE EmXorAxAx () ;
  904. BEGIN
  905. Ebyte (33H) ; Ebyte (0C0H)
  906. END EmXorAxAx ;
  907. PROCEDURE EmAddAxCx () ;
  908. BEGIN
  909. Ebyte (3H) ; Ebyte (0C1H)
  910. END EmAddAxCx ;
  911. PROCEDURE EmSubAxCx () ;
  912. BEGIN
  913. Ebyte (2BH) ; Ebyte (0C1H)
  914. END EmSubAxCx ;
  915. PROCEDURE EmMulAxCx () ;
  916. BEGIN
  917. Ebyte (0F7H) ; Ebyte (0E9H)
  918. END EmMulAxCx ;
  919. PROCEDURE EmIDivAxCx () ;
  920. BEGIN
  921. Ebyte (99H) ; Ebyte (0F7H) ; Ebyte (0F9H)
  922. END EmIDivAxCx ;
  923. PROCEDURE EmAndAxCx () ;
  924. BEGIN
  925. Ebyte (23H) ; Ebyte (0C1H)
  926. END EmAndAxCx ;
  927. PROCEDURE EmOrAxCx () ;
  928. BEGIN
  929. Ebyte (0BH) ; Ebyte (0C1H)
  930. END EmOrAxCx ;
  931. PROCEDURE EmOrAxAx () ;
  932. (* 09 C0: OR AX,AX - the 8086's flag-only test of AX, and the one the string
  933. comparison needs, because cmpstr hands back a signed -1/0/+1 rather than
  934. flags. OR AX,AX sets SF and ZF from the value and clears OF and CF, which
  935. is exactly the flag state a CMP AX,0 would leave - see EmSetcc and
  936. ParseCmp's EmRelSetcc. TEST AX,AX (85 C0) does the same thing, but
  937. tests/audit_helpers.py's name grammar has no `Test' mnemonic, and an
  938. emitter that cannot be name-checked is worse than one that can.
  939. It is NOT EmXorAxAx: XORing AX with itself zeroes it, which would throw
  940. away the very value the flags are supposed to describe. *)
  941. BEGIN
  942. Ebyte (09H) ; Ebyte (0C0H)
  943. END EmOrAxAx ;
  944. PROCEDURE EmNegAx () ;
  945. BEGIN
  946. Ebyte (0F7H) ; Ebyte (0D8H)
  947. END EmNegAx ;
  948. PROCEDURE EmNotAx () ;
  949. BEGIN
  950. Ebyte (0F7H) ; Ebyte (0D0H)
  951. END EmNotAx ;
  952. PROCEDURE EmXorAl01 () ;
  953. (* XOR AL,#01 - TPSRC9 neglevel's *boolean* NOT:
  954. CALL loadatom ; CALL ecode ; B $02,$34,$01
  955. neglevel tests the type first (CMP CL,#$0A -> integer -> NOT AX,
  956. CMP CL,#$0B -> boolean -> XOR AL,#01) and reports error 47 for anything
  957. else. Emitting NOT AX for a boolean leaves 0FFFEh or 0FFFFh, and the
  958. runtime's wrbool tests [BP+4] <> 0, so `not (a = a)' came out TRUE. *)
  959. BEGIN
  960. Ebyte (34H) ; Ebyte (01H)
  961. END EmXorAl01 ;
  962. PROCEDURE EmCmpAxCx () ;
  963. BEGIN
  964. Ebyte (3BH) ; Ebyte (0C1H)
  965. END EmCmpAxCx ;
  966. PROCEDURE EmCmpAxi (imm : CARDINAL) ;
  967. BEGIN
  968. Ebyte (03DH) ; Eword (imm)
  969. END EmCmpAxi ;
  970. PROCEDURE EmSetcc (cc : BYTE) ;
  971. (* Flags -> a Boolean in AX, on an 8086. `cc' is the SETcc opcode's low byte
  972. (94H = E, 95H = NE, 9CH = L, 9DH = GE, 9EH = LE, 9FH = G), i.e. the same
  973. condition nibble EmJcc takes.
  974. This used to emit `0F cc C0' - SETcc - which is 386-and-later, and then a
  975. MOV AH,0. The 8086 cannot read its flags as a value at all, so there was
  976. nothing else to fall back on.
  977. TPSRC9's flgbool is the fallback, and emits exactly this for exactly this
  978. case (CH = 04h, a comparison whose result is wanted as a value rather than
  979. as a branch):
  980. CALL ecode ; B $03,$B8,$01,$00 -> MOV AX,#0001
  981. MOV AL,brnchop ; CALL ebyte -> JNZ +1
  982. CALL ecode ; B $02,$01,$48 -> DEC AX
  983. AX stays 1 because the DEC was stepped over, and becomes 0 because it ran.
  984. So the shape is one MOV, one short Jcc whose displacement is the length of
  985. the DEC, and the DEC - which is EmJcc's shape with a different displacement,
  986. and the reason both are two instructions and a byte.
  987. The polarity is the opposite of EmJcc's, and deliberately so: here the jump
  988. must be taken when the comparison is TRUE, because what is being asked is
  989. "is this comparison true", and the nibble the six ParseCmp arms pass is the
  990. comparison's own opcode. So this is JccShort and EmJcc is JccShortInv --
  991. see EmJcc for why the difference is there at all. TP3's flgbool writes JNZ
  992. for the same reason; in the one case IT reaches flgbool from, the boolean is
  993. sitting in AX rather than in the flags, so JNZ is how it says "AX is
  994. non-zero".
  995. AH comes out 0 for free, which is why the EmMovAh0 this used to end with is
  996. gone: 6 bytes here where the old sequence was 5. The FLAGS do not survive,
  997. which the old SETcc did - and nothing reads them. Every conditional branch
  998. in the compiler is preceded by its own CMP (see EmJcc's note on the FOR
  999. test), and a comparison's value is consumed either as an AX operand or by
  1000. the test that follows it; the 30 executed fixtures are what holds that
  1001. down, not this comment. *)
  1002. BEGIN
  1003. Ebyte (0B8H) ; Eword (1) ; (* MOV AX,#0001 *)
  1004. Ebyte (JccShort (cc)) ; (* taken when the comparison HOLDS *)
  1005. Ebyte (01H) ; (* rel8: step over the DEC AX *)
  1006. Ebyte (48H) (* DEC AX *)
  1007. END EmSetcc ;
  1008. PROCEDURE EmRelSetcc (op : CARDINAL) ;
  1009. (* The relational operator -> SETcc table, in ONE place, because there are now
  1010. two callers: ParseCmp's numeric arm, whose flags come from EmCmpAxCx, and
  1011. its string arm, whose flags come from a cmpstr result put through
  1012. EmOrAxAx. It was factored out of ParseCmp when the string arm arrived, and
  1013. the note it carried is repeated here rather than referenced, because a
  1014. comment in the caller about a table in another routine is a comment nobody
  1015. reads.
  1016. The mnemonic is written next to every opcode on purpose. `op' is a number,
  1017. so the arm for ">" and the arm for ">=" differed only by two hex digits
  1018. that are each one letter from the other meaning -- SETG (9FH) and SETGE
  1019. (9DH). They were swapped once, which made a > b mean a >= b and a >= b
  1020. mean a > b. Only the equality boundary could see it: 6>5, 5<5, -1>-2 and
  1021. every other case I tried were already right. An opcode on its own does not
  1022. say which comparison it is the answer to.
  1023. `op' is ParseCmp's own numbering: 1 "=", 2 "<>", 3 "<", 4 ">", 5 ">=",
  1024. 6 "<=". The condition nibbles are the SIGNED ones (L/G/GE/LE), and both
  1025. callers hand it a value whose SIGN is the answer - ParseCmp's numeric arm
  1026. compares with CMP AX,CX on signed data, and cmpstr answers -1/0/+1 - so
  1027. the signed test is the right one in both places. One table also means that
  1028. swap cannot come back in one arm and not the other: tests/nonvacuity.sh
  1029. mutates exactly these two lines, and it now breaks the string comparison
  1030. at the same time as the numeric one. *)
  1031. BEGIN
  1032. CASE op OF
  1033. 1 : EmSetcc (94H) ; (* = SETE *)
  1034. | 2 : EmSetcc (95H) ; (* <> SETNE *)
  1035. | 3 : EmSetcc (9CH) ; (* < SETL *)
  1036. | 4 : EmSetcc (9FH) ; (* > SETG *)
  1037. | 5 : EmSetcc (9DH) ; (* >= SETGE *)
  1038. | 6 : EmSetcc (9EH) (* <= SETLE *)
  1039. END
  1040. END EmRelSetcc ;
  1041. PROCEDURE EmIncAx () ;
  1042. BEGIN
  1043. Ebyte (40H)
  1044. END EmIncAx ;
  1045. PROCEDURE EmDecAx () ;
  1046. BEGIN
  1047. Ebyte (48H)
  1048. END EmDecAx ;
  1049. PROCEDURE EmBpDisp (off, regf : CARDINAL) ;
  1050. (* Emit the ModR/M byte and displacement for a [BP+off] operand, picking the
  1051. encoding from the size of off. This is the ONE place that choice is made,
  1052. because getting it wrong is invisible: 8B 46 d8 and 8B 86 lo hi are both
  1053. well-formed MOVs, both decode cleanly, and only one of them reads the
  1054. variable the symbol table names. So the two are chosen here, once, rather
  1055. than re-derived at each of the four call sites. See the ModR/M table in
  1056. Runtime.mod.
  1057. off <= 127 -> mod=01 rm=110 -> 46 <disp8> 3 bytes with the opcode
  1058. otherwise -> mod=10 rm=110 -> 86 <disp16> 4 bytes with the opcode
  1059. Both displacements are SIGNED, and that is the whole subtlety:
  1060. - `off` is a 16-bit value and locals are packed top-anchored below BP:
  1061. locFree is the highest still-free byte (0FFFFh = -1 at entry), a local of
  1062. size n is based so its LAST byte sits on locFree, and locFree then drops
  1063. by n. So the first INTEGER local is at off = 0FFFEh = -2, the second at
  1064. 0FFFCh = -4, and so on - and a string local, which grows UP from its
  1065. base, lands wholly below BP instead of straddling it. The disp16 form
  1066. reads those same two bytes as a signed value and addresses the negative
  1067. slot correctly. There is no overflow case: all 65536 values of `off`
  1068. are representable, and a frame larger than 64K is a different problem.
  1069. - The old code took `off MOD 100H` and always emitted disp8. That is
  1070. the correct low byte for every displacement, so it was accidentally
  1071. right across -32768..+127, which is where locals actually live. It
  1072. went wrong at +128, where disp8 80h is -128 and not +128. So this
  1073. changes no existing program's bytes and fixes the one case that was
  1074. broken -- a bug nobody had hit yet, which is exactly why it wanted a
  1075. test rather than an argument. *)
  1076. BEGIN
  1077. (* mod=01 rm=110 -> 40H + regf*8 + 6H, mod=10 rm=110 -> 80H + regf*8 + 6H.
  1078. regf is the ModR/M reg field: 0 when the opcode's register is the
  1079. accumulator (every original caller), 7 for the DI forms EmLeaDi needs.
  1080. rm is 110 ([BP+disp]) in both. *)
  1081. IF off <= 127 THEN
  1082. Ebyte (VAL (BYTE, 40H + regf * 8 + 6H)) ; Ebyte (VAL (BYTE, off))
  1083. ELSE
  1084. Ebyte (VAL (BYTE, 80H + regf * 8 + 6H)) ; Eword (off)
  1085. END
  1086. END EmBpDisp ;
  1087. PROCEDURE EmLoadVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1088. (* A local is [BP+off] and `off' is already a frame displacement, so it needs
  1089. no bias. A global is [off] with a DIRECT displacement, i.e. an absolute
  1090. address, and that is the image offset + LoadBias - see Runtime.LoadBias. *)
  1091. BEGIN
  1092. IF nbytes = 1 THEN
  1093. IF local THEN
  1094. Ebyte (8AH) ; EmBpDisp (off, 0)
  1095. ELSE
  1096. Ebyte (0A0H) ; Eword ((off + LoadBias) MOD 10000H)
  1097. END
  1098. ELSE
  1099. IF local THEN
  1100. Ebyte (8BH) ; EmBpDisp (off, 0)
  1101. ELSE
  1102. Ebyte (0A1H) ; Eword ((off + LoadBias) MOD 10000H)
  1103. END
  1104. END
  1105. END EmLoadVar ;
  1106. PROCEDURE EmStoreVar (local : BOOLEAN ; off, nbytes : CARDINAL) ;
  1107. BEGIN
  1108. IF nbytes = 1 THEN
  1109. IF local THEN
  1110. Ebyte (88H) ; EmBpDisp (off, 0)
  1111. ELSE
  1112. Ebyte (0A2H) ; Eword ((off + LoadBias) MOD 10000H)
  1113. END
  1114. ELSE
  1115. IF local THEN
  1116. Ebyte (89H) ; EmBpDisp (off, 0)
  1117. ELSE
  1118. Ebyte (0A3H) ; Eword ((off + LoadBias) MOD 10000H)
  1119. END
  1120. END
  1121. END EmStoreVar ;
  1122. PROCEDURE EmPushVarAddr (local : BOOLEAN ; off : CARDINAL) ;
  1123. (* LEA AX,[BP+disp] / LEA AX,[off] then PUSH AX - READ passes the address of
  1124. a variable, not its value. 8D 46 disp is LEA AX,[BP+disp8] and
  1125. 8D 86 lo hi is LEA AX,[BP+disp16]; 8D 06 off is LEA AX,[off]
  1126. (mod=00 rm=110 = the direct disp16 form). All three are 8086-legal.
  1127. The [off] form is absolute and so carries LoadBias; the [BP+disp] forms
  1128. are displacements and so do not. *)
  1129. BEGIN
  1130. IF local THEN
  1131. Ebyte (8DH) ; EmBpDisp (off, 0)
  1132. ELSE
  1133. Ebyte (8DH) ; Ebyte (06H) ; Eword ((off + LoadBias) MOD 10000H)
  1134. END ;
  1135. EmPushAx ()
  1136. END EmPushVarAddr ;
  1137. PROCEDURE EmLeaDi (local : BOOLEAN ; off : CARDINAL) ;
  1138. (* LEA DI,[BP+disp] / LEA DI,[off] - the run-time address of an indexed
  1139. string's element, computed once in ParseSub and read by LoadAtom,
  1140. Assignment and IoCall.
  1141. It is the same three encodings EmPushVarAddr uses for AX - 8D 7E disp8,
  1142. 8D BE disp16, 8D 3E off - with the ModR/M reg field set to DI (111)
  1143. instead of the accumulator, which is why EmBpDisp now takes that field and
  1144. this is still the one place the disp8/disp16 choice is made. A local is
  1145. [BP+disp] with no bias; a global is [off] and carries LoadBias, absolute.
  1146. The later `MOV AL,[DI]` / `MOV [DI],AL` read through DS rather than SS.
  1147. That is correct here for the same reason TP3's own string ops use DI with
  1148. the default segment: a .COM loads with DS=SS=CS=ES, and nothing in this
  1149. compiler or its runtime ever reloads a segment register, so a BP-relative
  1150. frame address held in DI addresses the same byte. *)
  1151. BEGIN
  1152. IF local THEN
  1153. Ebyte (8DH) ; EmBpDisp (off, 7)
  1154. ELSE
  1155. Ebyte (8DH) ; Ebyte (3EH) ; Eword ((off + LoadBias) MOD 10000H)
  1156. END
  1157. END EmLeaDi ;
  1158. PROCEDURE EmAddDiAx () ;
  1159. BEGIN Ebyte (01H) ; Ebyte (0C7H) END EmAddDiAx ; (* 01 C7: DI := DI + AX *)
  1160. PROCEDURE EmLdAlDi () ;
  1161. BEGIN Ebyte (8AH) ; Ebyte (05H) END EmLdAlDi ; (* 8A 05: AL := [DI] *)
  1162. PROCEDURE EmStDiAl () ;
  1163. BEGIN Ebyte (88H) ; Ebyte (05H) END EmStDiAl ; (* 88 05: [DI] := AL *)
  1164. PROCEDURE EmPushDi () ;
  1165. BEGIN Ebyte (57H) END EmPushDi ; (* PUSH DI *)
  1166. PROCEDURE EmPopDi () ;
  1167. BEGIN Ebyte (5FH) END EmPopDi ; (* POP DI *)
  1168. PROCEDURE EmLoadVarInd (off, nbytes : CARDINAL) ;
  1169. (* AX := the value of a VAR parameter. [BP+off] holds the ADDRESS; BX carries
  1170. it so the byte/word load has a base register. The address is a DS offset:
  1171. a .COM has one segment, which is why no segment register appears here. *)
  1172. BEGIN
  1173. EmLoadVar (TRUE, off, 2) ; (* AX := [BP+off], the address *)
  1174. Ebyte (89H) ; Ebyte (0C3H) ; (* MOV BX,AX *)
  1175. IF nbytes = 1 THEN
  1176. Ebyte (8AH) ; Ebyte (07H) ; (* MOV AL,[BX] *)
  1177. EmMovAh0 ()
  1178. ELSE
  1179. Ebyte (8BH) ; Ebyte (07H) (* MOV AX,[BX] *)
  1180. END
  1181. END EmLoadVarInd ;
  1182. PROCEDURE EmStoreVarIndPrep (off : CARDINAL) ;
  1183. (* DI := the address of a VAR parameter, then PUSH DI. The push protects it
  1184. across the parse of the right-hand side, which may use DI for a string
  1185. element of its own. EmStoreInd finishes the store after POP DI. *)
  1186. BEGIN
  1187. Ebyte (8BH) ; EmBpDisp (off, 7) ; (* MOV DI,[BP+off] *)
  1188. EmPushDi ()
  1189. END EmStoreVarIndPrep ;
  1190. PROCEDURE EmStoreInd (nbytes : CARDINAL) ;
  1191. (* [DI] := AL/WORD, after POP DI - the companion of EmStoreVarIndPrep. *)
  1192. BEGIN
  1193. IF nbytes = 1 THEN
  1194. EmStDiAl () (* MOV [DI],AL *)
  1195. ELSE
  1196. Ebyte (89H) ; Ebyte (05H) (* MOV [DI],AX *)
  1197. END
  1198. END EmStoreInd ;
  1199. PROCEDURE EmSubSp (n : CARDINAL) ;
  1200. BEGIN
  1201. Ebyte (81H) ; Ebyte (0ECH) ; Eword (n MOD 10000H)
  1202. END EmSubSp ;
  1203. PROCEDURE EmAddSp (n : CARDINAL) ;
  1204. BEGIN
  1205. IF n <= 126 THEN
  1206. Ebyte (83H) ; Ebyte (0C4H) ; Ebyte (VAL (BYTE, n))
  1207. ELSE
  1208. Ebyte (81H) ; Ebyte (0C4H) ; Eword (n MOD 10000H)
  1209. END
  1210. END EmAddSp ;
  1211. PROCEDURE EmPushBp () ;
  1212. BEGIN
  1213. Ebyte (55H)
  1214. END EmPushBp ;
  1215. PROCEDURE EmLeave () ;
  1216. BEGIN
  1217. Ebyte (0C9H)
  1218. END EmLeave ;
  1219. PROCEDURE EmRet () ;
  1220. BEGIN
  1221. Ebyte (0C3H)
  1222. END EmRet ;
  1223. (* ---------------------------------------------------------------- *)
  1224. (* symbol table *)
  1225. (* ---------------------------------------------------------------- *)
  1226. PROCEDURE NameEq (a : ARRAY OF CHAR ; b : ARRAY OF CHAR) : BOOLEAN ;
  1227. VAR i : CARDINAL ;
  1228. BEGIN
  1229. i := 0 ;
  1230. LOOP
  1231. IF i > HIGH (a) THEN
  1232. RETURN FALSE
  1233. END ;
  1234. IF i > HIGH (b) THEN
  1235. RETURN FALSE
  1236. END ;
  1237. IF a [i] # b [i] THEN
  1238. RETURN FALSE
  1239. END ;
  1240. IF a [i] = 0C THEN
  1241. RETURN TRUE
  1242. END ;
  1243. INC (i)
  1244. END
  1245. END NameEq ;
  1246. PROCEDURE CopyStr (VAR dst : ARRAY OF CHAR ; src : ARRAY OF CHAR) ;
  1247. VAR i : CARDINAL ;
  1248. BEGIN
  1249. i := 0 ;
  1250. LOOP
  1251. IF i > HIGH (dst) THEN
  1252. dst [HIGH (dst)] := 0C ;
  1253. RETURN
  1254. END ;
  1255. IF i > HIGH (src) THEN
  1256. dst [i] := 0C ;
  1257. RETURN
  1258. END ;
  1259. dst [i] := src [i] ;
  1260. IF src [i] = 0C THEN
  1261. RETURN
  1262. END ;
  1263. INC (i)
  1264. END
  1265. END CopyStr ;
  1266. PROCEDURE CopyWord (name : ARRAY OF CHAR) ;
  1267. (* stash current word into global wrd (uppercased) *)
  1268. VAR i : CARDINAL ;
  1269. BEGIN
  1270. i := 0 ;
  1271. LOOP
  1272. IF i > HIGH (name) THEN
  1273. wrd [i] := 0C ;
  1274. RETURN
  1275. END ;
  1276. IF i > MaxName THEN
  1277. wrd [MaxName] := 0C ;
  1278. RETURN
  1279. END ;
  1280. IF name [i] = 0C THEN
  1281. wrd [i] := 0C ;
  1282. RETURN
  1283. END ;
  1284. wrd [i] := Upper (name [i]) ;
  1285. INC (i)
  1286. END
  1287. END CopyWord ;
  1288. PROCEDURE SaveWord (VAR dst : ARRAY OF CHAR) ;
  1289. (* copy wrd into dst *)
  1290. VAR i : CARDINAL ;
  1291. BEGIN
  1292. i := 0 ;
  1293. LOOP
  1294. IF i > HIGH (dst) THEN
  1295. dst [HIGH (dst)] := 0C ;
  1296. RETURN
  1297. END ;
  1298. IF i > MaxName THEN
  1299. dst [MaxName] := 0C ;
  1300. RETURN
  1301. END ;
  1302. dst [i] := wrd [i] ;
  1303. IF wrd [i] = 0C THEN
  1304. RETURN
  1305. END ;
  1306. INC (i)
  1307. END
  1308. END SaveWord ;
  1309. PROCEDURE NumToName (n : CARDINAL ; VAR dst : ARRAY OF CHAR) ;
  1310. VAR buf : ARRAY [0..9] OF CHAR ;
  1311. i, j : CARDINAL ;
  1312. BEGIN
  1313. IF n = 0 THEN
  1314. dst [0] := '0' ;
  1315. dst [1] := 0C ;
  1316. RETURN
  1317. END ;
  1318. i := 0 ;
  1319. WHILE n > 0 DO
  1320. IF i <= 9 THEN
  1321. buf [i] := CHR (ORD ('0') + (n MOD 10)) ;
  1322. INC (i)
  1323. END ;
  1324. n := n DIV 10
  1325. END ;
  1326. j := 0 ;
  1327. WHILE i > 0 DO
  1328. DEC (i) ;
  1329. IF j <= HIGH (dst) THEN
  1330. dst [j] := buf [i] ;
  1331. INC (j)
  1332. END
  1333. END ;
  1334. IF j <= HIGH (dst) THEN
  1335. dst [j] := 0C
  1336. END
  1337. END NumToName ;
  1338. PROCEDURE NewSym (name : ARRAY OF CHAR ; tag : CARDINAL ;
  1339. cls, size, elem, off : CARDINAL ; v : LONGINT ;
  1340. local : BOOLEAN) : CARDINAL ;
  1341. VAR e : SymEntry ;
  1342. BEGIN
  1343. IF symTop >= MaxSym THEN
  1344. Err (ECompOvf) ;
  1345. RETURN 0
  1346. END ;
  1347. CopyWord (name) ;
  1348. CopyStr (e.name, wrd) ;
  1349. e.tag := tag ;
  1350. e.cls := cls ;
  1351. e.size := size ;
  1352. e.elem := elem ;
  1353. e.off := off ;
  1354. e.lval := v ;
  1355. e.lo := 0 ;
  1356. e.hi := 0 ;
  1357. e.fldFirst := 0 ;
  1358. e.fldLast := 0 ;
  1359. e.arrIdx := 0 ;
  1360. e.parmFirst := 0 ;
  1361. e.parmCount := 0 ;
  1362. e.isKbd := FALSE ;
  1363. e.isVar := FALSE ;
  1364. e.level := lexnest ;
  1365. e.local := local ;
  1366. e.resvar := 0 ;
  1367. e.goPos := 0 ;
  1368. e.defnd := FALSE ;
  1369. e.fwd := FALSE ;
  1370. symtab [symTop] := e ;
  1371. INC (symTop) ;
  1372. RETURN symTop - 1
  1373. END NewSym ;
  1374. PROCEDURE Search (nm : ARRAY OF CHAR ; VAR idx : CARDINAL) : BOOLEAN ;
  1375. (* find nm among symbols visible at the current lexical level *)
  1376. VAR p : CARDINAL ;
  1377. BEGIN
  1378. CopyWord (nm) ;
  1379. p := symTop ;
  1380. WHILE p > 0 DO
  1381. DEC (p) ;
  1382. IF symtab [p].level <= lexnest THEN
  1383. IF NameEq (symtab [p].name, wrd) THEN
  1384. idx := p ;
  1385. RETURN TRUE
  1386. END
  1387. END
  1388. END ;
  1389. RETURN FALSE
  1390. END Search ;
  1391. PROCEDURE DupTest (nm : ARRAY OF CHAR) ;
  1392. (* A name may be declared twice only in the SAME scope. This used to reject
  1393. any name Search could see, so a parameter could not shadow a global - legal
  1394. ISO Pascal, and CALC.INC's `procedure IBMCh(var Ch: Char)' does exactly
  1395. that (`Ch' is a global). Same-level duplicates stay errors: two parameters
  1396. in one list, two locals, or two globals. *)
  1397. VAR i : CARDINAL ;
  1398. BEGIN
  1399. IF Search (nm, i) THEN
  1400. IF symtab [i].level = lexnest THEN
  1401. Err (EUnknown)
  1402. END
  1403. END
  1404. END DupTest ;
  1405. PROCEDURE HideLocals (from : CARDINAL) ;
  1406. (* Make every symbol from index `from' up invisible to everything outside the
  1407. procedure that declared it.
  1408. Search accepts a symbol when its level is <= lexnest, and every procedure
  1409. body is compiled at the same depth (lexnest 1), so a finished procedure's
  1410. parameters stayed visible to the NEXT procedure: a second `a : integer'
  1411. was a duplicate (err 41) and an unqualified `a' inside procedure two read
  1412. procedure one's argument. Level 0FFFFH fails `level <= lexnest' at every
  1413. depth a later procedure can be at, and by the time this runs the body that
  1414. could still legitimately see them is finished.
  1415. The symbols are relabelled, not popped: symtab[old].resvar holds an INDEX,
  1416. and a function's result variable is one of the entries being hidden. *)
  1417. VAR p : CARDINAL ;
  1418. BEGIN
  1419. p := from ;
  1420. WHILE p < symTop DO
  1421. symtab [p].level := 0FFFFH ;
  1422. INC (p)
  1423. END
  1424. END HideLocals ;
  1425. (* ---------------------------------------------------------------- *)
  1426. (* lexer *)
  1427. (* ---------------------------------------------------------------- *)
  1428. PROCEDURE InitKeys () ;
  1429. VAR i : CARDINAL ;
  1430. BEGIN
  1431. FOR i := 0 TO 42 DO
  1432. kTk [i] := 0 ;
  1433. kName [i] [0] := 0C
  1434. END ;
  1435. kName [1] := "PROGRAM" ; kTk [1] := TkProgram ;
  1436. kName [2] := "BEGIN" ; kTk [2] := TkBegin ;
  1437. kName [3] := "END" ; kTk [3] := TkEnd ;
  1438. kName [4] := "IF" ; kTk [4] := TkIf ;
  1439. kName [5] := "THEN" ; kTk [5] := TkThen ;
  1440. kName [6] := "ELSE" ; kTk [6] := TkElse ;
  1441. kName [7] := "WHILE" ; kTk [7] := TkWhile ;
  1442. kName [8] := "DO" ; kTk [8] := TkDo ;
  1443. kName [9] := "REPEAT" ; kTk [9] := TkRepeat ;
  1444. kName [10] := "UNTIL" ; kTk [10] := TkUntil ;
  1445. kName [11] := "FOR" ; kTk [11] := TkFor ;
  1446. kName [12] := "TO" ; kTk [12] := TkTo ;
  1447. kName [13] := "DOWNTO" ; kTk [13] := TkDownto ;
  1448. kName [14] := "CASE" ; kTk [14] := TkCase ;
  1449. kName [15] := "OF" ; kTk [15] := TkOf ;
  1450. kName [16] := "GOTO" ; kTk [16] := TkGoto ;
  1451. kName [17] := "EXIT" ; kTk [17] := TkExit ;
  1452. kName [18] := "WITH" ; kTk [18] := TkWith ;
  1453. kName [19] := "VAR" ; kTk [19] := TkVar ;
  1454. kName [20] := "CONST" ; kTk [20] := TkConst ;
  1455. kName [21] := "TYPE" ; kTk [21] := TkType ;
  1456. kName [22] := "LABEL" ; kTk [22] := TkLabel ;
  1457. kName [23] := "PROCEDURE" ; kTk [23] := TkProcedure ;
  1458. kName [24] := "FUNCTION" ; kTk [24] := TkFunction ;
  1459. kName [25] := "NIL" ; kTk [25] := TkNil ;
  1460. kName [26] := "AND" ; kTk [26] := TkAnd ;
  1461. kName [27] := "OR" ; kTk [27] := TkOr ;
  1462. kName [28] := "NOT" ; kTk [28] := TkNot ;
  1463. kName [29] := "DIV" ; kTk [29] := TkDiv ;
  1464. kName [30] := "MOD" ; kTk [30] := TkMod ;
  1465. kName [31] := "IN" ; kTk [31] := TkIn ;
  1466. kName [32] := "FILE" ; kTk [32] := TkFile ;
  1467. kName [33] := "TEXT" ; kTk [33] := TkText ;
  1468. kName [34] := "RECORD" ; kTk [34] := TkRecord ;
  1469. kName [35] := "ARRAY" ; kTk [35] := TkArray ;
  1470. kName [36] := "SET" ; kTk [36] := TkSet ;
  1471. kName [37] := "PACKED" ; kTk [37] := TkPacked ;
  1472. kName [38] := "FORWARD" ; kTk [38] := TkForward ;
  1473. kName [39] := "EXTERNAL" ; kTk [39] := TkExternal ;
  1474. kName [40] := "ABSOLUTE" ; kTk [40] := TkAbsolute ;
  1475. kName [41] := "OVERLAY" ; kTk [41] := TkOverlay ;
  1476. kName [42] := "STRING" ; kTk [42] := TkString
  1477. END InitKeys ;
  1478. PROCEDURE IsBlank (ch : CHAR) : BOOLEAN ;
  1479. BEGIN
  1480. RETURN (ch = ' ') OR (ORD (ch) = 09H) OR (ORD (ch) = 0DH) OR (ORD (ch) = 0AH) OR (ORD (ch) = 0CH)
  1481. END IsBlank ;
  1482. PROCEDURE Skip () ;
  1483. (* blanks, comments { } and (* *), compiler directives {$ } / (*$ *)
  1484. letter + sign toggles rng/chk. Include directives are already gone by the
  1485. time Skip runs: ExpandIncludes splices them into the buffer first, so the
  1486. {$I file} spelling never reaches here. {$I+}/{$I-} still do, and stay the
  1487. I/O-check toggle, exactly as TPSRC10 cdirec splits them on the sign. *)
  1488. VAR ch : CHAR ;
  1489. letter : CHAR ;
  1490. BEGIN
  1491. WHILE NOT abortFac DO
  1492. WHILE IsBlank (CurCh ()) DO
  1493. ch := GetCh ()
  1494. END ;
  1495. IF CurCh () = '{' THEN
  1496. ch := GetCh () ;
  1497. IF CurCh () = '$' THEN
  1498. ch := GetCh () ;
  1499. letter := Upper (GetCh ()) ;
  1500. IF CurCh () = '+' THEN
  1501. ch := GetCh () ;
  1502. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1503. IF letter = 'R' THEN dirs.rng := TRUE END
  1504. ELSIF CurCh () = '-' THEN
  1505. ch := GetCh () ;
  1506. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1507. IF letter = 'R' THEN dirs.rng := FALSE END
  1508. END
  1509. END ;
  1510. WHILE (CurCh () # '}') AND (CurCh () # 0C) DO
  1511. ch := GetCh ()
  1512. END ;
  1513. IF CurCh () = '}' THEN
  1514. ch := GetCh ()
  1515. END
  1516. ELSIF (CurCh () = '(') AND (PeekAhead (1) = '*') THEN
  1517. ch := GetCh () ;
  1518. ch := GetCh () ;
  1519. IF CurCh () = '$' THEN
  1520. ch := GetCh () ;
  1521. letter := Upper (GetCh ()) ;
  1522. IF CurCh () = '+' THEN
  1523. ch := GetCh () ;
  1524. IF letter = 'I' THEN dirs.chk := TRUE END ;
  1525. IF letter = 'R' THEN dirs.rng := TRUE END
  1526. ELSIF CurCh () = '-' THEN
  1527. ch := GetCh () ;
  1528. IF letter = 'I' THEN dirs.chk := FALSE END ;
  1529. IF letter = 'R' THEN dirs.rng := FALSE END
  1530. END
  1531. END ;
  1532. LOOP
  1533. IF (CurCh () = '*') AND (PeekAhead (1) = ')') THEN
  1534. ch := GetCh () ;
  1535. ch := GetCh () ;
  1536. EXIT
  1537. END ;
  1538. IF CurCh () = 0C THEN
  1539. EXIT
  1540. END ;
  1541. ch := GetCh ()
  1542. END
  1543. ELSE
  1544. RETURN
  1545. END
  1546. END
  1547. END Skip ;
  1548. PROCEDURE GetWord () ;
  1549. (* read identifier into wrd (uppercased); next char must be alpha *)
  1550. VAR i : CARDINAL ;
  1551. ch : CHAR ;
  1552. BEGIN
  1553. i := 0 ;
  1554. ch := GetCh () ;
  1555. LOOP
  1556. IF i > MaxName THEN
  1557. wrd [MaxName] := 0C ;
  1558. RETURN
  1559. END ;
  1560. wrd [i] := Upper (ch) ;
  1561. INC (i) ;
  1562. ch := CurCh () ;
  1563. IF NOT AlphaNum (ch) THEN
  1564. wrd [i] := 0C ;
  1565. RETURN
  1566. END ;
  1567. ch := GetCh ()
  1568. END
  1569. END GetWord ;
  1570. PROCEDURE WddTok () : CARDINAL ;
  1571. (* map wrd -> keyword token *)
  1572. VAR i : CARDINAL ;
  1573. BEGIN
  1574. i := 1 ;
  1575. WHILE i <= 42 DO
  1576. IF kName [i] [0] # 0C THEN
  1577. IF NameEq (wrd, kName [i]) THEN
  1578. RETURN kTk [i]
  1579. END
  1580. END ;
  1581. INC (i)
  1582. END ;
  1583. RETURN TkNone
  1584. END WddTok ;
  1585. PROCEDURE DeclaresProc () : BOOLEAN ;
  1586. (* Does the REST of the source declare a PROCEDURE or a FUNCTION?
  1587. Needed because the declaration part is compiled BEFORE the main statement
  1588. part, so a procedure's code lands between the program prologue and the
  1589. main body - and nothing jumps over it. A program with a procedure
  1590. therefore ran off the end of the prologue, straight into the first
  1591. procedure, which read its argument out of an uninitialised frame and
  1592. returned to address 0. Every Pascal program containing a procedure was
  1593. broken; `t13_proc` compiled and was never executed, so nothing saw it.
  1594. The jump that fixes it has to be emitted BEFORE the declaration part, but
  1595. whether one is needed is only known AFTER - so the only honest options are
  1596. to emit it unconditionally (3 dead bytes in every program, and every code
  1597. size in expected.tsv moves) or to know the answer in advance. This is the
  1598. second: it scans ahead and puts srcPos back.
  1599. That is safe because the whole program is already in `src` and `srcPos` is
  1600. a plain index into it - the same trick PeekKw and KwAhead use. The scan
  1601. looks for the keywords anywhere in the remainder rather than tracking the
  1602. nesting of `begin`s, which is deliberately loose: a program with no
  1603. procedures that merely mentions the word in a string literal would get a
  1604. 3-byte jump to the next instruction, which is harmless, whereas tracking
  1605. the main `begin` against a procedure's `begin` would be a second parser
  1606. to get wrong. *)
  1607. VAR save : CARDINAL ;
  1608. found : BOOLEAN ;
  1609. tk : CARDINAL ;
  1610. ch : CHAR ;
  1611. BEGIN
  1612. save := srcPos ;
  1613. found := FALSE ;
  1614. tk := TkNone ; (* so the answer is defined if src is empty *)
  1615. (* Step over delimiters as well as blanks. Stopping at the first
  1616. non-letter looked reasonable and was wrong: `var x : integer ;` is full
  1617. of ':' and ';', so the scan gave up inside the variable section and
  1618. never reached the PROCEDURE. The loop ends at the end of the source,
  1619. not at the first punctuation. *)
  1620. WHILE (NOT found) AND (srcPos < srcLen) DO
  1621. Skip () ;
  1622. IF Alpha (CurCh ()) THEN
  1623. GetWord () ;
  1624. tk := WddTok () ;
  1625. IF (tk = TkProcedure) OR (tk = TkFunction) THEN
  1626. found := TRUE
  1627. END
  1628. ELSE
  1629. ch := GetCh () (* a ':' or ';' - step over it *)
  1630. END
  1631. END ;
  1632. srcPos := save ;
  1633. RETURN (tk = TkProcedure) OR (tk = TkFunction)
  1634. END DeclaresProc ;
  1635. PROCEDURE KwAhead (word : ARRAY OF CHAR) : BOOLEAN ;
  1636. (* does the next token (past blanks/comments) equal the keyword 'word',
  1637. without consuming it? srcPos is saved and restored. *)
  1638. VAR save : CARDINAL ;
  1639. k : BOOLEAN ;
  1640. BEGIN
  1641. save := srcPos ;
  1642. Skip () ;
  1643. k := FALSE ;
  1644. IF Alpha (CurCh ()) THEN
  1645. GetWord () ;
  1646. k := NameEq (wrd, word)
  1647. END ;
  1648. srcPos := save ;
  1649. RETURN k
  1650. END KwAhead ;
  1651. PROCEDURE PeekKw (VAR tok : CARDINAL) ;
  1652. (* peek at the next keyword token without consuming it *)
  1653. VAR i : CARDINAL ;
  1654. BEGIN
  1655. tok := TkNone ;
  1656. i := 1 ;
  1657. WHILE i <= 42 DO
  1658. IF kName [i] [0] # 0C THEN
  1659. IF KwAhead (kName [i]) THEN
  1660. tok := kTk [i] ;
  1661. RETURN
  1662. END
  1663. END ;
  1664. INC (i)
  1665. END
  1666. END PeekKw ;
  1667. PROCEDURE MatchKey (VAR tok : CARDINAL) : BOOLEAN ;
  1668. (* skip; if next symbol is a word, read it into wrd and set its token.
  1669. Returns TRUE when a word was read (tok = TkNone for plain ids). *)
  1670. BEGIN
  1671. tok := TkNone ;
  1672. Skip () ;
  1673. IF NOT Alpha (CurCh ()) THEN
  1674. RETURN FALSE
  1675. END ;
  1676. GetWord () ;
  1677. tok := WddTok () ;
  1678. RETURN TRUE
  1679. END MatchKey ;
  1680. PROCEDURE MatchDelim (ch : CHAR) : BOOLEAN ;
  1681. BEGIN
  1682. Skip () ;
  1683. IF CurCh () = ch THEN
  1684. DropCh (GetCh ()) ;
  1685. RETURN TRUE
  1686. END ;
  1687. RETURN FALSE
  1688. END MatchDelim ;
  1689. PROCEDURE MatchAssign () : BOOLEAN ;
  1690. BEGIN
  1691. Skip () ;
  1692. IF (CurCh () = ':') AND (PeekAhead (1) = '=') THEN
  1693. DropCh (GetCh ()) ;
  1694. DropCh (GetCh ()) ;
  1695. RETURN TRUE
  1696. END ;
  1697. RETURN FALSE
  1698. END MatchAssign ;
  1699. PROCEDURE MatchRange () : BOOLEAN ;
  1700. BEGIN
  1701. Skip () ;
  1702. IF (CurCh () = '.') AND (PeekAhead (1) = '.') THEN
  1703. DropCh (GetCh ()) ;
  1704. DropCh (GetCh ()) ;
  1705. RETURN TRUE
  1706. END ;
  1707. RETURN FALSE
  1708. END MatchRange ;
  1709. PROCEDURE ExpectDelim (ch : CHAR ; n : CARDINAL) ;
  1710. BEGIN
  1711. Skip () ;
  1712. IF CurCh () = ch THEN
  1713. DropCh (GetCh ())
  1714. ELSE
  1715. Err (n)
  1716. END
  1717. END ExpectDelim ;
  1718. PROCEDURE HexVal (ch : CHAR) : CARDINAL ;
  1719. BEGIN
  1720. IF (ch >= '0') AND (ch <= '9') THEN
  1721. RETURN ORD (ch) - ORD ('0')
  1722. ELSIF (ch >= 'A') AND (ch <= 'F') THEN
  1723. RETURN ORD (ch) - ORD ('A') + 10
  1724. END ;
  1725. RETURN ORD (ch) - ORD ('a') + 10
  1726. END HexVal ;
  1727. PROCEDURE RdIntConst (VAR v : LONGINT) ;
  1728. (* bare integer constant; current char is digit or '$' *)
  1729. VAR acc : LONGINT ;
  1730. BEGIN
  1731. acc := 0 ;
  1732. IF CurCh () = '$' THEN
  1733. DropCh (GetCh ()) ;
  1734. WHILE IsHexCh (CurCh ()) DO
  1735. acc := acc * 16 + VAL (LONGINT, HexVal (CurCh ())) ;
  1736. DropCh (GetCh ())
  1737. END
  1738. ELSE
  1739. WHILE Digit (CurCh ()) DO
  1740. acc := acc * 10 + VAL (LONGINT, ORD (CurCh ()) - ORD ('0')) ;
  1741. DropCh (GetCh ())
  1742. END
  1743. END ;
  1744. v := acc
  1745. END RdIntConst ;
  1746. PROCEDURE StrNew (first : CARDINAL ; hasFirst : BOOLEAN ) : CARDINAL ;
  1747. (* Open a pool slot for a string literal, optionally pre-seeded with its
  1748. first character.
  1749. RdConst has to read the first character before it can tell a one-character
  1750. literal from a longer one - the "is the next character another quote?"
  1751. test only makes sense once something has been read - so the seeding has to
  1752. happen here and has to advance strTop. Leaving strTop alone and letting the
  1753. caller write the character by hand is a trap: strTop is the next FREE byte,
  1754. so the first StrPut lands on top of the seeded character and overwrites it.
  1755. (That bug shipped the literal 'hi' as 69 00 - 'i' then NUL.) *)
  1756. VAR x : CARDINAL ;
  1757. BEGIN
  1758. IF strCnt > HIGH (strOff) THEN
  1759. Err (ECompOvf) ; (* too many literals in one unit *)
  1760. RETURN 0
  1761. END ;
  1762. x := strCnt ;
  1763. strOff [x] := strTop ;
  1764. strLen [x] := 0 ;
  1765. INC (strCnt) ;
  1766. IF hasFirst THEN
  1767. strPool [strTop] := CHR (first) ;
  1768. INC (strTop) ;
  1769. strLen [x] := 1
  1770. END ;
  1771. rdStrX := x ;
  1772. RETURN x
  1773. END StrNew ;
  1774. PROCEDURE StrPut (x : CARDINAL ) ;
  1775. (* append the current source character to pool slot x *)
  1776. BEGIN
  1777. IF x > HIGH (strOff) THEN
  1778. RETURN
  1779. END ;
  1780. IF strTop > HIGH (strPool) THEN
  1781. Err (ECompOvf) ; (* literal longer than the pool *)
  1782. RETURN
  1783. END ;
  1784. strPool [strTop] := CurCh () ;
  1785. INC (strTop) ;
  1786. INC (strLen [x])
  1787. END StrPut ;
  1788. PROCEDURE RdConst (VAR v : LONGINT ; VAR cls : CARDINAL ;
  1789. VAR isStr : BOOLEAN) ;
  1790. (* scalar or string constant. A string literal's text is collected into the
  1791. pool and its slot index left in rdStrX; a single-character literal stays a
  1792. TScalar holding its character code, which is what "c := 'a'" wants. *)
  1793. CONST q = AposC ;
  1794. VAR ch : CHAR ;
  1795. idx : CARDINAL ;
  1796. BEGIN
  1797. isStr := FALSE ;
  1798. cls := TScalar ;
  1799. v := 0 ;
  1800. Skip () ;
  1801. IF CurCh () = '$' THEN
  1802. RdIntConst (v) ;
  1803. cls := TScalar
  1804. ELSIF Digit (CurCh ()) THEN
  1805. RdIntConst (v) ;
  1806. IF (CurCh () = '.') AND (Digit (PeekAhead (1))) THEN
  1807. cls := TReal ;
  1808. DropCh (GetCh ())
  1809. END ;
  1810. IF (CurCh () = 'E') OR (CurCh () = 'e') THEN
  1811. cls := TReal ;
  1812. DropCh (GetCh ())
  1813. END ;
  1814. IF cls = TReal THEN
  1815. WHILE AlphaNum (CurCh ()) OR (CurCh () = '.') OR (CurCh () = '-')
  1816. OR (CurCh () = '+') DO
  1817. DropCh (GetCh ())
  1818. END
  1819. END
  1820. ELSIF CurCh () = '^' THEN
  1821. (* TP3 caret character constant, unquoted: ^M is CR (13), ^[ is ESC
  1822. (27), ^@ is 0. The value is the upper-cased character minus 64, so
  1823. the +256-MOD-256 keeps ^@ and any control character from wrapping. *)
  1824. DropCh (GetCh ()) ;
  1825. IF CurCh () = 0C THEN
  1826. Err (EUnknown)
  1827. ELSE
  1828. ch := Upper (GetCh ()) ;
  1829. v := VAL (LONGINT, (ORD (ch) + 256 - 64) MOD 256) ;
  1830. cls := TScalar
  1831. END
  1832. ELSIF CurCh () = '#' THEN
  1833. (* TP3 decimal character constant: #27, #255. *)
  1834. DropCh (GetCh ()) ;
  1835. IF Digit (CurCh ()) THEN
  1836. RdIntConst (v) ;
  1837. cls := TScalar
  1838. ELSE
  1839. Err (EUnknown)
  1840. END
  1841. ELSIF Alpha (CurCh ()) THEN
  1842. (* TRUE / FALSE, or a NAMED constant - an enumerator (`[Constant,
  1843. Formula]'), or any earlier const. A constant expression may name a
  1844. constant, and set literals and `case' labels are full of enumerators. *)
  1845. GetWord () ;
  1846. IF NameEq (wrd, "TRUE") THEN
  1847. v := 1 ;
  1848. cls := TBool
  1849. ELSIF NameEq (wrd, "FALSE") THEN
  1850. v := 0 ;
  1851. cls := TBool
  1852. ELSIF Search (wrd, idx) AND (symtab [idx].tag = KConst) THEN
  1853. v := symtab [idx].lval ;
  1854. cls := symtab [idx].cls
  1855. ELSE
  1856. Err (EUnknown)
  1857. END
  1858. ELSIF ORD (CurCh ()) = q THEN
  1859. DropCh (GetCh ()) ;
  1860. IF ORD (CurCh ()) = q THEN
  1861. (* '' - the empty string. It used to be reported as the scalar 39,
  1862. so writeln('') printed a single quote mark. It is a string of
  1863. length zero, and an inline zero-length literal is exactly what the
  1864. runtime's JCXZ path is for. *)
  1865. DropCh (GetCh ()) ;
  1866. isStr := TRUE ;
  1867. cls := TString ;
  1868. v := 0 ;
  1869. rdStrX := StrNew (0, FALSE)
  1870. ELSIF (CurCh () = 0C) OR ((ORD (CurCh ()) = 0DH)) OR ((ORD (CurCh ()) = 0AH)) THEN
  1871. Err (EUnknown)
  1872. ELSE
  1873. v := VAL (LONGINT, ORD (GetCh ())) ;
  1874. cls := TScalar ;
  1875. IF ORD (CurCh ()) = q THEN
  1876. DropCh (GetCh ())
  1877. ELSE
  1878. isStr := TRUE ;
  1879. cls := TString ;
  1880. (* Scan to the closing quote. NB: the loop condition must test
  1881. the CURRENT character and only the current character. The
  1882. obvious-looking "while CurCh # quote" with a
  1883. "if PeekAhead(1) = quote then consume two" body is wrong:
  1884. consuming the quote moves the cursor past it, so the next
  1885. condition test sees the character AFTER the literal, is
  1886. satisfied, and the scan runs on to end-of-buffer - which
  1887. silently eats the rest of the program and makes every later
  1888. error point at end-of-file. Stop on the quote itself, and
  1889. treat a doubled quote as one embedded quote character.
  1890. The first character is already gone - it was read into v above -
  1891. so the pool slot is pre-seeded with it. *)
  1892. rdStrX := StrNew (VAL (CARDINAL, v), TRUE) ;
  1893. LOOP
  1894. IF ORD (CurCh ()) = q THEN
  1895. IF ORD (PeekAhead (1)) = q THEN
  1896. StrPut (rdStrX) ; (* '' inside *)
  1897. DropCh (GetCh ()) ; DropCh (GetCh ())
  1898. ELSE
  1899. EXIT (* closing quote *)
  1900. END
  1901. ELSIF (CurCh () = 0C) OR (ORD (CurCh ()) = 0DH) THEN
  1902. Err (EUnknown) ; (* unterminated *)
  1903. EXIT
  1904. ELSE
  1905. StrPut (rdStrX) ;
  1906. DropCh (GetCh ())
  1907. END
  1908. END ;
  1909. IF ORD (CurCh ()) = q THEN
  1910. DropCh (GetCh ())
  1911. END
  1912. END
  1913. END
  1914. ELSE
  1915. Err (EUnknown)
  1916. END
  1917. END RdConst ;
  1918. (* ---------------------------------------------------------------- *)
  1919. (* forward declarations *)
  1920. (* ---------------------------------------------------------------- *)
  1921. PROCEDURE ParseExpr (VAR r : ERes) ; FORWARD ;
  1922. PROCEDURE ParseAdd (VAR r : ERes) ; FORWARD ;
  1923. PROCEDURE ParseMul (VAR r : ERes) ; FORWARD ;
  1924. PROCEDURE ParseNeg (VAR r : ERes) ; FORWARD ;
  1925. PROCEDURE ParseAtom (VAR r : ERes) ; FORWARD ;
  1926. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ; FORWARD ;
  1927. PROCEDURE Statmnt () ; FORWARD ;
  1928. PROCEDURE ParseCall (idx : CARDINAL) ; FORWARD ;
  1929. PROCEDURE ParseCallArgs (idx : CARDINAL) ; FORWARD ;
  1930. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ; FORWARD ;
  1931. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ; FORWARD ;
  1932. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ; FORWARD ;
  1933. (* ---------------------------------------------------------------- *)
  1934. (* expressions (TPSRC9) *)
  1935. (* ---------------------------------------------------------------- *)
  1936. PROCEDURE VarSize (r : ERes) : CARDINAL ;
  1937. (* The width of a kind-1 value. An element (`b[i]') or a field (`r.f') has a
  1938. size of its own, which is NOT its variable's; when the parser has recorded
  1939. one, it wins. Otherwise the variable's declared size is the answer. *)
  1940. BEGIN
  1941. IF r.sz > 0 THEN
  1942. RETURN r.sz
  1943. END ;
  1944. RETURN symtab [r.idx].size
  1945. END VarSize ;
  1946. PROCEDURE LoadAtom (VAR r : ERes) ;
  1947. (* load value of r into AX (folding constants).
  1948. A string literal is refused here, and this is the single place that has to:
  1949. assignment, IF, WHILE, FOR, REPEAT, CASE, array subscripts and every
  1950. operator all reach their operand through LoadAtom, and none of them can use
  1951. a counted string where a 16-bit word is expected. Reporting it here rather
  1952. than in the parser means writeln('hi') still works - IoCall handles a
  1953. literal before it ever calls LoadAtom. *)
  1954. VAR emsz : CARDINAL ;
  1955. BEGIN
  1956. IF r.cls = TString THEN
  1957. Err (ENoLib) ; (* string value used as a number *)
  1958. r.kind := 2 ;
  1959. RETURN
  1960. END ;
  1961. IF r.cls = TSet THEN
  1962. (* A set is bytes, not a 16-bit value. It is legal as the right operand
  1963. of `in' (and later as a whole-value operand of `+'/`*'/'='/assignment),
  1964. all of which handle it BEFORE LoadAtom - but never as a number, which
  1965. would otherwise load its first two bytes as if it were an integer. *)
  1966. Err (ENoLib) ;
  1967. r.kind := 2 ;
  1968. RETURN
  1969. END ;
  1970. IF r.kind = 5 THEN
  1971. (* A string element with a variable index: ParseSub already computed its
  1972. address into DI (LEA DI,[base] / ADD DI,AX), so the byte is at [DI].
  1973. Zeroing AH keeps the value a clean 16-bit char, the same thing the
  1974. size-1 load below does, because every consumer of a CHAR expects the
  1975. high half to be zero. The read must happen HERE, before anything
  1976. else is emitted: the caller reaches this immediately after parsing
  1977. the subscript, or - for a binary operator - SaveLeft has already
  1978. materialised it, so DI is still the element's address. *)
  1979. EmLdAlDi () ;
  1980. EmMovAh0 () ;
  1981. r.kind := 2 ;
  1982. RETURN
  1983. END ;
  1984. IF r.kind = 0 THEN
  1985. EmMovAxi (W16 (r.imm)) ;
  1986. r.kind := 2
  1987. ELSIF r.kind = 1 THEN
  1988. IF symtab [r.idx].isVar THEN
  1989. (* A VAR parameter: [BP+off] holds the address, and the value is one
  1990. level down. r.boff is necessarily 0 - a by-reference parameter is
  1991. a scalar in this increment, so it has nothing to subscript. *)
  1992. IF r.boff # 0 THEN
  1993. Err (ENoLib) ;
  1994. r.kind := 2 ;
  1995. RETURN
  1996. END ;
  1997. EmLoadVarInd (symtab [r.idx].off, VarSize (r)) ;
  1998. r.kind := 2 ;
  1999. RETURN
  2000. END ;
  2001. IF (VarSize (r) > 2) AND NOT
  2002. ((r.cls = TChar) AND (symtab [r.idx].cls = TString)) THEN
  2003. Err (ENoLib)
  2004. ELSE
  2005. (* s[i] indexes one byte of a string, not the string, so its width is
  2006. one whatever the variable's declared width is. *)
  2007. emsz := VarSize (r) ;
  2008. IF (r.cls = TChar) AND (symtab [r.idx].cls = TString) THEN
  2009. emsz := 1
  2010. END ;
  2011. EmLoadVar (symtab [r.idx].local,
  2012. (symtab [r.idx].off + r.boff) MOD 10000H,
  2013. emsz) ;
  2014. IF emsz = 1 THEN
  2015. EmMovAh0 ()
  2016. END ;
  2017. r.kind := 2
  2018. END
  2019. END
  2020. END LoadAtom ;
  2021. PROCEDURE ParseSub (VAR r : ERes) ;
  2022. (* consume '[' expr ']' while present.
  2023. A CONSTANT index folds into the base offset boff, exactly as before. A
  2024. VARIABLE index on a STRING cannot fold - off+i is a run-time value - so it
  2025. is computed once here into DI and r.kind drops to 5, which is how LoadAtom,
  2026. Assignment and IoCall are told the element's address is in DI. Arrays
  2027. still accept only a constant index: a variable array subscript needs the
  2028. element-size scaling that a one-byte string element does not, and it is
  2029. item 2. *)
  2030. VAR t : ERes ;
  2031. ai, fi : CARDINAL ;
  2032. found : BOOLEAN ;
  2033. BEGIN
  2034. LOOP
  2035. Skip () ;
  2036. IF CurCh () = '.' THEN
  2037. (* FIELD selection: `r.f'. The field's offset adds to the record
  2038. base's, and the value's class and WIDTH become the field's - which
  2039. is the whole reason a width rides on the expression (VarSize). *)
  2040. DropCh (GetCh ()) ;
  2041. Skip () ;
  2042. IF NOT Alpha (CurCh ()) THEN
  2043. Err (EUnknown) ;
  2044. RETURN
  2045. END ;
  2046. GetWord () ;
  2047. IF symtab [r.idx].fldFirst >= symtab [r.idx].fldLast THEN
  2048. Err (ESimpType) ; (* not a record *)
  2049. RETURN
  2050. END ;
  2051. fi := symtab [r.idx].fldFirst ;
  2052. found := FALSE ;
  2053. WHILE (fi < symtab [r.idx].fldLast) AND NOT found DO
  2054. IF NameEq (fields [fi].name, wrd) THEN
  2055. found := TRUE
  2056. ELSE
  2057. INC (fi)
  2058. END
  2059. END ;
  2060. IF NOT found THEN
  2061. Err (EUnknown) ;
  2062. RETURN
  2063. END ;
  2064. r.boff := W16 (VAL (LONGINT, r.boff)
  2065. + VAL (LONGINT, fields [fi].off)) ;
  2066. r.cls := fields [fi].cls ;
  2067. r.sz := fields [fi].size
  2068. ELSIF CurCh () = '[' THEN
  2069. DropCh (GetCh ()) ;
  2070. ParseExpr (t) ;
  2071. IF OK () THEN
  2072. IF symtab [r.idx].cls = TString THEN
  2073. (* s[i]: a STRING is a length byte at s[0] followed by the
  2074. characters, so index i selects the one byte at off+i. A second
  2075. subscript on a character is not a type. *)
  2076. IF r.cls = TChar THEN
  2077. Err (ESimpType) ;
  2078. RETURN
  2079. END ;
  2080. IF t.kind = 0 THEN
  2081. (* constant index: fold it into boff, as an array's does, and
  2082. r.cls drops to TChar so every consumer below - LoadAtom,
  2083. Assignment, IoCall - sees a one-byte value instead of the
  2084. whole string. *)
  2085. r.boff := W16 (VAL (LONGINT, r.boff) + t.imm)
  2086. ELSE
  2087. (* Variable index. Compute the element address once, now:
  2088. the index is evaluated into AX (LoadAtom is a no-op for a
  2089. kind-2 value and re-reads [DI] for a nested subscript), then
  2090. DI := base + AX. This is TP3's indstr/ialoop shape (TPSRC9
  2091. 1100-1111, 1200-1229), which likewise holds the address in
  2092. DI until the byte is loaded or stored; a register is what
  2093. lets a later LoadAtom read [DI] and a later assignment PUSH
  2094. DI across its right-hand side. *)
  2095. LoadAtom (t) ;
  2096. EmLeaDi (symtab [r.idx].local,
  2097. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  2098. EmAddDiAx () ;
  2099. r.kind := 5
  2100. END ;
  2101. r.cls := TChar ;
  2102. r.sz := 1
  2103. ELSIF symtab [r.idx].cls = TArray THEN
  2104. (* A constant array subscript. The element's address is
  2105. (index - lower bound) * element size from the array base, and
  2106. the value's width and class become the ELEMENT's - so a store
  2107. writes two bytes for an `array of Integer', not the whole
  2108. array. A VARIABLE index needs scaled run-time addressing and
  2109. is the next increment. *)
  2110. IF t.kind # 0 THEN
  2111. Err (ENoLib) ;
  2112. RETURN
  2113. END ;
  2114. IF symtab [r.idx].arrIdx > 0 THEN
  2115. ai := symtab [r.idx].arrIdx - 1 ;
  2116. r.boff := W16 (VAL (LONGINT, r.boff)
  2117. + (t.imm - arrs [ai].lo [0])
  2118. * VAL (LONGINT, arrs [ai].elem)) ;
  2119. r.sz := arrs [ai].elem ;
  2120. r.cls := arrs [ai].ecls
  2121. ELSE
  2122. Err (ESimpType) ;
  2123. RETURN
  2124. END
  2125. ELSIF t.kind # 0 THEN
  2126. Err (ENoLib) ;
  2127. RETURN
  2128. ELSE
  2129. Err (ESimpType) ;
  2130. RETURN
  2131. END
  2132. END ;
  2133. ExpectDelim (']', ENoSemi)
  2134. ELSE
  2135. RETURN
  2136. END
  2137. END
  2138. END ParseSub ;
  2139. PROCEDURE ParseVar (VAR r : ERes) ;
  2140. (* name [ '[' constExpr ']' ]* ; a function name maps to its result var *)
  2141. VAR idx : CARDINAL ;
  2142. BEGIN
  2143. IF NOT Search (wrd, idx) THEN
  2144. Err (EUnknown) ;
  2145. RETURN
  2146. END ;
  2147. r.idx := idx ;
  2148. r.kind := 1 ;
  2149. r.boff := 0 ;
  2150. r.cls := symtab [idx].cls ;
  2151. IF symtab [idx].tag = KFunc THEN
  2152. idx := symtab [idx].resvar ;
  2153. r.idx := idx ;
  2154. r.cls := symtab [idx].cls
  2155. ELSIF (symtab [idx].tag # KVar) AND (symtab [idx].tag # KType) THEN
  2156. Err (EUnknown) ;
  2157. RETURN
  2158. END ;
  2159. IF r.cls = TSet THEN
  2160. (* a set value: carry where its bytes are so ParseCmp can fold `in' and
  2161. (later) compare. A set VARIABLE is still refused at its declaration,
  2162. so today this is a typed constant or an inline literal. *)
  2163. r.setoff := symtab [r.idx].off ;
  2164. r.setbase := symtab [r.idx].elem ;
  2165. r.setsize := symtab [r.idx].size
  2166. END ;
  2167. r.sz := symtab [r.idx].size ;
  2168. ParseSub (r)
  2169. END ParseVar ;
  2170. PROCEDURE ConstAdd (a, b : LONGINT) : LONGINT ;
  2171. BEGIN
  2172. RETURN VAL (LONGINT, W16 (a + b))
  2173. END ConstAdd ;
  2174. PROCEDURE ConstSub (a, b : LONGINT) : LONGINT ;
  2175. BEGIN
  2176. RETURN VAL (LONGINT, W16 (a - b))
  2177. END ConstSub ;
  2178. PROCEDURE ConstMul (a, b : LONGINT) : LONGINT ;
  2179. BEGIN
  2180. RETURN VAL (LONGINT, W16 (a * b))
  2181. END ConstMul ;
  2182. PROCEDURE EmXchgAxDx () ;
  2183. (* 92h = XCHG AX,DX. Named for what it EMITS, which is the point of the
  2184. whole naming convention: this used to be called EmMoveAxDx, which is what
  2185. somebody would expect the opcode to be, and it is not - 89 D8 is
  2186. MOV AX,DX, 92h is the exchange. Here the exchange is what is wanted, so
  2187. the name is the only thing that was wrong, and it was wrong in the exact
  2188. way this file's names are not allowed to be: reading as "a move" when it
  2189. is a swap. After EmIDivAxCx the remainder is in DX and `mod` wants it in
  2190. AX; an exchange gets it there in one byte where a move also would, so the
  2191. behaviour is identical either way and only the name lied. *)
  2192. BEGIN
  2193. Ebyte (92H)
  2194. END EmXchgAxDx ;
  2195. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ; FORWARD ;
  2196. PROCEDURE StrOperand (r : ERes) : BOOLEAN ; FORWARD ;
  2197. PROCEDURE BinOpEmit (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2198. (* binary operation at one precedence level; folds constant operands *)
  2199. VAR f : LONGINT ;
  2200. okc : BOOLEAN ;
  2201. BEGIN
  2202. IF StrOperand (left) OR StrOperand (right) THEN
  2203. (* A string OPERAND - a STRING or a CHAR, which is a one-character string
  2204. for this purpose - makes this a string operation, and `+' is the only
  2205. one ISO Modula-2 defines: every other binary operator reached here
  2206. (OR, and the multiplicative and additive numeric ops) has no meaning
  2207. over a STRING, and StrConcat rejects it.
  2208. The test is StrOperand and NOT `cls = TString' because of the two
  2209. CHAR operands. `'a' + 'b'' has no STRING in it at all, so a
  2210. TString-only test let it fall through to the integer path, where the
  2211. character codes were added and CHR(195) was printed - a silently
  2212. wrong program rather than an error (see t53_strcat_type). A CHAR
  2213. operand is still a string operand, which is also what makes `a + ch'
  2214. concatenate.
  2215. Handling it here, at the head of the one routine every binary
  2216. operator funnels through, is what keeps `a + b', `writeln(a + b)',
  2217. `(a + b) = c' and `s := a + b + c' all going through the same
  2218. emission. *)
  2219. StrConcat (op, left, right, res) ;
  2220. RETURN
  2221. END ;
  2222. IF op = TkAnd THEN
  2223. IF (left.kind = 0) AND (right.kind = 0) THEN
  2224. res.kind := 0 ;
  2225. res.imm := BitAnd (left.imm, right.imm) ;
  2226. res.cls := TBool ;
  2227. RETURN
  2228. END ;
  2229. LoadPair (left, right) ;
  2230. EmAndAxCx () ;
  2231. res.kind := 2 ; res.cls := TBool ;
  2232. RETURN
  2233. END ;
  2234. IF op = TkOr THEN
  2235. IF (left.kind = 0) AND (right.kind = 0) THEN
  2236. res.kind := 0 ;
  2237. res.imm := BitOr (left.imm, right.imm) ;
  2238. res.cls := TBool ;
  2239. RETURN
  2240. END ;
  2241. LoadPair (left, right) ;
  2242. EmOrAxCx () ;
  2243. res.kind := 2 ; res.cls := TBool ;
  2244. RETURN
  2245. END ;
  2246. IF (left.kind = 0) AND (right.kind = 0) THEN
  2247. okc := FALSE ;
  2248. CASE op OF
  2249. OpAdd : f := ConstAdd (left.imm, right.imm) ; okc := TRUE ;
  2250. | OpSub : f := ConstSub (left.imm, right.imm) ; okc := TRUE ;
  2251. | OpMul : f := ConstMul (left.imm, right.imm) ; okc := TRUE ;
  2252. | TkDiv : okc := (right.imm # 0) AND (right.imm > 0)
  2253. AND (left.imm >= 0) ;
  2254. IF okc THEN f := left.imm DIV right.imm END ;
  2255. | TkMod : okc := (right.imm # 0) AND (right.imm > 0)
  2256. AND (left.imm >= 0) ;
  2257. IF okc THEN f := left.imm MOD right.imm END ;
  2258. ELSE
  2259. okc := FALSE
  2260. END ;
  2261. IF okc THEN
  2262. res.kind := 0 ;
  2263. res.imm := VAL (LONGINT, W16 (f)) ;
  2264. res.cls := left.cls ;
  2265. RETURN
  2266. ELSIF op = TkDiv THEN
  2267. Err (EConstRange) ;
  2268. RETURN
  2269. END
  2270. END ;
  2271. LoadPair (left, right) ;
  2272. CASE op OF
  2273. OpAdd : EmAddAxCx ;
  2274. | OpSub : EmSubAxCx ;
  2275. | OpMul : EmMulAxCx ;
  2276. | TkDiv : EmIDivAxCx ;
  2277. | TkMod : EmIDivAxCx ; EmXchgAxDx ;
  2278. ELSE
  2279. Err (ETypeErr)
  2280. END ;
  2281. res.kind := 2 ;
  2282. res.cls := left.cls
  2283. END BinOpEmit ;
  2284. PROCEDURE ConstCmp (op : CARDINAL ; a, b : LONGINT ; VAR f : LONGINT)
  2285. : BOOLEAN ;
  2286. VAR a16, b16 : CARDINAL ;
  2287. BEGIN
  2288. a16 := W16 (a) ;
  2289. b16 := W16 (b) ;
  2290. f := 0 ;
  2291. CASE op OF
  2292. 1 : f := VAL (LONGINT, ORD (a16 = b16)) ;
  2293. | 2 : f := VAL (LONGINT, ORD (a16 # b16)) ;
  2294. | 3 : f := VAL (LONGINT, ORD (a16 < b16)) ;
  2295. | 4 : f := VAL (LONGINT, ORD (a16 >= b16)) ;
  2296. | 5 : f := VAL (LONGINT, ORD (a16 > b16)) ;
  2297. | 6 : f := VAL (LONGINT, ORD (a16 <= b16)) ;
  2298. ELSE
  2299. RETURN FALSE
  2300. END ;
  2301. RETURN TRUE
  2302. END ConstCmp ;
  2303. (* ---------------------------------------------------------------- *)
  2304. (* keeping an operand alive across the parse of the other one *)
  2305. (* ---------------------------------------------------------------- *)
  2306. PROCEDURE SaveLeft (VAR left : ERes) ;
  2307. (* Called the moment the operator has been recognised, i.e. *before* the
  2308. right-hand operand is parsed.
  2309. Every binary level in this parser has the shape
  2310. left := r ; ParseXxx (right) ; BinOpEmit (op, left, right, r) ;
  2311. so the right-hand operand's code is emitted between those two lines, and
  2312. the left-hand operand has to survive that. For kind 0 (a constant) and
  2313. kind 1 (a named variable) there is nothing to survive: LoadAtom re-emits
  2314. the MOV or the load at the operator site, and no code has been emitted
  2315. for the left yet. A kind-2 value is different - its code is already in
  2316. the image and its value exists only in AX, which the right-hand parse is
  2317. about to overwrite. The value had to be parked on the stack instead.
  2318. TPSRC9 does exactly this in the other order: addptr and mulptr CALL
  2319. pushres (which calls loadatom and sets flgpshax) *before* CALL mullevel,
  2320. so PUSH AX lands in the image ahead of the right-hand operand's code.
  2321. Without this, `(p > q) or (q > p)` emitted both comparisons and then
  2322. ORed the *second* comparison's result with itself - which is why it
  2323. printed FALSE for TRUE or FALSE. *)
  2324. BEGIN
  2325. IF left.kind = 2 THEN
  2326. EmPushAx () ;
  2327. left.kind := 4 (* 4 = on the top of the stack *)
  2328. ELSIF left.kind = 5 THEN
  2329. (* A string element whose address is in DI. This is the one place the
  2330. address must be spent BEFORE the right-hand operand is parsed: DI
  2331. cannot survive it, because the right operand may hold a subscript of
  2332. its own (which reuses DI) or call a routine (which may clobber it).
  2333. Reading [DI] now - which LoadAtom does, turning kind 5 into kind 2 -
  2334. and pushing the value is exactly what the kind-2 case above does
  2335. next, so the two branches converge on kind 4. A subscript on the
  2336. RIGHT is fine: it sets DI after this point and LoadPair reads it
  2337. immediately, with no parse in between. *)
  2338. LoadAtom (left) ; (* AL := [DI], AH := 0; kind := 2 *)
  2339. EmPushAx () ;
  2340. left.kind := 4
  2341. END
  2342. END SaveLeft ;
  2343. PROCEDURE LoadPair (VAR left, right : ERes) ;
  2344. (* Materialise both operands of a binary operator so that, once this
  2345. returns, AX holds the LEFT one and CX the RIGHT one - which is the state
  2346. EmAddAxCx/EmSubAxCx/EmMulAxCx/EmIDivAxCx/EmAndAxCx/EmOrAxCx/EmCmpAxCx
  2347. all expect (see EmXchgAxCx).
  2348. Three shapes, and only three:
  2349. left.kind = 4 SaveLeft pushed it before the right operand was
  2350. parsed, so the right value is in AX and the left one
  2351. is on the stack: load the right (a no-op for kind 2),
  2352. pop the left into CX, then swap.
  2353. right.kind = 2 The right value is in AX, and loading the left would
  2354. destroy it: push the right, load the left, then pop
  2355. the right straight into CX. No swap needed.
  2356. neither Both can still be materialised from scratch, and
  2357. neither is at risk, so this is the original sequence.
  2358. A kind-5 right-hand operand takes that last shape, and is safe there: the
  2359. only instruction emitted before its LoadAtom is the left's, and MOV AX,[var]
  2360. and MOV AX,imm do not touch DI, so [DI] still holds the element address.
  2361. Whichever shape is taken, exactly one push is matched by exactly one
  2362. pop. *)
  2363. BEGIN
  2364. IF left.kind = 4 THEN
  2365. LoadAtom (right) ;
  2366. EmPopCx () ;
  2367. EmXchgAxCx ()
  2368. ELSIF right.kind = 2 THEN
  2369. EmPushAx () ;
  2370. LoadAtom (left) ;
  2371. EmPopCx ()
  2372. ELSE
  2373. LoadAtom (left) ; EmPushAx () ;
  2374. LoadAtom (right) ; EmPopCx () ;
  2375. EmXchgAxCx ()
  2376. END
  2377. END LoadPair ;
  2378. PROCEDURE EmStrBlob (r : ERes) : CARDINAL ;
  2379. (* Emit a string literal's <len><chars> in the code stream behind a JMP and
  2380. return the image offset of the LENGTH byte. Shared by EmPushStrAddr (which
  2381. pushes that address) and EmPushStrSlot (which copies the bytes onto the
  2382. stack for a string value parameter). *)
  2383. VAR n, len, here : CARDINAL ;
  2384. BEGIN
  2385. len := strLen [r.strx] ;
  2386. IF len > 255 THEN
  2387. (* As in IoCall: the length is one byte, so a longer literal would wrap
  2388. and silently carry only its first (length MOD 256) characters.
  2389. TP3 strings are at most 255 characters. *)
  2390. Err (EConstRange) ;
  2391. RETURN 0
  2392. END ;
  2393. IF len + 1 <= 127 THEN
  2394. Ebyte (0EBH) ; Ebyte (VAL (BYTE, len + 1)) (* JMP rel8 over it *)
  2395. ELSE
  2396. Ebyte (0E9H) ; Eword (len + 1) (* JMP rel16 over it *)
  2397. END ;
  2398. here := pc ; (* the length byte: the literal's address *)
  2399. Ebyte (VAL (BYTE, len)) ;
  2400. n := 0 ;
  2401. WHILE n < len DO
  2402. Ebyte (VAL (BYTE, ORD (strPool [strOff [r.strx] + n]))) ;
  2403. INC (n)
  2404. END ;
  2405. RETURN here
  2406. END EmStrBlob ;
  2407. PROCEDURE EmPushStrAddr (r : ERes) ;
  2408. (* Push the ADDRESS of a whole-string operand - the argument shape cmpstr
  2409. takes, one per operand.
  2410. A string VARIABLE's value already is its address, so this is the same push
  2411. READ makes (EmPushVarAddr), through symtab's local/off.
  2412. A string LITERAL has no storage, and the image carries no initialised data
  2413. to put one in (globals are left to the loader's zero fill), so the
  2414. characters have to travel in the code stream and the operand is the address
  2415. of those bytes. TP3 does the same in TPSRC9 fullvar (993): it builds the
  2416. `JMP' opcode in AL and the length in AH (`MOV AL,#$EB' / `MOV.B AH,CH'),
  2417. emits that word, and takes the position immediately after it as varofs,
  2418. with varseg := CS - the instruction stream steps over the constant instead
  2419. of running into it.
  2420. The difference is one byte, and it is deliberate. TP3's constant is an
  2421. ARRAY [1..n] OF CHAR, and `estr2' (TPSRC10 85) emits it WITHOUT a length
  2422. byte because the length travelled on the stack instead. Every string in
  2423. THIS runtime - variable or literal - is a `string': a length byte and then
  2424. the characters, which is what rdstr writes and what cmpstr reads. So a
  2425. literal operand has to look the same, and the jump carries one extra byte:
  2426. <len><chars>, with the ADDRESS pushed being the length byte itself. The
  2427. jump still exists only to keep the CPU from walking into the characters.
  2428. Nothing is added to the data segment and no runtime entry is involved in
  2429. reading the literal; LEA AX,[that] is absolute into the code segment, which
  2430. is where a .COM's DS already is.
  2431. A 1-character literal is NOT a TString here: RdConst reports it as TScalar
  2432. (its character code), so `s = 'a'` compares a string with a character and
  2433. is a type error rather than a length-1 string compare. That is deliberate
  2434. - it is the same rule `c := 'a'` relies on - and the caller rejects it. *)
  2435. BEGIN
  2436. IF r.kind = 1 THEN
  2437. EmPushVarAddr (symtab [r.idx].local,
  2438. (symtab [r.idx].off + r.boff) MOD 10000H)
  2439. ELSIF r.kind = 3 THEN
  2440. EmPushVarAddr (FALSE, EmStrBlob (r)) (* the literal travels inline *)
  2441. ELSE
  2442. Err (ENoLib) (* a computed string is not a value *)
  2443. END
  2444. END EmPushStrAddr ;
  2445. PROCEDURE EmPushStrSlot (r : ERes ; reserve, copyN : CARDINAL) ;
  2446. (* Push a STRING VALUE argument's whole slot: reserve `reserve' bytes on the
  2447. stack and copy `copyN' of the source string's <len><chars> into them, so
  2448. that after the CALL the callee's BP+4 is the length byte and the characters
  2449. follow it.
  2450. <push the source address, then POP SI> ; local/global/literal alike
  2451. SUB SP,reserve ; MOV DI,SP ; MOV CX,copyN
  2452. loop: MOV AL,[SI] ; MOV [DI],AL ; INC SI ; INC DI ; LOOP loop
  2453. The address comes from EmPushStrAddr, which already knows how to form it for
  2454. a local ([BP+off]), a global (absolute) or a literal (inline blob) - so a
  2455. caller's LOCAL string can be passed too, not just a global.
  2456. A byte loop, not REP MOVSB, on purpose: MOVS/STOS address through ES, and a
  2457. .COM's ES happens to equal DS but nothing in this compiler establishes that
  2458. contract. Every access here is DS-relative, which is the one segment the
  2459. image already guarantees. `copyN' is at most `reserve' (a shorter actual
  2460. string than the formal leaves the tail of the slot untouched, harmless
  2461. because the length byte bounds every read). *)
  2462. BEGIN
  2463. EmPushStrAddr (r) ; (* push the source address *)
  2464. EmPopSi () ; (* SI := source *)
  2465. EmSubSp (reserve) ;
  2466. Ebyte (89H) ; Ebyte (0E7H) ; (* MOV DI,SP *)
  2467. EmMovCxi (copyN) ;
  2468. IF copyN > 0 THEN
  2469. Ebyte (8AH) ; Ebyte (04H) ; (* MOV AL,[SI] *)
  2470. Ebyte (88H) ; Ebyte (05H) ; (* MOV [DI],AL *)
  2471. Ebyte (46H) ; (* INC SI *)
  2472. Ebyte (47H) ; (* INC DI *)
  2473. Ebyte (0E2H) ; Ebyte (0F8H) (* LOOP -8: back to MOV AL,[SI] *)
  2474. END
  2475. END EmPushStrSlot ;
  2476. (* ---------------------------------------------------------------- *)
  2477. (* sets - type sizing, literals, compile-time membership *)
  2478. (* ---------------------------------------------------------------- *)
  2479. PROCEDURE SetRangeBits (VAR bytes : ARRAY OF CHAR ; size, base : CARDINAL ;
  2480. lo, hi : LONGINT) ;
  2481. (* Set the bits for every element in [lo, hi], using TP3's hybrid rule
  2482. (coeur-tp-ocr 4.7.2): element e is bit (e MOD 8) of byte
  2483. ((e DIV 8) - (base DIV 8)), and is IGNORED unless that byte is in
  2484. [0, size). A value that lands outside the used bytes is truncated away, as
  2485. TP3 does; one inside them but outside the DECLARED range still lands, which
  2486. is also TP3's behaviour. *)
  2487. VAR rel, first, last, bidx, bit, m, o : CARDINAL ;
  2488. BEGIN
  2489. IF (hi < 0) OR (lo > 255) THEN
  2490. RETURN
  2491. END ;
  2492. IF lo < 0 THEN first := 0 ELSE first := VAL (CARDINAL, lo) END ;
  2493. IF hi > 255 THEN last := 255 ELSE last := VAL (CARDINAL, hi) END ;
  2494. rel := first ;
  2495. WHILE rel <= last DO
  2496. IF rel >= base THEN
  2497. bidx := (rel - base) DIV 8 ;
  2498. IF bidx < size THEN
  2499. bit := (rel - base) MOD 8 ;
  2500. m := 1 ;
  2501. WHILE bit > 0 DO
  2502. m := m * 2 ; DEC (bit)
  2503. END ;
  2504. o := ORD (bytes [bidx]) ;
  2505. IF (o DIV m) MOD 2 = 0 THEN
  2506. bytes [bidx] := CHR (o + m)
  2507. END
  2508. END
  2509. END ;
  2510. INC (rel)
  2511. END
  2512. END SetRangeBits ;
  2513. PROCEDURE RdSetLiteral (base, size : CARDINAL ; VAR bytes : ARRAY OF CHAR) : BOOLEAN ;
  2514. (* Read a set constructor `[e, a..b, ...]' and fill `bytes' (already size
  2515. long). `[]' is the empty set. *)
  2516. VAR v, hi : LONGINT ; subcls : CARDINAL ; strf : BOOLEAN ; k : CARDINAL ;
  2517. BEGIN
  2518. k := 0 ;
  2519. WHILE k < size DO
  2520. bytes [k] := CHR (0) ;
  2521. INC (k)
  2522. END ;
  2523. ExpectDelim ('[', ENoSemi) ;
  2524. IF MatchDelim (']') THEN
  2525. RETURN OK () (* [] - the empty set *)
  2526. END ;
  2527. LOOP
  2528. RdConst (v, subcls, strf) ;
  2529. IF strf THEN
  2530. Err (ETypeErr) ;
  2531. RETURN FALSE
  2532. END ;
  2533. IF MatchRange () THEN
  2534. RdConst (hi, subcls, strf) ;
  2535. IF strf THEN
  2536. Err (ETypeErr) ;
  2537. RETURN FALSE
  2538. END
  2539. ELSE
  2540. hi := v
  2541. END ;
  2542. SetRangeBits (bytes, size, base, v, hi) ;
  2543. IF MatchDelim (',') THEN
  2544. (* another element *)
  2545. ELSE
  2546. EXIT
  2547. END
  2548. END ;
  2549. ExpectDelim (']', ENoSemi) ;
  2550. RETURN OK ()
  2551. END RdSetLiteral ;
  2552. PROCEDURE EmSetBlob (VAR bytes : ARRAY OF CHAR ; size : CARDINAL) : CARDINAL ;
  2553. (* Emit a set's bytes into the code stream behind a JMP over them - the same
  2554. trick EmPushStrAddr uses for a string literal - and return the image offset
  2555. of the first byte. Nothing goes in the data segment: a .COM's DS already
  2556. covers the code segment, which is why this port needs no `seg cs' where the
  2557. original did (see CALC-COMPILE.md's typed-constant storage decision). *)
  2558. VAR here, k : CARDINAL ;
  2559. BEGIN
  2560. IF size + 2 <= 127 THEN
  2561. Ebyte (0EBH) ; Ebyte (VAL (BYTE, size)) (* JMP rel8 over it *)
  2562. ELSE
  2563. Ebyte (0E9H) ; Eword (size) (* JMP rel16 over it *)
  2564. END ;
  2565. here := pc ;
  2566. k := 0 ;
  2567. WHILE k < size DO
  2568. Ebyte (VAL (BYTE, ORD (bytes [k]))) ;
  2569. INC (k)
  2570. END ;
  2571. RETURN here
  2572. END EmSetBlob ;
  2573. PROCEDURE FoldSetIn (left, right : ERes ; VAR res : ERes) ;
  2574. (* `e IN s' where e is a compile-time ordinal and s a set whose bytes are
  2575. already in the image: answer at compile time, exactly as TPSRC2's xsetin
  2576. answers at run time (AH > 255 -> FALSE, else test the bit). A run-time
  2577. element or a run-time set is still ENoLib - that is the next milestone, and
  2578. it must stay LOUD rather than silently answer wrong. *)
  2579. VAR off, base, size, rel, bidx, bit, m, o : CARDINAL ; isIn : BOOLEAN ;
  2580. BEGIN
  2581. res.kind := 0 ;
  2582. res.imm := 0 ;
  2583. res.cls := TBool ;
  2584. res.chr := FALSE ;
  2585. IF (left.kind # 0) OR (right.cls # TSet) THEN
  2586. Err (ENoLib) ;
  2587. RETURN
  2588. END ;
  2589. isIn := FALSE ;
  2590. IF (left.imm >= 0) AND (left.imm <= 255) THEN
  2591. off := right.setoff ; base := right.setbase ; size := right.setsize ;
  2592. rel := VAL (CARDINAL, left.imm) ;
  2593. IF rel >= base THEN
  2594. bidx := (rel - base) DIV 8 ;
  2595. IF bidx < size THEN
  2596. bit := (rel - base) MOD 8 ;
  2597. m := 1 ;
  2598. WHILE bit > 0 DO
  2599. m := m * 2 ; DEC (bit)
  2600. END ;
  2601. o := VAL (CARDINAL, cbuf [off + bidx]) ;
  2602. isIn := (o DIV m) MOD 2 # 0
  2603. END
  2604. END
  2605. END ;
  2606. res.imm := ORD (isIn)
  2607. END FoldSetIn ;
  2608. PROCEDURE RdSetBase (VAR baseCls : CARDINAL ; VAR lo, hi : LONGINT) ;
  2609. (* The base type of `set of ...': an ordinal range. `Char' and `byte' are
  2610. 0..255; a literal subrange `a..b' is read directly. A named or enumerated
  2611. base is ENoLib for now - `set of Attributes' waits for enums. *)
  2612. VAR idx, subcls : CARDINAL ; strf : BOOLEAN ;
  2613. BEGIN
  2614. baseCls := TScalar ;
  2615. Skip () ;
  2616. IF Alpha (CurCh ()) THEN
  2617. GetWord () ;
  2618. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  2619. IF symtab [idx].cls = TEnum THEN
  2620. lo := symtab [idx].lo ;
  2621. hi := symtab [idx].hi ;
  2622. baseCls := TEnum
  2623. ELSIF (symtab [idx].cls = TChar)
  2624. OR ((symtab [idx].cls = TScalar) AND (symtab [idx].size = 1)) THEN
  2625. lo := 0 ; hi := 255 ; baseCls := symtab [idx].cls
  2626. ELSE
  2627. Err (ENoLib)
  2628. END
  2629. ELSE
  2630. Err (EUnknown)
  2631. END
  2632. ELSE
  2633. RdConst (lo, subcls, strf) ;
  2634. IF NOT MatchRange () THEN
  2635. Err (ESimpType) ;
  2636. RETURN
  2637. END ;
  2638. RdConst (hi, subcls, strf) ;
  2639. IF (lo < 0) OR (hi > 255) OR (lo > hi) THEN
  2640. Err (EConstRange)
  2641. END
  2642. END
  2643. END RdSetBase ;
  2644. PROCEDURE NewScratchStr () : CARDINAL ;
  2645. (* Allocate a fresh 256-byte global STRING and return its symbol index.
  2646. A concatenation result needs STORAGE the emitted code can name. Making the
  2647. result a string VARIABLE (kind 1) is what keeps every downstream consumer
  2648. untouched: Assignment, IoCall and ParseCmp already handle kind 1, so `s :=
  2649. a + b', `writeln(a + b)' and `(a + b) = c' work with no code of their own.
  2650. One scratch PER `+' in the source, so a repeated or nested concatenation
  2651. never shares a destination - `a + b + c' is two occurrences and gets two
  2652. scratch strings, and the first result survives until the second consumes it.
  2653. (A loop reuses its site's scratch, which is correct because each execution
  2654. writes before it reads.) Recursion would break that, but this compiler
  2655. compiles no procedures yet - see the item list.
  2656. 256 bytes is the STRING type's own size, length byte plus 255 characters:
  2657. see ParseType's TkString arm and the predefined STRING in Inittur. The name
  2658. is a placeholder (nothing looks a scratch up by name) spelled with '@', as
  2659. tmpA/tmpB are, so it cannot collide with a Modula-2 identifier. *)
  2660. BEGIN
  2661. DropC (NewSym ("@@SC", KVar, TString, 256, 1, dc, 0, FALSE)) ;
  2662. dc := dc + 256 ;
  2663. RETURN symTop - 1
  2664. END NewScratchStr ;
  2665. PROCEDURE StrOperand (r : ERes) : BOOLEAN ;
  2666. (* Is r usable as one operand of `+'? A STRING, or a CHAR - which can appear
  2667. three ways: a quoted literal (cls TScalar with chr set), a CHAR variable
  2668. (cls TChar), and a string element s[i] (cls TChar, kind 5). A number is
  2669. not, and neither is a BOOLEAN. *)
  2670. BEGIN
  2671. RETURN (r.cls = TString) OR (r.cls = TChar) OR
  2672. ((r.cls = TScalar) AND r.chr)
  2673. END StrOperand ;
  2674. PROCEDURE EmPushStrOperand (r : ERes) ;
  2675. (* Push the ADDRESS of one concatenation operand, converting a CHAR to a
  2676. length-1 string first.
  2677. A STRING operand is pushed exactly as cmpstr pushes one (EmPushStrAddr):
  2678. a variable's value already IS its address, and a literal travels inline.
  2679. A CHAR operand has no such address, so it is materialised as a
  2680. `<length 1><character>' string in a fresh 2-byte scratch and the address of
  2681. THAT is pushed. This is TPSRC9's addch/addch2, which splice a character
  2682. into a concatenation by building a one-character string. The character is
  2683. loaded into AL (LoadAtom), the character is stored at [coff+1] and the
  2684. length 1 at [coff]. At most one operand of a concatenation is a CHAR -
  2685. StrConcat rejects char+char - so at most one such scratch is ever made. *)
  2686. VAR coff : CARDINAL ;
  2687. BEGIN
  2688. IF r.cls = TString THEN
  2689. EmPushStrAddr (r)
  2690. ELSE
  2691. coff := dc ;
  2692. dc := dc + 2 ;
  2693. LoadAtom (r) ; (* AX := the character *)
  2694. EmStoreVar (FALSE, (coff + 1) MOD 10000H, 1) ; (* [coff+1] := AL *)
  2695. EmMovAxi (1) ; (* AX := 1 *)
  2696. EmStoreVar (FALSE, coff MOD 10000H, 1) ; (* [coff] := AL = length *)
  2697. EmPushVarAddr (FALSE, coff MOD 10000H)
  2698. END
  2699. END EmPushStrOperand ;
  2700. PROCEDURE StrConcat (op : CARDINAL ; left, right : ERes ; VAR res : ERes) ;
  2701. (* `left + right' for strings: TPSRC2's xconcat, emitted as two runtime calls.
  2702. The layout is `<length byte><characters>' and `+' needs a place to build its
  2703. result, so this allocates one 256-byte global scratch (NewScratchStr) and
  2704. copies into it: first `dest := left' through the runtime's strstore, then
  2705. `dest := dest + right' through strcat, which appends. Using strstore for
  2706. the left operand and strcat for the right keeps the append logic in one
  2707. place and gives the compiler exactly one new entry to reach; it also means
  2708. the two calls have the same argument shape (source pushed first, destination
  2709. last, limit in CX), so the emission differs only in the entry named.
  2710. The limit is 255 - the scratch's 255 usable characters. An overflowing
  2711. result is a RUNTIME ERROR with exit code 16, TP3's `String too long', not a
  2712. truncation; see Runtime.EmitStrCat.
  2713. The operator rule: `+' concatenates, anything else over a STRING is a type
  2714. error, and char+char is ALSO a type error. ISO Modula-2 gives no meaning to
  2715. two characters summed, and inventing one (a two-character string?) would be
  2716. a guess this compiler does not make; TP3's own behaviour there is not
  2717. something the reference pins down. That char+char choice is the one place
  2718. this differs from a literal reading of the reference, and it is recorded
  2719. here and in v-TP3-STRCAT.md rather than left to be discovered.
  2720. The guard below is what ENFORCES that rule, and it only runs because
  2721. BinOpEmit's hook routes a CHAR operand here too. A hook that tested for a
  2722. STRING operand only would send `'a' + 'b'' to the integer path instead and
  2723. this test would never be reached - which is exactly what it did until
  2724. t53_strcat_type caught it. Three ways to fail it: a non-`+' operator over
  2725. a string operand, an operand that is neither a string nor a CHAR (a number),
  2726. and two CHARs with no STRING on either side. *)
  2727. VAR dest : CARDINAL ;
  2728. BEGIN
  2729. (* A placeholder for the paths below that bail out through Err. Err only
  2730. records the first error and does not unwind, so the caller goes on to use
  2731. res regardless: after `Err (ETypeErr)' in the guard, ParseAdd hands res
  2732. straight back to IoCall, to Assignment or to an enclosing concatenation.
  2733. The placeholder's SHAPE therefore matters. It must not claim to be a
  2734. STRING, because the string consumers reach symtab[res.idx] for any TString
  2735. (IoCall's `writeln' arm does) and idx is not a symbol here; and it must be
  2736. something LoadAtom can fold, because the numeric consumers will try. The
  2737. integer 0 is both. Leaving kind-2/TString here, as this once did, turned
  2738. `writeln('a' + 'b')' - two CHARs, a type error - into a compiler segfault
  2739. instead of an error message. *)
  2740. res.kind := 0 ;
  2741. res.imm := 0 ;
  2742. res.cls := TScalar ;
  2743. res.boff := 0 ;
  2744. res.chr := FALSE ;
  2745. IF (op # OpAdd) OR NOT StrOperand (left) OR NOT StrOperand (right) OR
  2746. ((left.cls # TString) AND (right.cls # TString)) THEN
  2747. Err (ETypeErr) ; (* a STRING on the wrong operator, a number,
  2748. or two CHARs *)
  2749. RETURN
  2750. END ;
  2751. dest := NewScratchStr () ;
  2752. (* dest := left *)
  2753. EmPushStrOperand (left) ;
  2754. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  2755. EmMovCxi (255) ;
  2756. DropC (EmCall (TU_StrStore)) ;
  2757. EmAddSp (4) ; (* pop the two addresses strstore took *)
  2758. (* dest := dest + right *)
  2759. EmPushStrOperand (right) ;
  2760. EmPushVarAddr (FALSE, (symtab [dest].off) MOD 10000H) ;
  2761. EmMovCxi (255) ;
  2762. DropC (EmCall (TU_StrCat)) ;
  2763. EmAddSp (4) ;
  2764. res.kind := 1 ;
  2765. res.idx := dest ;
  2766. res.cls := TString ;
  2767. res.boff := 0 ;
  2768. res.chr := FALSE
  2769. END StrConcat ;
  2770. PROCEDURE ParseCmp (VAR r : ERes) ;
  2771. (* "=" | "<>" | "<" | "<=" | ">" | ">=" *)
  2772. VAR op : CARDINAL ;
  2773. left, right : ERes ;
  2774. f : LONGINT ;
  2775. BEGIN
  2776. ParseAdd (r) ;
  2777. LOOP
  2778. op := 0 ;
  2779. Skip () ;
  2780. IF CurCh () = '=' THEN
  2781. op := 1 ; DropCh (GetCh ())
  2782. ELSIF (CurCh () = '<') AND (PeekAhead (1) = '>') THEN
  2783. op := 2 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2784. ELSIF CurCh () = '<' THEN
  2785. IF PeekAhead (1) = '=' THEN
  2786. op := 6 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2787. ELSE
  2788. op := 3 ; DropCh (GetCh ())
  2789. END
  2790. ELSIF CurCh () = '>' THEN
  2791. IF PeekAhead (1) = '=' THEN
  2792. op := 5 ; DropCh (GetCh ()) ; DropCh (GetCh ())
  2793. ELSE
  2794. op := 4 ; DropCh (GetCh ())
  2795. END
  2796. END ;
  2797. IF op = 0 THEN
  2798. IF KwAhead ("IN") THEN
  2799. (* `e IN s' is at the comparison level in TP3 (TPSRC9 cmpin, 116).
  2800. Only the compile-time case is implemented; see FoldSetIn. *)
  2801. GetWord () ;
  2802. left := r ;
  2803. ParseAdd (right) ;
  2804. FoldSetIn (left, right, r) ;
  2805. RETURN
  2806. END ;
  2807. RETURN
  2808. END ;
  2809. left := r ;
  2810. SaveLeft (left) ;
  2811. ParseAdd (right) ;
  2812. IF (left.cls = TString) OR (right.cls = TString) THEN
  2813. (* A string comparison: cmpstr, the entry TPSRC9's vcompare (133)
  2814. reaches through TPSRC2's csteq/cstne/cstge/cstle/cstg/cstl
  2815. wrappers (890-925). It is intercepted BEFORE the constant-fold
  2816. arm, because a string literal is never a kind-0 constant and,
  2817. without this branch, both operands would fall through to LoadAtom,
  2818. which refuses a TString (ENoLib) - the symptom this arm cures.
  2819. cmpstr returns AX = -1/0/+1 (see Runtime.mod for why a value and
  2820. not flags), so the second half is exactly the numeric arm's: put
  2821. the sign in the flags and let the shared six-arm table answer.
  2822. EmOrAxAx is OR AX,AX rather than EmCmpAxi(0) on purpose: tests/
  2823. check_8086.py reads every `CMP AX,0000' in the program region as
  2824. an IF/WHILE/REPEAT test and requires a branch right after it, and
  2825. a comparison used as a VALUE (writeln(a = b)) is not one. *)
  2826. IF (left.cls # TString) OR (right.cls # TString) THEN
  2827. Err (ETypeErr) ; (* a string compared with a number/char *)
  2828. RETURN
  2829. END ;
  2830. EmPushStrAddr (left) ;
  2831. EmPushStrAddr (right) ;
  2832. DropC (EmCall (TU_CmpStr)) ;
  2833. EmAddSp (4) ;
  2834. EmOrAxAx () ;
  2835. EmRelSetcc (op) ;
  2836. r.kind := 2 ;
  2837. r.cls := TBool
  2838. ELSIF (left.kind = 0) AND (right.kind = 0) THEN
  2839. IF ConstCmp (op, left.imm, right.imm, f) THEN
  2840. r.kind := 0 ;
  2841. r.imm := f ;
  2842. r.cls := TBool
  2843. ELSE
  2844. r.kind := 0 ;
  2845. r.imm := 0 ;
  2846. r.cls := TBool
  2847. END
  2848. ELSE
  2849. LoadPair (left, right) ;
  2850. EmCmpAxCx () ;
  2851. EmRelSetcc (op) ;
  2852. r.kind := 2 ;
  2853. r.cls := TBool
  2854. END
  2855. END
  2856. END ParseCmp ;
  2857. PROCEDURE ParseAdd (VAR r : ERes) ;
  2858. VAR op : CARDINAL ;
  2859. left, right : ERes ;
  2860. BEGIN
  2861. ParseMul (r) ;
  2862. LOOP
  2863. op := 0 ;
  2864. Skip () ;
  2865. IF CurCh () = '+' THEN
  2866. op := OpAdd ; DropCh (GetCh ())
  2867. ELSIF CurCh () = '-' THEN
  2868. op := OpSub ; DropCh (GetCh ())
  2869. ELSIF KwAhead ("OR") THEN
  2870. GetWord () ;
  2871. op := TkOr
  2872. ELSE
  2873. RETURN
  2874. END ;
  2875. left := r ;
  2876. SaveLeft (left) ;
  2877. ParseMul (right) ;
  2878. BinOpEmit (op, left, right, r)
  2879. END
  2880. END ParseAdd ;
  2881. PROCEDURE ParseMul (VAR r : ERes) ;
  2882. VAR op : CARDINAL ;
  2883. left, right : ERes ;
  2884. BEGIN
  2885. ParseNeg (r) ;
  2886. LOOP
  2887. op := 0 ;
  2888. Skip () ;
  2889. IF CurCh () = '*' THEN
  2890. op := OpMul ; DropCh (GetCh ()) (* OpAdd here meant a*b -> a+b *)
  2891. ELSIF CurCh () = '/' THEN
  2892. op := 2 ; DropCh (GetCh ()) ; Err (ENoLib)
  2893. ELSIF KwAhead ("DIV") THEN
  2894. GetWord () ; op := TkDiv
  2895. ELSIF KwAhead ("MOD") THEN
  2896. GetWord () ; op := TkMod
  2897. ELSIF KwAhead ("AND") THEN
  2898. GetWord () ; op := TkAnd
  2899. ELSE
  2900. RETURN
  2901. END ;
  2902. IF op = 2 THEN
  2903. RETURN
  2904. END ;
  2905. left := r ;
  2906. SaveLeft (left) ;
  2907. ParseNeg (right) ;
  2908. BinOpEmit (op, left, right, r)
  2909. END
  2910. END ParseMul ;
  2911. PROCEDURE ParseNeg (VAR r : ERes) ;
  2912. BEGIN
  2913. Skip () ;
  2914. IF CurCh () = '+' THEN
  2915. DropCh (GetCh ()) ;
  2916. ParseNeg (r) ;
  2917. RETURN
  2918. ELSIF CurCh () = '-' THEN
  2919. DropCh (GetCh ()) ;
  2920. ParseNeg (r) ;
  2921. IF r.kind = 0 THEN
  2922. r.imm := VAL (LONGINT, W16 (0 - r.imm))
  2923. ELSE
  2924. LoadAtom (r) ;
  2925. EmNegAx () ;
  2926. r.kind := 2
  2927. END ;
  2928. RETURN
  2929. ELSIF KwAhead ("NOT") THEN
  2930. GetWord () ;
  2931. ParseNeg (r) ;
  2932. (* TPSRC9 neglevel branches on the operand's type before emitting
  2933. anything: CMP CL,#$0A (integer) -> NOT AX, CMP CL,#$0B (boolean)
  2934. -> XOR AL,#01, anything else -> error. This used to emit NOT AX
  2935. for both, so `not (a = a)' produced 0FFFEh and the runtime's
  2936. wrbool test ([BP+4] <> 0) read it as TRUE.
  2937. The integer constant fold stays: the 16 bits are the same either
  2938. way. A boolean constant must not go through BitNot - 0FFFFH-1 is
  2939. 0FFFEh, which wrbool also reads as TRUE - so it is loaded and
  2940. xor-ed, exactly as neglevel does it. *)
  2941. IF r.cls = TBool THEN
  2942. LoadAtom (r) ;
  2943. EmXorAl01 () ;
  2944. r.kind := 2
  2945. ELSIF r.cls = TScalar THEN
  2946. IF r.kind = 0 THEN
  2947. r.imm := BitNot (r.imm)
  2948. ELSE
  2949. LoadAtom (r) ;
  2950. EmNotAx () ;
  2951. r.kind := 2
  2952. END
  2953. ELSE
  2954. Err (ETypeErr)
  2955. END ;
  2956. RETURN
  2957. END ;
  2958. ParseAtom (r)
  2959. END ParseNeg ;
  2960. PROCEDURE ParseAtom (VAR r : ERes) ;
  2961. (* const | variable | func(params) | '(' expr ')' | '[' set ']' *)
  2962. VAR idx : CARDINAL ;
  2963. strf : BOOLEAN ;
  2964. quoted : BOOLEAN ;
  2965. ssize, sbase : CARDINAL ;
  2966. sbuf : ARRAY [0..31] OF CHAR ;
  2967. BEGIN
  2968. r.chr := FALSE ; (* default: not a quoted char literal *)
  2969. Skip () ;
  2970. IF CurCh () = '(' THEN
  2971. DropCh (GetCh ()) ;
  2972. ParseExpr (r) ;
  2973. ExpectDelim (')', ENoSemi) ;
  2974. RETURN
  2975. END ;
  2976. IF CurCh () = '[' THEN
  2977. (* An inline set literal. Full TP3 takes its type from context; here it
  2978. defaults to `set of Char' (0..255), which is what CALC writes
  2979. (`Ch in ['a'..'z']'), and its bytes are materialised in the code
  2980. stream. A typed/larger-base literal is a later milestone. *)
  2981. ssize := 32 ;
  2982. sbase := 0 ;
  2983. IF RdSetLiteral (sbase, ssize, sbuf) THEN
  2984. r.kind := 7 ;
  2985. r.cls := TSet ;
  2986. r.setoff := EmSetBlob (sbuf, ssize) ;
  2987. r.setbase := sbase ;
  2988. r.setsize := ssize
  2989. END ;
  2990. RETURN
  2991. END ;
  2992. IF (CurCh () = '$') OR (Digit (CurCh ())) OR (ORD (CurCh ()) = AposC)
  2993. OR (CurCh () = '^') OR (CurCh () = '#') THEN
  2994. (* remember that this was a quoted literal BEFORE RdConst consumes it:
  2995. RdConst reports a 1-character literal as TScalar (its char code),
  2996. which is right for "c := 'a'" but would make writeln('a') print 97.
  2997. Mark it so the writer picks the char entry, not the integer one. A
  2998. caret (^M) or decimal (#27) character constant is a character too. *)
  2999. quoted := (ORD (CurCh ()) = AposC) OR (CurCh () = '^')
  3000. OR (CurCh () = '#') ;
  3001. RdConst (r.imm, r.cls, strf) ;
  3002. r.chr := quoted AND (r.cls = TScalar) AND NOT strf ;
  3003. IF r.cls = TReal THEN
  3004. Err (ENoLib) ;
  3005. r.kind := 2 ;
  3006. RETURN
  3007. END ;
  3008. IF strf THEN
  3009. (* A string literal is legal here as a *value* - it is not rejected
  3010. at this point, because writeln('hi') needs it and IoCall is the
  3011. only place that knows how to emit one. Everywhere else the
  3012. literal has to end up as a machine word, and that is caught by
  3013. LoadAtom, which refuses a TString. *)
  3014. r.strx := rdStrX ;
  3015. r.kind := 3 ;
  3016. RETURN
  3017. END ;
  3018. r.kind := 0 ;
  3019. RETURN
  3020. END ;
  3021. IF NOT Alpha (CurCh ()) THEN
  3022. Err (EUnknown) ;
  3023. RETURN
  3024. END ;
  3025. GetWord () ;
  3026. IF NOT Search (wrd, idx) THEN
  3027. Err (EUnknown) ;
  3028. RETURN
  3029. END ;
  3030. IF symtab [idx].tag = KConst THEN
  3031. r.kind := 0 ;
  3032. r.imm := symtab [idx].lval ;
  3033. r.cls := symtab [idx].cls ;
  3034. RETURN
  3035. ELSIF symtab [idx].tag = KFunc THEN
  3036. ParseCall (idx) ;
  3037. r.kind := 2 ;
  3038. r.cls := symtab [idx].cls ;
  3039. RETURN
  3040. ELSIF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KType) THEN
  3041. (* ParseVar initialises boff to 0 and then ParseSub folds any constant
  3042. subscript into it. Do NOT reset boff here: doing so after ParseVar
  3043. returns threw away the subscript, so s[i] read/wrote off+0 (the
  3044. length byte) while still reporting itself as a char. This was
  3045. latent for arrays because an array cannot be declared yet, so no
  3046. fixture had ever exercised the fold. *)
  3047. ParseVar (r) ;
  3048. RETURN
  3049. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_KeyPressed) THEN
  3050. (* KeyPressed: a boolean FUNCTION with no argument, and TP3 lets it be
  3051. written without a parameter list (`until KeyPressed'). *)
  3052. EmCrtSeq (CrtKey) ;
  3053. r.kind := 2 ;
  3054. r.cls := TBool ;
  3055. r.chr := FALSE ;
  3056. RETURN
  3057. ELSIF (symtab [idx].tag = KBuiltin) AND (symtab [idx].cls = BI_Length) THEN
  3058. (* LENGTH (s): the string's length byte, loaded inline. No runtime
  3059. entry, and no address is pushed - a string's value already carries its
  3060. length at [addr]. A literal is emitted inline (EmStrBlob) and the
  3061. byte is read from that image offset. *)
  3062. IF NOT MatchDelim ('(') THEN
  3063. Err (ENoSemi) ;
  3064. RETURN
  3065. END ;
  3066. ParseExpr (r) ;
  3067. ExpectDelim (')', ENoSemi) ;
  3068. IF NOT OK () THEN
  3069. RETURN
  3070. END ;
  3071. IF r.cls # TString THEN
  3072. Err (ETypeErr) ;
  3073. RETURN
  3074. END ;
  3075. IF r.kind = 1 THEN
  3076. EmLoadVar (symtab [r.idx].local,
  3077. (symtab [r.idx].off + r.boff) MOD 10000H, 1)
  3078. ELSIF r.kind = 3 THEN
  3079. EmLoadVar (FALSE, EmStrBlob (r), 1)
  3080. ELSE
  3081. Err (ENoLib) ;
  3082. RETURN
  3083. END ;
  3084. EmMovAh0 () ;
  3085. r.kind := 2 ;
  3086. r.cls := TScalar ;
  3087. r.chr := FALSE ;
  3088. RETURN
  3089. ELSE
  3090. Err (EUnknown)
  3091. END
  3092. END ParseAtom ;
  3093. PROCEDURE AddPend (kind, who, place : CARDINAL) ;
  3094. BEGIN
  3095. IF nPend < MaxPend THEN
  3096. pend [nPend].kind := kind ;
  3097. pend [nPend].who := who ;
  3098. pend [nPend].place := place ;
  3099. INC (nPend)
  3100. ELSE
  3101. Err (ECompOvf)
  3102. END
  3103. END AddPend ;
  3104. PROCEDURE ParmSlot (idx, k : CARDINAL) : CARDINAL ;
  3105. (* The stack slot of argument k (0-based) of procedure/function idx, from the
  3106. parameter list recorded on the symbol. Out of range means the source passed
  3107. more arguments than there are parameters: keep the old two-byte assumption
  3108. rather than inventing an arity error here. *)
  3109. VAR pi : CARDINAL ;
  3110. BEGIN
  3111. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3112. RETURN 2
  3113. END ;
  3114. pi := symtab [idx].parmFirst + k ;
  3115. RETURN ParamSlotBytes (symtab [pi])
  3116. END ParmSlot ;
  3117. PROCEDURE ParmIsVar (idx, k : CARDINAL) : BOOLEAN ;
  3118. (* Is argument k (0-based) of procedure/function idx declared VAR? Out of
  3119. range means the source passed more arguments than there are formals; treat
  3120. it as a value parameter, as ParmSlot already does. *)
  3121. VAR pi : CARDINAL ;
  3122. BEGIN
  3123. IF (symtab [idx].parmCount = 0) OR (k >= symtab [idx].parmCount) THEN
  3124. RETURN FALSE
  3125. END ;
  3126. pi := symtab [idx].parmFirst + k ;
  3127. RETURN symtab [pi].isVar
  3128. END ParmIsVar ;
  3129. PROCEDURE EmCallMost (idx, cleanup : CARDINAL) ;
  3130. (* emit the call to sym 'idx' and clean up `cleanup' bytes of arguments, which
  3131. is the SUM of their slot sizes - not 2 per argument once a slot can be
  3132. larger than a word. *)
  3133. VAR p : CARDINAL ;
  3134. BEGIN
  3135. IF symtab [idx].defnd THEN
  3136. DropC (EmCall (symtab [idx].goPos))
  3137. ELSE
  3138. p := EmCall (0) ;
  3139. AddPend (1, idx, p)
  3140. END ;
  3141. IF cleanup > 0 THEN
  3142. EmAddSp (cleanup)
  3143. END
  3144. END EmCallMost ;
  3145. PROCEDURE ParseCallArgs (idx : CARDINAL) ;
  3146. (* '(' already consumed: read args ')' then call.
  3147. Each argument is loaded and pushed the moment it has been parsed, which is
  3148. what TPSRC8 cproc/cprlp1/cprlp2 do - CALL exprsave, CALL epushax, one per
  3149. argument, then the CALL. A computed argument (kind 2) exists only in AX,
  3150. so parsing the argument after it would destroy it before the push loop
  3151. ever reached it: `p (a > b, x)' passed x twice.
  3152. Pushing in parse order is also the order the callee is laid out for: the
  3153. first argument goes on first and so ends up farthest from BP, and the LAST
  3154. declared parameter is the one at BP+4 (RESUME-TP3.md 3.11). *)
  3155. VAR arg : ERes ;
  3156. nArgs, cleanup, slot, nCopy : CARDINAL ;
  3157. BEGIN
  3158. nArgs := 0 ;
  3159. cleanup := 0 ;
  3160. IF CurCh () = ')' THEN
  3161. DropCh (GetCh ())
  3162. ELSE
  3163. LOOP
  3164. IF nArgs >= 16 THEN
  3165. Err (ECompOvf) ;
  3166. EXIT
  3167. END ;
  3168. ParseExpr (arg) ;
  3169. slot := ParmSlot (idx, nArgs) ;
  3170. IF ParmIsVar (idx, nArgs) THEN
  3171. (* VAR formal: push the actual's ADDRESS. Only a variable has
  3172. one; a constant or a computed value is refused rather than
  3173. quietly passed by value. An element with a constant index
  3174. (`s[i]') is a variable too: its address is off+boff, which
  3175. EmPushVarAddr forms directly. *)
  3176. IF arg.kind # 1 THEN
  3177. Err (ENoLib) ;
  3178. EXIT
  3179. END ;
  3180. IF symtab [arg.idx].isVar THEN
  3181. (* Passing a VAR parameter on: its slot already HOLDS the
  3182. address, so push that, not the address of the slot. *)
  3183. IF arg.boff # 0 THEN
  3184. Err (ENoLib) ;
  3185. EXIT
  3186. END ;
  3187. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  3188. EmPushAx ()
  3189. ELSE
  3190. EmPushVarAddr (symtab [arg.idx].local,
  3191. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  3192. END
  3193. ELSIF slot > 2 THEN
  3194. (* A STRING VALUE parameter: push its whole slot, copied.
  3195. `copyN' is at most the slot: an actual shorter than the formal
  3196. leaves the tail untouched, which is harmless because the length
  3197. byte bounds every read. *)
  3198. IF arg.cls # TString THEN
  3199. Err (ETypeErr) ;
  3200. EXIT
  3201. END ;
  3202. nCopy := slot ;
  3203. IF arg.kind = 1 THEN
  3204. IF VarSize (arg) < nCopy THEN
  3205. nCopy := VarSize (arg)
  3206. END
  3207. ELSIF arg.kind = 3 THEN
  3208. IF strLen [arg.strx] + 1 < nCopy THEN
  3209. nCopy := strLen [arg.strx] + 1
  3210. END
  3211. ELSE
  3212. Err (ENoLib) ; (* a computed string is not a value *)
  3213. EXIT
  3214. END ;
  3215. EmPushStrSlot (arg, slot, nCopy)
  3216. ELSE
  3217. LoadAtom (arg) ;
  3218. EmPushAx ()
  3219. END ;
  3220. cleanup := cleanup + slot ;
  3221. INC (nArgs) ;
  3222. IF NOT MatchDelim (',') THEN
  3223. EXIT
  3224. END
  3225. END ;
  3226. ExpectDelim (')', ENoSemi)
  3227. END ;
  3228. EmCallMost (idx, cleanup)
  3229. END ParseCallArgs ;
  3230. PROCEDURE ParseCall (idx : CARDINAL) ;
  3231. (* procedure/function call; '(' optional - same parse-then-push as above,
  3232. reached from ParseAtom when a FUNCTION is called in an expression *)
  3233. VAR arg : ERes ;
  3234. nArgs, cleanup, slot, nCopy : CARDINAL ;
  3235. BEGIN
  3236. nArgs := 0 ;
  3237. cleanup := 0 ;
  3238. IF MatchDelim ('(') THEN
  3239. IF CurCh () # ')' THEN
  3240. LOOP
  3241. IF nArgs >= 16 THEN
  3242. Err (ECompOvf) ;
  3243. EXIT
  3244. END ;
  3245. ParseExpr (arg) ;
  3246. slot := ParmSlot (idx, nArgs) ;
  3247. IF slot > 2 THEN
  3248. (* see ParseCallArgs: push the whole string slot *)
  3249. IF arg.cls # TString THEN
  3250. Err (ETypeErr) ;
  3251. EXIT
  3252. END ;
  3253. nCopy := slot ;
  3254. IF arg.kind = 1 THEN
  3255. IF VarSize (arg) < nCopy THEN
  3256. nCopy := VarSize (arg)
  3257. END
  3258. ELSIF arg.kind = 3 THEN
  3259. IF strLen [arg.strx] + 1 < nCopy THEN
  3260. nCopy := strLen [arg.strx] + 1
  3261. END
  3262. ELSE
  3263. Err (ENoLib) ;
  3264. EXIT
  3265. END ;
  3266. EmPushStrSlot (arg, slot, nCopy)
  3267. ELSE
  3268. LoadAtom (arg) ;
  3269. EmPushAx ()
  3270. END ;
  3271. cleanup := cleanup + slot ;
  3272. INC (nArgs) ;
  3273. IF NOT MatchDelim (',') THEN
  3274. EXIT
  3275. END
  3276. END ;
  3277. ExpectDelim (')', ENoSemi)
  3278. ELSE
  3279. DropCh (GetCh ())
  3280. END
  3281. END ;
  3282. EmCallMost (idx, cleanup)
  3283. END ParseCall ;
  3284. PROCEDURE ParseExpr (VAR r : ERes) ;
  3285. BEGIN
  3286. ParseCmp (r)
  3287. END ParseExpr ;
  3288. (* ---------------------------------------------------------------- *)
  3289. (* statements (TPSRC8) *)
  3290. (* ---------------------------------------------------------------- *)
  3291. PROCEDURE ParseLabelStmt () ;
  3292. (* numeric label definition 'n :' *)
  3293. VAR n : CARDINAL ;
  3294. nm : ARRAY [0..9] OF CHAR ;
  3295. idx : CARDINAL ;
  3296. i : CARDINAL ;
  3297. BEGIN
  3298. n := 0 ;
  3299. WHILE Digit (CurCh ()) DO
  3300. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  3301. DropCh (GetCh ())
  3302. END ;
  3303. ExpectDelim (':', ENoSemi) ;
  3304. NumToName (n, nm) ;
  3305. IF Search (nm, idx) THEN
  3306. IF symtab [idx].tag = KLabel THEN
  3307. symtab [idx].defnd := TRUE ;
  3308. symtab [idx].goPos := pc ;
  3309. i := 0 ;
  3310. WHILE i < nPend DO
  3311. IF (pend [i].kind = 0) AND (pend [i].who = idx) THEN
  3312. SetPatTgt (pend [i].place, pc) ;
  3313. pend [i].kind := 99
  3314. END ;
  3315. INC (i)
  3316. END
  3317. ELSE
  3318. Err (EUnknown)
  3319. END
  3320. ELSE
  3321. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  3322. symtab [idx].defnd := TRUE ;
  3323. symtab [idx].goPos := pc
  3324. END
  3325. END ParseLabelStmt ;
  3326. PROCEDURE Assignment (r : ERes) ;
  3327. (* ':=' already consumed by the caller; store expression into r *)
  3328. VAR src : ERes ;
  3329. k, n : CARDINAL ;
  3330. BEGIN
  3331. IF (r.kind # 1) AND (r.kind # 5) THEN
  3332. Err (EUnknown) ;
  3333. RETURN
  3334. END ;
  3335. IF (r.kind = 1) AND symtab [r.idx].isVar THEN
  3336. (* `varparam := expr': store through the address the slot holds. DI is
  3337. parked across the right-hand side because that expression may use DI
  3338. for a string element of its own. *)
  3339. IF r.boff # 0 THEN
  3340. Err (ENoLib) ;
  3341. RETURN
  3342. END ;
  3343. EmStoreVarIndPrep (symtab [r.idx].off) ;
  3344. ParseExpr (src) ;
  3345. LoadAtom (src) ;
  3346. EmPopDi () ;
  3347. EmStoreInd (VarSize (r)) ;
  3348. RETURN
  3349. END ;
  3350. IF (r.cls = TString) AND (VarSize (r) > 1) THEN
  3351. (* s := <string literal>. TPSRC8 asn2 sends a string through the scalar
  3352. store path, and estcpl's string arm emits `MOV CL,max_len' (max_len =
  3353. varsize-1) then `CALL strstore', which copies the source - length byte
  3354. and characters - into the destination and TRUNCATES a source longer
  3355. than max_len by rewriting the length byte (TPSRC2 strstore's
  3356. `CMP.B CL,AL / JBE stslenok / MOV.B [SI],AL'). Here the literal is
  3357. known at compile time, so its bytes become immediate stores instead of
  3358. a stack push and a block move. The variable that results is the same,
  3359. truncation included, and the tail past the new length is left as it
  3360. was, exactly as strstore leaves it. *)
  3361. ParseExpr (src) ;
  3362. IF (src.cls # TString) THEN
  3363. Err (ENoLib) ;
  3364. RETURN
  3365. END ;
  3366. IF src.kind # 3 THEN
  3367. (* s := <string variable>. TPSRC8 asnvar pushes the destination
  3368. address, then the expression (strload) pushes the source, and
  3369. estcpl emits MOV CL,max_len then CALL strstore, which copies
  3370. length byte + chars, TRUNCATING to max_len and leaving the
  3371. destination tail past the new length untouched. Here both
  3372. addresses are pushed - source first, so it sits at [BP+6] and the
  3373. destination at [BP+4] - the caller pops both, and the limit is a
  3374. full MOV CX,imm16 because this runtime reads it in CX outright. *)
  3375. IF src.kind # 1 THEN
  3376. Err (ENoLib) ; (* a computed string is not a value *)
  3377. RETURN
  3378. END ;
  3379. EmPushVarAddr (symtab [src.idx].local,
  3380. (symtab [src.idx].off + src.boff) MOD 10000H) ;
  3381. EmPushVarAddr (symtab [r.idx].local,
  3382. (symtab [r.idx].off + r.boff) MOD 10000H) ;
  3383. EmMovCxi ((VarSize (r) - 1) MOD 10000H) ;
  3384. DropC (EmCall (TU_StrStore)) ;
  3385. EmAddSp (4) ;
  3386. RETURN
  3387. END ;
  3388. n := strLen [src.strx] ;
  3389. IF n > VarSize (r) - 1 THEN
  3390. n := VarSize (r) - 1
  3391. END ;
  3392. EmMovAxi (n) ;
  3393. EmStoreVar (symtab [r.idx].local,
  3394. (symtab [r.idx].off + r.boff) MOD 10000H, 1) ;
  3395. k := 0 ;
  3396. WHILE k < n DO
  3397. EmMovAxi (ORD (strPool [strOff [src.strx] + k])) ;
  3398. EmStoreVar (symtab [r.idx].local,
  3399. (symtab [r.idx].off + r.boff + 1 + k) MOD 10000H, 1) ;
  3400. INC (k)
  3401. END ;
  3402. RETURN
  3403. END ;
  3404. IF (r.kind = 5) OR (VarSize (r) > 2) THEN
  3405. IF (r.cls # TChar) OR (r.kind = 1) THEN
  3406. Err (ENoLib) ;
  3407. RETURN
  3408. END ;
  3409. (* s[i] := c : one byte, either at off+boff (a constant index) or at [DI]
  3410. (a variable one, r.kind = 5). The whole-string path above was skipped
  3411. because r.cls is TChar, not TString, so this is the element store; a
  3412. plain char variable has size 1 and takes the scalar path below
  3413. instead.
  3414. For a variable index the destination address is in DI, and the
  3415. right-hand side is parsed next, so DI has to be saved first - the RHS
  3416. may hold a subscript of its own, which reuses DI, or call a routine
  3417. that clobbers it. This is TPSRC8 asnscal2/asnscal3 (758-760,
  3418. 786-789), which set flgpshdi around the expression for the same
  3419. reason. After the save, DI is free for the RHS, and the store reads
  3420. it back. *)
  3421. IF r.kind = 5 THEN
  3422. EmPushDi ()
  3423. END ;
  3424. ParseExpr (src) ;
  3425. LoadAtom (src) ;
  3426. IF r.kind = 5 THEN
  3427. EmPopDi () ; (* DI := the destination again *)
  3428. EmStDiAl () (* [DI] := AL *)
  3429. ELSE
  3430. EmStoreVar (symtab [r.idx].local,
  3431. (symtab [r.idx].off + r.boff) MOD 10000H, 1)
  3432. END ;
  3433. RETURN
  3434. END ;
  3435. ParseExpr (src) ;
  3436. LoadAtom (src) ;
  3437. EmStoreVar (symtab [r.idx].local,
  3438. (symtab [r.idx].off + r.boff) MOD 10000H,
  3439. VarSize (r))
  3440. END Assignment ;
  3441. PROCEDURE Compound () ;
  3442. (* BEGIN statement ';' ... END; END is consumed here *)
  3443. VAR tok : CARDINAL ;
  3444. BEGIN
  3445. LOOP
  3446. PeekKw (tok) ;
  3447. IF tok = TkEnd THEN
  3448. DropB (MatchKey (tok)) ;
  3449. RETURN
  3450. END ;
  3451. Statmnt () ;
  3452. IF NOT OK () THEN
  3453. RETURN
  3454. END ;
  3455. IF NOT MatchDelim (';') THEN
  3456. PeekKw (tok) ;
  3457. IF tok = TkEnd THEN
  3458. DropB (MatchKey (tok)) ;
  3459. RETURN
  3460. END ;
  3461. Err (ENoSemi) ;
  3462. RETURN
  3463. END
  3464. END
  3465. END Compound ;
  3466. PROCEDURE EmCrtSeq (which : CARDINAL) ;
  3467. (* The CRT byte sequences, in one parameterised helper. Every one is a fixed
  3468. BIOS call:
  3469. CrtClr - INT 10h AH=06 blank the whole window, then AH=02 home the cursor
  3470. CrtDl - DEC AX ; MOV DL,AL (a 1-based column -> 0-based)
  3471. CrtDh - DEC AX ; MOV DH,AL (a 1-based row)
  3472. CrtCaret - INT 10h AH=02, page 0, cursor at DH,DL
  3473. It takes a parameter on purpose: audit_helpers audits helpers with an EMPTY
  3474. parameter list byte-for-byte, and these multi-instruction sequences have no
  3475. single name grammar. Listed as COMP in NON_ONE_LINE, like SetBlob. *)
  3476. BEGIN
  3477. IF which = CrtClr THEN
  3478. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h *)
  3479. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  3480. Ebyte (0B9H) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV CX,0000h *)
  3481. Ebyte (0BAH) ; Ebyte (4FH) ; Ebyte (18H) ; (* MOV DX,184Fh *)
  3482. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h *)
  3483. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (02H) ; (* MOV AX,0200h *)
  3484. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3485. Ebyte (0BAH) ; Ebyte (00H) ; Ebyte (00H) ; (* MOV DX,0000h *)
  3486. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3487. ELSIF which = CrtDl THEN
  3488. Ebyte (48H) ; (* DEC AX *)
  3489. Ebyte (88H) ; Ebyte (0C2H) (* MOV DL,AL *)
  3490. ELSIF which = CrtDh THEN
  3491. Ebyte (48H) ; (* DEC AX *)
  3492. Ebyte (88H) ; Ebyte (0C6H) (* MOV DH,AL *)
  3493. ELSIF which = CrtEol THEN
  3494. Ebyte (0B4H) ; Ebyte (03H) ; (* MOV AH,03h get cursor *)
  3495. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3496. Ebyte (0CDH) ; Ebyte (10H) ; (* INT 10h -> DH,DL *)
  3497. Ebyte (89H) ; Ebyte (0D1H) ; (* MOV CX,DX upper-left *)
  3498. Ebyte (0B2H) ; Ebyte (4FH) ; (* MOV DL,4Fh col 79 *)
  3499. Ebyte (0B8H) ; Ebyte (00H) ; Ebyte (06H) ; (* MOV AX,0600h blank *)
  3500. Ebyte (8AH) ; Ebyte (3EH) ; Eword (crtAttrOff) ; (* MOV BH,[crtAttr] *)
  3501. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3502. ELSIF which = CrtLow THEN
  3503. (* [crtAttr] := 7: the dim attribute ClrScr/ClrEol use from now on. The
  3504. runtime's console writer is INT 21h teletype, which has no attribute
  3505. channel, but the clear operations do - so this is where the setting is
  3506. observable, not a no-op. *)
  3507. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (07H)
  3508. ELSIF which = CrtNorm THEN
  3509. Ebyte (0C6H) ; Ebyte (06H) ; Eword (crtAttrOff) ; Ebyte (0FH)
  3510. ELSIF which = CrtKey THEN
  3511. (* KeyPressed: DOS AH=0Bh asks whether a character is waiting. AL is
  3512. 0FFh when one is, 0 when not; the boolean representation here is 0/1.
  3513. AND AX,1, not AND AL,1: the interrupt leaves AH = 0Bh, so the
  3514. comparison that follows (`CMP AX,0') would read 0B00h and call the
  3515. false case TRUE. bootcom happened to return AH=0 (it IRETs the
  3516. handler's whole AX) and hid this; hlt. No argument, no runtime
  3517. entry. *)
  3518. Ebyte (0B4H) ; Ebyte (0BH) ; (* MOV AH,0Bh *)
  3519. Ebyte (0CDH) ; Ebyte (21H) ; (* INT 21h *)
  3520. Ebyte (25H) ; Ebyte (01H) ; Ebyte (00H) (* AND AX,1 *)
  3521. ELSIF which = CrtDelay THEN
  3522. (* Delay(AX) milliseconds: TP3's xdelay, a calibrated busy loop. The
  3523. count 110 is TP3's default `delaycnt' for 1 ms (TPSRC1). AX = 0 does
  3524. nothing. *)
  3525. (* OR AX,AX, not CMP AX,0: check_8086 treats every `CMP AX,0000' in the
  3526. program region as one of the IF/WHILE/REPEAT tests and demands
  3527. Jcc+3;EJMP after it. This is neither. *)
  3528. Ebyte (0BH) ; Ebyte (0C0H) ; (* OR AX,AX *)
  3529. Ebyte (74H) ; Ebyte (08H) ; (* JZ past the loop *)
  3530. Ebyte (0B9H) ; Ebyte (6EH) ; Ebyte (00H) ; (* MOV CX,110 (1 ms) *)
  3531. Ebyte (0E2H) ; Ebyte (0FEH) ; (* LOOP -> itself *)
  3532. Ebyte (48H) ; (* DEC AX *)
  3533. Ebyte (75H) ; Ebyte (0F8H) (* JNZ -> MOV CX *)
  3534. ELSE
  3535. Ebyte (0B4H) ; Ebyte (02H) ; (* MOV AH,02h *)
  3536. Ebyte (0B7H) ; Ebyte (00H) ; (* MOV BH,00h *)
  3537. Ebyte (0CDH) ; Ebyte (10H) (* INT 10h *)
  3538. END
  3539. END EmCrtSeq ;
  3540. PROCEDURE IoCall (idx : CARDINAL) ;
  3541. (* WRITE / WRITELN / READ / READLN / HALT.
  3542. TP3 (TPSRC8 pwriteln, pwrloop, prdtyped) does not pass a descriptor to
  3543. the runtime: it looks at each argument's class and emits a *different*
  3544. call per type, so the formatting is fixed at compile time. Mirrored
  3545. here - one call per argument, then a final call for the line break.
  3546. WRITE/WRITELN push the value; READ/READLN push the address, so the
  3547. runtime can store. As everywhere else in this compiler the caller
  3548. cleans the argument off the stack. *)
  3549. VAR arg : ERes ;
  3550. nArgs, ent, which, acls : CARDINAL ;
  3551. reading : BOOLEAN ;
  3552. pushed : BOOLEAN ;
  3553. skipArg : BOOLEAN ;
  3554. n : CARDINAL ;
  3555. dummy : ERes ;
  3556. BEGIN
  3557. which := symtab [idx].cls ; (* BI_* *)
  3558. IF which = BI_Halt THEN
  3559. IF MatchDelim ('(') THEN (* halt(0) - code ignored *)
  3560. ParseExpr (dummy) ;
  3561. ExpectDelim (')', ENoSemi)
  3562. END ;
  3563. DropC (EmCall (TU_Halt)) ;
  3564. RETURN
  3565. END ;
  3566. IF which = BI_ClrScr THEN
  3567. EmCrtSeq (CrtClr) ;
  3568. RETURN
  3569. END ;
  3570. IF which = BI_ClrEol THEN
  3571. (* clear from the cursor to the end of the line - a real INT 10h call,
  3572. not a no-op: AH=03 reads the cursor, CX := it, DL := 79, AH=06 blanks
  3573. that window. *)
  3574. EmCrtSeq (CrtEol) ;
  3575. RETURN
  3576. END ;
  3577. IF which = BI_GotoXY THEN
  3578. (* GotoXY (x, y): 1-based; evaluate x first and park it, then y, so the
  3579. code for y cannot clobber DL. *)
  3580. IF MatchDelim ('(') THEN
  3581. ParseExpr (dummy) ;
  3582. IF OK () THEN
  3583. LoadAtom (dummy) ;
  3584. EmPushAx ()
  3585. END ;
  3586. ExpectDelim (',', ENoSemi) ;
  3587. ParseExpr (dummy) ;
  3588. IF OK () THEN
  3589. LoadAtom (dummy) ;
  3590. EmCrtSeq (CrtDh)
  3591. END ;
  3592. ExpectDelim (')', ENoSemi) ;
  3593. EmPopAx () ;
  3594. EmCrtSeq (CrtDl) ;
  3595. EmCrtSeq (CrtCaret)
  3596. ELSE
  3597. Err (ENoSemi)
  3598. END ;
  3599. RETURN
  3600. END ;
  3601. IF which = BI_LowVideo THEN
  3602. (* set the attribute the CLEAR operations use to 7; see EmCrtSeq *)
  3603. EmCrtSeq (CrtLow) ;
  3604. RETURN
  3605. END ;
  3606. IF which = BI_NormVideo THEN
  3607. EmCrtSeq (CrtNorm) ;
  3608. RETURN
  3609. END ;
  3610. IF which = BI_Delay THEN
  3611. (* Delay(ms): a real busy loop (EmCrtSeq's CrtDelay), no INT, so it is
  3612. identical under qemu and Exec86. *)
  3613. IF MatchDelim ('(') THEN
  3614. ParseExpr (dummy) ;
  3615. IF OK () THEN
  3616. LoadAtom (dummy) ;
  3617. EmCrtSeq (CrtDelay)
  3618. END ;
  3619. ExpectDelim (')', ENoSemi)
  3620. ELSE
  3621. Err (ENoSemi)
  3622. END ;
  3623. RETURN
  3624. END ;
  3625. reading := (which = BI_Read) OR (which = BI_ReadLn) ;
  3626. nArgs := 0 ;
  3627. IF MatchDelim ('(') THEN
  3628. IF CurCh () # ')' THEN
  3629. LOOP
  3630. IF nArgs >= 16 THEN
  3631. Err (ECompOvf) ;
  3632. EXIT
  3633. END ;
  3634. ParseExpr (arg) ;
  3635. IF NOT OK () THEN
  3636. (* An argument that did not type-check has no value and arg.idx
  3637. is not a symbol. The string arm below dereferences
  3638. symtab[arg.idx] for ANY value whose class is TString - unlike
  3639. the string assign in Assignment, which can tell a failed
  3640. concat from a real one by its kind - so a `writeln' of a
  3641. rejected expression read symtab with whatever idx held
  3642. before and dereferenced it. That is exactly how
  3643. `writeln('a' + 'b')' - two CHARs, a type error since
  3644. v-TP3-STRCAT - segfaulted the compiler instead of reporting
  3645. the error. ParseSub guards its subscript the same way (see
  3646. `IF OK () THEN' before symtab[r.idx] there), and the
  3647. statement loop stops at the next iteration, so leaving the
  3648. rest of this WRITELN unparsed is harmless. *)
  3649. RETURN
  3650. END ;
  3651. (* One argument at a time: parse it, give it its own push or its
  3652. own runtime call, and only then read the next one. TPSRC8
  3653. pwrloop does exactly this, and it has to - a computed argument
  3654. exists only in AX, so parsing the argument after it, and the
  3655. call made for THIS one, are both free to destroy it. Reading
  3656. the whole list first and emitting afterwards printed the first
  3657. argument as the last argument's value, and pushed an argument
  3658. that an earlier inline string's call had already overwritten. *)
  3659. skipArg := FALSE ;
  3660. IF (nArgs = 0) AND ((arg.cls = TText) OR (arg.cls = TFile)) THEN
  3661. (* A leading FILE argument: `Read(Kbd, Ch)'. KBD is the console
  3662. keyboard and this runtime's read entries already read the
  3663. console, so the file is dropped and the rest of the argument
  3664. list is read exactly as without it. A real file is not
  3665. implemented yet - loud, rather than silently reading the file
  3666. variable as a data argument. *)
  3667. IF reading AND (arg.kind = 1) AND symtab [arg.idx].isKbd THEN
  3668. IF NOT MatchDelim (',') THEN
  3669. Err (ENoSemi) ;
  3670. RETURN
  3671. END ;
  3672. skipArg := TRUE
  3673. ELSE
  3674. Err (ENoLib) ;
  3675. RETURN
  3676. END
  3677. END ;
  3678. IF NOT skipArg THEN
  3679. pushed := TRUE ; (* default: value is on the stack -> call + pop *)
  3680. IF reading THEN
  3681. IF (arg.kind # 1) AND (arg.kind # 5) THEN
  3682. Err (ETypeErr) ; (* READ needs a variable *)
  3683. RETURN
  3684. END ;
  3685. acls := symtab [arg.idx].cls ;
  3686. (* s[i] is a CHAR variable, so read(s[i]) must read one byte at
  3687. off+boff, not the whole string at off. arg.cls is TChar
  3688. (set by ParseSub) while the symbol's own class is still
  3689. TString, which is exactly how the element is told from the
  3690. whole string; the address push has to carry boff. For a
  3691. plain variable arg.boff is 0, so nothing changes. *)
  3692. IF (acls = TString) AND (arg.cls = TChar) THEN
  3693. acls := TChar
  3694. END ;
  3695. IF arg.kind = 5 THEN
  3696. (* A variable index: ParseSub computed the element's address
  3697. into DI, and nothing has been emitted since, so that is
  3698. the address READ wants. A constant index folds into boff
  3699. and takes the LEA path below. *)
  3700. EmPushDi ()
  3701. ELSIF symtab [arg.idx].isVar THEN
  3702. (* A VAR parameter: its slot holds the address READ must
  3703. store through, not the address of the slot. *)
  3704. IF arg.boff # 0 THEN
  3705. Err (ENoLib) ;
  3706. RETURN
  3707. END ;
  3708. EmLoadVar (TRUE, symtab [arg.idx].off, 2) ;
  3709. EmPushAx ()
  3710. ELSE
  3711. EmPushVarAddr (symtab [arg.idx].local,
  3712. (symtab [arg.idx].off + arg.boff) MOD 10000H)
  3713. END ;
  3714. IF acls = TString THEN
  3715. (* readln(s)/read(s) of a string variable: TPSRC8 prdstr
  3716. pushes the address, emits MOV CL,max_len and CALL
  3717. xrdstr. Here the limit is a full MOV CX,imm16 (this
  3718. runtime has no byte-register CH/CL setup), and rdstr
  3719. leaves the terminator pending so the readln wrapper can
  3720. consume the newline. *)
  3721. EmMovCxi ((VarSize (arg) - 1) MOD 10000H) ;
  3722. ent := TU_RdStr
  3723. ELSIF acls = TReal THEN
  3724. ent := TU_RdInt (* real reads: not yet *)
  3725. ELSIF acls = TBool THEN
  3726. (* TP3 refuses boolean I/O: TPSRC8 prderrtp is error 66,
  3727. "I/O not allowed here", and the runtime has no xrdbool
  3728. at all. rdbool stores a WORD, so one byte of an
  3729. accepted read would land on the variable AFTER b - the
  3730. exact overflow t37_readbyte pins for a byte. TP3's
  3731. answer to the whole class is the error; so is ours. *)
  3732. Err (EIoHere) ;
  3733. RETURN
  3734. ELSIF acls = TChar THEN
  3735. ent := TU_RdChar (* one byte, not a word *)
  3736. ELSIF acls = TScalar THEN
  3737. (* Dispatch on the SIZE, as TPSRC8 prdnum does:
  3738. `CMP varsize,#$01 / JA prdemit' keeps xrdint for
  3739. anything wider and falls through to `MOV AX,#xrdbyte'
  3740. for a one-byte variable. A BYTE is still TScalar (it
  3741. is *written* as an integer, as in TP3), but reading one
  3742. through rdint stored a word - and the second byte of
  3743. that word is the byte that FOLLOWS the variable. *)
  3744. IF VarSize (arg) = 1 THEN
  3745. ent := TU_RdByte
  3746. ELSE
  3747. ent := TU_RdInt
  3748. END
  3749. ELSE
  3750. Err (ETypeErr) ;
  3751. RETURN
  3752. END
  3753. ELSE
  3754. acls := arg.cls ;
  3755. IF (acls = TString) AND (arg.kind = 3) THEN
  3756. (* An inline string literal. TP3 TPSRC8 pwrinlin special-cases a
  3757. literal that is followed directly by ',' or ')' - i.e. an
  3758. argument, not an expression - and emits
  3759. CALL wrtinl <length byte> <characters...>
  3760. with no stack argument at all; wrtinl reads the length from the
  3761. return address and returns to just past the last character.
  3762. Mirrored exactly, so the literal costs only its own characters
  3763. in the code stream and nothing in the data segment. *)
  3764. IF strLen [arg.strx] > 255 THEN
  3765. (* The length is one byte, so a literal of 256 characters or
  3766. more would wrap: 300 characters emitted behind a length of
  3767. 44, and the runtime would print 44 of them and silently drop
  3768. the rest. TP3 strings are at most 255 characters, so refuse
  3769. rather than truncate. *)
  3770. Err (EConstRange) ;
  3771. RETURN
  3772. END ;
  3773. DropC (EmCall (TU_WrInl)) ;
  3774. Ebyte (VAL (BYTE, strLen [arg.strx])) ;
  3775. n := 0 ;
  3776. WHILE n < strLen [arg.strx] DO
  3777. Ebyte (VAL (BYTE, ORD (strPool [strOff [arg.strx] + n]))) ;
  3778. INC (n)
  3779. END ;
  3780. pushed := FALSE (* nothing was pushed for this one *)
  3781. ELSE
  3782. IF acls = TString THEN
  3783. (* A string *variable*. Its value IS its address, so it is
  3784. passed exactly the way READ passes an address: push it
  3785. and call the owner of the layout - wrstr - which reads
  3786. the length byte and prints that many characters. TPSRC8
  3787. pwrstr/pwrchk route a string argument to xwrtstr, and
  3788. xwrtstr reaches its argument through BP just like WrChar
  3789. does. The only difference from the inline-literal arm
  3790. above is where the bytes live: a literal's are in the
  3791. code stream (wrtinl) and a variable's are in the data
  3792. segment or the frame (wrstr). *)
  3793. EmPushVarAddr (symtab [arg.idx].local, symtab [arg.idx].off) ;
  3794. ent := TU_WrStr
  3795. ELSE
  3796. LoadAtom (arg) ;
  3797. EmPushAx () ;
  3798. IF arg.chr THEN
  3799. ent := TU_WrChar (* 'a' - one char, not 97 *)
  3800. ELSIF acls = TReal THEN
  3801. ent := TU_WrReal
  3802. ELSIF acls = TBool THEN
  3803. ent := TU_WrBool
  3804. ELSIF acls = TChar THEN
  3805. ent := TU_WrChar (* c : char - one char *)
  3806. ELSIF acls = TScalar THEN
  3807. ent := TU_WrInt
  3808. ELSE
  3809. Err (ETypeErr) ;
  3810. RETURN
  3811. END
  3812. END
  3813. END
  3814. END ;
  3815. IF pushed THEN
  3816. DropC (EmCall (ent)) ;
  3817. EmAddSp (2) (* one 16-bit argument *)
  3818. END ;
  3819. INC (nArgs)
  3820. END ;
  3821. IF NOT skipArg THEN
  3822. IF NOT MatchDelim (',') THEN
  3823. EXIT
  3824. END
  3825. END
  3826. END ;
  3827. IF NOT MatchDelim (')') THEN
  3828. Err (ENoSemi) ;
  3829. RETURN
  3830. END
  3831. ELSE
  3832. DropCh (GetCh ())
  3833. END
  3834. END ;
  3835. IF reading AND (nArgs = 0) THEN
  3836. (* readln with no variable: just skip to the next line *)
  3837. DropC (EmCall (TU_RdLn)) ;
  3838. RETURN
  3839. END ;
  3840. IF which = BI_WriteLn THEN
  3841. DropC (EmCall (TU_WrLn))
  3842. ELSIF which = BI_ReadLn THEN
  3843. DropC (EmCall (TU_RdLn))
  3844. END
  3845. END IoCall ;
  3846. PROCEDURE Statmnt () ;
  3847. VAR tok : CARDINAL ;
  3848. idx, i2 : CARDINAL ;
  3849. t, src : ERes ;
  3850. L1, zj, zj2, exj : CARDINAL ;
  3851. lo, hi, v : LONGINT ;
  3852. clso : CARDINAL ;
  3853. i : CARDINAL ;
  3854. nm : ARRAY [0..MaxName] OF CHAR ;
  3855. strf : BOOLEAN ;
  3856. dow : BOOLEAN ;
  3857. BEGIN
  3858. Skip () ;
  3859. IF Digit (CurCh ()) THEN
  3860. ParseLabelStmt () ; (* consumed 'n' ':' *)
  3861. Statmnt () ; (* 'n : statement' - the statement follows
  3862. the label directly, with no ';' between *)
  3863. RETURN
  3864. END ;
  3865. IF NOT Alpha (CurCh ()) THEN
  3866. ExpectDelim (';', ENoSemi) ;
  3867. RETURN
  3868. END ;
  3869. DropB (MatchKey (tok)) ;
  3870. IF tok = TkBegin THEN
  3871. Compound ()
  3872. ELSIF tok = TkIf THEN
  3873. ParseExpr (t) ;
  3874. LoadAtom (t) ;
  3875. EmCmpAxi (0) ;
  3876. zj := EmJcc (84H, 0) ; (* JZ -> else/end *)
  3877. IF NOT (MatchKey (tok) AND (tok = TkThen)) THEN
  3878. Err (ENoSemi)
  3879. END ;
  3880. Statmnt () ;
  3881. (* Peek the ELSE, do not match it. `MatchKey (tok) AND (tok = TkElse)`
  3882. consumes whatever the next keyword is even when the AND fails, so an
  3883. `if` that was the LAST statement of a BEGIN..END block ate the block's
  3884. own END: Compound then found neither ';' nor END and raised ENoSemi.
  3885. Any `if` as the last statement of a compound was unparseable - not
  3886. in a loop, not anywhere - and no fixture had one, so nothing noticed.
  3887. The visible symptom was a parse error at the statement AFTER the
  3888. block, which points at entirely the wrong piece of source. *)
  3889. PeekKw (tok) ;
  3890. IF tok = TkElse THEN
  3891. DropB (MatchKey (tok)) ;
  3892. exj := EmJmpNear (0) ;
  3893. SetPatTgt (zj, pc) ;
  3894. Statmnt () ;
  3895. SetPatTgt (exj, pc)
  3896. ELSE
  3897. SetPatTgt (zj, pc)
  3898. END
  3899. ELSIF tok = TkWhile THEN
  3900. L1 := pc ;
  3901. ParseExpr (t) ;
  3902. LoadAtom (t) ;
  3903. EmCmpAxi (0) ;
  3904. zj := EmJcc (84H, 0) ; (* JZ -> end *)
  3905. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  3906. Err (ENoSemi)
  3907. END ;
  3908. brkSave [brkN] := exitCnt ;
  3909. loopTy [brkN] := 1 ;
  3910. INC (brkN) ;
  3911. Statmnt () ;
  3912. DEC (brkN) ;
  3913. i := brkSave [brkN] ;
  3914. WHILE i < exitCnt DO
  3915. SetPatTgt (exitPatch [i], pc) ;
  3916. INC (i)
  3917. END ;
  3918. exitCnt := brkSave [brkN] ;
  3919. DropC (EmJmpNear (L1)) ;
  3920. SetPatTgt (zj, pc)
  3921. ELSIF tok = TkRepeat THEN
  3922. L1 := pc ;
  3923. brkSave [brkN] := exitCnt ;
  3924. loopTy [brkN] := 1 ;
  3925. INC (brkN) ;
  3926. (* The body is a STATEMENT SEQUENCE, not one statement: `repeat a; b
  3927. until c'. This used to call Statmnt once and then demand UNTIL, so
  3928. any body with a second statement was ENoSemi at the first ';'. t12's
  3929. two bodies are single statements and never saw it; CALC's `Flash' does
  3930. (GotoXY; Blink := not Blink; if ...; Write; Delay). Same shape as
  3931. Compound, stopping at UNTIL instead of END. *)
  3932. LOOP
  3933. PeekKw (tok) ;
  3934. IF tok = TkUntil THEN
  3935. DropB (MatchKey (tok)) ;
  3936. EXIT
  3937. END ;
  3938. Statmnt () ;
  3939. IF NOT OK () THEN
  3940. RETURN
  3941. END ;
  3942. IF NOT MatchDelim (';') THEN
  3943. PeekKw (tok) ;
  3944. IF tok = TkUntil THEN
  3945. DropB (MatchKey (tok)) ;
  3946. EXIT
  3947. END ;
  3948. Err (ENoSemi) ;
  3949. RETURN
  3950. END
  3951. END ;
  3952. ParseExpr (t) ;
  3953. LoadAtom (t) ;
  3954. EmCmpAxi (0) ;
  3955. (* UNTIL exits when the condition is TRUE, so the body runs again when
  3956. it is FALSE. The condition is a 0/1 in AX and EmCmpAxi (0) has just
  3957. compared it with 0, so ZF=1 means "condition false" -- which is
  3958. exactly the case that loops, hence JZ.
  3959. This was JNZ, which compiled repeat-until as while-until: the body
  3960. ran once, the condition was tested, and it stopped. t12_repeat is
  3961. `i:=0; repeat i:=i+1 until i>5' and it printed 1.
  3962. No patch slot: L1 is backwards and already known, so EmJcc returns
  3963. 0 and there is nothing to SetPatTgt. *)
  3964. DropC (EmJcc (84H, L1)) ; (* JZ -> body again *)
  3965. DEC (brkN) ;
  3966. i := brkSave [brkN] ;
  3967. WHILE i < exitCnt DO
  3968. SetPatTgt (exitPatch [i], pc) ;
  3969. INC (i)
  3970. END ;
  3971. exitCnt := brkSave [brkN]
  3972. ELSIF tok = TkFor THEN
  3973. (* control variable *)
  3974. Skip () ; (* after the FOR keyword: skip blanks *)
  3975. IF NOT Alpha (CurCh ()) THEN
  3976. Err (EUnknown) ;
  3977. RETURN
  3978. END ;
  3979. GetWord () ;
  3980. IF NOT Search (wrd, idx) THEN
  3981. Err (EUnknown) ;
  3982. RETURN
  3983. END ;
  3984. IF symtab [idx].size > 2 THEN
  3985. Err (ENoLib) ;
  3986. RETURN
  3987. END ;
  3988. IF NOT MatchAssign () THEN
  3989. Err (ENoSemi)
  3990. END ;
  3991. ParseExpr (src) ;
  3992. LoadAtom (src) ;
  3993. EmStoreVar (symtab [idx].local, symtab [idx].off,
  3994. symtab [idx].size) ;
  3995. IF NOT MatchKey (tok) THEN
  3996. Err (ESimpType) ;
  3997. RETURN
  3998. END ;
  3999. IF (tok = TkTo) OR (tok = TkDownto) THEN
  4000. dow := (tok = TkDownto)
  4001. ELSE
  4002. Err (ESimpType) ;
  4003. RETURN
  4004. END ;
  4005. ParseExpr (t) ;
  4006. LoadAtom (t) ;
  4007. EmPushAx () ; (* loop bound on the stack *)
  4008. IF NOT (MatchKey (tok) AND (tok = TkDo)) THEN
  4009. Err (ENoSemi)
  4010. END ;
  4011. brkSave [brkN] := exitCnt ;
  4012. loopTy [brkN] := 2 ;
  4013. INC (brkN) ;
  4014. L1 := pc ; (* Ltest: the test comes FIRST *)
  4015. (* The test is emitted before the body, not after it. It used to be
  4016. emitted after, which is a post-test loop and runs the body one time
  4017. too many: with `for i := 1 to 5`, the sequence of i at the test is
  4018. 1,2,3,4,5,6 - the test at i=5 is `5 > 5`, which is false, so the
  4019. body ran a sixth time with i=6. `for i := 1 to 5 do s := s + i`
  4020. printed 21. The size was right and the shape was right; only the
  4021. order was wrong, and no byte check can see an order.
  4022. The bound stays on the stack for the whole loop, so EmMovCxSp has to
  4023. re-read it every iteration - which is also what makes the bound a
  4024. *variable* rather than a constant. [SP] cannot be encoded on the
  4025. 8086, so EmMovCxSp is POP CX ; PUSH CX, an observational no-op that
  4026. leaves the bound in place. *)
  4027. EmMovCxSp () ;
  4028. EmLoadVar (symtab [idx].local, symtab [idx].off,
  4029. symtab [idx].size) ;
  4030. EmCmpAxCx () ;
  4031. IF dow THEN
  4032. zj := EmJcc (8CH, 0) (* JL -> done *)
  4033. ELSE
  4034. zj := EmJcc (8FH, 0) (* JG -> done *)
  4035. END ;
  4036. Statmnt () ;
  4037. DEC (brkN) ;
  4038. (* A FOR's exits are NOT patched here, even though `done` is not known
  4039. yet. For a WHILE or REPEAT, "just after the body" is a correct
  4040. target: the jump back to the test re-evaluates the condition and
  4041. leaves. For a FOR there is a STEP between the body and `done`, so
  4042. an EXIT that jumped here would increment the control variable and
  4043. jump back to the test - and if the incremented value still satisfied
  4044. the bound, it would run the body AGAIN. `exit` did not exit.
  4045. The fix needs no new bookkeeping: `brkSave [brkN] .. exitCnt` still
  4046. names exactly this loop's exits, because Statmnt may have added more
  4047. and nothing has reset exitCnt. So they are patched at `done`, below.
  4048. A WHILE nested inside the FOR saves and restores its own range and
  4049. leaves this one intact. *)
  4050. (* step *)
  4051. EmLoadVar (symtab [idx].local, symtab [idx].off,
  4052. symtab [idx].size) ;
  4053. IF dow THEN
  4054. EmDecAx ()
  4055. ELSE
  4056. EmIncAx ()
  4057. END ;
  4058. EmStoreVar (symtab [idx].local, symtab [idx].off,
  4059. symtab [idx].size) ;
  4060. DropC (EmJmpNear (L1)) ;
  4061. SetPatTgt (zj, pc) ; (* done: *)
  4062. (* A WHILE loop here, not a FOR over the exit range. The range is
  4063. usually EMPTY - most loops have no `exit` - and `exitCnt` is a
  4064. CARDINAL, so `TO exitCnt - 1` with exitCnt = 0 is `TO 65535`: the
  4065. loop does not terminate, it wraps, and it walks exitPatch [0..65535]
  4066. off the end of a 64-element array. `for i := 1 to 10 do i := i` has
  4067. no exit, so this is the ORDINARY case, and it faulted with
  4068. "invalid address referenced" on every FOR loop without an exit. *)
  4069. i := brkSave [brkN] ;
  4070. WHILE i < exitCnt DO
  4071. SetPatTgt (exitPatch [i], pc) ;
  4072. INC (i)
  4073. END ;
  4074. exitCnt := brkSave [brkN] ;
  4075. EmAddSp (2) (* drop the loop bound *)
  4076. ELSIF tok = TkCase THEN
  4077. ParseExpr (t) ;
  4078. LoadAtom (t) ;
  4079. EmPushAx () ; (* selector on the stack *)
  4080. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4081. Err (ENoSemi)
  4082. END ;
  4083. caseN := 0 ;
  4084. LOOP
  4085. Skip () ;
  4086. IF MatchDelim (';') THEN
  4087. Skip ()
  4088. END ;
  4089. PeekKw (tok) ;
  4090. IF (tok = TkEnd) OR (tok = TkElse) THEN
  4091. EXIT
  4092. END ;
  4093. (* case label : constant identifier or literal *)
  4094. IF Alpha (CurCh ()) THEN
  4095. GetWord () ;
  4096. IF Search (wrd, i2) AND (symtab [i2].tag = KConst) THEN
  4097. lo := symtab [i2].lval
  4098. ELSE
  4099. Err (EUnknown) ;
  4100. EXIT
  4101. END
  4102. ELSE
  4103. RdConst (lo, clso, strf)
  4104. END ;
  4105. IF MatchRange () THEN
  4106. RdConst (hi, clso, strf)
  4107. ELSE
  4108. hi := lo
  4109. END ;
  4110. ExpectDelim (':', ENoSemi) ;
  4111. EmMovAxSp () ;
  4112. EmCmpAxi (W16 (lo)) ;
  4113. zj := EmJcc (85H, 0) ; (* JNZ -> next *)
  4114. IF hi # lo THEN
  4115. EmCmpAxi (W16 (hi)) ;
  4116. zj2 := EmJcc (85H, 0)
  4117. ELSE
  4118. zj2 := 0
  4119. END ;
  4120. Statmnt () ;
  4121. IF caseN >= 64 THEN
  4122. Err (ECompOvf) ;
  4123. EXIT
  4124. END ;
  4125. caseJmp [caseN] := EmJmpNear (0) ;
  4126. INC (caseN) ;
  4127. SetPatTgt (zj, pc) ;
  4128. IF zj2 # 0 THEN
  4129. SetPatTgt (zj2, pc)
  4130. END
  4131. END ;
  4132. IF tok = TkElse THEN
  4133. DropB (MatchKey (tok)) ;
  4134. Statmnt () ;
  4135. IF NOT (MatchKey (tok) AND (tok = TkEnd)) THEN
  4136. Err (ENoSemi)
  4137. END
  4138. ELSE
  4139. DropB (MatchKey (tok))
  4140. END ;
  4141. EmAddSp (2) ;
  4142. FOR i := 0 TO caseN - 1 DO
  4143. SetPatTgt (caseJmp [i], pc)
  4144. END
  4145. ELSIF tok = TkGoto THEN
  4146. v := 0 ;
  4147. Skip () ; (* after the GOTO keyword: skip blanks *)
  4148. IF Digit (CurCh ()) THEN
  4149. RdIntConst (v) ;
  4150. NumToName (W16 (v), nm) ;
  4151. IF Search (nm, idx) THEN
  4152. IF symtab [idx].tag = KLabel THEN
  4153. IF symtab [idx].defnd THEN
  4154. DropC (EmJmpNear (symtab [idx].goPos))
  4155. ELSE
  4156. zj := EmJmpNear (0) ;
  4157. AddPend (0, idx, zj)
  4158. END
  4159. ELSE
  4160. Err (EUnknown)
  4161. END
  4162. ELSE
  4163. idx := NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE) ;
  4164. zj := EmJmpNear (0) ;
  4165. AddPend (0, idx, zj)
  4166. END
  4167. ELSE
  4168. Err (EUnknown)
  4169. END
  4170. ELSIF tok = TkExit THEN
  4171. IF brkN = 0 THEN
  4172. Err (EUnknown)
  4173. ELSE
  4174. (* No EmAddSp (2) here, even inside a FOR. The FOR's `done` label
  4175. drops the bound, so an EXIT that jumped to `done` would drop it a
  4176. second time - 4 bytes off a stack that only had 2 to give, which
  4177. silently corrupts the caller's frame. It used to do exactly
  4178. that, and it was doubly wrong: the exits were patched to the STEP
  4179. rather than to `done`, so the EXIT also incremented the control
  4180. variable and jumped back into the test. *)
  4181. zj := EmJmpNear (0) ;
  4182. IF exitCnt < 64 THEN
  4183. exitPatch [exitCnt] := zj ;
  4184. INC (exitCnt)
  4185. END
  4186. END
  4187. ELSIF tok = TkWith THEN
  4188. Err (ENoLib)
  4189. ELSE
  4190. (* identifier statement: assignment or call *)
  4191. IF NOT Search (wrd, idx) THEN
  4192. Err (EUnknown) ;
  4193. RETURN
  4194. END ;
  4195. IF symtab [idx].tag = KBuiltin THEN
  4196. IoCall (idx) ;
  4197. RETURN
  4198. END ;
  4199. IF symtab [idx].tag = KProc THEN
  4200. IF MatchDelim ('(') THEN
  4201. ParseCallArgs (idx)
  4202. ELSE
  4203. ParseCall (idx)
  4204. END ;
  4205. RETURN
  4206. END ;
  4207. IF (symtab [idx].tag = KVar) OR (symtab [idx].tag = KFunc) THEN
  4208. t.idx := idx ;
  4209. t.kind := 1 ;
  4210. t.boff := 0 ;
  4211. t.cls := symtab [idx].cls ;
  4212. IF symtab [idx].tag = KFunc THEN
  4213. t.idx := symtab [idx].resvar ;
  4214. t.cls := symtab [t.idx].cls
  4215. END ;
  4216. t.sz := symtab [t.idx].size ; (* ParseSub may narrow it further *)
  4217. ParseSub (t) ;
  4218. IF MatchAssign () THEN
  4219. Assignment (t) ;
  4220. RETURN
  4221. END ;
  4222. Err (ENoSemi) ;
  4223. RETURN
  4224. END ;
  4225. Err (ENoSemi)
  4226. END
  4227. END Statmnt ;
  4228. (* ---------------------------------------------------------------- *)
  4229. (* types and declarations (TPSRC7) *)
  4230. (* ---------------------------------------------------------------- *)
  4231. PROCEDURE ParseType (VAR cls, size, elem : CARDINAL) ;
  4232. VAR tok : CARDINAL ;
  4233. idx : CARDINAL ;
  4234. lo, hi : LONGINT ;
  4235. s2, e2 : CARDINAL ;
  4236. subcls : CARDINAL ;
  4237. strf : BOOLEAN ;
  4238. consumed : BOOLEAN ;
  4239. running, groupFirst, i, an : CARDINAL ;
  4240. alo, ahi : ARRAY [0..3] OF LONGINT ;
  4241. ecls2 : CARDINAL ;
  4242. BEGIN
  4243. cls := TNone ; size := 0 ; elem := 0 ;
  4244. consumed := FALSE ;
  4245. newArrIdx := 0 ;
  4246. Skip () ; (* after ':' / '=' : skip blanks *)
  4247. IF CurCh () = '(' THEN
  4248. (* An enumeration: `(Constant, Formula, Txt, ...)'. Each enumerator
  4249. becomes a constant with its ordinal position as its value, and the
  4250. TYPE is 1 byte (TP3 uses one below 256 values) with bounds 0..n-1,
  4251. which DefType records so `set of Attributes' can size its base.
  4252. Enumerators are TScalar, not TEnum: they behave as ordinals; only the
  4253. TYPE carries the enum identity and its bounds. *)
  4254. DropCh (GetCh ()) ;
  4255. lo := 0 ;
  4256. hi := -1 ;
  4257. LOOP
  4258. Skip () ;
  4259. IF NOT Alpha (CurCh ()) THEN
  4260. Err (EUnknown) ;
  4261. RETURN
  4262. END ;
  4263. GetWord () ;
  4264. DupTest (wrd) ;
  4265. DropC (NewSym (wrd, KConst, TScalar, 1, 1, 0, hi + 1, FALSE)) ;
  4266. hi := hi + 1 ;
  4267. IF MatchDelim (',') THEN
  4268. (* another enumerator *)
  4269. ELSE
  4270. EXIT
  4271. END
  4272. END ;
  4273. ExpectDelim (')', ENoSemi) ;
  4274. enumLo := lo ;
  4275. enumHi := hi ;
  4276. cls := TEnum ;
  4277. size := 1 ;
  4278. elem := 1 ;
  4279. RETURN
  4280. END ;
  4281. IF Alpha (CurCh ()) THEN
  4282. DropB (MatchKey (tok)) ;
  4283. consumed := TRUE
  4284. ELSE
  4285. tok := TkNone
  4286. END ;
  4287. IF tok = TkArray THEN
  4288. (* array [range, range, ...] of T. Several ranges are allowed; the LAST
  4289. varies fastest (row-major), so `Sheet[fx,fy]' strides the first range
  4290. by the second's count (RESUME-TP3.md §2). The shape is kept in the
  4291. array table; the symbol carries a pointer to it (SymEntry.arrIdx) so
  4292. indexing can scale by the element size and subtract each lower bound. *)
  4293. ExpectDelim ('[', ENoSemi) ;
  4294. an := 0 ;
  4295. LOOP
  4296. RdConst (lo, subcls, strf) ;
  4297. IF NOT MatchRange () THEN
  4298. Err (ESimpType) ;
  4299. RETURN
  4300. END ;
  4301. RdConst (hi, subcls, strf) ;
  4302. IF an < 4 THEN
  4303. alo [an] := lo ;
  4304. ahi [an] := hi ;
  4305. INC (an)
  4306. END ;
  4307. IF MatchDelim (',') THEN
  4308. (* another range *)
  4309. ELSE
  4310. EXIT
  4311. END
  4312. END ;
  4313. ExpectDelim (']', ENoSemi) ;
  4314. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4315. Err (ENoSemi) ;
  4316. RETURN
  4317. END ;
  4318. ParseType (cls, s2, e2) ;
  4319. ecls2 := cls ;
  4320. cls := TArray ;
  4321. elem := s2 ;
  4322. size := s2 ;
  4323. i := 0 ;
  4324. WHILE i < an DO
  4325. size := size * W16 (VAL (LONGINT, W16 (ahi [i]))
  4326. - VAL (LONGINT, W16 (alo [i])) + 1) ;
  4327. INC (i)
  4328. END ;
  4329. (* register the shape so indexing can scale by element size and subtract
  4330. each lower bound; the symbol points at this slot *)
  4331. IF arrTop < MaxArrs THEN
  4332. arrs [arrTop].n := an ;
  4333. arrs [arrTop].elem := s2 ;
  4334. arrs [arrTop].ecls := ecls2 ;
  4335. i := 0 ;
  4336. WHILE i < an DO
  4337. arrs [arrTop].lo [i] := alo [i] ;
  4338. arrs [arrTop].hi [i] := ahi [i] ;
  4339. INC (i)
  4340. END ;
  4341. newArrIdx := arrTop + 1 ;
  4342. INC (arrTop)
  4343. ELSE
  4344. Err (ECompOvf)
  4345. END
  4346. ELSIF tok = TkString THEN
  4347. cls := TString ;
  4348. size := 256 ;
  4349. elem := 1 ;
  4350. IF MatchDelim ('[') THEN
  4351. RdConst (hi, subcls, strf) ;
  4352. ExpectDelim (']', ENoSemi) ;
  4353. size := W16 (hi) + 1
  4354. END
  4355. ELSIF tok = TkSet THEN
  4356. (* set of <ordinal>. TP3's hybrid layout (coeur-tp-ocr 4.7.2): only the
  4357. whole BYTES covering the base range are stored, so `set of Char' is 32
  4358. bytes and `set of 12..17' is 2. `elem' carries the origin - the first
  4359. element of the first byte, a multiple of 8 - which is all the
  4360. membership and constructor arithmetic needs. *)
  4361. PeekKw (tok) ;
  4362. IF tok = TkOf THEN
  4363. DropB (MatchKey (tok)) ;
  4364. RdSetBase (subcls, lo, hi) ;
  4365. IF OK () THEN
  4366. cls := TSet ;
  4367. elem := (VAL (CARDINAL, lo) DIV 8) * 8 ;
  4368. size := (VAL (CARDINAL, hi) DIV 8)
  4369. - (VAL (CARDINAL, lo) DIV 8) + 1
  4370. END
  4371. ELSE
  4372. Err (ENoSemi)
  4373. END
  4374. ELSIF tok = TkRecord THEN
  4375. (* record fieldList end, fields NON-COMPACTED and juxtaposed
  4376. (RESUME-TP3.md §2). Each name in a `a, b : T' group is a field of its
  4377. own at the running offset; the field table is where `x.f' looks, keyed
  4378. per record so field names need not be globally unique.
  4379. recFldFirst/recFldLast hand the range to DefType, or to the enclosing
  4380. record's field entry when records nest. *)
  4381. recFldFirst := fldTop ;
  4382. running := 0 ;
  4383. LOOP
  4384. PeekKw (tok) ;
  4385. IF tok = TkEnd THEN
  4386. DropB (MatchKey (tok)) ;
  4387. EXIT
  4388. END ;
  4389. IF CurCh () = 0C THEN
  4390. Err (EUnknown) ;
  4391. EXIT
  4392. END ;
  4393. (* the group's names, then ONE `: type' *)
  4394. groupFirst := fldTop ;
  4395. LOOP
  4396. Skip () ;
  4397. IF NOT Alpha (CurCh ()) THEN
  4398. Err (EUnknown) ;
  4399. RETURN
  4400. END ;
  4401. GetWord () ;
  4402. IF fldTop < MaxFields THEN
  4403. CopyStr (fields [fldTop].name, wrd) ;
  4404. fields [fldTop].off := 0 ;
  4405. INC (fldTop)
  4406. ELSE
  4407. Err (ECompOvf)
  4408. END ;
  4409. IF NOT MatchDelim (',') THEN
  4410. EXIT
  4411. END
  4412. END ;
  4413. ExpectDelim (':', ENoSemi) ;
  4414. ParseType (subcls, s2, e2) ;
  4415. IF NOT OK () THEN
  4416. RETURN
  4417. END ;
  4418. (* every name in the group gets the type and its own slot *)
  4419. i := groupFirst ;
  4420. WHILE i < fldTop DO
  4421. fields [i].cls := subcls ;
  4422. fields [i].size := s2 ;
  4423. fields [i].elem := e2 ;
  4424. fields [i].off := running ;
  4425. fields [i].lo := enumLo ;
  4426. fields [i].hi := enumHi ;
  4427. running := running + s2 ;
  4428. INC (i)
  4429. END ;
  4430. IF NOT MatchDelim (';') THEN
  4431. Err (ENoSemi) ;
  4432. RETURN
  4433. END
  4434. END ;
  4435. recFldLast := fldTop ;
  4436. cls := TRecord ;
  4437. size := running ;
  4438. elem := running
  4439. ELSIF tok = TkText THEN
  4440. (* A TEXT file variable. We do our own unbuffered INT 21h I/O, so the
  4441. file variable is just our control block (see FileVarSize) and the
  4442. element is one byte; TP3 keeps a 128-byte buffer in its own, which is
  4443. a divergence we do not need. *)
  4444. cls := TText ;
  4445. size := FileVarSize ;
  4446. elem := 1
  4447. ELSIF tok = TkFile THEN
  4448. (* file of T. The element type is parsed for its SIZE, which is what a
  4449. Read/Write moves per record; the variable itself is the control
  4450. block. *)
  4451. IF NOT (MatchKey (tok) AND (tok = TkOf)) THEN
  4452. Err (ENoSemi) ;
  4453. RETURN
  4454. END ;
  4455. ParseType (subcls, s2, e2) ;
  4456. IF OK () THEN
  4457. cls := TFile ;
  4458. size := FileVarSize ;
  4459. elem := s2
  4460. END
  4461. ELSE
  4462. IF consumed THEN
  4463. IF Search (wrd, idx) AND (symtab [idx].tag = KType) THEN
  4464. cls := symtab [idx].cls ;
  4465. size := symtab [idx].size ;
  4466. elem := symtab [idx].size ;
  4467. enumLo := symtab [idx].lo ;
  4468. enumHi := symtab [idx].hi ;
  4469. recFldFirst := symtab [idx].fldFirst ;
  4470. recFldLast := symtab [idx].fldLast ;
  4471. newArrIdx := symtab [idx].arrIdx
  4472. ELSE
  4473. Err (EUnknown)
  4474. END
  4475. ELSE
  4476. (* subrange lo .. hi. TP3 sizes it by its bounds: ONE byte when both
  4477. are inside 0..255, else two (RESUME-TP3.md §2). `0..20' and
  4478. `'A'..'G'' are one byte - which is what makes CellRec 80 and not
  4479. 82, and `Sheet' 147*80. The bounds are kept for `set of T'. *)
  4480. RdConst (lo, subcls, strf) ;
  4481. IF NOT MatchRange () THEN
  4482. Err (ESimpType) ;
  4483. RETURN
  4484. END ;
  4485. RdConst (hi, subcls, strf) ;
  4486. cls := TScalar ;
  4487. IF (lo >= 0) AND (hi <= 255) AND (lo <= hi) THEN
  4488. size := 1
  4489. ELSE
  4490. size := 2
  4491. END ;
  4492. elem := size ;
  4493. enumLo := lo ;
  4494. enumHi := hi
  4495. END
  4496. END
  4497. END ParseType ;
  4498. PROCEDURE DefVar () ;
  4499. (* 'name' (',' name)* ':' type [ABSOLUTE addr] ; group repeated until a
  4500. declaration keyword appears *)
  4501. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4502. cls, size, elem : CARDINAL ;
  4503. tok : CARDINAL ;
  4504. v : LONGINT ;
  4505. off : CARDINAL ;
  4506. first, i : CARDINAL ;
  4507. BEGIN
  4508. LOOP
  4509. Skip () ; (* after the VAR keyword: skip blanks *)
  4510. IF NOT Alpha (CurCh ()) THEN
  4511. Err (EUnknown) ;
  4512. RETURN
  4513. END ;
  4514. (* A group is `name (, name)* : type' - TPSRC7 rdvarlst/rdvloop collects
  4515. the whole comma-separated list of names FIRST (`CALL ccomma / JZ
  4516. rdvloop'), then reads one `: type' with ecolon/rdvartp, then vardef2
  4517. gives every name in the list that one type. The names are created as
  4518. placeholders here and filled in once the type is known, which is the
  4519. same shape as TP3 reserving a symtab slot per name and storing the
  4520. type pointer into each afterwards. *)
  4521. first := symTop ;
  4522. LOOP
  4523. Skip () ; (* GetWord does not skip blanks, and the cursor
  4524. sits on the space after the ',' *)
  4525. IF NOT Alpha (CurCh ()) THEN
  4526. Err (EUnknown) ;
  4527. RETURN
  4528. END ;
  4529. GetWord () ;
  4530. SaveWord (nm) ;
  4531. DupTest (nm) ;
  4532. DropC (NewSym (nm, KVar, TNone, 0, 0, 0, 0, lexnest # 0)) ;
  4533. IF NOT MatchDelim (',') THEN
  4534. EXIT
  4535. END
  4536. END ;
  4537. ExpectDelim (':', ENoSemi) ;
  4538. ParseType (cls, size, elem) ;
  4539. IF OK () THEN
  4540. IF lexnest = 0 THEN
  4541. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  4542. AND (cls # TArray) AND (cls # TFile) AND (cls # TText) THEN
  4543. (* Still the catch-all for a type whose storage this compiler does
  4544. not lay out yet (an ARRAY at its point of use, a RECORD, ...).
  4545. A STRING is the exception now: its layout is length byte +
  4546. characters, and the rest of the compiler knows it - see
  4547. Assignment and IoCall. *)
  4548. Err (ENoLib) ;
  4549. RETURN
  4550. END ;
  4551. PeekKw (tok) ;
  4552. IF tok = TkAbsolute THEN
  4553. DropB (MatchKey (tok)) ;
  4554. IF (CurCh () = '$') OR (Digit (CurCh ())) THEN
  4555. RdIntConst (v) ;
  4556. off := W16 (v)
  4557. ELSE
  4558. Err (EUnknown) ;
  4559. off := 0
  4560. END ;
  4561. (* TP3's absolute path (vdstore) leaves the offset fixed, so
  4562. every name in the group aliases the same address. *)
  4563. i := first ;
  4564. WHILE i < symTop DO
  4565. symtab [i].cls := cls ; symtab [i].size := size ;
  4566. symtab [i].elem := elem ; symtab [i].off := off ;
  4567. symtab [i].fldFirst := recFldFirst ;
  4568. symtab [i].fldLast := recFldLast ;
  4569. symtab [i].arrIdx := newArrIdx ;
  4570. INC (i)
  4571. END
  4572. ELSE
  4573. i := first ;
  4574. WHILE i < symTop DO
  4575. symtab [i].cls := cls ; symtab [i].size := size ;
  4576. symtab [i].elem := elem ; symtab [i].off := dc ;
  4577. symtab [i].fldFirst := recFldFirst ;
  4578. symtab [i].fldLast := recFldLast ;
  4579. symtab [i].arrIdx := newArrIdx ;
  4580. dc := dc + size ;
  4581. INC (i)
  4582. END
  4583. END ;
  4584. varspc := varspc + size * (symTop - first)
  4585. ELSE
  4586. IF (size > 2) AND (cls # TString) AND (cls # TRecord)
  4587. AND (cls # TArray) AND (cls # TFile) AND (cls # TText) THEN
  4588. Err (ENoLib) ;
  4589. RETURN
  4590. END ;
  4591. (* A local occupies [off, off+size-1] and lives BELOW the saved BP,
  4592. because BP-relative locals grow down from the top of the frame
  4593. while a STRING grows UP from its base (length byte, then chars).
  4594. Top-anchored packing keeps both true at once: locFree is the
  4595. highest still-free byte (-1 at the top), the new symbol's base
  4596. is placed so that its LAST byte lands on that byte, and locFree
  4597. then drops by the whole size. So the first INTEGER (size 2) is
  4598. at -2 and the second at -4, byte for byte what the old
  4599. pre-decrement rule produced, while a string[5] local (size 6) is
  4600. at -6..-1 instead of the old -2..+3 - which straddled the saved
  4601. BP at [BP] and the return address at [BP+2] and made `readln(s)'
  4602. into a local store characters over its own return address.
  4603. Each name in the group gets its own slot. *)
  4604. i := first ;
  4605. WHILE i < symTop DO
  4606. symtab [i].cls := cls ; symtab [i].size := size ;
  4607. symtab [i].elem := elem ;
  4608. symtab [i].fldFirst := recFldFirst ;
  4609. symtab [i].fldLast := recFldLast ;
  4610. symtab [i].arrIdx := newArrIdx ;
  4611. symtab [i].off := (locFree - size + 1) MOD 10000H ;
  4612. locFree := (locFree - size) MOD 10000H ;
  4613. INC (i)
  4614. END ;
  4615. locBytes := locBytes + size * (symTop - first)
  4616. END
  4617. END ;
  4618. IF MatchDelim (',') THEN
  4619. (* The older `name : type, name : type' spelling: another group
  4620. follows without a semicolon. TP3's grammar is names-then-one-type
  4621. with ',' inside a group and ';' between groups (TPSRC7 rdvarlst /
  4622. rdvloop then ecolon/rdvartp), and both spellings reach the same
  4623. symbols, so both separators are accepted here. *)
  4624. ELSIF MatchDelim (';') THEN
  4625. PeekKw (tok) ;
  4626. IF tok # TkNone THEN
  4627. RETURN
  4628. END
  4629. ELSE
  4630. Err (ENoSemi) ;
  4631. RETURN
  4632. END
  4633. END
  4634. END DefVar ;
  4635. PROCEDURE DefConst () ;
  4636. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4637. v : LONGINT ;
  4638. cls, typCls, typSize, typElem, soff, ci : CARDINAL ;
  4639. isStr : BOOLEAN ;
  4640. tok : CARDINAL ;
  4641. typed, setTyped, arrTyped : BOOLEAN ;
  4642. nb, k, divi, w : CARDINAL ;
  4643. BEGIN
  4644. LOOP
  4645. PeekKw (tok) ;
  4646. IF tok # TkNone THEN
  4647. RETURN
  4648. END ;
  4649. Skip () ; (* after the CONST keyword: skip blanks *)
  4650. IF NOT Alpha (CurCh ()) THEN
  4651. Err (EUnknown) ;
  4652. RETURN
  4653. END ;
  4654. GetWord () ;
  4655. SaveWord (nm) ;
  4656. DupTest (nm) ;
  4657. (* Two spellings: a plain constant `name = value', and a TYPED constant
  4658. `name : Type = value', which TP3 3.0 added (TPSRC7's constant reader
  4659. takes the type first and the value second). For a SCALAR type the
  4660. value still folds to an immediate, so the declared type is simply
  4661. recorded as the symbol's class - `FXMax : Char = 'G'' is a TChar
  4662. constant holding 71, and `writeln (FXMax)' prints G rather than 71.
  4663. A SET typed constant (`Numbers : set of Char = ['0'..'9']') is a value
  4664. with a layout, so it cannot fold: its bytes are emitted code-resident
  4665. and the name becomes an addressable value. See the storage decision
  4666. in CALC-COMPILE.md. An ARRAY or RECORD typed constant is still
  4667. refused loudly - those layouts come later. *)
  4668. typed := FALSE ;
  4669. setTyped := FALSE ;
  4670. arrTyped := FALSE ;
  4671. Skip () ;
  4672. IF CurCh () = ':' THEN
  4673. DropCh (GetCh ()) ;
  4674. ParseType (typCls, typSize, typElem) ;
  4675. IF OK () THEN
  4676. IF typCls = TSet THEN
  4677. setTyped := TRUE
  4678. ELSIF typCls = TArray THEN
  4679. arrTyped := TRUE
  4680. ELSIF typSize > 2 THEN
  4681. Err (ENoLib)
  4682. ELSE
  4683. typed := TRUE
  4684. END
  4685. END
  4686. END ;
  4687. IF OK () AND setTyped THEN
  4688. ExpectDelim ('=', ENoSemi) ;
  4689. IF RdSetLiteral (typElem, typSize, constBlob) THEN
  4690. soff := EmSetBlob (constBlob, typSize) ;
  4691. DropC (NewSym (nm, KVar, TSet, typSize, typElem, soff, 0, FALSE))
  4692. END
  4693. ELSIF OK () AND arrTyped THEN
  4694. (* array typed constant: `(v1, v2, ...)' in element order, each value
  4695. written little-endian in typElem bytes. CALC's is XPOS (seven
  4696. Integers, 14 bytes). An element that is a STRING (CALC.INC's
  4697. StandardfunctionNames) is a later increment, and is refused here. *)
  4698. ExpectDelim ('=', ENoSemi) ;
  4699. ExpectDelim ('(', ENoSemi) ;
  4700. nb := 0 ;
  4701. LOOP
  4702. RdConst (v, cls, isStr) ;
  4703. IF isStr OR (nb + typElem > 512) THEN
  4704. Err (ENoLib) ;
  4705. EXIT
  4706. END ;
  4707. w := VAL (CARDINAL, W16 (v)) ;
  4708. divi := 1 ;
  4709. k := 0 ;
  4710. WHILE k < typElem DO
  4711. constBlob [nb] := CHR ((w DIV divi) MOD 256) ;
  4712. divi := divi * 256 ;
  4713. INC (nb) ;
  4714. INC (k)
  4715. END ;
  4716. IF MatchDelim (',') THEN
  4717. (* another element *)
  4718. ELSE
  4719. EXIT
  4720. END
  4721. END ;
  4722. ExpectDelim (')', ENoSemi) ;
  4723. IF OK () THEN
  4724. soff := EmSetBlob (constBlob, typSize) ;
  4725. ci := NewSym (nm, KVar, TArray, typSize, typElem, soff, 0, FALSE) ;
  4726. symtab [ci].arrIdx := newArrIdx
  4727. END
  4728. ELSIF OK () THEN
  4729. ExpectDelim ('=', ENoSemi) ;
  4730. RdConst (v, cls, isStr) ;
  4731. IF isStr THEN
  4732. Err (ENoLib)
  4733. END ;
  4734. IF OK () THEN
  4735. IF typed THEN
  4736. cls := typCls
  4737. END ;
  4738. DropC (NewSym (nm, KConst, cls, 0, 0, 0, v, FALSE))
  4739. END
  4740. END ;
  4741. IF NOT MatchDelim (';') THEN
  4742. Err (ENoSemi) ;
  4743. RETURN
  4744. END
  4745. END
  4746. END DefConst ;
  4747. PROCEDURE DefLabelPart () ;
  4748. VAR nm : ARRAY [0..9] OF CHAR ;
  4749. n : CARDINAL ;
  4750. BEGIN
  4751. LOOP
  4752. Skip () ;
  4753. IF NOT Digit (CurCh ()) THEN
  4754. Err (EUnknown) ;
  4755. RETURN
  4756. END ;
  4757. n := 0 ;
  4758. WHILE Digit (CurCh ()) DO
  4759. n := n * 10 + (ORD (CurCh ()) - ORD ('0')) ;
  4760. DropCh (GetCh ())
  4761. END ;
  4762. NumToName (n, nm) ;
  4763. IF NOT Search (nm, n) THEN
  4764. DropC (NewSym (nm, KLabel, TScalar, 0, 0, 0, 0, FALSE))
  4765. END ;
  4766. IF NOT MatchDelim (',') THEN
  4767. IF MatchDelim (';') THEN
  4768. RETURN
  4769. END ;
  4770. Err (ENoSemi) ;
  4771. RETURN
  4772. END
  4773. END
  4774. END DefLabelPart ;
  4775. PROCEDURE IfMatchSemi () ;
  4776. BEGIN
  4777. IF NOT MatchDelim (';') THEN
  4778. Err (ENoSemi)
  4779. END
  4780. END IfMatchSemi ;
  4781. PROCEDURE SymEpi () ;
  4782. (* function result: AX := result var *)
  4783. BEGIN
  4784. IF curIsFunc THEN
  4785. IF OK () THEN
  4786. EmLoadVar (TRUE, symtab [resultVar].off, symtab [resultVar].size)
  4787. END
  4788. END
  4789. END SymEpi ;
  4790. PROCEDURE SlotSize (cls, size : CARDINAL) : CARDINAL ;
  4791. (* How many bytes a value parameter occupies in the callee's stack frame.
  4792. TP3's `tstscal' (TPSRC7 1243): a scalar-like parameter is AT LEAST two
  4793. bytes on the stack even when its type is one byte; anything larger spends
  4794. its own size. Generalised here so step 2 can put a string's 71 bytes on
  4795. the stack without changing what a scalar does today. *)
  4796. BEGIN
  4797. IF (cls = TScalar) OR (cls = TChar) OR (cls = TBool) OR (cls = TEnum) THEN
  4798. RETURN 2
  4799. END ;
  4800. RETURN size
  4801. END SlotSize ;
  4802. PROCEDURE ParamSlotBytes (e : SymEntry) : CARDINAL ;
  4803. (* The bytes a parameter occupies in the frame. A VAR parameter's slot is the
  4804. ADDRESS, always two bytes, whatever its type: `size' stays the type's width
  4805. so loads and stores know whether they read one byte or two. *)
  4806. BEGIN
  4807. IF e.isVar THEN
  4808. RETURN 2
  4809. END ;
  4810. RETURN SlotSize (e.cls, e.size)
  4811. END ParamSlotBytes ;
  4812. PROCEDURE ProcFunc () ;
  4813. (* PROCEDURE name (params) ; body | FUNCTION name (params) : type ; body *)
  4814. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  4815. idx, old : CARDINAL ;
  4816. tok, tok2 : CARDINAL ;
  4817. parmNm : ARRAY [0..MaxName] OF CHAR ;
  4818. cls, size, elem : CARDINAL ;
  4819. isFunc, groupVar : BOOLEAN ;
  4820. saveNest, saveLoc, saveRes, saveF : CARDINAL ;
  4821. saveLB, savePO : CARDINAL ;
  4822. nestMark : CARDINAL ; (* symTop just inside this procedure *)
  4823. i, first : CARDINAL ;
  4824. BEGIN
  4825. isFunc := curIsFunc ;
  4826. Skip () ; (* after the PROCEDURE/FUNCTION keyword *)
  4827. IF NOT Alpha (CurCh ()) THEN
  4828. Err (EUnknown) ;
  4829. RETURN
  4830. END ;
  4831. GetWord () ;
  4832. SaveWord (nm) ;
  4833. IF Search (nm, idx) AND (symtab [idx].tag = KProc)
  4834. AND (symtab [idx].fwd) THEN
  4835. old := idx
  4836. ELSIF Search (nm, idx) THEN
  4837. Err (EUnknown) ;
  4838. RETURN
  4839. ELSE
  4840. old := NewSym (nm, KProc, TNone, 0, 0, 0, 0, FALSE)
  4841. END ;
  4842. IF isFunc THEN
  4843. symtab [old].tag := KFunc
  4844. END ;
  4845. saveNest := lexnest ;
  4846. saveLoc := locFree ;
  4847. saveRes := resultVar ;
  4848. saveF := VAL (CARDINAL, ORD (curIsFunc)) ;
  4849. saveLB := locBytes ;
  4850. savePO := parmOff ;
  4851. INC (lexnest) ;
  4852. nestMark := symTop ; (* after the proc's own name, before its params *)
  4853. locFree := 0FFFFH ;
  4854. locBytes := 0 ;
  4855. parmOff := 4 ;
  4856. IF MatchDelim ('(') THEN
  4857. IF CurCh () # ')' THEN
  4858. LOOP
  4859. (* PeekKw, not MatchKey: MatchKey CONSUMES the word it reads, so
  4860. using it to test for VAR would eat the parameter's name. *)
  4861. PeekKw (tok) ;
  4862. groupVar := FALSE ;
  4863. IF tok = TkVar THEN
  4864. (* A by-reference parameter: the slot will hold an ADDRESS.
  4865. `size' still carries the type's own width, because the
  4866. callee's loads and stores must know whether they move one
  4867. byte or two. *)
  4868. DropB (MatchKey (tok)) ;
  4869. groupVar := TRUE
  4870. END ;
  4871. first := symTop ;
  4872. LOOP
  4873. Skip () ; (* blanks before the parameter name *)
  4874. IF NOT Alpha (CurCh ()) THEN
  4875. Err (EUnknown) ;
  4876. RETURN
  4877. END ;
  4878. GetWord () ;
  4879. SaveWord (parmNm) ;
  4880. DupTest (parmNm) ;
  4881. DropC (NewSym (parmNm, KVar, TNone, 0, 0, 0, 0, TRUE)) ;
  4882. IF NOT MatchDelim (',') THEN
  4883. EXIT
  4884. END
  4885. END ;
  4886. ExpectDelim (':', ENoSemi) ; (* formal is 'name : type' *)
  4887. ParseType (cls, size, elem) ;
  4888. IF groupVar AND ((size > 2) OR (cls = TString)) THEN
  4889. (* A VAR parameter of a record, array or string would need the
  4890. callee to address through a larger object (or a counted
  4891. string) than the scalar [BX] paths below; refusing is the
  4892. honest answer, not quietly passing it by value. *)
  4893. Err (ENoLib) ;
  4894. RETURN
  4895. END ;
  4896. IF (size > 2) AND (cls # TString) THEN
  4897. (* A string VALUE parameter is a whole-slot copy (n+1 bytes on
  4898. the stack); any other type wider than a word - a record, an
  4899. array, a set - is still refused. *)
  4900. Err (ENoLib) ;
  4901. RETURN
  4902. END ;
  4903. i := first ;
  4904. WHILE i < symTop DO
  4905. symtab [i].cls := cls ; symtab [i].size := size ;
  4906. symtab [i].elem := elem ;
  4907. symtab [i].off := parmOff ;
  4908. symtab [i].isVar := groupVar ;
  4909. IF groupVar THEN
  4910. parmOff := parmOff + 2 (* the address, whatever the type *)
  4911. ELSE
  4912. parmOff := parmOff + SlotSize (cls, size)
  4913. END ;
  4914. INC (i)
  4915. END ;
  4916. IF MatchDelim (')') THEN
  4917. EXIT
  4918. END ;
  4919. IF MatchDelim (';') THEN
  4920. (* next group *)
  4921. ELSIF MatchDelim (',') THEN
  4922. (* the older `name : type, name : type' spelling *)
  4923. ELSE
  4924. Err (ENoSemi) ;
  4925. EXIT
  4926. END
  4927. END
  4928. ELSE
  4929. DropCh (GetCh ())
  4930. END
  4931. END ;
  4932. (* TP3 lays a parameter list out BACKWARDS from BP+4: the LAST declared
  4933. parameter sits at BP+4 and each earlier one is 2 bytes farther from BP
  4934. (RESUME-TP3.md 3.11 - "le dernier paramètre déclaré est le plus proche
  4935. (BP+4)" - and the Code Generation Internals stack frame, "BP+4: last
  4936. parameter"). This is the other half of pushing the arguments as they
  4937. are parsed: the first argument is pushed first and so ends up farthest
  4938. from BP, which has to be the FIRST declared parameter's slot.
  4939. During the loop the offsets were provisional, in declaration order
  4940. (parmOff starts at 4 and grows by each parameter's SLOT size), so
  4941. parameter k sat at 4 + sum of the slots before it. For slot sizes s and
  4942. frame total T, the parameter's final base is
  4943. 4 + (T - prefix - s) = 8 + T - off - s, which sends the FIRST declared
  4944. parameter to the far end and the LAST to BP+4. With every slot 2 -
  4945. every scalar, which is all this compiler accepts today - that reduces
  4946. exactly to the old `parmOff + 2 - off`, so no existing frame moves.
  4947. A slot larger than 2 (a string's 71 bytes) falls out of the same
  4948. formula, and a VAR parameter is exactly 2 even when its TYPE is one
  4949. byte: ParamSlotBytes carries that rule.
  4950. The range is exactly the parameters: the only symbol created while the
  4951. list is read is the parameter itself (NewSym inside the loop),
  4952. ParseType creates no symbols, the procedure's own name predates
  4953. nestMark, and a function's result variable is created after this point. *)
  4954. i := nestMark ;
  4955. WHILE i < symTop DO
  4956. symtab [i].off := 8 + (parmOff - 4) - symtab [i].off
  4957. - ParamSlotBytes (symtab [i]) ;
  4958. INC (i)
  4959. END ;
  4960. (* Record the parameter list on the procedure symbol: a call site has to
  4961. know each argument's SLOT size to push and clean up the right number of
  4962. bytes. Only when this definition actually read a list - a FORWARD's
  4963. list is kept, and the later `function Expression;' that repeats only the
  4964. name must not wipe it. *)
  4965. IF symTop > nestMark THEN
  4966. symtab [old].parmFirst := nestMark ;
  4967. symtab [old].parmCount := symTop - nestMark
  4968. END ;
  4969. IF isFunc THEN
  4970. IF MatchDelim (':') THEN
  4971. ParseType (cls, size, elem)
  4972. ELSE
  4973. cls := TScalar ;
  4974. size := 2 ;
  4975. elem := 2
  4976. END ;
  4977. IF size > 2 THEN
  4978. Err (ENoLib) ;
  4979. RETURN
  4980. END ;
  4981. symtab [old].cls := cls ;
  4982. symtab [old].size := size ;
  4983. resultVar := NewSym (nm, KVar, cls, size, elem,
  4984. (locFree - size + 1) MOD 10000H, 0, TRUE) ;
  4985. symtab [old].resvar := resultVar ;
  4986. locFree := (locFree - size) MOD 10000H ;
  4987. locBytes := locBytes + size
  4988. END ;
  4989. IfMatchSemi () ;
  4990. PeekKw (tok2) ;
  4991. IF (tok2 = TkForward) OR (tok2 = TkExternal) THEN
  4992. DropB (MatchKey (tok2)) ;
  4993. symtab [old].fwd := TRUE ;
  4994. symtab [old].defnd := (tok2 = TkExternal) ;
  4995. IfMatchSemi () ;
  4996. HideLocals (nestMark) ; (* a FORWARD's parameters are not the
  4997. caller's to see either *)
  4998. lexnest := saveNest ;
  4999. locFree := saveLoc ;
  5000. resultVar := saveRes ;
  5001. curIsFunc := (saveF # 0) ;
  5002. locBytes := saveLB ;
  5003. parmOff := savePO ;
  5004. RETURN
  5005. END ;
  5006. (* body *)
  5007. symtab [old].goPos := pc ;
  5008. symtab [old].defnd := TRUE ;
  5009. EmPushBp () ;
  5010. EmMovBpSp () ;
  5011. DefPart () ; (* nested declarations; stops at BEGIN *)
  5012. IF locBytes > 0 THEN
  5013. EmSubSp (locBytes)
  5014. END ;
  5015. DropC (EmCall (TU_StackChk)) ;
  5016. Statmnt () ; (* body *)
  5017. IF OK () THEN
  5018. SymEpi () ;
  5019. EmLeave () ;
  5020. EmRet ()
  5021. END ;
  5022. (* patch pending forward calls to this proc *)
  5023. i := 0 ;
  5024. WHILE i < nPend DO
  5025. IF (pend [i].kind = 1) AND (pend [i].who = old) THEN
  5026. SetPatTgt (pend [i].place, symtab [old].goPos) ;
  5027. pend [i].kind := 99
  5028. END ;
  5029. INC (i)
  5030. END ;
  5031. HideLocals (nestMark) ; (* parameters and locals stop here *)
  5032. lexnest := saveNest ;
  5033. locFree := saveLoc ;
  5034. resultVar := saveRes ;
  5035. curIsFunc := (saveF # 0) ;
  5036. locBytes := saveLB ;
  5037. parmOff := savePO
  5038. END ProcFunc ;
  5039. PROCEDURE DefType () ;
  5040. (* 'name' '=' typeDef ; ... until a declaration keyword appears *)
  5041. VAR nm : ARRAY [0..MaxName] OF CHAR ;
  5042. cls, size, elem, tidx : CARDINAL ;
  5043. tok : CARDINAL ;
  5044. BEGIN
  5045. LOOP
  5046. PeekKw (tok) ;
  5047. IF tok # TkNone THEN
  5048. RETURN
  5049. END ;
  5050. Skip () ; (* after the TYPE keyword: skip blanks *)
  5051. IF NOT Alpha (CurCh ()) THEN
  5052. Err (EUnknown) ;
  5053. RETURN
  5054. END ;
  5055. GetWord () ;
  5056. SaveWord (nm) ;
  5057. DupTest (nm) ;
  5058. ExpectDelim ('=', ENoSemi) ;
  5059. ParseType (cls, size, elem) ;
  5060. IF NOT OK () THEN
  5061. RETURN
  5062. END ;
  5063. tidx := NewSym (nm, KType, cls, size, elem, 0, 0, FALSE) ;
  5064. IF cls = TEnum THEN
  5065. (* the enumeration's bounds, set by ParseType, belong to the type - so
  5066. `set of Attributes' can size its base (0..n-1, one byte) *)
  5067. symtab [tidx].lo := enumLo ;
  5068. symtab [tidx].hi := enumHi
  5069. END ;
  5070. IF cls = TRecord THEN
  5071. (* and a record's fields live in the field table; the type records
  5072. which range is its own *)
  5073. symtab [tidx].fldFirst := recFldFirst ;
  5074. symtab [tidx].fldLast := recFldLast
  5075. END ;
  5076. IF cls = TArray THEN
  5077. symtab [tidx].arrIdx := newArrIdx
  5078. END ;
  5079. DropC (tidx) ;
  5080. IF NOT MatchDelim (';') THEN
  5081. Err (ENoSemi) ;
  5082. RETURN
  5083. END
  5084. END
  5085. END DefType ;
  5086. PROCEDURE DefPart () ;
  5087. (* LABEL / CONST / TYPE / VAR / OVERLAY / PROC / FUNCTION / BEGIN *)
  5088. VAR tok : CARDINAL ;
  5089. BEGIN
  5090. LOOP
  5091. IF MatchDelim (';') THEN
  5092. (* separator between declarations *)
  5093. ELSE
  5094. PeekKw (tok) ;
  5095. IF tok = TkBegin THEN
  5096. RETURN
  5097. END ;
  5098. IF NOT MatchKey (tok) THEN
  5099. Err (EUnknown) ;
  5100. RETURN
  5101. END ;
  5102. CASE tok OF
  5103. TkLabel : DefLabelPart () ;
  5104. | TkConst : DefConst () ;
  5105. | TkType : DefType () ;
  5106. | TkVar : DefVar () ;
  5107. | TkOverlay :
  5108. LOOP
  5109. Skip () ;
  5110. IF CurCh () = ';' THEN
  5111. DropCh (GetCh ()) ;
  5112. EXIT
  5113. END ;
  5114. IF CurCh () = 0C THEN
  5115. Err (ENoSemi) ;
  5116. EXIT
  5117. END ;
  5118. DropCh (GetCh ())
  5119. END ;
  5120. | TkProcedure : curIsFunc := FALSE ; ProcFunc () ;
  5121. | TkFunction : curIsFunc := TRUE ; ProcFunc () ;
  5122. ELSE
  5123. Err (EUnknown) ;
  5124. RETURN
  5125. END ;
  5126. IF NOT OK () THEN
  5127. RETURN
  5128. END
  5129. END
  5130. END
  5131. END DefPart ;
  5132. (* ---------------------------------------------------------------- *)
  5133. (* driver (TPSRC7 compile) *)
  5134. (* ---------------------------------------------------------------- *)
  5135. PROCEDURE DefBuiltins () ;
  5136. (* The standard procedures. Without these, WRITELN is absent from the
  5137. symbol table, Statmnt's identifier branch fails its Search and every
  5138. program that prints anything dies with EUnknown (41) on the '(' after the
  5139. call name - the single remaining cause of failure in the fixture matrix.
  5140. Tagged KBuiltin (not KProc) because these are not called generically:
  5141. WRITE/WRITELN/READ/READLN need TP3's per-argument type dispatch
  5142. (IoCall), and HALT takes no argument at all. defnd is TRUE because the
  5143. entry point is known - there is no forward reference to patch. *)
  5144. VAR i : CARDINAL ;
  5145. BEGIN
  5146. i := NewSym ("WRITE" , KBuiltin, BI_Write , 0, 0, 0, 0, FALSE) ;
  5147. symtab [i].defnd := TRUE ;
  5148. symtab [i].goPos := TU_WrInt ;
  5149. i := NewSym ("WRITELN", KBuiltin, BI_WriteLn, 0, 0, 0, 0, FALSE) ;
  5150. symtab [i].defnd := TRUE ;
  5151. symtab [i].goPos := TU_WrInt ;
  5152. i := NewSym ("READ" , KBuiltin, BI_Read , 0, 0, 0, 0, FALSE) ;
  5153. symtab [i].defnd := TRUE ;
  5154. symtab [i].goPos := TU_RdInt ;
  5155. i := NewSym ("READLN" , KBuiltin, BI_ReadLn , 0, 0, 0, 0, FALSE) ;
  5156. symtab [i].defnd := TRUE ;
  5157. symtab [i].goPos := TU_RdInt ;
  5158. i := NewSym ("HALT" , KBuiltin, BI_Halt , 0, 0, 0, 0, FALSE) ;
  5159. symtab [i].defnd := TRUE ;
  5160. symtab [i].goPos := TU_Halt ;
  5161. i := NewSym ("LENGTH" , KBuiltin, BI_Length , 0, 0, 0, 0, FALSE) ;
  5162. symtab [i].defnd := TRUE ;
  5163. symtab [i].goPos := 0 ; (* inline: the length byte, no entry *)
  5164. (* The CRT identifiers. ClrScr and GotoXY emit real INT 10h code; the other
  5165. four are registered so they are recognised, and IoCall refuses them with
  5166. ENoLib - loud, not inert. *)
  5167. i := NewSym ("CLRSCR" , KBuiltin, BI_ClrScr , 0, 0, 0, 0, FALSE) ;
  5168. symtab [i].defnd := TRUE ;
  5169. i := NewSym ("GOTOXY" , KBuiltin, BI_GotoXY , 0, 0, 0, 0, FALSE) ;
  5170. symtab [i].defnd := TRUE ;
  5171. i := NewSym ("LOWVIDEO", KBuiltin, BI_LowVideo, 0, 0, 0, 0, FALSE) ;
  5172. symtab [i].defnd := TRUE ;
  5173. i := NewSym ("NORMVIDEO", KBuiltin, BI_NormVideo, 0, 0, 0, 0, FALSE) ;
  5174. symtab [i].defnd := TRUE ;
  5175. i := NewSym ("CLREOL" , KBuiltin, BI_ClrEol , 0, 0, 0, 0, FALSE) ;
  5176. symtab [i].defnd := TRUE ;
  5177. i := NewSym ("DELAY" , KBuiltin, BI_Delay , 0, 0, 0, 0, FALSE) ;
  5178. symtab [i].defnd := TRUE ;
  5179. i := NewSym ("KEYPRESSED", KBuiltin, BI_KeyPressed, 0, 0, 0, 0, FALSE) ;
  5180. symtab [i].defnd := TRUE ;
  5181. (* KBD: the console keyboard as a TEXT file. This runtime's read entries
  5182. already read the console, so `Read(Kbd, Ch)' drops the file argument and
  5183. reads a character exactly as `Read(Ch)' does. *)
  5184. i := NewSym ("KBD", KVar, TText, FileVarSize, 1, 0, 0, FALSE) ;
  5185. symtab [i].isKbd := TRUE
  5186. END DefBuiltins ;
  5187. PROCEDURE Inittur () ;
  5188. (* reset compiler state and define the standard types *)
  5189. VAR i, rt : CARDINAL ;
  5190. BEGIN
  5191. abortFac := FALSE ;
  5192. errNum := 0 ;
  5193. txerrPos := 0 ;
  5194. srcPos := 0 ;
  5195. srcLen := Length () ;
  5196. inclActive := FALSE ;
  5197. inclEnd := 0 ;
  5198. (* The image layout is
  5199. [JMP rel16][runtime][program header][program code]
  5200. The runtime is copied to the front, which is what the original does:
  5201. TPSRC7 "copyrt" runs REPZ MOVSB with SI=DI=0 and then "MOV pc,#$2D7C".
  5202. Because the runtime sits at (near) offset 0, every address the compiler
  5203. emits is already image-absolute - the data symbols' offsets, the TU_*
  5204. call targets and the rel16 displacements all need no relocation pass.
  5205. (The base shift would in fact cancel in EmCall's arithmetic, since both
  5206. sides of a CALL move together; making the offsets absolute just means
  5207. the linker has nothing to do but copy bytes.)
  5208. The JMP is new, and it is not cosmetic. A DOS .COM is entered at
  5209. CS:0100, i.e. FILE offset 0, and for a long time offset 0 held the
  5210. runtime's first bytes - so a .COM built by this compiler started by
  5211. executing initmem with AX holding whatever the loader left in it. Every
  5212. test up to that point checked bytes and never ran the thing, so it could
  5213. not see this. The jump is the program's entry and the runtime is
  5214. ordinary data to it; keeping the runtime at the front is what preserves
  5215. the no-relocation property, so the jump goes in front of the runtime
  5216. rather than the runtime being moved behind the program.
  5217. dc is put a fixed 4 KiB above the end of the program so that data cannot
  5218. collide with code in a single 64 KiB .COM segment. LIMITATION: a
  5219. program whose code exceeds 4 KiB overruns its own data area. TP3 had
  5220. overlay segments for this; we do not, and the check belongs where the
  5221. limit is documented rather than as a silent truncation. *)
  5222. RT_Build (EntSize) ;
  5223. rt := RT_Size () ;
  5224. IF rt >= MaxCode THEN
  5225. Err (EMemOvf) ; (* cannot happen: rt is 436 *)
  5226. RETURN
  5227. END ;
  5228. (* The entry jump, at image offset 0. See the layout note above: a DOS
  5229. .COM is entered at CS:0100, which is file offset 0, so whatever sits
  5230. at offset 0 is the program's first executed instruction. *)
  5231. (* The jump's three bytes are written out longhand rather than through
  5232. Eword, because Eword writes at pc and advances it, and pc is stale at
  5233. this point -- the operand landed wherever the last compile left pc. *)
  5234. cbuf [0] := 0E9H ; (* JMP rel16 *)
  5235. entRel := 1 ;
  5236. cbuf [entRel] := 0 ;
  5237. cbuf [entRel + 1] := 0 ;
  5238. i := EntSize ;
  5239. WHILE i - EntSize < rt DO
  5240. cbuf [i] := RT_Byte (i - EntSize) ;
  5241. INC (i)
  5242. END ;
  5243. pc := rt + EntSize ;
  5244. rtSz := rt + EntSize ;
  5245. dataBase := rtSz + 1000H ;
  5246. dc := dataBase ;
  5247. imgReady := TRUE ;
  5248. strTop := 0 ;
  5249. strCnt := 0 ;
  5250. rdStrX := 0 ;
  5251. varspc := 0 ;
  5252. symTop := 0 ;
  5253. nPatch := 0 ;
  5254. nPend := 0 ;
  5255. exitCnt := 0 ;
  5256. brkN := 0 ;
  5257. caseN := 0 ;
  5258. lexnest := 0 ;
  5259. curIsFunc := FALSE ;
  5260. resultVar := 0 ;
  5261. locFree := 0FFFFH ;
  5262. locBytes := 0 ;
  5263. parmOff := 4 ;
  5264. dirs.rng := TRUE ;
  5265. dirs.chk := TRUE ;
  5266. InitKeys () ;
  5267. DropC (NewSym ("INTEGER", KType, TScalar, 2, 2, 0, 0, FALSE)) ;
  5268. DropC (NewSym ("BYTE" , KType, TScalar, 1, 1, 0, 0, FALSE)) ;
  5269. DropC (NewSym ("CHAR" , KType, TChar, 1, 1, 0, 0, FALSE)) ;
  5270. DropC (NewSym ("BOOLEAN", KType, TBool , 1, 1, 0, 0, FALSE)) ;
  5271. DropC (NewSym ("REAL" , KType, TReal , 6, 6, 0, 0, FALSE)) ;
  5272. DropC (NewSym ("STRING" , KType, TString, 256, 1, 0, 0, FALSE)) ;
  5273. DropC (NewSym ("TRUE" , KConst, TBool, 1, 1, 0, 1, FALSE)) ;
  5274. DropC (NewSym ("FALSE" , KConst, TBool, 1, 1, 0, 0, FALSE)) ;
  5275. DefBuiltins () ;
  5276. tmpA := NewSym ("@@T1", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  5277. dc := dc + 2 ;
  5278. tmpB := NewSym ("@@T2", KVar, TScalar, 2, 2, dc, 0, FALSE) ;
  5279. dc := dc + 2 ;
  5280. (* The text attribute LowVideo/NormVideo set (default 7, written by the
  5281. prologue). One byte, and its address is baked into the clear sequences. *)
  5282. crtAttrOff := dc ;
  5283. DropC (NewSym ("@@ATTR", KVar, TScalar, 1, 1, dc, 0, FALSE)) ;
  5284. dc := dc + 1 ;
  5285. (* Runtime entry offsets, derived from the blob rather than assumed. This
  5286. has to happen after RT_Build, since RT_Entry only knows where the code
  5287. landed once the blob is assembled.
  5288. RT_Entry returns an IMAGE-ABSOLUTE address, already biased by the base
  5289. RT_Build was given, so nothing here has to know where the runtime
  5290. landed. It used to return a blob-relative offset, and the bias was
  5291. applied here instead - three bytes' worth, for the entry jump. With
  5292. that line missing, every CALL landed three bytes short, in the middle of
  5293. a neighbouring runtime entry, and a CALL into the middle of wrtin's
  5294. `INT 21h' behaves perfectly plausibly: the program runs, prints nothing
  5295. and hangs. Only running it finds that. *)
  5296. IF (RT_Entry (13) = 0) OR (RT_Entry (11) = 0) OR (RT_Entry (3) = 0) THEN
  5297. (* RT_Entry returns 0 for an unknown selector. initmem sits at 0
  5298. legitimately, so it cannot appear in this test - but wrtinl, rdln
  5299. and wrint never can, so catching them is enough to catch a runtime
  5300. that failed to build or a selector that went stale. This test is on
  5301. 0 is not a usable address here, since RT_Entry returns an
  5302. image-absolute address and the base is EntSize. *)
  5303. Err (EMemOvf)
  5304. END ;
  5305. TU_InitMem := RT_Entry (0) ;
  5306. TU_ProgEnd := RT_Entry (1) ;
  5307. TU_StackChk := RT_Entry (2) ;
  5308. TU_WrInt := RT_Entry (3) ;
  5309. TU_WrChar := RT_Entry (4) ;
  5310. TU_WrBool := RT_Entry (5) ;
  5311. TU_WrReal := RT_Entry (6) ;
  5312. TU_WrLn := RT_Entry (7) ;
  5313. TU_RdInt := RT_Entry (8) ;
  5314. TU_RdChar := RT_Entry (9) ;
  5315. TU_RdBool := RT_Entry (10) ;
  5316. TU_RdLn := RT_Entry (11) ;
  5317. TU_Halt := RT_Entry (12) ;
  5318. TU_WrInl := RT_Entry (13) ; (* inline string literal *)
  5319. TU_RdByte := RT_Entry (14) ; (* a BYTE read stores one byte *)
  5320. TU_WrStr := RT_Entry (15) ; (* a string variable is written through
  5321. the address on the stack *)
  5322. TU_RdStr := RT_Entry (16) ; (* readln(s)/read(s): TPSRC8 prdstr,
  5323. TPSRC4 xrdstr *)
  5324. TU_StrStore := RT_Entry (17) ; (* s := t: TPSRC8 asnvar, TPSRC2 strstore *)
  5325. TU_CmpStr := RT_Entry (18) ; (* string compare: TPSRC9 vcompare,
  5326. TPSRC2 cmpstr *)
  5327. TU_StrCat := RT_Entry (19) ; (* string concatenation: TPSRC2 xconcat *)
  5328. END Inittur ;
  5329. PROCEDURE HeadWord (VAR slot : CARDINAL) ;
  5330. BEGIN
  5331. slot := pc ;
  5332. Eword (0)
  5333. END HeadWord ;
  5334. PROCEDURE Compile (VAR errNo, errPos : CARDINAL) : BOOLEAN ;
  5335. VAR tok : CARDINAL ;
  5336. overProc : CARDINAL ;
  5337. hasProc : BOOLEAN ;
  5338. BEGIN
  5339. Inittur () ;
  5340. IF OK () THEN
  5341. (* Resolve every {$I} first: the parser (and DeclaresProc's lookahead)
  5342. must see one finished buffer. See ExpandIncludes. *)
  5343. ExpandIncludes ()
  5344. END ;
  5345. IF OK () THEN
  5346. (* program prologue: header words, CALL initmem, MOV BP,SP *)
  5347. HeadWord (hdrFlag) ;
  5348. HeadWord (hdrCS) ;
  5349. HeadWord (hdrDS) ;
  5350. HeadWord (hdrHeap) ;
  5351. HeadWord (hdrMax) ;
  5352. Eword (16) ; (* max open files *)
  5353. Eword (0) ; (* input buffer word *)
  5354. Eword (0) ; (* output buffer word *)
  5355. (* Here, and not one line earlier, is the first instruction of the
  5356. program: everything above is the header, which is DATA. The entry
  5357. jump has to land exactly here. Recorded rather than assumed, so that
  5358. a header that grows a word moves the target with it. *)
  5359. prologAt := pc ;
  5360. (* TU_InitMem takes the header offset in AX, not on the stack, so the
  5361. AX load has to precede the call. Previously the prologue called
  5362. offset 8 - which in this layout is the hdrMax word - and that was
  5363. coherent only because the runtime was not there. Now it is the
  5364. real header. *)
  5365. EmMovAxi ((rtSz + LoadBias) MOD 10000H) ;
  5366. DropC (EmCall (TU_InitMem)) ;
  5367. EmMovBpSp () ;
  5368. (* [@@ATTR] := 7 - the default text attribute, before any LowVideo or
  5369. NormVideo runs. The data area is zero-filled, and attribute 0 would
  5370. make every clear black-on-black. Through EmCrtSeq, not raw Ebyte:
  5371. Compile is not a one-line emitter, and the helper audit rightly
  5372. refuses to let a byte-emitting statement hide inside it. *)
  5373. EmCrtSeq (CrtLow) ;
  5374. IF MatchKey (tok) AND (tok = TkProgram) THEN
  5375. (* MatchKey stops right after "PROGRAM", so the optional program
  5376. name normally follows blanks. Skip them before testing for the
  5377. name: otherwise Alpha sees the blank, the name is never consumed
  5378. and IfMatchSemi reports ENoSemi at the name. *)
  5379. Skip () ;
  5380. IF Alpha (CurCh ()) THEN
  5381. GetWord ()
  5382. END ;
  5383. IF MatchDelim ('(') THEN
  5384. WHILE NOT MatchDelim (')') DO
  5385. IF Alpha (CurCh ()) THEN
  5386. GetWord ()
  5387. END ;
  5388. IF CurCh () = ',' THEN
  5389. DropCh (GetCh ())
  5390. END
  5391. END
  5392. END ;
  5393. IfMatchSemi ()
  5394. END ;
  5395. IF OK () THEN
  5396. (* Jump over the procedure bodies, if there are any. DefPart
  5397. compiles them HERE, between the prologue and the main statement
  5398. part, and there was no jump - so a program with a procedure fell
  5399. off the end of the prologue into the first procedure. See
  5400. DeclaresProc for why the condition is asked before DefPart runs
  5401. and not after. *)
  5402. hasProc := DeclaresProc () ;
  5403. IF hasProc THEN
  5404. overProc := EmJmpNear (0)
  5405. END ;
  5406. DefPart () ;
  5407. IF OK () THEN
  5408. (* A separate flag, NOT `overProc # 0`. EmJmpNear returns a
  5409. patch SLOT, and slot 0 is a perfectly ordinary slot - the
  5410. first forward jump in a program is slot 0. So a zero test
  5411. cannot tell "no forward jump" from "forward jump in slot 0",
  5412. it just skips the first patch, and the jump keeps its
  5413. placeholder target of 0. The program then jumped to image
  5414. offset 0, i.e. back to the entry jump, and ran the runtime
  5415. and the whole program again, forever. The slot is only
  5416. valid together with a boolean saying a slot was taken. *)
  5417. IF hasProc THEN
  5418. SetPatTgt (overProc, pc)
  5419. END ;
  5420. IF MatchKey (tok) AND (tok = TkBegin) THEN
  5421. Compound () ;
  5422. IF OK () THEN
  5423. EmXorAxAx () ;
  5424. DropC (EmCall (TU_ProgEnd)) ;
  5425. ResolvePatches () ;
  5426. (* Program-only sizes. The runtime is not part of the
  5427. program's code, and the fixture table has always meant
  5428. "the program's own code", so subtract it here rather
  5429. than making every expectation in expected.tsv wrong. *)
  5430. codeSz := pc - rtSz ;
  5431. dataSz := dc - dataBase ;
  5432. (* Header words. The layout is ours (the original's is
  5433. bigger and serves a real overlay loader), but
  5434. Runtime.EmitInitMem reads +4 and +8, so hdrDS and
  5435. hdrHeap must be the data base and the data end. *)
  5436. (* The entry jump's displacement. A .COM is entered at
  5437. CS:0100 = file offset 0, so the jump is the only thing
  5438. that decides where execution starts, and it has to land
  5439. on the START of the program code - the prologue, which is
  5440. at rtSz - not on pc, which is the END of it. (Patching
  5441. pc - EntSize, i.e. the end, lands one byte past the last
  5442. instruction, in the zero-filled code/data gap, where the
  5443. CPU slides through `ADD [BX+SI],AL' until it faults.)
  5444. The displacement is measured from the END of the jump,
  5445. and both addresses are image-absolute, so the load
  5446. segment cancels. *)
  5447. (* The entry jump's displacement. A .COM is entered at
  5448. CS:0100 = file offset 0, so this jump is the only thing
  5449. that decides where execution starts.
  5450. The target is prologAt - where the prologue ACTUALLY
  5451. began, recorded before the header words were emitted,
  5452. and the header is 16 bytes long, so this is rtSz + 16 and
  5453. NOT rtSz. Landing on rtSz lands on the HEADER, which is
  5454. data, and the CPU then decodes sixteen bytes of it as
  5455. instructions. That failure is spectacularly
  5456. non-deterministic across programs: 01 00 is
  5457. `ADD [BX+SI],AX' and is harmless, so writeln('hi') ran
  5458. fine by sliding through the header into the prologue,
  5459. while t07's hdrHeap word 90 12 decodes as a LOCK-prefixed
  5460. ADD whose displacement crosses a page and faults, and the
  5461. program hung with no output at all. Both looked like
  5462. "the jump is in the right area". Recording the position
  5463. rather than assuming it means a future header that grows
  5464. a word cannot silently reintroduce this. *)
  5465. PatchWord (entRel, (prologAt - EntSize) MOD 10000H) ;
  5466. PatchWord (hdrFlag, 1) ;
  5467. (* Every OFFSET field in the header is a segment offset,
  5468. i.e. an image offset plus LoadBias - one convention for
  5469. the whole structure, so that nobody has to remember
  5470. which of these five words is numbered which way.
  5471. hdrFlag 1 set, so a loader can recognise the header
  5472. hdrCS end of the generated code
  5473. hdrDS first byte of the data area <- read by initmem
  5474. hdrHeap one past the last <- read by initmem
  5475. hdrMax 0 (no overlay loader yet)
  5476. hdrDS and hdrHeap are the two that are CONSUMED, and
  5477. omitting the bias there is a silent no-op: initmem would
  5478. clear a range starting 0100h below the data, off the
  5479. front of the image, and never reach the globals at the
  5480. end. Nothing crashes, and the globals keep whatever the
  5481. loader left in them. *)
  5482. PatchWord (hdrCS, pc + LoadBias) ;
  5483. PatchWord (hdrDS, dataBase + LoadBias) ;
  5484. PatchWord (hdrHeap, dc + LoadBias) ;
  5485. PatchWord (hdrMax, 0)
  5486. END
  5487. ELSE
  5488. Err (EUnknown)
  5489. END
  5490. END
  5491. END
  5492. END ;
  5493. IF NOT MatchDelim ('.') THEN
  5494. Err (EPointExp)
  5495. END ;
  5496. IF abortFac THEN
  5497. errNo := errNum ; (* was "errNo := errNo": a self-assignment,
  5498. because the formal shadowed the module
  5499. variable, so the error code always
  5500. reached the caller as 0 *)
  5501. errPos := txerrPos ;
  5502. RETURN FALSE
  5503. END ;
  5504. errNo := 0 ;
  5505. errPos := 0 ;
  5506. RETURN TRUE
  5507. END Compile ;
  5508. PROCEDURE CodeBytes () : CARDINAL ;
  5509. BEGIN
  5510. RETURN codeSz
  5511. END CodeBytes ;
  5512. PROCEDURE DataBytes () : CARDINAL ;
  5513. BEGIN
  5514. RETURN dataSz
  5515. END DataBytes ;
  5516. PROCEDURE ImageBytes () : CARDINAL ;
  5517. (* Total linked image size: rtSz (the runtime) + CodeBytes (the program).
  5518. The program is NOT padded out to the data base here - the linker does
  5519. that, and only it knows the .COM's final size. *)
  5520. BEGIN
  5521. RETURN rtSz + codeSz
  5522. END ImageBytes ;
  5523. PROCEDURE DataBase () : CARDINAL ;
  5524. (* image-absolute offset at which the data area begins (rtSz + 1000H). The
  5525. linker must place the program's data here and zero-fill from the end of
  5526. the code up to it. *)
  5527. BEGIN
  5528. RETURN dataBase
  5529. END DataBase ;
  5530. PROCEDURE ImageByteAt (i : CARDINAL) : BYTE ;
  5531. (* i-th byte of the WHOLE image, runtime included, so a test can check the
  5532. real thing a .COM would contain. Returns 0 past the end. *)
  5533. BEGIN
  5534. IF i >= rtSz + codeSz THEN
  5535. RETURN 0
  5536. END ;
  5537. RETURN cbuf [i]
  5538. END ImageByteAt ;
  5539. PROCEDURE CodeByteAt (i : CARDINAL) : BYTE ;
  5540. (* i-th byte of the emitted image, for test harnesses that need to check
  5541. the generated 8086 code rather than just its size. Returns 0 past the
  5542. end of the image. *)
  5543. BEGIN
  5544. IF i >= codeSz THEN
  5545. RETURN 0
  5546. END ;
  5547. RETURN cbuf [i]
  5548. END CodeByteAt ;
  5549. END Compiler.