Compiler.mod 249 KB

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