Compiler.mod 223 KB

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