Compiler.mod 259 KB

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