Compiler.mod 246 KB

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