Compiler.mod 191 KB

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