Compiler.mod 271 KB

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