Compiler.mod 204 KB

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