Compiler.mod 232 KB

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