Compiler.mod 315 KB

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