Compiler.mod 192 KB

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