lemon.c 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889
  1. /*
  2. ** This file contains all sources (including headers) to the LEMON
  3. ** LALR(1) parser generator. The sources have been combined into a
  4. ** single file to make it easy to include LEMON in the source tree
  5. ** and Makefile of another program.
  6. **
  7. ** The author of this program disclaims copyright.
  8. */
  9. #include <stdio.h>
  10. #include <stdarg.h>
  11. #include <string.h>
  12. #include <ctype.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #ifndef __WIN32__
  16. # if defined(_WIN32) || defined(WIN32)
  17. # define __WIN32__
  18. # endif
  19. #endif
  20. #ifdef __WIN32__
  21. extern int access();
  22. #else
  23. #include <unistd.h>
  24. #endif
  25. /* #define PRIVATE static */
  26. #define PRIVATE
  27. #ifdef TEST
  28. #define MAXRHS 5 /* Set low to exercise exception code */
  29. #else
  30. #define MAXRHS 1000
  31. #endif
  32. static char *msort(char*,char**,int(*)(const char*,const char*));
  33. /*
  34. ** Compilers are getting increasingly pedantic about type conversions
  35. ** as C evolves ever closer to Ada.... To work around the latest problems
  36. ** we have to define the following variant of strlen().
  37. */
  38. #define lemonStrlen(X) ((int)strlen(X))
  39. static struct action *Action_new(void);
  40. static struct action *Action_sort(struct action *);
  41. /********** From the file "build.h" ************************************/
  42. void FindRulePrecedences();
  43. void FindFirstSets();
  44. void FindStates();
  45. void FindLinks();
  46. void FindFollowSets();
  47. void FindActions();
  48. /********* From the file "configlist.h" *********************************/
  49. void Configlist_init(/* void */);
  50. struct config *Configlist_add(/* struct rule *, int */);
  51. struct config *Configlist_addbasis(/* struct rule *, int */);
  52. void Configlist_closure(/* void */);
  53. void Configlist_sort(/* void */);
  54. void Configlist_sortbasis(/* void */);
  55. struct config *Configlist_return(/* void */);
  56. struct config *Configlist_basis(/* void */);
  57. void Configlist_eat(/* struct config * */);
  58. void Configlist_reset(/* void */);
  59. /********* From the file "error.h" ***************************************/
  60. void ErrorMsg(const char *, int,const char *, ...);
  61. /****** From the file "option.h" ******************************************/
  62. struct s_options {
  63. enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
  64. OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
  65. char *label;
  66. char *arg;
  67. char *message;
  68. };
  69. int OptInit(/* char**,struct s_options*,FILE* */);
  70. int OptNArgs(/* void */);
  71. char *OptArg(/* int */);
  72. void OptErr(/* int */);
  73. void OptPrint(/* void */);
  74. /******** From the file "parse.h" *****************************************/
  75. void Parse(/* struct lemon *lemp */);
  76. /********* From the file "plink.h" ***************************************/
  77. struct plink *Plink_new(/* void */);
  78. void Plink_add(/* struct plink **, struct config * */);
  79. void Plink_copy(/* struct plink **, struct plink * */);
  80. void Plink_delete(/* struct plink * */);
  81. /********** From the file "report.h" *************************************/
  82. void Reprint(/* struct lemon * */);
  83. void ReportOutput(/* struct lemon * */);
  84. void ReportTable(/* struct lemon * */);
  85. void ReportHeader(/* struct lemon * */);
  86. void CompressTables(/* struct lemon * */);
  87. void ResortStates(/* struct lemon * */);
  88. /********** From the file "set.h" ****************************************/
  89. void SetSize(/* int N */); /* All sets will be of size N */
  90. char *SetNew(/* void */); /* A new set for element 0..N */
  91. void SetFree(/* char* */); /* Deallocate a set */
  92. int SetAdd(/* char*,int */); /* Add element to a set */
  93. int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
  94. #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
  95. /********** From the file "struct.h" *************************************/
  96. /*
  97. ** Principal data structures for the LEMON parser generator.
  98. */
  99. typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
  100. /* Symbols (terminals and nonterminals) of the grammar are stored
  101. ** in the following: */
  102. struct symbol {
  103. char *name; /* Name of the symbol */
  104. int index; /* Index number for this symbol */
  105. enum {
  106. TERMINAL,
  107. NONTERMINAL,
  108. MULTITERMINAL
  109. } type; /* Symbols are all either TERMINALS or NTs */
  110. struct rule *rule; /* Linked list of rules of this (if an NT) */
  111. struct symbol *fallback; /* fallback token in case this token doesn't parse */
  112. int prec; /* Precedence if defined (-1 otherwise) */
  113. enum e_assoc {
  114. LEFT,
  115. RIGHT,
  116. NONE,
  117. UNK
  118. } assoc; /* Associativity if precedence is defined */
  119. char *firstset; /* First-set for all rules of this symbol */
  120. Boolean lambda; /* True if NT and can generate an empty string */
  121. int useCnt; /* Number of times used */
  122. char *destructor; /* Code which executes whenever this symbol is
  123. ** popped from the stack during error processing */
  124. int destLineno; /* Line number for start of destructor */
  125. char *datatype; /* The data type of information held by this
  126. ** object. Only used if type==NONTERMINAL */
  127. int dtnum; /* The data type number. In the parser, the value
  128. ** stack is a union. The .yy%d element of this
  129. ** union is the correct data type for this object */
  130. /* The following fields are used by MULTITERMINALs only */
  131. int nsubsym; /* Number of constituent symbols in the MULTI */
  132. struct symbol **subsym; /* Array of constituent symbols */
  133. };
  134. /* Each production rule in the grammar is stored in the following
  135. ** structure. */
  136. struct rule {
  137. struct symbol *lhs; /* Left-hand side of the rule */
  138. char *lhsalias; /* Alias for the LHS (NULL if none) */
  139. int lhsStart; /* True if left-hand side is the start symbol */
  140. int ruleline; /* Line number for the rule */
  141. int nrhs; /* Number of RHS symbols */
  142. struct symbol **rhs; /* The RHS symbols */
  143. char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
  144. int line; /* Line number at which code begins */
  145. char *code; /* The code executed when this rule is reduced */
  146. struct symbol *precsym; /* Precedence symbol for this rule */
  147. int index; /* An index number for this rule */
  148. Boolean canReduce; /* True if this rule is ever reduced */
  149. struct rule *nextlhs; /* Next rule with the same LHS */
  150. struct rule *next; /* Next rule in the global list */
  151. };
  152. /* A configuration is a production rule of the grammar together with
  153. ** a mark (dot) showing how much of that rule has been processed so far.
  154. ** Configurations also contain a follow-set which is a list of terminal
  155. ** symbols which are allowed to immediately follow the end of the rule.
  156. ** Every configuration is recorded as an instance of the following: */
  157. struct config {
  158. struct rule *rp; /* The rule upon which the configuration is based */
  159. int dot; /* The parse point */
  160. char *fws; /* Follow-set for this configuration only */
  161. struct plink *fplp; /* Follow-set forward propagation links */
  162. struct plink *bplp; /* Follow-set backwards propagation links */
  163. struct state *stp; /* Pointer to state which contains this */
  164. enum {
  165. COMPLETE, /* The status is used during followset and */
  166. INCOMPLETE /* shift computations */
  167. } status;
  168. struct config *next; /* Next configuration in the state */
  169. struct config *bp; /* The next basis configuration */
  170. };
  171. /* Every shift or reduce operation is stored as one of the following */
  172. struct action {
  173. struct symbol *sp; /* The look-ahead symbol */
  174. enum e_action {
  175. SHIFT,
  176. ACCEPT,
  177. REDUCE,
  178. ERROR,
  179. SSCONFLICT, /* A shift/shift conflict */
  180. SRCONFLICT, /* Was a reduce, but part of a conflict */
  181. RRCONFLICT, /* Was a reduce, but part of a conflict */
  182. SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
  183. RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
  184. NOT_USED /* Deleted by compression */
  185. } type;
  186. union {
  187. struct state *stp; /* The new state, if a shift */
  188. struct rule *rp; /* The rule, if a reduce */
  189. } x;
  190. struct action *next; /* Next action for this state */
  191. struct action *collide; /* Next action with the same hash */
  192. };
  193. /* Each state of the generated parser's finite state machine
  194. ** is encoded as an instance of the following structure. */
  195. struct state {
  196. struct config *bp; /* The basis configurations for this state */
  197. struct config *cfp; /* All configurations in this set */
  198. int statenum; /* Sequential number for this state */
  199. struct action *ap; /* Array of actions for this state */
  200. int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
  201. int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
  202. int iDflt; /* Default action */
  203. };
  204. #define NO_OFFSET (-2147483647)
  205. /* A followset propagation link indicates that the contents of one
  206. ** configuration followset should be propagated to another whenever
  207. ** the first changes. */
  208. struct plink {
  209. struct config *cfp; /* The configuration to which linked */
  210. struct plink *next; /* The next propagate link */
  211. };
  212. /* The state vector for the entire parser generator is recorded as
  213. ** follows. (LEMON uses no global variables and makes little use of
  214. ** static variables. Fields in the following structure can be thought
  215. ** of as begin global variables in the program.) */
  216. struct lemon {
  217. struct state **sorted; /* Table of states sorted by state number */
  218. struct rule *rule; /* List of all rules */
  219. int nstate; /* Number of states */
  220. int nrule; /* Number of rules */
  221. int nsymbol; /* Number of terminal and nonterminal symbols */
  222. int nterminal; /* Number of terminal symbols */
  223. struct symbol **symbols; /* Sorted array of pointers to symbols */
  224. int errorcnt; /* Number of errors */
  225. struct symbol *errsym; /* The error symbol */
  226. struct symbol *wildcard; /* Token that matches anything */
  227. char *name; /* Name of the generated parser */
  228. char *arg; /* Declaration of the 3th argument to parser */
  229. char *tokentype; /* Type of terminal symbols in the parser stack */
  230. char *vartype; /* The default type of non-terminal symbols */
  231. char *start; /* Name of the start symbol for the grammar */
  232. char *stacksize; /* Size of the parser stack */
  233. char *include; /* Code to put at the start of the C file */
  234. char *error; /* Code to execute when an error is seen */
  235. char *overflow; /* Code to execute on a stack overflow */
  236. char *failure; /* Code to execute on parser failure */
  237. char *accept; /* Code to execute when the parser excepts */
  238. char *extracode; /* Code appended to the generated file */
  239. char *tokendest; /* Code to execute to destroy token data */
  240. char *vardest; /* Code for the default non-terminal destructor */
  241. char *filename; /* Name of the input file */
  242. char *outname; /* Name of the current output file */
  243. char *tokenprefix; /* A prefix added to token names in the .h file */
  244. int nconflict; /* Number of parsing conflicts */
  245. int tablesize; /* Size of the parse tables */
  246. int basisflag; /* Print only basis configurations */
  247. int has_fallback; /* True if any %fallback is seen in the grammar */
  248. int nolinenosflag; /* True if #line statements should not be printed */
  249. char *argv0; /* Name of the program */
  250. };
  251. #define MemoryCheck(X) if((X)==0){ \
  252. extern void memory_error(); \
  253. memory_error(); \
  254. }
  255. /**************** From the file "table.h" *********************************/
  256. /*
  257. ** All code in this file has been automatically generated
  258. ** from a specification in the file
  259. ** "table.q"
  260. ** by the associative array code building program "aagen".
  261. ** Do not edit this file! Instead, edit the specification
  262. ** file, then rerun aagen.
  263. */
  264. /*
  265. ** Code for processing tables in the LEMON parser generator.
  266. */
  267. /* Routines for handling a strings */
  268. char *Strsafe();
  269. void Strsafe_init(/* void */);
  270. int Strsafe_insert(/* char * */);
  271. char *Strsafe_find(/* char * */);
  272. /* Routines for handling symbols of the grammar */
  273. struct symbol *Symbol_new();
  274. int Symbolcmpp(/* struct symbol **, struct symbol ** */);
  275. void Symbol_init(/* void */);
  276. int Symbol_insert(/* struct symbol *, char * */);
  277. struct symbol *Symbol_find(/* char * */);
  278. struct symbol *Symbol_Nth(/* int */);
  279. int Symbol_count(/* */);
  280. struct symbol **Symbol_arrayof(/* */);
  281. /* Routines to manage the state table */
  282. int Configcmp(/* struct config *, struct config * */);
  283. struct state *State_new();
  284. void State_init(/* void */);
  285. int State_insert(/* struct state *, struct config * */);
  286. struct state *State_find(/* struct config * */);
  287. struct state **State_arrayof(/* */);
  288. /* Routines used for efficiency in Configlist_add */
  289. void Configtable_init(/* void */);
  290. int Configtable_insert(/* struct config * */);
  291. struct config *Configtable_find(/* struct config * */);
  292. void Configtable_clear(/* int(*)(struct config *) */);
  293. /****************** From the file "action.c" *******************************/
  294. /*
  295. ** Routines processing parser actions in the LEMON parser generator.
  296. */
  297. /* Allocate a new parser action */
  298. static struct action *Action_new(void){
  299. static struct action *freelist = 0;
  300. struct action *new;
  301. if( freelist==0 ){
  302. int i;
  303. int amt = 100;
  304. freelist = (struct action *)calloc(amt, sizeof(struct action));
  305. if( freelist==0 ){
  306. fprintf(stderr,"Unable to allocate memory for a new parser action.");
  307. exit(1);
  308. }
  309. for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
  310. freelist[amt-1].next = 0;
  311. }
  312. new = freelist;
  313. freelist = freelist->next;
  314. return new;
  315. }
  316. /* Compare two actions for sorting purposes. Return negative, zero, or
  317. ** positive if the first action is less than, equal to, or greater than
  318. ** the first
  319. */
  320. static int actioncmp(
  321. struct action *ap1,
  322. struct action *ap2
  323. ){
  324. int rc;
  325. rc = ap1->sp->index - ap2->sp->index;
  326. if( rc==0 ){
  327. rc = (int)ap1->type - (int)ap2->type;
  328. }
  329. if( rc==0 && ap1->type==REDUCE ){
  330. rc = ap1->x.rp->index - ap2->x.rp->index;
  331. }
  332. return rc;
  333. }
  334. /* Sort parser actions */
  335. static struct action *Action_sort(
  336. struct action *ap
  337. ){
  338. ap = (struct action *)msort((char *)ap,(char **)&ap->next,
  339. (int(*)(const char*,const char*))actioncmp);
  340. return ap;
  341. }
  342. void Action_add(app,type,sp,arg)
  343. struct action **app;
  344. enum e_action type;
  345. struct symbol *sp;
  346. char *arg;
  347. {
  348. struct action *new;
  349. new = Action_new();
  350. new->next = *app;
  351. *app = new;
  352. new->type = type;
  353. new->sp = sp;
  354. if( type==SHIFT ){
  355. new->x.stp = (struct state *)arg;
  356. }else{
  357. new->x.rp = (struct rule *)arg;
  358. }
  359. }
  360. /********************** New code to implement the "acttab" module ***********/
  361. /*
  362. ** This module implements routines use to construct the yy_action[] table.
  363. */
  364. /*
  365. ** The state of the yy_action table under construction is an instance of
  366. ** the following structure
  367. */
  368. typedef struct acttab acttab;
  369. struct acttab {
  370. int nAction; /* Number of used slots in aAction[] */
  371. int nActionAlloc; /* Slots allocated for aAction[] */
  372. struct {
  373. int lookahead; /* Value of the lookahead token */
  374. int action; /* Action to take on the given lookahead */
  375. } *aAction, /* The yy_action[] table under construction */
  376. *aLookahead; /* A single new transaction set */
  377. int mnLookahead; /* Minimum aLookahead[].lookahead */
  378. int mnAction; /* Action associated with mnLookahead */
  379. int mxLookahead; /* Maximum aLookahead[].lookahead */
  380. int nLookahead; /* Used slots in aLookahead[] */
  381. int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
  382. };
  383. /* Return the number of entries in the yy_action table */
  384. #define acttab_size(X) ((X)->nAction)
  385. /* The value for the N-th entry in yy_action */
  386. #define acttab_yyaction(X,N) ((X)->aAction[N].action)
  387. /* The value for the N-th entry in yy_lookahead */
  388. #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
  389. /* Free all memory associated with the given acttab */
  390. void acttab_free(acttab *p){
  391. free( p->aAction );
  392. free( p->aLookahead );
  393. free( p );
  394. }
  395. /* Allocate a new acttab structure */
  396. acttab *acttab_alloc(void){
  397. acttab *p = calloc( 1, sizeof(*p) );
  398. if( p==0 ){
  399. fprintf(stderr,"Unable to allocate memory for a new acttab.");
  400. exit(1);
  401. }
  402. memset(p, 0, sizeof(*p));
  403. return p;
  404. }
  405. /* Add a new action to the current transaction set
  406. */
  407. void acttab_action(acttab *p, int lookahead, int action){
  408. if( p->nLookahead>=p->nLookaheadAlloc ){
  409. p->nLookaheadAlloc += 25;
  410. p->aLookahead = realloc( p->aLookahead,
  411. sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
  412. if( p->aLookahead==0 ){
  413. fprintf(stderr,"malloc failed\n");
  414. exit(1);
  415. }
  416. }
  417. if( p->nLookahead==0 ){
  418. p->mxLookahead = lookahead;
  419. p->mnLookahead = lookahead;
  420. p->mnAction = action;
  421. }else{
  422. if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
  423. if( p->mnLookahead>lookahead ){
  424. p->mnLookahead = lookahead;
  425. p->mnAction = action;
  426. }
  427. }
  428. p->aLookahead[p->nLookahead].lookahead = lookahead;
  429. p->aLookahead[p->nLookahead].action = action;
  430. p->nLookahead++;
  431. }
  432. /*
  433. ** Add the transaction set built up with prior calls to acttab_action()
  434. ** into the current action table. Then reset the transaction set back
  435. ** to an empty set in preparation for a new round of acttab_action() calls.
  436. **
  437. ** Return the offset into the action table of the new transaction.
  438. */
  439. int acttab_insert(acttab *p){
  440. int i, j, k, n;
  441. assert( p->nLookahead>0 );
  442. /* Make sure we have enough space to hold the expanded action table
  443. ** in the worst case. The worst case occurs if the transaction set
  444. ** must be appended to the current action table
  445. */
  446. n = p->mxLookahead + 1;
  447. if( p->nAction + n >= p->nActionAlloc ){
  448. int oldAlloc = p->nActionAlloc;
  449. p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
  450. p->aAction = realloc( p->aAction,
  451. sizeof(p->aAction[0])*p->nActionAlloc);
  452. if( p->aAction==0 ){
  453. fprintf(stderr,"malloc failed\n");
  454. exit(1);
  455. }
  456. for(i=oldAlloc; i<p->nActionAlloc; i++){
  457. p->aAction[i].lookahead = -1;
  458. p->aAction[i].action = -1;
  459. }
  460. }
  461. /* Scan the existing action table looking for an offset where we can
  462. ** insert the current transaction set. Fall out of the loop when that
  463. ** offset is found. In the worst case, we fall out of the loop when
  464. ** i reaches p->nAction, which means we append the new transaction set.
  465. **
  466. ** i is the index in p->aAction[] where p->mnLookahead is inserted.
  467. */
  468. for(i=0; i<p->nAction+p->mnLookahead; i++){
  469. if( p->aAction[i].lookahead<0 ){
  470. for(j=0; j<p->nLookahead; j++){
  471. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  472. if( k<0 ) break;
  473. if( p->aAction[k].lookahead>=0 ) break;
  474. }
  475. if( j<p->nLookahead ) continue;
  476. for(j=0; j<p->nAction; j++){
  477. if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
  478. }
  479. if( j==p->nAction ){
  480. break; /* Fits in empty slots */
  481. }
  482. }else if( p->aAction[i].lookahead==p->mnLookahead ){
  483. if( p->aAction[i].action!=p->mnAction ) continue;
  484. for(j=0; j<p->nLookahead; j++){
  485. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  486. if( k<0 || k>=p->nAction ) break;
  487. if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
  488. if( p->aLookahead[j].action!=p->aAction[k].action ) break;
  489. }
  490. if( j<p->nLookahead ) continue;
  491. n = 0;
  492. for(j=0; j<p->nAction; j++){
  493. if( p->aAction[j].lookahead<0 ) continue;
  494. if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
  495. }
  496. if( n==p->nLookahead ){
  497. break; /* Same as a prior transaction set */
  498. }
  499. }
  500. }
  501. /* Insert transaction set at index i. */
  502. for(j=0; j<p->nLookahead; j++){
  503. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  504. p->aAction[k] = p->aLookahead[j];
  505. if( k>=p->nAction ) p->nAction = k+1;
  506. }
  507. p->nLookahead = 0;
  508. /* Return the offset that is added to the lookahead in order to get the
  509. ** index into yy_action of the action */
  510. return i - p->mnLookahead;
  511. }
  512. /********************** From the file "build.c" *****************************/
  513. /*
  514. ** Routines to construction the finite state machine for the LEMON
  515. ** parser generator.
  516. */
  517. /* Find a precedence symbol of every rule in the grammar.
  518. **
  519. ** Those rules which have a precedence symbol coded in the input
  520. ** grammar using the "[symbol]" construct will already have the
  521. ** rp->precsym field filled. Other rules take as their precedence
  522. ** symbol the first RHS symbol with a defined precedence. If there
  523. ** are not RHS symbols with a defined precedence, the precedence
  524. ** symbol field is left blank.
  525. */
  526. void FindRulePrecedences(xp)
  527. struct lemon *xp;
  528. {
  529. struct rule *rp;
  530. for(rp=xp->rule; rp; rp=rp->next){
  531. if( rp->precsym==0 ){
  532. int i, j;
  533. for(i=0; i<rp->nrhs && rp->precsym==0; i++){
  534. struct symbol *sp = rp->rhs[i];
  535. if( sp->type==MULTITERMINAL ){
  536. for(j=0; j<sp->nsubsym; j++){
  537. if( sp->subsym[j]->prec>=0 ){
  538. rp->precsym = sp->subsym[j];
  539. break;
  540. }
  541. }
  542. }else if( sp->prec>=0 ){
  543. rp->precsym = rp->rhs[i];
  544. }
  545. }
  546. }
  547. }
  548. return;
  549. }
  550. /* Find all nonterminals which will generate the empty string.
  551. ** Then go back and compute the first sets of every nonterminal.
  552. ** The first set is the set of all terminal symbols which can begin
  553. ** a string generated by that nonterminal.
  554. */
  555. void FindFirstSets(lemp)
  556. struct lemon *lemp;
  557. {
  558. int i, j;
  559. struct rule *rp;
  560. int progress;
  561. for(i=0; i<lemp->nsymbol; i++){
  562. lemp->symbols[i]->lambda = LEMON_FALSE;
  563. }
  564. for(i=lemp->nterminal; i<lemp->nsymbol; i++){
  565. lemp->symbols[i]->firstset = SetNew();
  566. }
  567. /* First compute all lambdas */
  568. do{
  569. progress = 0;
  570. for(rp=lemp->rule; rp; rp=rp->next){
  571. if( rp->lhs->lambda ) continue;
  572. for(i=0; i<rp->nrhs; i++){
  573. struct symbol *sp = rp->rhs[i];
  574. if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
  575. }
  576. if( i==rp->nrhs ){
  577. rp->lhs->lambda = LEMON_TRUE;
  578. progress = 1;
  579. }
  580. }
  581. }while( progress );
  582. /* Now compute all first sets */
  583. do{
  584. struct symbol *s1, *s2;
  585. progress = 0;
  586. for(rp=lemp->rule; rp; rp=rp->next){
  587. s1 = rp->lhs;
  588. for(i=0; i<rp->nrhs; i++){
  589. s2 = rp->rhs[i];
  590. if( s2->type==TERMINAL ){
  591. progress += SetAdd(s1->firstset,s2->index);
  592. break;
  593. }else if( s2->type==MULTITERMINAL ){
  594. for(j=0; j<s2->nsubsym; j++){
  595. progress += SetAdd(s1->firstset,s2->subsym[j]->index);
  596. }
  597. break;
  598. }else if( s1==s2 ){
  599. if( s1->lambda==LEMON_FALSE ) break;
  600. }else{
  601. progress += SetUnion(s1->firstset,s2->firstset);
  602. if( s2->lambda==LEMON_FALSE ) break;
  603. }
  604. }
  605. }
  606. }while( progress );
  607. return;
  608. }
  609. /* Compute all LR(0) states for the grammar. Links
  610. ** are added to between some states so that the LR(1) follow sets
  611. ** can be computed later.
  612. */
  613. PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
  614. void FindStates(lemp)
  615. struct lemon *lemp;
  616. {
  617. struct symbol *sp;
  618. struct rule *rp;
  619. Configlist_init();
  620. /* Find the start symbol */
  621. if( lemp->start ){
  622. sp = Symbol_find(lemp->start);
  623. if( sp==0 ){
  624. ErrorMsg(lemp->filename,0,
  625. "The specified start symbol \"%s\" is not \
  626. in a nonterminal of the grammar. \"%s\" will be used as the start \
  627. symbol instead.",lemp->start,lemp->rule->lhs->name);
  628. lemp->errorcnt++;
  629. sp = lemp->rule->lhs;
  630. }
  631. }else{
  632. sp = lemp->rule->lhs;
  633. }
  634. /* Make sure the start symbol doesn't occur on the right-hand side of
  635. ** any rule. Report an error if it does. (YACC would generate a new
  636. ** start symbol in this case.) */
  637. for(rp=lemp->rule; rp; rp=rp->next){
  638. int i;
  639. for(i=0; i<rp->nrhs; i++){
  640. if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
  641. ErrorMsg(lemp->filename,0,
  642. "The start symbol \"%s\" occurs on the \
  643. right-hand side of a rule. This will result in a parser which \
  644. does not work properly.",sp->name);
  645. lemp->errorcnt++;
  646. }
  647. }
  648. }
  649. /* The basis configuration set for the first state
  650. ** is all rules which have the start symbol as their
  651. ** left-hand side */
  652. for(rp=sp->rule; rp; rp=rp->nextlhs){
  653. struct config *newcfp;
  654. rp->lhsStart = 1;
  655. newcfp = Configlist_addbasis(rp,0);
  656. SetAdd(newcfp->fws,0);
  657. }
  658. /* Compute the first state. All other states will be
  659. ** computed automatically during the computation of the first one.
  660. ** The returned pointer to the first state is not used. */
  661. (void)getstate(lemp);
  662. return;
  663. }
  664. /* Return a pointer to a state which is described by the configuration
  665. ** list which has been built from calls to Configlist_add.
  666. */
  667. PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
  668. PRIVATE struct state *getstate(lemp)
  669. struct lemon *lemp;
  670. {
  671. struct config *cfp, *bp;
  672. struct state *stp;
  673. /* Extract the sorted basis of the new state. The basis was constructed
  674. ** by prior calls to "Configlist_addbasis()". */
  675. Configlist_sortbasis();
  676. bp = Configlist_basis();
  677. /* Get a state with the same basis */
  678. stp = State_find(bp);
  679. if( stp ){
  680. /* A state with the same basis already exists! Copy all the follow-set
  681. ** propagation links from the state under construction into the
  682. ** preexisting state, then return a pointer to the preexisting state */
  683. struct config *x, *y;
  684. for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
  685. Plink_copy(&y->bplp,x->bplp);
  686. Plink_delete(x->fplp);
  687. x->fplp = x->bplp = 0;
  688. }
  689. cfp = Configlist_return();
  690. Configlist_eat(cfp);
  691. }else{
  692. /* This really is a new state. Construct all the details */
  693. Configlist_closure(lemp); /* Compute the configuration closure */
  694. Configlist_sort(); /* Sort the configuration closure */
  695. cfp = Configlist_return(); /* Get a pointer to the config list */
  696. stp = State_new(); /* A new state structure */
  697. MemoryCheck(stp);
  698. stp->bp = bp; /* Remember the configuration basis */
  699. stp->cfp = cfp; /* Remember the configuration closure */
  700. stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
  701. stp->ap = 0; /* No actions, yet. */
  702. State_insert(stp,stp->bp); /* Add to the state table */
  703. buildshifts(lemp,stp); /* Recursively compute successor states */
  704. }
  705. return stp;
  706. }
  707. /*
  708. ** Return true if two symbols are the same.
  709. */
  710. int same_symbol(a,b)
  711. struct symbol *a;
  712. struct symbol *b;
  713. {
  714. int i;
  715. if( a==b ) return 1;
  716. if( a->type!=MULTITERMINAL ) return 0;
  717. if( b->type!=MULTITERMINAL ) return 0;
  718. if( a->nsubsym!=b->nsubsym ) return 0;
  719. for(i=0; i<a->nsubsym; i++){
  720. if( a->subsym[i]!=b->subsym[i] ) return 0;
  721. }
  722. return 1;
  723. }
  724. /* Construct all successor states to the given state. A "successor"
  725. ** state is any state which can be reached by a shift action.
  726. */
  727. PRIVATE void buildshifts(lemp,stp)
  728. struct lemon *lemp;
  729. struct state *stp; /* The state from which successors are computed */
  730. {
  731. struct config *cfp; /* For looping thru the config closure of "stp" */
  732. struct config *bcfp; /* For the inner loop on config closure of "stp" */
  733. struct config *new; /* */
  734. struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
  735. struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
  736. struct state *newstp; /* A pointer to a successor state */
  737. /* Each configuration becomes complete after it contibutes to a successor
  738. ** state. Initially, all configurations are incomplete */
  739. for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
  740. /* Loop through all configurations of the state "stp" */
  741. for(cfp=stp->cfp; cfp; cfp=cfp->next){
  742. if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
  743. if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
  744. Configlist_reset(); /* Reset the new config set */
  745. sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
  746. /* For every configuration in the state "stp" which has the symbol "sp"
  747. ** following its dot, add the same configuration to the basis set under
  748. ** construction but with the dot shifted one symbol to the right. */
  749. for(bcfp=cfp; bcfp; bcfp=bcfp->next){
  750. if( bcfp->status==COMPLETE ) continue; /* Already used */
  751. if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
  752. bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
  753. if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
  754. bcfp->status = COMPLETE; /* Mark this config as used */
  755. new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
  756. Plink_add(&new->bplp,bcfp);
  757. }
  758. /* Get a pointer to the state described by the basis configuration set
  759. ** constructed in the preceding loop */
  760. newstp = getstate(lemp);
  761. /* The state "newstp" is reached from the state "stp" by a shift action
  762. ** on the symbol "sp" */
  763. if( sp->type==MULTITERMINAL ){
  764. int i;
  765. for(i=0; i<sp->nsubsym; i++){
  766. Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
  767. }
  768. }else{
  769. Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
  770. }
  771. }
  772. }
  773. /*
  774. ** Construct the propagation links
  775. */
  776. void FindLinks(lemp)
  777. struct lemon *lemp;
  778. {
  779. int i;
  780. struct config *cfp, *other;
  781. struct state *stp;
  782. struct plink *plp;
  783. /* Housekeeping detail:
  784. ** Add to every propagate link a pointer back to the state to
  785. ** which the link is attached. */
  786. for(i=0; i<lemp->nstate; i++){
  787. stp = lemp->sorted[i];
  788. for(cfp=stp->cfp; cfp; cfp=cfp->next){
  789. cfp->stp = stp;
  790. }
  791. }
  792. /* Convert all backlinks into forward links. Only the forward
  793. ** links are used in the follow-set computation. */
  794. for(i=0; i<lemp->nstate; i++){
  795. stp = lemp->sorted[i];
  796. for(cfp=stp->cfp; cfp; cfp=cfp->next){
  797. for(plp=cfp->bplp; plp; plp=plp->next){
  798. other = plp->cfp;
  799. Plink_add(&other->fplp,cfp);
  800. }
  801. }
  802. }
  803. }
  804. /* Compute all followsets.
  805. **
  806. ** A followset is the set of all symbols which can come immediately
  807. ** after a configuration.
  808. */
  809. void FindFollowSets(lemp)
  810. struct lemon *lemp;
  811. {
  812. int i;
  813. struct config *cfp;
  814. struct plink *plp;
  815. int progress;
  816. int change;
  817. for(i=0; i<lemp->nstate; i++){
  818. for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
  819. cfp->status = INCOMPLETE;
  820. }
  821. }
  822. do{
  823. progress = 0;
  824. for(i=0; i<lemp->nstate; i++){
  825. for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
  826. if( cfp->status==COMPLETE ) continue;
  827. for(plp=cfp->fplp; plp; plp=plp->next){
  828. change = SetUnion(plp->cfp->fws,cfp->fws);
  829. if( change ){
  830. plp->cfp->status = INCOMPLETE;
  831. progress = 1;
  832. }
  833. }
  834. cfp->status = COMPLETE;
  835. }
  836. }
  837. }while( progress );
  838. }
  839. static int resolve_conflict();
  840. /* Compute the reduce actions, and resolve conflicts.
  841. */
  842. void FindActions(lemp)
  843. struct lemon *lemp;
  844. {
  845. int i,j;
  846. struct config *cfp;
  847. struct state *stp;
  848. struct symbol *sp;
  849. struct rule *rp;
  850. /* Add all of the reduce actions
  851. ** A reduce action is added for each element of the followset of
  852. ** a configuration which has its dot at the extreme right.
  853. */
  854. for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
  855. stp = lemp->sorted[i];
  856. for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
  857. if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
  858. for(j=0; j<lemp->nterminal; j++){
  859. if( SetFind(cfp->fws,j) ){
  860. /* Add a reduce action to the state "stp" which will reduce by the
  861. ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
  862. Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
  863. }
  864. }
  865. }
  866. }
  867. }
  868. /* Add the accepting token */
  869. if( lemp->start ){
  870. sp = Symbol_find(lemp->start);
  871. if( sp==0 ) sp = lemp->rule->lhs;
  872. }else{
  873. sp = lemp->rule->lhs;
  874. }
  875. /* Add to the first state (which is always the starting state of the
  876. ** finite state machine) an action to ACCEPT if the lookahead is the
  877. ** start nonterminal. */
  878. Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
  879. /* Resolve conflicts */
  880. for(i=0; i<lemp->nstate; i++){
  881. struct action *ap, *nap;
  882. struct state *stp;
  883. stp = lemp->sorted[i];
  884. /* assert( stp->ap ); */
  885. stp->ap = Action_sort(stp->ap);
  886. for(ap=stp->ap; ap && ap->next; ap=ap->next){
  887. for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
  888. /* The two actions "ap" and "nap" have the same lookahead.
  889. ** Figure out which one should be used */
  890. lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
  891. }
  892. }
  893. }
  894. /* Report an error for each rule that can never be reduced. */
  895. for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
  896. for(i=0; i<lemp->nstate; i++){
  897. struct action *ap;
  898. for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
  899. if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
  900. }
  901. }
  902. for(rp=lemp->rule; rp; rp=rp->next){
  903. if( rp->canReduce ) continue;
  904. ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
  905. lemp->errorcnt++;
  906. }
  907. }
  908. /* Resolve a conflict between the two given actions. If the
  909. ** conflict can't be resolved, return non-zero.
  910. **
  911. ** NO LONGER TRUE:
  912. ** To resolve a conflict, first look to see if either action
  913. ** is on an error rule. In that case, take the action which
  914. ** is not associated with the error rule. If neither or both
  915. ** actions are associated with an error rule, then try to
  916. ** use precedence to resolve the conflict.
  917. **
  918. ** If either action is a SHIFT, then it must be apx. This
  919. ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
  920. */
  921. static int resolve_conflict(apx,apy,errsym)
  922. struct action *apx;
  923. struct action *apy;
  924. struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
  925. {
  926. struct symbol *spx, *spy;
  927. int errcnt = 0;
  928. assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
  929. if( apx->type==SHIFT && apy->type==SHIFT ){
  930. apy->type = SSCONFLICT;
  931. errcnt++;
  932. }
  933. if( apx->type==SHIFT && apy->type==REDUCE ){
  934. spx = apx->sp;
  935. spy = apy->x.rp->precsym;
  936. if( spy==0 || spx->prec<0 || spy->prec<0 ){
  937. /* Not enough precedence information. */
  938. apy->type = SRCONFLICT;
  939. errcnt++;
  940. }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
  941. apy->type = RD_RESOLVED;
  942. }else if( spx->prec<spy->prec ){
  943. apx->type = SH_RESOLVED;
  944. }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
  945. apy->type = RD_RESOLVED; /* associativity */
  946. }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
  947. apx->type = SH_RESOLVED;
  948. }else{
  949. assert( spx->prec==spy->prec && spx->assoc==NONE );
  950. apy->type = SRCONFLICT;
  951. errcnt++;
  952. }
  953. }else if( apx->type==REDUCE && apy->type==REDUCE ){
  954. spx = apx->x.rp->precsym;
  955. spy = apy->x.rp->precsym;
  956. if( spx==0 || spy==0 || spx->prec<0 ||
  957. spy->prec<0 || spx->prec==spy->prec ){
  958. apy->type = RRCONFLICT;
  959. errcnt++;
  960. }else if( spx->prec>spy->prec ){
  961. apy->type = RD_RESOLVED;
  962. }else if( spx->prec<spy->prec ){
  963. apx->type = RD_RESOLVED;
  964. }
  965. }else{
  966. assert(
  967. apx->type==SH_RESOLVED ||
  968. apx->type==RD_RESOLVED ||
  969. apx->type==SSCONFLICT ||
  970. apx->type==SRCONFLICT ||
  971. apx->type==RRCONFLICT ||
  972. apy->type==SH_RESOLVED ||
  973. apy->type==RD_RESOLVED ||
  974. apy->type==SSCONFLICT ||
  975. apy->type==SRCONFLICT ||
  976. apy->type==RRCONFLICT
  977. );
  978. /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
  979. ** REDUCEs on the list. If we reach this point it must be because
  980. ** the parser conflict had already been resolved. */
  981. }
  982. return errcnt;
  983. }
  984. /********************* From the file "configlist.c" *************************/
  985. /*
  986. ** Routines to processing a configuration list and building a state
  987. ** in the LEMON parser generator.
  988. */
  989. static struct config *freelist = 0; /* List of free configurations */
  990. static struct config *current = 0; /* Top of list of configurations */
  991. static struct config **currentend = 0; /* Last on list of configs */
  992. static struct config *basis = 0; /* Top of list of basis configs */
  993. static struct config **basisend = 0; /* End of list of basis configs */
  994. /* Return a pointer to a new configuration */
  995. PRIVATE struct config *newconfig(){
  996. struct config *new;
  997. if( freelist==0 ){
  998. int i;
  999. int amt = 3;
  1000. freelist = (struct config *)calloc( amt, sizeof(struct config) );
  1001. if( freelist==0 ){
  1002. fprintf(stderr,"Unable to allocate memory for a new configuration.");
  1003. exit(1);
  1004. }
  1005. for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
  1006. freelist[amt-1].next = 0;
  1007. }
  1008. new = freelist;
  1009. freelist = freelist->next;
  1010. return new;
  1011. }
  1012. /* The configuration "old" is no longer used */
  1013. PRIVATE void deleteconfig(old)
  1014. struct config *old;
  1015. {
  1016. old->next = freelist;
  1017. freelist = old;
  1018. }
  1019. /* Initialized the configuration list builder */
  1020. void Configlist_init(){
  1021. current = 0;
  1022. currentend = &current;
  1023. basis = 0;
  1024. basisend = &basis;
  1025. Configtable_init();
  1026. return;
  1027. }
  1028. /* Initialized the configuration list builder */
  1029. void Configlist_reset(){
  1030. current = 0;
  1031. currentend = &current;
  1032. basis = 0;
  1033. basisend = &basis;
  1034. Configtable_clear(0);
  1035. return;
  1036. }
  1037. /* Add another configuration to the configuration list */
  1038. struct config *Configlist_add(rp,dot)
  1039. struct rule *rp; /* The rule */
  1040. int dot; /* Index into the RHS of the rule where the dot goes */
  1041. {
  1042. struct config *cfp, model;
  1043. assert( currentend!=0 );
  1044. model.rp = rp;
  1045. model.dot = dot;
  1046. cfp = Configtable_find(&model);
  1047. if( cfp==0 ){
  1048. cfp = newconfig();
  1049. cfp->rp = rp;
  1050. cfp->dot = dot;
  1051. cfp->fws = SetNew();
  1052. cfp->stp = 0;
  1053. cfp->fplp = cfp->bplp = 0;
  1054. cfp->next = 0;
  1055. cfp->bp = 0;
  1056. *currentend = cfp;
  1057. currentend = &cfp->next;
  1058. Configtable_insert(cfp);
  1059. }
  1060. return cfp;
  1061. }
  1062. /* Add a basis configuration to the configuration list */
  1063. struct config *Configlist_addbasis(rp,dot)
  1064. struct rule *rp;
  1065. int dot;
  1066. {
  1067. struct config *cfp, model;
  1068. assert( basisend!=0 );
  1069. assert( currentend!=0 );
  1070. model.rp = rp;
  1071. model.dot = dot;
  1072. cfp = Configtable_find(&model);
  1073. if( cfp==0 ){
  1074. cfp = newconfig();
  1075. cfp->rp = rp;
  1076. cfp->dot = dot;
  1077. cfp->fws = SetNew();
  1078. cfp->stp = 0;
  1079. cfp->fplp = cfp->bplp = 0;
  1080. cfp->next = 0;
  1081. cfp->bp = 0;
  1082. *currentend = cfp;
  1083. currentend = &cfp->next;
  1084. *basisend = cfp;
  1085. basisend = &cfp->bp;
  1086. Configtable_insert(cfp);
  1087. }
  1088. return cfp;
  1089. }
  1090. /* Compute the closure of the configuration list */
  1091. void Configlist_closure(lemp)
  1092. struct lemon *lemp;
  1093. {
  1094. struct config *cfp, *newcfp;
  1095. struct rule *rp, *newrp;
  1096. struct symbol *sp, *xsp;
  1097. int i, dot;
  1098. assert( currentend!=0 );
  1099. for(cfp=current; cfp; cfp=cfp->next){
  1100. rp = cfp->rp;
  1101. dot = cfp->dot;
  1102. if( dot>=rp->nrhs ) continue;
  1103. sp = rp->rhs[dot];
  1104. if( sp->type==NONTERMINAL ){
  1105. if( sp->rule==0 && sp!=lemp->errsym ){
  1106. ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
  1107. sp->name);
  1108. lemp->errorcnt++;
  1109. }
  1110. for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
  1111. newcfp = Configlist_add(newrp,0);
  1112. for(i=dot+1; i<rp->nrhs; i++){
  1113. xsp = rp->rhs[i];
  1114. if( xsp->type==TERMINAL ){
  1115. SetAdd(newcfp->fws,xsp->index);
  1116. break;
  1117. }else if( xsp->type==MULTITERMINAL ){
  1118. int k;
  1119. for(k=0; k<xsp->nsubsym; k++){
  1120. SetAdd(newcfp->fws, xsp->subsym[k]->index);
  1121. }
  1122. break;
  1123. }else{
  1124. SetUnion(newcfp->fws,xsp->firstset);
  1125. if( xsp->lambda==LEMON_FALSE ) break;
  1126. }
  1127. }
  1128. if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
  1129. }
  1130. }
  1131. }
  1132. return;
  1133. }
  1134. /* Sort the configuration list */
  1135. void Configlist_sort(){
  1136. current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
  1137. currentend = 0;
  1138. return;
  1139. }
  1140. /* Sort the basis configuration list */
  1141. void Configlist_sortbasis(){
  1142. basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
  1143. basisend = 0;
  1144. return;
  1145. }
  1146. /* Return a pointer to the head of the configuration list and
  1147. ** reset the list */
  1148. struct config *Configlist_return(){
  1149. struct config *old;
  1150. old = current;
  1151. current = 0;
  1152. currentend = 0;
  1153. return old;
  1154. }
  1155. /* Return a pointer to the head of the configuration list and
  1156. ** reset the list */
  1157. struct config *Configlist_basis(){
  1158. struct config *old;
  1159. old = basis;
  1160. basis = 0;
  1161. basisend = 0;
  1162. return old;
  1163. }
  1164. /* Free all elements of the given configuration list */
  1165. void Configlist_eat(cfp)
  1166. struct config *cfp;
  1167. {
  1168. struct config *nextcfp;
  1169. for(; cfp; cfp=nextcfp){
  1170. nextcfp = cfp->next;
  1171. assert( cfp->fplp==0 );
  1172. assert( cfp->bplp==0 );
  1173. if( cfp->fws ) SetFree(cfp->fws);
  1174. deleteconfig(cfp);
  1175. }
  1176. return;
  1177. }
  1178. /***************** From the file "error.c" *********************************/
  1179. /*
  1180. ** Code for printing error message.
  1181. */
  1182. /* Find a good place to break "msg" so that its length is at least "min"
  1183. ** but no more than "max". Make the point as close to max as possible.
  1184. */
  1185. static int findbreak(msg,min,max)
  1186. char *msg;
  1187. int min;
  1188. int max;
  1189. {
  1190. int i,spot;
  1191. char c;
  1192. for(i=spot=min; i<=max; i++){
  1193. c = msg[i];
  1194. if( c=='\t' ) msg[i] = ' ';
  1195. if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
  1196. if( c==0 ){ spot = i; break; }
  1197. if( c=='-' && i<max-1 ) spot = i+1;
  1198. if( c==' ' ) spot = i;
  1199. }
  1200. return spot;
  1201. }
  1202. /*
  1203. ** The error message is split across multiple lines if necessary. The
  1204. ** splits occur at a space, if there is a space available near the end
  1205. ** of the line.
  1206. */
  1207. #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
  1208. #define LINEWIDTH 79 /* Max width of any output line */
  1209. #define PREFIXLIMIT 30 /* Max width of the prefix on each line */
  1210. void ErrorMsg(const char *filename, int lineno, const char *format, ...){
  1211. char errmsg[ERRMSGSIZE];
  1212. char prefix[PREFIXLIMIT+10];
  1213. int errmsgsize;
  1214. int prefixsize;
  1215. int availablewidth;
  1216. va_list ap;
  1217. int end, restart, base;
  1218. va_start(ap, format);
  1219. /* Prepare a prefix to be prepended to every output line */
  1220. if( lineno>0 ){
  1221. sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
  1222. }else{
  1223. sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
  1224. }
  1225. prefixsize = lemonStrlen(prefix);
  1226. availablewidth = LINEWIDTH - prefixsize;
  1227. /* Generate the error message */
  1228. vsprintf(errmsg,format,ap);
  1229. va_end(ap);
  1230. errmsgsize = lemonStrlen(errmsg);
  1231. /* Remove trailing '\n's from the error message. */
  1232. while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
  1233. errmsg[--errmsgsize] = 0;
  1234. }
  1235. /* Print the error message */
  1236. base = 0;
  1237. while( errmsg[base]!=0 ){
  1238. end = restart = findbreak(&errmsg[base],0,availablewidth);
  1239. restart += base;
  1240. while( errmsg[restart]==' ' ) restart++;
  1241. fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
  1242. base = restart;
  1243. }
  1244. }
  1245. /**************** From the file "main.c" ************************************/
  1246. /*
  1247. ** Main program file for the LEMON parser generator.
  1248. */
  1249. /* Report an out-of-memory condition and abort. This function
  1250. ** is used mostly by the "MemoryCheck" macro in struct.h
  1251. */
  1252. void memory_error(){
  1253. fprintf(stderr,"Out of memory. Aborting...\n");
  1254. exit(1);
  1255. }
  1256. static int nDefine = 0; /* Number of -D options on the command line */
  1257. static char **azDefine = 0; /* Name of the -D macros */
  1258. /* This routine is called with the argument to each -D command-line option.
  1259. ** Add the macro defined to the azDefine array.
  1260. */
  1261. static void handle_D_option(char *z){
  1262. char **paz;
  1263. nDefine++;
  1264. azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
  1265. if( azDefine==0 ){
  1266. fprintf(stderr,"out of memory\n");
  1267. exit(1);
  1268. }
  1269. paz = &azDefine[nDefine-1];
  1270. *paz = malloc( lemonStrlen(z)+1 );
  1271. if( *paz==0 ){
  1272. fprintf(stderr,"out of memory\n");
  1273. exit(1);
  1274. }
  1275. strcpy(*paz, z);
  1276. for(z=*paz; *z && *z!='='; z++){}
  1277. *z = 0;
  1278. }
  1279. /* The main program. Parse the command line and do it... */
  1280. int main(argc,argv)
  1281. int argc;
  1282. char **argv;
  1283. {
  1284. static int version = 0;
  1285. static int rpflag = 0;
  1286. static int basisflag = 0;
  1287. static int compress = 0;
  1288. static int quiet = 0;
  1289. static int statistics = 0;
  1290. static int mhflag = 0;
  1291. static int nolinenosflag = 0;
  1292. static struct s_options options[] = {
  1293. {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
  1294. {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
  1295. {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
  1296. {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
  1297. {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
  1298. {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
  1299. {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
  1300. {OPT_FLAG, "s", (char*)&statistics,
  1301. "Print parser stats to standard output."},
  1302. {OPT_FLAG, "x", (char*)&version, "Print the version number."},
  1303. {OPT_FLAG,0,0,0}
  1304. };
  1305. int i;
  1306. struct lemon lem;
  1307. OptInit(argv,options,stderr);
  1308. if( version ){
  1309. printf("Lemon version 1.0\n");
  1310. exit(0);
  1311. }
  1312. if( OptNArgs()!=1 ){
  1313. fprintf(stderr,"Exactly one filename argument is required.\n");
  1314. exit(1);
  1315. }
  1316. memset(&lem, 0, sizeof(lem));
  1317. lem.errorcnt = 0;
  1318. /* Initialize the machine */
  1319. Strsafe_init();
  1320. Symbol_init();
  1321. State_init();
  1322. lem.argv0 = argv[0];
  1323. lem.filename = OptArg(0);
  1324. lem.basisflag = basisflag;
  1325. lem.nolinenosflag = nolinenosflag;
  1326. Symbol_new("$");
  1327. lem.errsym = Symbol_new("error");
  1328. lem.errsym->useCnt = 0;
  1329. /* Parse the input file */
  1330. Parse(&lem);
  1331. if( lem.errorcnt ) exit(lem.errorcnt);
  1332. if( lem.nrule==0 ){
  1333. fprintf(stderr,"Empty grammar.\n");
  1334. exit(1);
  1335. }
  1336. /* Count and index the symbols of the grammar */
  1337. lem.nsymbol = Symbol_count();
  1338. Symbol_new("{default}");
  1339. lem.symbols = Symbol_arrayof();
  1340. for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
  1341. qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
  1342. (int(*)())Symbolcmpp);
  1343. for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
  1344. for(i=1; isupper(lem.symbols[i]->name[0]); i++);
  1345. lem.nterminal = i;
  1346. /* Generate a reprint of the grammar, if requested on the command line */
  1347. if( rpflag ){
  1348. Reprint(&lem);
  1349. }else{
  1350. /* Initialize the size for all follow and first sets */
  1351. SetSize(lem.nterminal+1);
  1352. /* Find the precedence for every production rule (that has one) */
  1353. FindRulePrecedences(&lem);
  1354. /* Compute the lambda-nonterminals and the first-sets for every
  1355. ** nonterminal */
  1356. FindFirstSets(&lem);
  1357. /* Compute all LR(0) states. Also record follow-set propagation
  1358. ** links so that the follow-set can be computed later */
  1359. lem.nstate = 0;
  1360. FindStates(&lem);
  1361. lem.sorted = State_arrayof();
  1362. /* Tie up loose ends on the propagation links */
  1363. FindLinks(&lem);
  1364. /* Compute the follow set of every reducible configuration */
  1365. FindFollowSets(&lem);
  1366. /* Compute the action tables */
  1367. FindActions(&lem);
  1368. /* Compress the action tables */
  1369. if( compress==0 ) CompressTables(&lem);
  1370. /* Reorder and renumber the states so that states with fewer choices
  1371. ** occur at the end. */
  1372. ResortStates(&lem);
  1373. /* Generate a report of the parser generated. (the "y.output" file) */
  1374. if( !quiet ) ReportOutput(&lem);
  1375. /* Generate the source code for the parser */
  1376. ReportTable(&lem, mhflag);
  1377. /* Produce a header file for use by the scanner. (This step is
  1378. ** omitted if the "-m" option is used because makeheaders will
  1379. ** generate the file for us.) */
  1380. if( !mhflag ) ReportHeader(&lem);
  1381. }
  1382. if( statistics ){
  1383. printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
  1384. lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
  1385. printf(" %d states, %d parser table entries, %d conflicts\n",
  1386. lem.nstate, lem.tablesize, lem.nconflict);
  1387. }
  1388. if( lem.nconflict ){
  1389. fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
  1390. }
  1391. exit(lem.errorcnt + lem.nconflict);
  1392. return (lem.errorcnt + lem.nconflict);
  1393. }
  1394. /******************** From the file "msort.c" *******************************/
  1395. /*
  1396. ** A generic merge-sort program.
  1397. **
  1398. ** USAGE:
  1399. ** Let "ptr" be a pointer to some structure which is at the head of
  1400. ** a null-terminated list. Then to sort the list call:
  1401. **
  1402. ** ptr = msort(ptr,&(ptr->next),cmpfnc);
  1403. **
  1404. ** In the above, "cmpfnc" is a pointer to a function which compares
  1405. ** two instances of the structure and returns an integer, as in
  1406. ** strcmp. The second argument is a pointer to the pointer to the
  1407. ** second element of the linked list. This address is used to compute
  1408. ** the offset to the "next" field within the structure. The offset to
  1409. ** the "next" field must be constant for all structures in the list.
  1410. **
  1411. ** The function returns a new pointer which is the head of the list
  1412. ** after sorting.
  1413. **
  1414. ** ALGORITHM:
  1415. ** Merge-sort.
  1416. */
  1417. /*
  1418. ** Return a pointer to the next structure in the linked list.
  1419. */
  1420. #define NEXT(A) (*(char**)(((unsigned long)A)+offset))
  1421. /*
  1422. ** Inputs:
  1423. ** a: A sorted, null-terminated linked list. (May be null).
  1424. ** b: A sorted, null-terminated linked list. (May be null).
  1425. ** cmp: A pointer to the comparison function.
  1426. ** offset: Offset in the structure to the "next" field.
  1427. **
  1428. ** Return Value:
  1429. ** A pointer to the head of a sorted list containing the elements
  1430. ** of both a and b.
  1431. **
  1432. ** Side effects:
  1433. ** The "next" pointers for elements in the lists a and b are
  1434. ** changed.
  1435. */
  1436. static char *merge(
  1437. char *a,
  1438. char *b,
  1439. int (*cmp)(const char*,const char*),
  1440. int offset
  1441. ){
  1442. char *ptr, *head;
  1443. if( a==0 ){
  1444. head = b;
  1445. }else if( b==0 ){
  1446. head = a;
  1447. }else{
  1448. if( (*cmp)(a,b)<0 ){
  1449. ptr = a;
  1450. a = NEXT(a);
  1451. }else{
  1452. ptr = b;
  1453. b = NEXT(b);
  1454. }
  1455. head = ptr;
  1456. while( a && b ){
  1457. if( (*cmp)(a,b)<0 ){
  1458. NEXT(ptr) = a;
  1459. ptr = a;
  1460. a = NEXT(a);
  1461. }else{
  1462. NEXT(ptr) = b;
  1463. ptr = b;
  1464. b = NEXT(b);
  1465. }
  1466. }
  1467. if( a ) NEXT(ptr) = a;
  1468. else NEXT(ptr) = b;
  1469. }
  1470. return head;
  1471. }
  1472. /*
  1473. ** Inputs:
  1474. ** list: Pointer to a singly-linked list of structures.
  1475. ** next: Pointer to pointer to the second element of the list.
  1476. ** cmp: A comparison function.
  1477. **
  1478. ** Return Value:
  1479. ** A pointer to the head of a sorted list containing the elements
  1480. ** orginally in list.
  1481. **
  1482. ** Side effects:
  1483. ** The "next" pointers for elements in list are changed.
  1484. */
  1485. #define LISTSIZE 30
  1486. static char *msort(
  1487. char *list,
  1488. char **next,
  1489. int (*cmp)(const char*,const char*)
  1490. ){
  1491. unsigned long offset;
  1492. char *ep;
  1493. char *set[LISTSIZE];
  1494. int i;
  1495. offset = (unsigned long)next - (unsigned long)list;
  1496. for(i=0; i<LISTSIZE; i++) set[i] = 0;
  1497. while( list ){
  1498. ep = list;
  1499. list = NEXT(list);
  1500. NEXT(ep) = 0;
  1501. for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
  1502. ep = merge(ep,set[i],cmp,offset);
  1503. set[i] = 0;
  1504. }
  1505. set[i] = ep;
  1506. }
  1507. ep = 0;
  1508. for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
  1509. return ep;
  1510. }
  1511. /************************ From the file "option.c" **************************/
  1512. static char **argv;
  1513. static struct s_options *op;
  1514. static FILE *errstream;
  1515. #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
  1516. /*
  1517. ** Print the command line with a carrot pointing to the k-th character
  1518. ** of the n-th field.
  1519. */
  1520. static void errline(n,k,err)
  1521. int n;
  1522. int k;
  1523. FILE *err;
  1524. {
  1525. int spcnt, i;
  1526. if( argv[0] ) fprintf(err,"%s",argv[0]);
  1527. spcnt = lemonStrlen(argv[0]) + 1;
  1528. for(i=1; i<n && argv[i]; i++){
  1529. fprintf(err," %s",argv[i]);
  1530. spcnt += lemonStrlen(argv[i])+1;
  1531. }
  1532. spcnt += k;
  1533. for(; argv[i]; i++) fprintf(err," %s",argv[i]);
  1534. if( spcnt<20 ){
  1535. fprintf(err,"\n%*s^-- here\n",spcnt,"");
  1536. }else{
  1537. fprintf(err,"\n%*shere --^\n",spcnt-7,"");
  1538. }
  1539. }
  1540. /*
  1541. ** Return the index of the N-th non-switch argument. Return -1
  1542. ** if N is out of range.
  1543. */
  1544. static int argindex(n)
  1545. int n;
  1546. {
  1547. int i;
  1548. int dashdash = 0;
  1549. if( argv!=0 && *argv!=0 ){
  1550. for(i=1; argv[i]; i++){
  1551. if( dashdash || !ISOPT(argv[i]) ){
  1552. if( n==0 ) return i;
  1553. n--;
  1554. }
  1555. if( strcmp(argv[i],"--")==0 ) dashdash = 1;
  1556. }
  1557. }
  1558. return -1;
  1559. }
  1560. static char emsg[] = "Command line syntax error: ";
  1561. /*
  1562. ** Process a flag command line argument.
  1563. */
  1564. static int handleflags(i,err)
  1565. int i;
  1566. FILE *err;
  1567. {
  1568. int v;
  1569. int errcnt = 0;
  1570. int j;
  1571. for(j=0; op[j].label; j++){
  1572. if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
  1573. }
  1574. v = argv[i][0]=='-' ? 1 : 0;
  1575. if( op[j].label==0 ){
  1576. if( err ){
  1577. fprintf(err,"%sundefined option.\n",emsg);
  1578. errline(i,1,err);
  1579. }
  1580. errcnt++;
  1581. }else if( op[j].type==OPT_FLAG ){
  1582. *((int*)op[j].arg) = v;
  1583. }else if( op[j].type==OPT_FFLAG ){
  1584. (*(void(*)())(op[j].arg))(v);
  1585. }else if( op[j].type==OPT_FSTR ){
  1586. (*(void(*)())(op[j].arg))(&argv[i][2]);
  1587. }else{
  1588. if( err ){
  1589. fprintf(err,"%smissing argument on switch.\n",emsg);
  1590. errline(i,1,err);
  1591. }
  1592. errcnt++;
  1593. }
  1594. return errcnt;
  1595. }
  1596. /*
  1597. ** Process a command line switch which has an argument.
  1598. */
  1599. static int handleswitch(i,err)
  1600. int i;
  1601. FILE *err;
  1602. {
  1603. int lv = 0;
  1604. double dv = 0.0;
  1605. char *sv = 0, *end;
  1606. char *cp;
  1607. int j;
  1608. int errcnt = 0;
  1609. cp = strchr(argv[i],'=');
  1610. assert( cp!=0 );
  1611. *cp = 0;
  1612. for(j=0; op[j].label; j++){
  1613. if( strcmp(argv[i],op[j].label)==0 ) break;
  1614. }
  1615. *cp = '=';
  1616. if( op[j].label==0 ){
  1617. if( err ){
  1618. fprintf(err,"%sundefined option.\n",emsg);
  1619. errline(i,0,err);
  1620. }
  1621. errcnt++;
  1622. }else{
  1623. cp++;
  1624. switch( op[j].type ){
  1625. case OPT_FLAG:
  1626. case OPT_FFLAG:
  1627. if( err ){
  1628. fprintf(err,"%soption requires an argument.\n",emsg);
  1629. errline(i,0,err);
  1630. }
  1631. errcnt++;
  1632. break;
  1633. case OPT_DBL:
  1634. case OPT_FDBL:
  1635. dv = strtod(cp,&end);
  1636. if( *end ){
  1637. if( err ){
  1638. fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
  1639. errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
  1640. }
  1641. errcnt++;
  1642. }
  1643. break;
  1644. case OPT_INT:
  1645. case OPT_FINT:
  1646. lv = strtol(cp,&end,0);
  1647. if( *end ){
  1648. if( err ){
  1649. fprintf(err,"%sillegal character in integer argument.\n",emsg);
  1650. errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
  1651. }
  1652. errcnt++;
  1653. }
  1654. break;
  1655. case OPT_STR:
  1656. case OPT_FSTR:
  1657. sv = cp;
  1658. break;
  1659. }
  1660. switch( op[j].type ){
  1661. case OPT_FLAG:
  1662. case OPT_FFLAG:
  1663. break;
  1664. case OPT_DBL:
  1665. *(double*)(op[j].arg) = dv;
  1666. break;
  1667. case OPT_FDBL:
  1668. (*(void(*)())(op[j].arg))(dv);
  1669. break;
  1670. case OPT_INT:
  1671. *(int*)(op[j].arg) = lv;
  1672. break;
  1673. case OPT_FINT:
  1674. (*(void(*)())(op[j].arg))((int)lv);
  1675. break;
  1676. case OPT_STR:
  1677. *(char**)(op[j].arg) = sv;
  1678. break;
  1679. case OPT_FSTR:
  1680. (*(void(*)())(op[j].arg))(sv);
  1681. break;
  1682. }
  1683. }
  1684. return errcnt;
  1685. }
  1686. int OptInit(a,o,err)
  1687. char **a;
  1688. struct s_options *o;
  1689. FILE *err;
  1690. {
  1691. int errcnt = 0;
  1692. argv = a;
  1693. op = o;
  1694. errstream = err;
  1695. if( argv && *argv && op ){
  1696. int i;
  1697. for(i=1; argv[i]; i++){
  1698. if( argv[i][0]=='+' || argv[i][0]=='-' ){
  1699. errcnt += handleflags(i,err);
  1700. }else if( strchr(argv[i],'=') ){
  1701. errcnt += handleswitch(i,err);
  1702. }
  1703. }
  1704. }
  1705. if( errcnt>0 ){
  1706. fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
  1707. OptPrint();
  1708. exit(1);
  1709. }
  1710. return 0;
  1711. }
  1712. int OptNArgs(){
  1713. int cnt = 0;
  1714. int dashdash = 0;
  1715. int i;
  1716. if( argv!=0 && argv[0]!=0 ){
  1717. for(i=1; argv[i]; i++){
  1718. if( dashdash || !ISOPT(argv[i]) ) cnt++;
  1719. if( strcmp(argv[i],"--")==0 ) dashdash = 1;
  1720. }
  1721. }
  1722. return cnt;
  1723. }
  1724. char *OptArg(n)
  1725. int n;
  1726. {
  1727. int i;
  1728. i = argindex(n);
  1729. return i>=0 ? argv[i] : 0;
  1730. }
  1731. void OptErr(n)
  1732. int n;
  1733. {
  1734. int i;
  1735. i = argindex(n);
  1736. if( i>=0 ) errline(i,0,errstream);
  1737. }
  1738. void OptPrint(){
  1739. int i;
  1740. int max, len;
  1741. max = 0;
  1742. for(i=0; op[i].label; i++){
  1743. len = lemonStrlen(op[i].label) + 1;
  1744. switch( op[i].type ){
  1745. case OPT_FLAG:
  1746. case OPT_FFLAG:
  1747. break;
  1748. case OPT_INT:
  1749. case OPT_FINT:
  1750. len += 9; /* length of "<integer>" */
  1751. break;
  1752. case OPT_DBL:
  1753. case OPT_FDBL:
  1754. len += 6; /* length of "<real>" */
  1755. break;
  1756. case OPT_STR:
  1757. case OPT_FSTR:
  1758. len += 8; /* length of "<string>" */
  1759. break;
  1760. }
  1761. if( len>max ) max = len;
  1762. }
  1763. for(i=0; op[i].label; i++){
  1764. switch( op[i].type ){
  1765. case OPT_FLAG:
  1766. case OPT_FFLAG:
  1767. fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
  1768. break;
  1769. case OPT_INT:
  1770. case OPT_FINT:
  1771. fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
  1772. (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
  1773. break;
  1774. case OPT_DBL:
  1775. case OPT_FDBL:
  1776. fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
  1777. (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
  1778. break;
  1779. case OPT_STR:
  1780. case OPT_FSTR:
  1781. fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
  1782. (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
  1783. break;
  1784. }
  1785. }
  1786. }
  1787. /*********************** From the file "parse.c" ****************************/
  1788. /*
  1789. ** Input file parser for the LEMON parser generator.
  1790. */
  1791. /* The state of the parser */
  1792. struct pstate {
  1793. char *filename; /* Name of the input file */
  1794. int tokenlineno; /* Linenumber at which current token starts */
  1795. int errorcnt; /* Number of errors so far */
  1796. char *tokenstart; /* Text of current token */
  1797. struct lemon *gp; /* Global state vector */
  1798. enum e_state {
  1799. INITIALIZE,
  1800. WAITING_FOR_DECL_OR_RULE,
  1801. WAITING_FOR_DECL_KEYWORD,
  1802. WAITING_FOR_DECL_ARG,
  1803. WAITING_FOR_PRECEDENCE_SYMBOL,
  1804. WAITING_FOR_ARROW,
  1805. IN_RHS,
  1806. LHS_ALIAS_1,
  1807. LHS_ALIAS_2,
  1808. LHS_ALIAS_3,
  1809. RHS_ALIAS_1,
  1810. RHS_ALIAS_2,
  1811. PRECEDENCE_MARK_1,
  1812. PRECEDENCE_MARK_2,
  1813. RESYNC_AFTER_RULE_ERROR,
  1814. RESYNC_AFTER_DECL_ERROR,
  1815. WAITING_FOR_DESTRUCTOR_SYMBOL,
  1816. WAITING_FOR_DATATYPE_SYMBOL,
  1817. WAITING_FOR_FALLBACK_ID,
  1818. WAITING_FOR_WILDCARD_ID
  1819. } state; /* The state of the parser */
  1820. struct symbol *fallback; /* The fallback token */
  1821. struct symbol *lhs; /* Left-hand side of current rule */
  1822. char *lhsalias; /* Alias for the LHS */
  1823. int nrhs; /* Number of right-hand side symbols seen */
  1824. struct symbol *rhs[MAXRHS]; /* RHS symbols */
  1825. char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
  1826. struct rule *prevrule; /* Previous rule parsed */
  1827. char *declkeyword; /* Keyword of a declaration */
  1828. char **declargslot; /* Where the declaration argument should be put */
  1829. int insertLineMacro; /* Add #line before declaration insert */
  1830. int *decllinenoslot; /* Where to write declaration line number */
  1831. enum e_assoc declassoc; /* Assign this association to decl arguments */
  1832. int preccounter; /* Assign this precedence to decl arguments */
  1833. struct rule *firstrule; /* Pointer to first rule in the grammar */
  1834. struct rule *lastrule; /* Pointer to the most recently parsed rule */
  1835. };
  1836. /* Parse a single token */
  1837. static void parseonetoken(psp)
  1838. struct pstate *psp;
  1839. {
  1840. char *x;
  1841. x = Strsafe(psp->tokenstart); /* Save the token permanently */
  1842. #if 0
  1843. printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
  1844. x,psp->state);
  1845. #endif
  1846. switch( psp->state ){
  1847. case INITIALIZE:
  1848. psp->prevrule = 0;
  1849. psp->preccounter = 0;
  1850. psp->firstrule = psp->lastrule = 0;
  1851. psp->gp->nrule = 0;
  1852. /* Fall thru to next case */
  1853. case WAITING_FOR_DECL_OR_RULE:
  1854. if( x[0]=='%' ){
  1855. psp->state = WAITING_FOR_DECL_KEYWORD;
  1856. }else if( islower(x[0]) ){
  1857. psp->lhs = Symbol_new(x);
  1858. psp->nrhs = 0;
  1859. psp->lhsalias = 0;
  1860. psp->state = WAITING_FOR_ARROW;
  1861. }else if( x[0]=='{' ){
  1862. if( psp->prevrule==0 ){
  1863. ErrorMsg(psp->filename,psp->tokenlineno,
  1864. "There is no prior rule opon which to attach the code \
  1865. fragment which begins on this line.");
  1866. psp->errorcnt++;
  1867. }else if( psp->prevrule->code!=0 ){
  1868. ErrorMsg(psp->filename,psp->tokenlineno,
  1869. "Code fragment beginning on this line is not the first \
  1870. to follow the previous rule.");
  1871. psp->errorcnt++;
  1872. }else{
  1873. psp->prevrule->line = psp->tokenlineno;
  1874. psp->prevrule->code = &x[1];
  1875. }
  1876. }else if( x[0]=='[' ){
  1877. psp->state = PRECEDENCE_MARK_1;
  1878. }else{
  1879. ErrorMsg(psp->filename,psp->tokenlineno,
  1880. "Token \"%s\" should be either \"%%\" or a nonterminal name.",
  1881. x);
  1882. psp->errorcnt++;
  1883. }
  1884. break;
  1885. case PRECEDENCE_MARK_1:
  1886. if( !isupper(x[0]) ){
  1887. ErrorMsg(psp->filename,psp->tokenlineno,
  1888. "The precedence symbol must be a terminal.");
  1889. psp->errorcnt++;
  1890. }else if( psp->prevrule==0 ){
  1891. ErrorMsg(psp->filename,psp->tokenlineno,
  1892. "There is no prior rule to assign precedence \"[%s]\".",x);
  1893. psp->errorcnt++;
  1894. }else if( psp->prevrule->precsym!=0 ){
  1895. ErrorMsg(psp->filename,psp->tokenlineno,
  1896. "Precedence mark on this line is not the first \
  1897. to follow the previous rule.");
  1898. psp->errorcnt++;
  1899. }else{
  1900. psp->prevrule->precsym = Symbol_new(x);
  1901. }
  1902. psp->state = PRECEDENCE_MARK_2;
  1903. break;
  1904. case PRECEDENCE_MARK_2:
  1905. if( x[0]!=']' ){
  1906. ErrorMsg(psp->filename,psp->tokenlineno,
  1907. "Missing \"]\" on precedence mark.");
  1908. psp->errorcnt++;
  1909. }
  1910. psp->state = WAITING_FOR_DECL_OR_RULE;
  1911. break;
  1912. case WAITING_FOR_ARROW:
  1913. if( x[0]==':' && x[1]==':' && x[2]=='=' ){
  1914. psp->state = IN_RHS;
  1915. }else if( x[0]=='(' ){
  1916. psp->state = LHS_ALIAS_1;
  1917. }else{
  1918. ErrorMsg(psp->filename,psp->tokenlineno,
  1919. "Expected to see a \":\" following the LHS symbol \"%s\".",
  1920. psp->lhs->name);
  1921. psp->errorcnt++;
  1922. psp->state = RESYNC_AFTER_RULE_ERROR;
  1923. }
  1924. break;
  1925. case LHS_ALIAS_1:
  1926. if( isalpha(x[0]) ){
  1927. psp->lhsalias = x;
  1928. psp->state = LHS_ALIAS_2;
  1929. }else{
  1930. ErrorMsg(psp->filename,psp->tokenlineno,
  1931. "\"%s\" is not a valid alias for the LHS \"%s\"\n",
  1932. x,psp->lhs->name);
  1933. psp->errorcnt++;
  1934. psp->state = RESYNC_AFTER_RULE_ERROR;
  1935. }
  1936. break;
  1937. case LHS_ALIAS_2:
  1938. if( x[0]==')' ){
  1939. psp->state = LHS_ALIAS_3;
  1940. }else{
  1941. ErrorMsg(psp->filename,psp->tokenlineno,
  1942. "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
  1943. psp->errorcnt++;
  1944. psp->state = RESYNC_AFTER_RULE_ERROR;
  1945. }
  1946. break;
  1947. case LHS_ALIAS_3:
  1948. if( x[0]==':' && x[1]==':' && x[2]=='=' ){
  1949. psp->state = IN_RHS;
  1950. }else{
  1951. ErrorMsg(psp->filename,psp->tokenlineno,
  1952. "Missing \"->\" following: \"%s(%s)\".",
  1953. psp->lhs->name,psp->lhsalias);
  1954. psp->errorcnt++;
  1955. psp->state = RESYNC_AFTER_RULE_ERROR;
  1956. }
  1957. break;
  1958. case IN_RHS:
  1959. if( x[0]=='.' ){
  1960. struct rule *rp;
  1961. rp = (struct rule *)calloc( sizeof(struct rule) +
  1962. sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
  1963. if( rp==0 ){
  1964. ErrorMsg(psp->filename,psp->tokenlineno,
  1965. "Can't allocate enough memory for this rule.");
  1966. psp->errorcnt++;
  1967. psp->prevrule = 0;
  1968. }else{
  1969. int i;
  1970. rp->ruleline = psp->tokenlineno;
  1971. rp->rhs = (struct symbol**)&rp[1];
  1972. rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
  1973. for(i=0; i<psp->nrhs; i++){
  1974. rp->rhs[i] = psp->rhs[i];
  1975. rp->rhsalias[i] = psp->alias[i];
  1976. }
  1977. rp->lhs = psp->lhs;
  1978. rp->lhsalias = psp->lhsalias;
  1979. rp->nrhs = psp->nrhs;
  1980. rp->code = 0;
  1981. rp->precsym = 0;
  1982. rp->index = psp->gp->nrule++;
  1983. rp->nextlhs = rp->lhs->rule;
  1984. rp->lhs->rule = rp;
  1985. rp->next = 0;
  1986. if( psp->firstrule==0 ){
  1987. psp->firstrule = psp->lastrule = rp;
  1988. }else{
  1989. psp->lastrule->next = rp;
  1990. psp->lastrule = rp;
  1991. }
  1992. psp->prevrule = rp;
  1993. }
  1994. psp->state = WAITING_FOR_DECL_OR_RULE;
  1995. }else if( isalpha(x[0]) ){
  1996. if( psp->nrhs>=MAXRHS ){
  1997. ErrorMsg(psp->filename,psp->tokenlineno,
  1998. "Too many symbols on RHS of rule beginning at \"%s\".",
  1999. x);
  2000. psp->errorcnt++;
  2001. psp->state = RESYNC_AFTER_RULE_ERROR;
  2002. }else{
  2003. psp->rhs[psp->nrhs] = Symbol_new(x);
  2004. psp->alias[psp->nrhs] = 0;
  2005. psp->nrhs++;
  2006. }
  2007. }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
  2008. struct symbol *msp = psp->rhs[psp->nrhs-1];
  2009. if( msp->type!=MULTITERMINAL ){
  2010. struct symbol *origsp = msp;
  2011. msp = calloc(1,sizeof(*msp));
  2012. memset(msp, 0, sizeof(*msp));
  2013. msp->type = MULTITERMINAL;
  2014. msp->nsubsym = 1;
  2015. msp->subsym = calloc(1,sizeof(struct symbol*));
  2016. msp->subsym[0] = origsp;
  2017. msp->name = origsp->name;
  2018. psp->rhs[psp->nrhs-1] = msp;
  2019. }
  2020. msp->nsubsym++;
  2021. msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
  2022. msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
  2023. if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
  2024. ErrorMsg(psp->filename,psp->tokenlineno,
  2025. "Cannot form a compound containing a non-terminal");
  2026. psp->errorcnt++;
  2027. }
  2028. }else if( x[0]=='(' && psp->nrhs>0 ){
  2029. psp->state = RHS_ALIAS_1;
  2030. }else{
  2031. ErrorMsg(psp->filename,psp->tokenlineno,
  2032. "Illegal character on RHS of rule: \"%s\".",x);
  2033. psp->errorcnt++;
  2034. psp->state = RESYNC_AFTER_RULE_ERROR;
  2035. }
  2036. break;
  2037. case RHS_ALIAS_1:
  2038. if( isalpha(x[0]) ){
  2039. psp->alias[psp->nrhs-1] = x;
  2040. psp->state = RHS_ALIAS_2;
  2041. }else{
  2042. ErrorMsg(psp->filename,psp->tokenlineno,
  2043. "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
  2044. x,psp->rhs[psp->nrhs-1]->name);
  2045. psp->errorcnt++;
  2046. psp->state = RESYNC_AFTER_RULE_ERROR;
  2047. }
  2048. break;
  2049. case RHS_ALIAS_2:
  2050. if( x[0]==')' ){
  2051. psp->state = IN_RHS;
  2052. }else{
  2053. ErrorMsg(psp->filename,psp->tokenlineno,
  2054. "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
  2055. psp->errorcnt++;
  2056. psp->state = RESYNC_AFTER_RULE_ERROR;
  2057. }
  2058. break;
  2059. case WAITING_FOR_DECL_KEYWORD:
  2060. if( isalpha(x[0]) ){
  2061. psp->declkeyword = x;
  2062. psp->declargslot = 0;
  2063. psp->decllinenoslot = 0;
  2064. psp->insertLineMacro = 1;
  2065. psp->state = WAITING_FOR_DECL_ARG;
  2066. if( strcmp(x,"name")==0 ){
  2067. psp->declargslot = &(psp->gp->name);
  2068. psp->insertLineMacro = 0;
  2069. }else if( strcmp(x,"include")==0 ){
  2070. psp->declargslot = &(psp->gp->include);
  2071. }else if( strcmp(x,"code")==0 ){
  2072. psp->declargslot = &(psp->gp->extracode);
  2073. }else if( strcmp(x,"token_destructor")==0 ){
  2074. psp->declargslot = &psp->gp->tokendest;
  2075. }else if( strcmp(x,"default_destructor")==0 ){
  2076. psp->declargslot = &psp->gp->vardest;
  2077. }else if( strcmp(x,"token_prefix")==0 ){
  2078. psp->declargslot = &psp->gp->tokenprefix;
  2079. psp->insertLineMacro = 0;
  2080. }else if( strcmp(x,"syntax_error")==0 ){
  2081. psp->declargslot = &(psp->gp->error);
  2082. }else if( strcmp(x,"parse_accept")==0 ){
  2083. psp->declargslot = &(psp->gp->accept);
  2084. }else if( strcmp(x,"parse_failure")==0 ){
  2085. psp->declargslot = &(psp->gp->failure);
  2086. }else if( strcmp(x,"stack_overflow")==0 ){
  2087. psp->declargslot = &(psp->gp->overflow);
  2088. }else if( strcmp(x,"extra_argument")==0 ){
  2089. psp->declargslot = &(psp->gp->arg);
  2090. psp->insertLineMacro = 0;
  2091. }else if( strcmp(x,"token_type")==0 ){
  2092. psp->declargslot = &(psp->gp->tokentype);
  2093. psp->insertLineMacro = 0;
  2094. }else if( strcmp(x,"default_type")==0 ){
  2095. psp->declargslot = &(psp->gp->vartype);
  2096. psp->insertLineMacro = 0;
  2097. }else if( strcmp(x,"stack_size")==0 ){
  2098. psp->declargslot = &(psp->gp->stacksize);
  2099. psp->insertLineMacro = 0;
  2100. }else if( strcmp(x,"start_symbol")==0 ){
  2101. psp->declargslot = &(psp->gp->start);
  2102. psp->insertLineMacro = 0;
  2103. }else if( strcmp(x,"left")==0 ){
  2104. psp->preccounter++;
  2105. psp->declassoc = LEFT;
  2106. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2107. }else if( strcmp(x,"right")==0 ){
  2108. psp->preccounter++;
  2109. psp->declassoc = RIGHT;
  2110. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2111. }else if( strcmp(x,"nonassoc")==0 ){
  2112. psp->preccounter++;
  2113. psp->declassoc = NONE;
  2114. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2115. }else if( strcmp(x,"destructor")==0 ){
  2116. psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
  2117. }else if( strcmp(x,"type")==0 ){
  2118. psp->state = WAITING_FOR_DATATYPE_SYMBOL;
  2119. }else if( strcmp(x,"fallback")==0 ){
  2120. psp->fallback = 0;
  2121. psp->state = WAITING_FOR_FALLBACK_ID;
  2122. }else if( strcmp(x,"wildcard")==0 ){
  2123. psp->state = WAITING_FOR_WILDCARD_ID;
  2124. }else{
  2125. ErrorMsg(psp->filename,psp->tokenlineno,
  2126. "Unknown declaration keyword: \"%%%s\".",x);
  2127. psp->errorcnt++;
  2128. psp->state = RESYNC_AFTER_DECL_ERROR;
  2129. }
  2130. }else{
  2131. ErrorMsg(psp->filename,psp->tokenlineno,
  2132. "Illegal declaration keyword: \"%s\".",x);
  2133. psp->errorcnt++;
  2134. psp->state = RESYNC_AFTER_DECL_ERROR;
  2135. }
  2136. break;
  2137. case WAITING_FOR_DESTRUCTOR_SYMBOL:
  2138. if( !isalpha(x[0]) ){
  2139. ErrorMsg(psp->filename,psp->tokenlineno,
  2140. "Symbol name missing after %destructor keyword");
  2141. psp->errorcnt++;
  2142. psp->state = RESYNC_AFTER_DECL_ERROR;
  2143. }else{
  2144. struct symbol *sp = Symbol_new(x);
  2145. psp->declargslot = &sp->destructor;
  2146. psp->decllinenoslot = &sp->destLineno;
  2147. psp->insertLineMacro = 1;
  2148. psp->state = WAITING_FOR_DECL_ARG;
  2149. }
  2150. break;
  2151. case WAITING_FOR_DATATYPE_SYMBOL:
  2152. if( !isalpha(x[0]) ){
  2153. ErrorMsg(psp->filename,psp->tokenlineno,
  2154. "Symbol name missing after %destructor keyword");
  2155. psp->errorcnt++;
  2156. psp->state = RESYNC_AFTER_DECL_ERROR;
  2157. }else{
  2158. struct symbol *sp = Symbol_new(x);
  2159. psp->declargslot = &sp->datatype;
  2160. psp->insertLineMacro = 0;
  2161. psp->state = WAITING_FOR_DECL_ARG;
  2162. }
  2163. break;
  2164. case WAITING_FOR_PRECEDENCE_SYMBOL:
  2165. if( x[0]=='.' ){
  2166. psp->state = WAITING_FOR_DECL_OR_RULE;
  2167. }else if( isupper(x[0]) ){
  2168. struct symbol *sp;
  2169. sp = Symbol_new(x);
  2170. if( sp->prec>=0 ){
  2171. ErrorMsg(psp->filename,psp->tokenlineno,
  2172. "Symbol \"%s\" has already be given a precedence.",x);
  2173. psp->errorcnt++;
  2174. }else{
  2175. sp->prec = psp->preccounter;
  2176. sp->assoc = psp->declassoc;
  2177. }
  2178. }else{
  2179. ErrorMsg(psp->filename,psp->tokenlineno,
  2180. "Can't assign a precedence to \"%s\".",x);
  2181. psp->errorcnt++;
  2182. }
  2183. break;
  2184. case WAITING_FOR_DECL_ARG:
  2185. if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
  2186. char *zOld, *zNew, *zBuf, *z;
  2187. int nOld, n, nLine, nNew, nBack;
  2188. int addLineMacro;
  2189. char zLine[50];
  2190. zNew = x;
  2191. if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
  2192. nNew = lemonStrlen(zNew);
  2193. if( *psp->declargslot ){
  2194. zOld = *psp->declargslot;
  2195. }else{
  2196. zOld = "";
  2197. }
  2198. nOld = lemonStrlen(zOld);
  2199. n = nOld + nNew + 20;
  2200. addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
  2201. (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
  2202. if( addLineMacro ){
  2203. for(z=psp->filename, nBack=0; *z; z++){
  2204. if( *z=='\\' ) nBack++;
  2205. }
  2206. sprintf(zLine, "#line %d ", psp->tokenlineno);
  2207. nLine = lemonStrlen(zLine);
  2208. n += nLine + lemonStrlen(psp->filename) + nBack;
  2209. }
  2210. *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
  2211. zBuf += nOld;
  2212. if( addLineMacro ){
  2213. if( nOld && zBuf[-1]!='\n' ){
  2214. *(zBuf++) = '\n';
  2215. }
  2216. memcpy(zBuf, zLine, nLine);
  2217. zBuf += nLine;
  2218. *(zBuf++) = '"';
  2219. for(z=psp->filename; *z; z++){
  2220. if( *z=='\\' ){
  2221. *(zBuf++) = '\\';
  2222. }
  2223. *(zBuf++) = *z;
  2224. }
  2225. *(zBuf++) = '"';
  2226. *(zBuf++) = '\n';
  2227. }
  2228. if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
  2229. psp->decllinenoslot[0] = psp->tokenlineno;
  2230. }
  2231. memcpy(zBuf, zNew, nNew);
  2232. zBuf += nNew;
  2233. *zBuf = 0;
  2234. psp->state = WAITING_FOR_DECL_OR_RULE;
  2235. }else{
  2236. ErrorMsg(psp->filename,psp->tokenlineno,
  2237. "Illegal argument to %%%s: %s",psp->declkeyword,x);
  2238. psp->errorcnt++;
  2239. psp->state = RESYNC_AFTER_DECL_ERROR;
  2240. }
  2241. break;
  2242. case WAITING_FOR_FALLBACK_ID:
  2243. if( x[0]=='.' ){
  2244. psp->state = WAITING_FOR_DECL_OR_RULE;
  2245. }else if( !isupper(x[0]) ){
  2246. ErrorMsg(psp->filename, psp->tokenlineno,
  2247. "%%fallback argument \"%s\" should be a token", x);
  2248. psp->errorcnt++;
  2249. }else{
  2250. struct symbol *sp = Symbol_new(x);
  2251. if( psp->fallback==0 ){
  2252. psp->fallback = sp;
  2253. }else if( sp->fallback ){
  2254. ErrorMsg(psp->filename, psp->tokenlineno,
  2255. "More than one fallback assigned to token %s", x);
  2256. psp->errorcnt++;
  2257. }else{
  2258. sp->fallback = psp->fallback;
  2259. psp->gp->has_fallback = 1;
  2260. }
  2261. }
  2262. break;
  2263. case WAITING_FOR_WILDCARD_ID:
  2264. if( x[0]=='.' ){
  2265. psp->state = WAITING_FOR_DECL_OR_RULE;
  2266. }else if( !isupper(x[0]) ){
  2267. ErrorMsg(psp->filename, psp->tokenlineno,
  2268. "%%wildcard argument \"%s\" should be a token", x);
  2269. psp->errorcnt++;
  2270. }else{
  2271. struct symbol *sp = Symbol_new(x);
  2272. if( psp->gp->wildcard==0 ){
  2273. psp->gp->wildcard = sp;
  2274. }else{
  2275. ErrorMsg(psp->filename, psp->tokenlineno,
  2276. "Extra wildcard to token: %s", x);
  2277. psp->errorcnt++;
  2278. }
  2279. }
  2280. break;
  2281. case RESYNC_AFTER_RULE_ERROR:
  2282. /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
  2283. ** break; */
  2284. case RESYNC_AFTER_DECL_ERROR:
  2285. if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
  2286. if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
  2287. break;
  2288. }
  2289. }
  2290. /* Run the preprocessor over the input file text. The global variables
  2291. ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
  2292. ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
  2293. ** comments them out. Text in between is also commented out as appropriate.
  2294. */
  2295. static void preprocess_input(char *z){
  2296. int i, j, k, n;
  2297. int exclude = 0;
  2298. int start = 0;
  2299. int lineno = 1;
  2300. int start_lineno = 1;
  2301. for(i=0; z[i]; i++){
  2302. if( z[i]=='\n' ) lineno++;
  2303. if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
  2304. if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
  2305. if( exclude ){
  2306. exclude--;
  2307. if( exclude==0 ){
  2308. for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
  2309. }
  2310. }
  2311. for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
  2312. }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
  2313. || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
  2314. if( exclude ){
  2315. exclude++;
  2316. }else{
  2317. for(j=i+7; isspace(z[j]); j++){}
  2318. for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
  2319. exclude = 1;
  2320. for(k=0; k<nDefine; k++){
  2321. if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
  2322. exclude = 0;
  2323. break;
  2324. }
  2325. }
  2326. if( z[i+3]=='n' ) exclude = !exclude;
  2327. if( exclude ){
  2328. start = i;
  2329. start_lineno = lineno;
  2330. }
  2331. }
  2332. for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
  2333. }
  2334. }
  2335. if( exclude ){
  2336. fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
  2337. exit(1);
  2338. }
  2339. }
  2340. /* In spite of its name, this function is really a scanner. It read
  2341. ** in the entire input file (all at once) then tokenizes it. Each
  2342. ** token is passed to the function "parseonetoken" which builds all
  2343. ** the appropriate data structures in the global state vector "gp".
  2344. */
  2345. void Parse(gp)
  2346. struct lemon *gp;
  2347. {
  2348. struct pstate ps;
  2349. FILE *fp;
  2350. char *filebuf;
  2351. int filesize;
  2352. int lineno;
  2353. int c;
  2354. char *cp, *nextcp;
  2355. int startline = 0;
  2356. memset(&ps, '\0', sizeof(ps));
  2357. ps.gp = gp;
  2358. ps.filename = gp->filename;
  2359. ps.errorcnt = 0;
  2360. ps.state = INITIALIZE;
  2361. /* Begin by reading the input file */
  2362. fp = fopen(ps.filename,"rb");
  2363. if( fp==0 ){
  2364. ErrorMsg(ps.filename,0,"Can't open this file for reading.");
  2365. gp->errorcnt++;
  2366. return;
  2367. }
  2368. fseek(fp,0,2);
  2369. filesize = ftell(fp);
  2370. rewind(fp);
  2371. filebuf = (char *)malloc( filesize+1 );
  2372. if( filebuf==0 ){
  2373. ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
  2374. filesize+1);
  2375. gp->errorcnt++;
  2376. return;
  2377. }
  2378. if( fread(filebuf,1,filesize,fp)!=filesize ){
  2379. ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
  2380. filesize);
  2381. free(filebuf);
  2382. gp->errorcnt++;
  2383. return;
  2384. }
  2385. fclose(fp);
  2386. filebuf[filesize] = 0;
  2387. /* Make an initial pass through the file to handle %ifdef and %ifndef */
  2388. preprocess_input(filebuf);
  2389. /* Now scan the text of the input file */
  2390. lineno = 1;
  2391. for(cp=filebuf; (c= *cp)!=0; ){
  2392. if( c=='\n' ) lineno++; /* Keep track of the line number */
  2393. if( isspace(c) ){ cp++; continue; } /* Skip all white space */
  2394. if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
  2395. cp+=2;
  2396. while( (c= *cp)!=0 && c!='\n' ) cp++;
  2397. continue;
  2398. }
  2399. if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
  2400. cp+=2;
  2401. while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
  2402. if( c=='\n' ) lineno++;
  2403. cp++;
  2404. }
  2405. if( c ) cp++;
  2406. continue;
  2407. }
  2408. ps.tokenstart = cp; /* Mark the beginning of the token */
  2409. ps.tokenlineno = lineno; /* Linenumber on which token begins */
  2410. if( c=='\"' ){ /* String literals */
  2411. cp++;
  2412. while( (c= *cp)!=0 && c!='\"' ){
  2413. if( c=='\n' ) lineno++;
  2414. cp++;
  2415. }
  2416. if( c==0 ){
  2417. ErrorMsg(ps.filename,startline,
  2418. "String starting on this line is not terminated before the end of the file.");
  2419. ps.errorcnt++;
  2420. nextcp = cp;
  2421. }else{
  2422. nextcp = cp+1;
  2423. }
  2424. }else if( c=='{' ){ /* A block of C code */
  2425. int level;
  2426. cp++;
  2427. for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
  2428. if( c=='\n' ) lineno++;
  2429. else if( c=='{' ) level++;
  2430. else if( c=='}' ) level--;
  2431. else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
  2432. int prevc;
  2433. cp = &cp[2];
  2434. prevc = 0;
  2435. while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
  2436. if( c=='\n' ) lineno++;
  2437. prevc = c;
  2438. cp++;
  2439. }
  2440. }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
  2441. cp = &cp[2];
  2442. while( (c= *cp)!=0 && c!='\n' ) cp++;
  2443. if( c ) lineno++;
  2444. }else if( c=='\'' || c=='\"' ){ /* String a character literals */
  2445. int startchar, prevc;
  2446. startchar = c;
  2447. prevc = 0;
  2448. for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
  2449. if( c=='\n' ) lineno++;
  2450. if( prevc=='\\' ) prevc = 0;
  2451. else prevc = c;
  2452. }
  2453. }
  2454. }
  2455. if( c==0 ){
  2456. ErrorMsg(ps.filename,ps.tokenlineno,
  2457. "C code starting on this line is not terminated before the end of the file.");
  2458. ps.errorcnt++;
  2459. nextcp = cp;
  2460. }else{
  2461. nextcp = cp+1;
  2462. }
  2463. }else if( isalnum(c) ){ /* Identifiers */
  2464. while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
  2465. nextcp = cp;
  2466. }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
  2467. cp += 3;
  2468. nextcp = cp;
  2469. }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
  2470. cp += 2;
  2471. while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
  2472. nextcp = cp;
  2473. }else{ /* All other (one character) operators */
  2474. cp++;
  2475. nextcp = cp;
  2476. }
  2477. c = *cp;
  2478. *cp = 0; /* Null terminate the token */
  2479. parseonetoken(&ps); /* Parse the token */
  2480. *cp = c; /* Restore the buffer */
  2481. cp = nextcp;
  2482. }
  2483. free(filebuf); /* Release the buffer after parsing */
  2484. gp->rule = ps.firstrule;
  2485. gp->errorcnt = ps.errorcnt;
  2486. }
  2487. /*************************** From the file "plink.c" *********************/
  2488. /*
  2489. ** Routines processing configuration follow-set propagation links
  2490. ** in the LEMON parser generator.
  2491. */
  2492. static struct plink *plink_freelist = 0;
  2493. /* Allocate a new plink */
  2494. struct plink *Plink_new(){
  2495. struct plink *new;
  2496. if( plink_freelist==0 ){
  2497. int i;
  2498. int amt = 100;
  2499. plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
  2500. if( plink_freelist==0 ){
  2501. fprintf(stderr,
  2502. "Unable to allocate memory for a new follow-set propagation link.\n");
  2503. exit(1);
  2504. }
  2505. for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
  2506. plink_freelist[amt-1].next = 0;
  2507. }
  2508. new = plink_freelist;
  2509. plink_freelist = plink_freelist->next;
  2510. return new;
  2511. }
  2512. /* Add a plink to a plink list */
  2513. void Plink_add(plpp,cfp)
  2514. struct plink **plpp;
  2515. struct config *cfp;
  2516. {
  2517. struct plink *new;
  2518. new = Plink_new();
  2519. new->next = *plpp;
  2520. *plpp = new;
  2521. new->cfp = cfp;
  2522. }
  2523. /* Transfer every plink on the list "from" to the list "to" */
  2524. void Plink_copy(to,from)
  2525. struct plink **to;
  2526. struct plink *from;
  2527. {
  2528. struct plink *nextpl;
  2529. while( from ){
  2530. nextpl = from->next;
  2531. from->next = *to;
  2532. *to = from;
  2533. from = nextpl;
  2534. }
  2535. }
  2536. /* Delete every plink on the list */
  2537. void Plink_delete(plp)
  2538. struct plink *plp;
  2539. {
  2540. struct plink *nextpl;
  2541. while( plp ){
  2542. nextpl = plp->next;
  2543. plp->next = plink_freelist;
  2544. plink_freelist = plp;
  2545. plp = nextpl;
  2546. }
  2547. }
  2548. /*********************** From the file "report.c" **************************/
  2549. /*
  2550. ** Procedures for generating reports and tables in the LEMON parser generator.
  2551. */
  2552. /* Generate a filename with the given suffix. Space to hold the
  2553. ** name comes from malloc() and must be freed by the calling
  2554. ** function.
  2555. */
  2556. PRIVATE char *file_makename(lemp,suffix)
  2557. struct lemon *lemp;
  2558. char *suffix;
  2559. {
  2560. char *name;
  2561. char *cp;
  2562. name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
  2563. if( name==0 ){
  2564. fprintf(stderr,"Can't allocate space for a filename.\n");
  2565. exit(1);
  2566. }
  2567. strcpy(name,lemp->filename);
  2568. cp = strrchr(name,'.');
  2569. if( cp ) *cp = 0;
  2570. strcat(name,suffix);
  2571. return name;
  2572. }
  2573. /* Open a file with a name based on the name of the input file,
  2574. ** but with a different (specified) suffix, and return a pointer
  2575. ** to the stream */
  2576. PRIVATE FILE *file_open(lemp,suffix,mode)
  2577. struct lemon *lemp;
  2578. char *suffix;
  2579. char *mode;
  2580. {
  2581. FILE *fp;
  2582. if( lemp->outname ) free(lemp->outname);
  2583. lemp->outname = file_makename(lemp, suffix);
  2584. fp = fopen(lemp->outname,mode);
  2585. if( fp==0 && *mode=='w' ){
  2586. fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
  2587. lemp->errorcnt++;
  2588. return 0;
  2589. }
  2590. return fp;
  2591. }
  2592. /* Duplicate the input file without comments and without actions
  2593. ** on rules */
  2594. void Reprint(lemp)
  2595. struct lemon *lemp;
  2596. {
  2597. struct rule *rp;
  2598. struct symbol *sp;
  2599. int i, j, maxlen, len, ncolumns, skip;
  2600. printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
  2601. maxlen = 10;
  2602. for(i=0; i<lemp->nsymbol; i++){
  2603. sp = lemp->symbols[i];
  2604. len = lemonStrlen(sp->name);
  2605. if( len>maxlen ) maxlen = len;
  2606. }
  2607. ncolumns = 76/(maxlen+5);
  2608. if( ncolumns<1 ) ncolumns = 1;
  2609. skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
  2610. for(i=0; i<skip; i++){
  2611. printf("//");
  2612. for(j=i; j<lemp->nsymbol; j+=skip){
  2613. sp = lemp->symbols[j];
  2614. assert( sp->index==j );
  2615. printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
  2616. }
  2617. printf("\n");
  2618. }
  2619. for(rp=lemp->rule; rp; rp=rp->next){
  2620. printf("%s",rp->lhs->name);
  2621. /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
  2622. printf(" ::=");
  2623. for(i=0; i<rp->nrhs; i++){
  2624. sp = rp->rhs[i];
  2625. printf(" %s", sp->name);
  2626. if( sp->type==MULTITERMINAL ){
  2627. for(j=1; j<sp->nsubsym; j++){
  2628. printf("|%s", sp->subsym[j]->name);
  2629. }
  2630. }
  2631. /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
  2632. }
  2633. printf(".");
  2634. if( rp->precsym ) printf(" [%s]",rp->precsym->name);
  2635. /* if( rp->code ) printf("\n %s",rp->code); */
  2636. printf("\n");
  2637. }
  2638. }
  2639. void ConfigPrint(fp,cfp)
  2640. FILE *fp;
  2641. struct config *cfp;
  2642. {
  2643. struct rule *rp;
  2644. struct symbol *sp;
  2645. int i, j;
  2646. rp = cfp->rp;
  2647. fprintf(fp,"%s ::=",rp->lhs->name);
  2648. for(i=0; i<=rp->nrhs; i++){
  2649. if( i==cfp->dot ) fprintf(fp," *");
  2650. if( i==rp->nrhs ) break;
  2651. sp = rp->rhs[i];
  2652. fprintf(fp," %s", sp->name);
  2653. if( sp->type==MULTITERMINAL ){
  2654. for(j=1; j<sp->nsubsym; j++){
  2655. fprintf(fp,"|%s",sp->subsym[j]->name);
  2656. }
  2657. }
  2658. }
  2659. }
  2660. /* #define TEST */
  2661. #if 0
  2662. /* Print a set */
  2663. PRIVATE void SetPrint(out,set,lemp)
  2664. FILE *out;
  2665. char *set;
  2666. struct lemon *lemp;
  2667. {
  2668. int i;
  2669. char *spacer;
  2670. spacer = "";
  2671. fprintf(out,"%12s[","");
  2672. for(i=0; i<lemp->nterminal; i++){
  2673. if( SetFind(set,i) ){
  2674. fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
  2675. spacer = " ";
  2676. }
  2677. }
  2678. fprintf(out,"]\n");
  2679. }
  2680. /* Print a plink chain */
  2681. PRIVATE void PlinkPrint(out,plp,tag)
  2682. FILE *out;
  2683. struct plink *plp;
  2684. char *tag;
  2685. {
  2686. while( plp ){
  2687. fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
  2688. ConfigPrint(out,plp->cfp);
  2689. fprintf(out,"\n");
  2690. plp = plp->next;
  2691. }
  2692. }
  2693. #endif
  2694. /* Print an action to the given file descriptor. Return FALSE if
  2695. ** nothing was actually printed.
  2696. */
  2697. int PrintAction(struct action *ap, FILE *fp, int indent){
  2698. int result = 1;
  2699. switch( ap->type ){
  2700. case SHIFT:
  2701. fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
  2702. break;
  2703. case REDUCE:
  2704. fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
  2705. break;
  2706. case ACCEPT:
  2707. fprintf(fp,"%*s accept",indent,ap->sp->name);
  2708. break;
  2709. case ERROR:
  2710. fprintf(fp,"%*s error",indent,ap->sp->name);
  2711. break;
  2712. case SRCONFLICT:
  2713. case RRCONFLICT:
  2714. fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
  2715. indent,ap->sp->name,ap->x.rp->index);
  2716. break;
  2717. case SSCONFLICT:
  2718. fprintf(fp,"%*s shift %d ** Parsing conflict **",
  2719. indent,ap->sp->name,ap->x.stp->statenum);
  2720. break;
  2721. case SH_RESOLVED:
  2722. case RD_RESOLVED:
  2723. case NOT_USED:
  2724. result = 0;
  2725. break;
  2726. }
  2727. return result;
  2728. }
  2729. /* Generate the "y.output" log file */
  2730. void ReportOutput(lemp)
  2731. struct lemon *lemp;
  2732. {
  2733. int i;
  2734. struct state *stp;
  2735. struct config *cfp;
  2736. struct action *ap;
  2737. FILE *fp;
  2738. fp = file_open(lemp,".out","wb");
  2739. if( fp==0 ) return;
  2740. for(i=0; i<lemp->nstate; i++){
  2741. stp = lemp->sorted[i];
  2742. fprintf(fp,"State %d:\n",stp->statenum);
  2743. if( lemp->basisflag ) cfp=stp->bp;
  2744. else cfp=stp->cfp;
  2745. while( cfp ){
  2746. char buf[20];
  2747. if( cfp->dot==cfp->rp->nrhs ){
  2748. sprintf(buf,"(%d)",cfp->rp->index);
  2749. fprintf(fp," %5s ",buf);
  2750. }else{
  2751. fprintf(fp," ");
  2752. }
  2753. ConfigPrint(fp,cfp);
  2754. fprintf(fp,"\n");
  2755. #if 0
  2756. SetPrint(fp,cfp->fws,lemp);
  2757. PlinkPrint(fp,cfp->fplp,"To ");
  2758. PlinkPrint(fp,cfp->bplp,"From");
  2759. #endif
  2760. if( lemp->basisflag ) cfp=cfp->bp;
  2761. else cfp=cfp->next;
  2762. }
  2763. fprintf(fp,"\n");
  2764. for(ap=stp->ap; ap; ap=ap->next){
  2765. if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
  2766. }
  2767. fprintf(fp,"\n");
  2768. }
  2769. fprintf(fp, "----------------------------------------------------\n");
  2770. fprintf(fp, "Symbols:\n");
  2771. for(i=0; i<lemp->nsymbol; i++){
  2772. int j;
  2773. struct symbol *sp;
  2774. sp = lemp->symbols[i];
  2775. fprintf(fp, " %3d: %s", i, sp->name);
  2776. if( sp->type==NONTERMINAL ){
  2777. fprintf(fp, ":");
  2778. if( sp->lambda ){
  2779. fprintf(fp, " <lambda>");
  2780. }
  2781. for(j=0; j<lemp->nterminal; j++){
  2782. if( sp->firstset && SetFind(sp->firstset, j) ){
  2783. fprintf(fp, " %s", lemp->symbols[j]->name);
  2784. }
  2785. }
  2786. }
  2787. fprintf(fp, "\n");
  2788. }
  2789. fclose(fp);
  2790. return;
  2791. }
  2792. /* Search for the file "name" which is in the same directory as
  2793. ** the exacutable */
  2794. PRIVATE char *pathsearch(argv0,name,modemask)
  2795. char *argv0;
  2796. char *name;
  2797. int modemask;
  2798. {
  2799. char *pathlist;
  2800. char *path,*cp;
  2801. char c;
  2802. #ifdef __WIN32__
  2803. cp = strrchr(argv0,'\\');
  2804. #else
  2805. cp = strrchr(argv0,'/');
  2806. #endif
  2807. if( cp ){
  2808. c = *cp;
  2809. *cp = 0;
  2810. path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
  2811. if( path ) sprintf(path,"%s/%s",argv0,name);
  2812. *cp = c;
  2813. }else{
  2814. extern char *getenv();
  2815. pathlist = getenv("PATH");
  2816. if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
  2817. path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
  2818. if( path!=0 ){
  2819. while( *pathlist ){
  2820. cp = strchr(pathlist,':');
  2821. if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
  2822. c = *cp;
  2823. *cp = 0;
  2824. sprintf(path,"%s/%s",pathlist,name);
  2825. *cp = c;
  2826. if( c==0 ) pathlist = "";
  2827. else pathlist = &cp[1];
  2828. if( access(path,modemask)==0 ) break;
  2829. }
  2830. }
  2831. }
  2832. return path;
  2833. }
  2834. /* Given an action, compute the integer value for that action
  2835. ** which is to be put in the action table of the generated machine.
  2836. ** Return negative if no action should be generated.
  2837. */
  2838. PRIVATE int compute_action(lemp,ap)
  2839. struct lemon *lemp;
  2840. struct action *ap;
  2841. {
  2842. int act;
  2843. switch( ap->type ){
  2844. case SHIFT: act = ap->x.stp->statenum; break;
  2845. case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
  2846. case ERROR: act = lemp->nstate + lemp->nrule; break;
  2847. case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
  2848. default: act = -1; break;
  2849. }
  2850. return act;
  2851. }
  2852. #define LINESIZE 1000
  2853. /* The next cluster of routines are for reading the template file
  2854. ** and writing the results to the generated parser */
  2855. /* The first function transfers data from "in" to "out" until
  2856. ** a line is seen which begins with "%%". The line number is
  2857. ** tracked.
  2858. **
  2859. ** if name!=0, then any word that begin with "Parse" is changed to
  2860. ** begin with *name instead.
  2861. */
  2862. PRIVATE void tplt_xfer(name,in,out,lineno)
  2863. char *name;
  2864. FILE *in;
  2865. FILE *out;
  2866. int *lineno;
  2867. {
  2868. int i, iStart;
  2869. char line[LINESIZE];
  2870. while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
  2871. (*lineno)++;
  2872. iStart = 0;
  2873. if( name ){
  2874. for(i=0; line[i]; i++){
  2875. if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
  2876. && (i==0 || !isalpha(line[i-1]))
  2877. ){
  2878. if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
  2879. fprintf(out,"%s",name);
  2880. i += 4;
  2881. iStart = i+1;
  2882. }
  2883. }
  2884. }
  2885. fprintf(out,"%s",&line[iStart]);
  2886. }
  2887. }
  2888. /* The next function finds the template file and opens it, returning
  2889. ** a pointer to the opened file. */
  2890. PRIVATE FILE *tplt_open(lemp)
  2891. struct lemon *lemp;
  2892. {
  2893. static char templatename[] = "lempar.c";
  2894. char buf[1000];
  2895. FILE *in;
  2896. char *tpltname;
  2897. char *cp;
  2898. cp = strrchr(lemp->filename,'.');
  2899. if( cp ){
  2900. sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
  2901. }else{
  2902. sprintf(buf,"%s.lt",lemp->filename);
  2903. }
  2904. if( access(buf,004)==0 ){
  2905. tpltname = buf;
  2906. }else if( access(templatename,004)==0 ){
  2907. tpltname = templatename;
  2908. }else{
  2909. tpltname = pathsearch(lemp->argv0,templatename,0);
  2910. }
  2911. if( tpltname==0 ){
  2912. fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
  2913. templatename);
  2914. lemp->errorcnt++;
  2915. return 0;
  2916. }
  2917. in = fopen(tpltname,"rb");
  2918. if( in==0 ){
  2919. fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
  2920. lemp->errorcnt++;
  2921. return 0;
  2922. }
  2923. return in;
  2924. }
  2925. /* Print a #line directive line to the output file. */
  2926. PRIVATE void tplt_linedir(out,lineno,filename)
  2927. FILE *out;
  2928. int lineno;
  2929. char *filename;
  2930. {
  2931. fprintf(out,"#line %d \"",lineno);
  2932. while( *filename ){
  2933. if( *filename == '\\' ) putc('\\',out);
  2934. putc(*filename,out);
  2935. filename++;
  2936. }
  2937. fprintf(out,"\"\n");
  2938. }
  2939. /* Print a string to the file and keep the linenumber up to date */
  2940. PRIVATE void tplt_print(out,lemp,str,lineno)
  2941. FILE *out;
  2942. struct lemon *lemp;
  2943. char *str;
  2944. int *lineno;
  2945. {
  2946. if( str==0 ) return;
  2947. while( *str ){
  2948. putc(*str,out);
  2949. if( *str=='\n' ) (*lineno)++;
  2950. str++;
  2951. }
  2952. if( str[-1]!='\n' ){
  2953. putc('\n',out);
  2954. (*lineno)++;
  2955. }
  2956. if (!lemp->nolinenosflag) {
  2957. (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
  2958. }
  2959. return;
  2960. }
  2961. /*
  2962. ** The following routine emits code for the destructor for the
  2963. ** symbol sp
  2964. */
  2965. void emit_destructor_code(out,sp,lemp,lineno)
  2966. FILE *out;
  2967. struct symbol *sp;
  2968. struct lemon *lemp;
  2969. int *lineno;
  2970. {
  2971. char *cp = 0;
  2972. if( sp->type==TERMINAL ){
  2973. cp = lemp->tokendest;
  2974. if( cp==0 ) return;
  2975. fprintf(out,"{\n"); (*lineno)++;
  2976. }else if( sp->destructor ){
  2977. cp = sp->destructor;
  2978. fprintf(out,"{\n"); (*lineno)++;
  2979. if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
  2980. }else if( lemp->vardest ){
  2981. cp = lemp->vardest;
  2982. if( cp==0 ) return;
  2983. fprintf(out,"{\n"); (*lineno)++;
  2984. }else{
  2985. assert( 0 ); /* Cannot happen */
  2986. }
  2987. for(; *cp; cp++){
  2988. if( *cp=='$' && cp[1]=='$' ){
  2989. fprintf(out,"(yypminor->yy%d)",sp->dtnum);
  2990. cp++;
  2991. continue;
  2992. }
  2993. if( *cp=='\n' ) (*lineno)++;
  2994. fputc(*cp,out);
  2995. }
  2996. fprintf(out,"\n"); (*lineno)++;
  2997. if (!lemp->nolinenosflag) {
  2998. (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
  2999. }
  3000. fprintf(out,"}\n"); (*lineno)++;
  3001. return;
  3002. }
  3003. /*
  3004. ** Return TRUE (non-zero) if the given symbol has a destructor.
  3005. */
  3006. int has_destructor(sp, lemp)
  3007. struct symbol *sp;
  3008. struct lemon *lemp;
  3009. {
  3010. int ret;
  3011. if( sp->type==TERMINAL ){
  3012. ret = lemp->tokendest!=0;
  3013. }else{
  3014. ret = lemp->vardest!=0 || sp->destructor!=0;
  3015. }
  3016. return ret;
  3017. }
  3018. /*
  3019. ** Append text to a dynamically allocated string. If zText is 0 then
  3020. ** reset the string to be empty again. Always return the complete text
  3021. ** of the string (which is overwritten with each call).
  3022. **
  3023. ** n bytes of zText are stored. If n==0 then all of zText up to the first
  3024. ** \000 terminator is stored. zText can contain up to two instances of
  3025. ** %d. The values of p1 and p2 are written into the first and second
  3026. ** %d.
  3027. **
  3028. ** If n==-1, then the previous character is overwritten.
  3029. */
  3030. PRIVATE char *append_str(char *zText, int n, int p1, int p2){
  3031. static char *z = 0;
  3032. static int alloced = 0;
  3033. static int used = 0;
  3034. int c;
  3035. char zInt[40];
  3036. if( zText==0 ){
  3037. used = 0;
  3038. return z;
  3039. }
  3040. if( n<=0 ){
  3041. if( n<0 ){
  3042. used += n;
  3043. assert( used>=0 );
  3044. }
  3045. n = lemonStrlen(zText);
  3046. }
  3047. if( n+sizeof(zInt)*2+used >= alloced ){
  3048. alloced = n + sizeof(zInt)*2 + used + 200;
  3049. z = realloc(z, alloced);
  3050. }
  3051. if( z==0 ) return "";
  3052. while( n-- > 0 ){
  3053. c = *(zText++);
  3054. if( c=='%' && n>0 && zText[0]=='d' ){
  3055. sprintf(zInt, "%d", p1);
  3056. p1 = p2;
  3057. strcpy(&z[used], zInt);
  3058. used += lemonStrlen(&z[used]);
  3059. zText++;
  3060. n--;
  3061. }else{
  3062. z[used++] = c;
  3063. }
  3064. }
  3065. z[used] = 0;
  3066. return z;
  3067. }
  3068. /*
  3069. ** zCode is a string that is the action associated with a rule. Expand
  3070. ** the symbols in this string so that the refer to elements of the parser
  3071. ** stack.
  3072. */
  3073. PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
  3074. char *cp, *xp;
  3075. int i;
  3076. char lhsused = 0; /* True if the LHS element has been used */
  3077. char used[MAXRHS]; /* True for each RHS element which is used */
  3078. for(i=0; i<rp->nrhs; i++) used[i] = 0;
  3079. lhsused = 0;
  3080. if( rp->code==0 ){
  3081. rp->code = "\n";
  3082. rp->line = rp->ruleline;
  3083. }
  3084. append_str(0,0,0,0);
  3085. for(cp=rp->code; *cp; cp++){
  3086. if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
  3087. char saved;
  3088. for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
  3089. saved = *xp;
  3090. *xp = 0;
  3091. if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
  3092. append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
  3093. cp = xp;
  3094. lhsused = 1;
  3095. }else{
  3096. for(i=0; i<rp->nrhs; i++){
  3097. if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
  3098. if( cp!=rp->code && cp[-1]=='@' ){
  3099. /* If the argument is of the form @X then substituted
  3100. ** the token number of X, not the value of X */
  3101. append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
  3102. }else{
  3103. struct symbol *sp = rp->rhs[i];
  3104. int dtnum;
  3105. if( sp->type==MULTITERMINAL ){
  3106. dtnum = sp->subsym[0]->dtnum;
  3107. }else{
  3108. dtnum = sp->dtnum;
  3109. }
  3110. append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
  3111. }
  3112. cp = xp;
  3113. used[i] = 1;
  3114. break;
  3115. }
  3116. }
  3117. }
  3118. *xp = saved;
  3119. }
  3120. append_str(cp, 1, 0, 0);
  3121. } /* End loop */
  3122. /* Check to make sure the LHS has been used */
  3123. if( rp->lhsalias && !lhsused ){
  3124. ErrorMsg(lemp->filename,rp->ruleline,
  3125. "Label \"%s\" for \"%s(%s)\" is never used.",
  3126. rp->lhsalias,rp->lhs->name,rp->lhsalias);
  3127. lemp->errorcnt++;
  3128. }
  3129. /* Generate destructor code for RHS symbols which are not used in the
  3130. ** reduce code */
  3131. for(i=0; i<rp->nrhs; i++){
  3132. if( rp->rhsalias[i] && !used[i] ){
  3133. ErrorMsg(lemp->filename,rp->ruleline,
  3134. "Label %s for \"%s(%s)\" is never used.",
  3135. rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
  3136. lemp->errorcnt++;
  3137. }else if( rp->rhsalias[i]==0 ){
  3138. if( has_destructor(rp->rhs[i],lemp) ){
  3139. append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
  3140. rp->rhs[i]->index,i-rp->nrhs+1);
  3141. }else{
  3142. /* No destructor defined for this term */
  3143. }
  3144. }
  3145. }
  3146. if( rp->code ){
  3147. cp = append_str(0,0,0,0);
  3148. rp->code = Strsafe(cp?cp:"");
  3149. }
  3150. }
  3151. /*
  3152. ** Generate code which executes when the rule "rp" is reduced. Write
  3153. ** the code to "out". Make sure lineno stays up-to-date.
  3154. */
  3155. PRIVATE void emit_code(out,rp,lemp,lineno)
  3156. FILE *out;
  3157. struct rule *rp;
  3158. struct lemon *lemp;
  3159. int *lineno;
  3160. {
  3161. char *cp;
  3162. /* Generate code to do the reduce action */
  3163. if( rp->code ){
  3164. if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
  3165. fprintf(out,"{%s",rp->code);
  3166. for(cp=rp->code; *cp; cp++){
  3167. if( *cp=='\n' ) (*lineno)++;
  3168. } /* End loop */
  3169. fprintf(out,"}\n"); (*lineno)++;
  3170. if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
  3171. } /* End if( rp->code ) */
  3172. return;
  3173. }
  3174. /*
  3175. ** Print the definition of the union used for the parser's data stack.
  3176. ** This union contains fields for every possible data type for tokens
  3177. ** and nonterminals. In the process of computing and printing this
  3178. ** union, also set the ".dtnum" field of every terminal and nonterminal
  3179. ** symbol.
  3180. */
  3181. void print_stack_union(out,lemp,plineno,mhflag)
  3182. FILE *out; /* The output stream */
  3183. struct lemon *lemp; /* The main info structure for this parser */
  3184. int *plineno; /* Pointer to the line number */
  3185. int mhflag; /* True if generating makeheaders output */
  3186. {
  3187. int lineno = *plineno; /* The line number of the output */
  3188. char **types; /* A hash table of datatypes */
  3189. int arraysize; /* Size of the "types" array */
  3190. int maxdtlength; /* Maximum length of any ".datatype" field. */
  3191. char *stddt; /* Standardized name for a datatype */
  3192. int i,j; /* Loop counters */
  3193. int hash; /* For hashing the name of a type */
  3194. char *name; /* Name of the parser */
  3195. /* Allocate and initialize types[] and allocate stddt[] */
  3196. arraysize = lemp->nsymbol * 2;
  3197. types = (char**)calloc( arraysize, sizeof(char*) );
  3198. for(i=0; i<arraysize; i++) types[i] = 0;
  3199. maxdtlength = 0;
  3200. if( lemp->vartype ){
  3201. maxdtlength = lemonStrlen(lemp->vartype);
  3202. }
  3203. for(i=0; i<lemp->nsymbol; i++){
  3204. int len;
  3205. struct symbol *sp = lemp->symbols[i];
  3206. if( sp->datatype==0 ) continue;
  3207. len = lemonStrlen(sp->datatype);
  3208. if( len>maxdtlength ) maxdtlength = len;
  3209. }
  3210. stddt = (char*)malloc( maxdtlength*2 + 1 );
  3211. if( types==0 || stddt==0 ){
  3212. fprintf(stderr,"Out of memory.\n");
  3213. exit(1);
  3214. }
  3215. /* Build a hash table of datatypes. The ".dtnum" field of each symbol
  3216. ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
  3217. ** used for terminal symbols. If there is no %default_type defined then
  3218. ** 0 is also used as the .dtnum value for nonterminals which do not specify
  3219. ** a datatype using the %type directive.
  3220. */
  3221. for(i=0; i<lemp->nsymbol; i++){
  3222. struct symbol *sp = lemp->symbols[i];
  3223. char *cp;
  3224. if( sp==lemp->errsym ){
  3225. sp->dtnum = arraysize+1;
  3226. continue;
  3227. }
  3228. if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
  3229. sp->dtnum = 0;
  3230. continue;
  3231. }
  3232. cp = sp->datatype;
  3233. if( cp==0 ) cp = lemp->vartype;
  3234. j = 0;
  3235. while( isspace(*cp) ) cp++;
  3236. while( *cp ) stddt[j++] = *cp++;
  3237. while( j>0 && isspace(stddt[j-1]) ) j--;
  3238. stddt[j] = 0;
  3239. if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
  3240. sp->dtnum = 0;
  3241. continue;
  3242. }
  3243. hash = 0;
  3244. for(j=0; stddt[j]; j++){
  3245. hash = hash*53 + stddt[j];
  3246. }
  3247. hash = (hash & 0x7fffffff)%arraysize;
  3248. while( types[hash] ){
  3249. if( strcmp(types[hash],stddt)==0 ){
  3250. sp->dtnum = hash + 1;
  3251. break;
  3252. }
  3253. hash++;
  3254. if( hash>=arraysize ) hash = 0;
  3255. }
  3256. if( types[hash]==0 ){
  3257. sp->dtnum = hash + 1;
  3258. types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
  3259. if( types[hash]==0 ){
  3260. fprintf(stderr,"Out of memory.\n");
  3261. exit(1);
  3262. }
  3263. strcpy(types[hash],stddt);
  3264. }
  3265. }
  3266. /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
  3267. name = lemp->name ? lemp->name : "Parse";
  3268. lineno = *plineno;
  3269. if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
  3270. fprintf(out,"#define %sTOKENTYPE %s\n",name,
  3271. lemp->tokentype?lemp->tokentype:"void*"); lineno++;
  3272. if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
  3273. fprintf(out,"typedef union {\n"); lineno++;
  3274. fprintf(out," int yyinit;\n"); lineno++;
  3275. fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
  3276. for(i=0; i<arraysize; i++){
  3277. if( types[i]==0 ) continue;
  3278. fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
  3279. free(types[i]);
  3280. }
  3281. if( lemp->errsym->useCnt ){
  3282. fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
  3283. }
  3284. free(stddt);
  3285. free(types);
  3286. fprintf(out,"} YYMINORTYPE;\n"); lineno++;
  3287. *plineno = lineno;
  3288. }
  3289. /*
  3290. ** Return the name of a C datatype able to represent values between
  3291. ** lwr and upr, inclusive.
  3292. */
  3293. static const char *minimum_size_type(int lwr, int upr){
  3294. if( lwr>=0 ){
  3295. if( upr<=255 ){
  3296. return "unsigned char";
  3297. }else if( upr<65535 ){
  3298. return "unsigned short int";
  3299. }else{
  3300. return "unsigned int";
  3301. }
  3302. }else if( lwr>=-127 && upr<=127 ){
  3303. return "signed char";
  3304. }else if( lwr>=-32767 && upr<32767 ){
  3305. return "short";
  3306. }else{
  3307. return "int";
  3308. }
  3309. }
  3310. /*
  3311. ** Each state contains a set of token transaction and a set of
  3312. ** nonterminal transactions. Each of these sets makes an instance
  3313. ** of the following structure. An array of these structures is used
  3314. ** to order the creation of entries in the yy_action[] table.
  3315. */
  3316. struct axset {
  3317. struct state *stp; /* A pointer to a state */
  3318. int isTkn; /* True to use tokens. False for non-terminals */
  3319. int nAction; /* Number of actions */
  3320. };
  3321. /*
  3322. ** Compare to axset structures for sorting purposes
  3323. */
  3324. static int axset_compare(const void *a, const void *b){
  3325. struct axset *p1 = (struct axset*)a;
  3326. struct axset *p2 = (struct axset*)b;
  3327. return p2->nAction - p1->nAction;
  3328. }
  3329. /*
  3330. ** Write text on "out" that describes the rule "rp".
  3331. */
  3332. static void writeRuleText(FILE *out, struct rule *rp){
  3333. int j;
  3334. fprintf(out,"%s ::=", rp->lhs->name);
  3335. for(j=0; j<rp->nrhs; j++){
  3336. struct symbol *sp = rp->rhs[j];
  3337. fprintf(out," %s", sp->name);
  3338. if( sp->type==MULTITERMINAL ){
  3339. int k;
  3340. for(k=1; k<sp->nsubsym; k++){
  3341. fprintf(out,"|%s",sp->subsym[k]->name);
  3342. }
  3343. }
  3344. }
  3345. }
  3346. /* Generate C source code for the parser */
  3347. void ReportTable(lemp, mhflag)
  3348. struct lemon *lemp;
  3349. int mhflag; /* Output in makeheaders format if true */
  3350. {
  3351. FILE *out, *in;
  3352. char line[LINESIZE];
  3353. int lineno;
  3354. struct state *stp;
  3355. struct action *ap;
  3356. struct rule *rp;
  3357. struct acttab *pActtab;
  3358. int i, j, n;
  3359. char *name;
  3360. int mnTknOfst, mxTknOfst;
  3361. int mnNtOfst, mxNtOfst;
  3362. struct axset *ax;
  3363. in = tplt_open(lemp);
  3364. if( in==0 ) return;
  3365. out = file_open(lemp,".c","wb");
  3366. if( out==0 ){
  3367. fclose(in);
  3368. return;
  3369. }
  3370. lineno = 1;
  3371. tplt_xfer(lemp->name,in,out,&lineno);
  3372. /* Generate the include code, if any */
  3373. tplt_print(out,lemp,lemp->include,&lineno);
  3374. if( mhflag ){
  3375. char *name = file_makename(lemp, ".h");
  3376. fprintf(out,"#include \"%s\"\n", name); lineno++;
  3377. free(name);
  3378. }
  3379. tplt_xfer(lemp->name,in,out,&lineno);
  3380. /* Generate #defines for all tokens */
  3381. if( mhflag ){
  3382. char *prefix;
  3383. fprintf(out,"#if INTERFACE\n"); lineno++;
  3384. if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
  3385. else prefix = "";
  3386. for(i=1; i<lemp->nterminal; i++){
  3387. fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
  3388. lineno++;
  3389. }
  3390. fprintf(out,"#endif\n"); lineno++;
  3391. }
  3392. tplt_xfer(lemp->name,in,out,&lineno);
  3393. /* Generate the defines */
  3394. fprintf(out,"#define YYCODETYPE %s\n",
  3395. minimum_size_type(0, lemp->nsymbol+1)); lineno++;
  3396. fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
  3397. fprintf(out,"#define YYACTIONTYPE %s\n",
  3398. minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
  3399. if( lemp->wildcard ){
  3400. fprintf(out,"#define YYWILDCARD %d\n",
  3401. lemp->wildcard->index); lineno++;
  3402. }
  3403. print_stack_union(out,lemp,&lineno,mhflag);
  3404. fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
  3405. if( lemp->stacksize ){
  3406. fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
  3407. }else{
  3408. fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
  3409. }
  3410. fprintf(out, "#endif\n"); lineno++;
  3411. if( mhflag ){
  3412. fprintf(out,"#if INTERFACE\n"); lineno++;
  3413. }
  3414. name = lemp->name ? lemp->name : "Parse";
  3415. if( lemp->arg && lemp->arg[0] ){
  3416. int i;
  3417. i = lemonStrlen(lemp->arg);
  3418. while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
  3419. while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
  3420. fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
  3421. fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
  3422. fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
  3423. name,lemp->arg,&lemp->arg[i]); lineno++;
  3424. fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
  3425. name,&lemp->arg[i],&lemp->arg[i]); lineno++;
  3426. }else{
  3427. fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
  3428. fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
  3429. fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
  3430. fprintf(out,"#define %sARG_STORE\n",name); lineno++;
  3431. }
  3432. if( mhflag ){
  3433. fprintf(out,"#endif\n"); lineno++;
  3434. }
  3435. fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
  3436. fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
  3437. if( lemp->errsym->useCnt ){
  3438. fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
  3439. fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
  3440. }
  3441. if( lemp->has_fallback ){
  3442. fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
  3443. }
  3444. tplt_xfer(lemp->name,in,out,&lineno);
  3445. /* Generate the action table and its associates:
  3446. **
  3447. ** yy_action[] A single table containing all actions.
  3448. ** yy_lookahead[] A table containing the lookahead for each entry in
  3449. ** yy_action. Used to detect hash collisions.
  3450. ** yy_shift_ofst[] For each state, the offset into yy_action for
  3451. ** shifting terminals.
  3452. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  3453. ** shifting non-terminals after a reduce.
  3454. ** yy_default[] Default action for each state.
  3455. */
  3456. /* Compute the actions on all states and count them up */
  3457. ax = calloc(lemp->nstate*2, sizeof(ax[0]));
  3458. if( ax==0 ){
  3459. fprintf(stderr,"malloc failed\n");
  3460. exit(1);
  3461. }
  3462. for(i=0; i<lemp->nstate; i++){
  3463. stp = lemp->sorted[i];
  3464. ax[i*2].stp = stp;
  3465. ax[i*2].isTkn = 1;
  3466. ax[i*2].nAction = stp->nTknAct;
  3467. ax[i*2+1].stp = stp;
  3468. ax[i*2+1].isTkn = 0;
  3469. ax[i*2+1].nAction = stp->nNtAct;
  3470. }
  3471. mxTknOfst = mnTknOfst = 0;
  3472. mxNtOfst = mnNtOfst = 0;
  3473. /* Compute the action table. In order to try to keep the size of the
  3474. ** action table to a minimum, the heuristic of placing the largest action
  3475. ** sets first is used.
  3476. */
  3477. qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
  3478. pActtab = acttab_alloc();
  3479. for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
  3480. stp = ax[i].stp;
  3481. if( ax[i].isTkn ){
  3482. for(ap=stp->ap; ap; ap=ap->next){
  3483. int action;
  3484. if( ap->sp->index>=lemp->nterminal ) continue;
  3485. action = compute_action(lemp, ap);
  3486. if( action<0 ) continue;
  3487. acttab_action(pActtab, ap->sp->index, action);
  3488. }
  3489. stp->iTknOfst = acttab_insert(pActtab);
  3490. if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
  3491. if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
  3492. }else{
  3493. for(ap=stp->ap; ap; ap=ap->next){
  3494. int action;
  3495. if( ap->sp->index<lemp->nterminal ) continue;
  3496. if( ap->sp->index==lemp->nsymbol ) continue;
  3497. action = compute_action(lemp, ap);
  3498. if( action<0 ) continue;
  3499. acttab_action(pActtab, ap->sp->index, action);
  3500. }
  3501. stp->iNtOfst = acttab_insert(pActtab);
  3502. if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
  3503. if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
  3504. }
  3505. }
  3506. free(ax);
  3507. /* Output the yy_action table */
  3508. fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
  3509. n = acttab_size(pActtab);
  3510. for(i=j=0; i<n; i++){
  3511. int action = acttab_yyaction(pActtab, i);
  3512. if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
  3513. if( j==0 ) fprintf(out," /* %5d */ ", i);
  3514. fprintf(out, " %4d,", action);
  3515. if( j==9 || i==n-1 ){
  3516. fprintf(out, "\n"); lineno++;
  3517. j = 0;
  3518. }else{
  3519. j++;
  3520. }
  3521. }
  3522. fprintf(out, "};\n"); lineno++;
  3523. /* Output the yy_lookahead table */
  3524. fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
  3525. for(i=j=0; i<n; i++){
  3526. int la = acttab_yylookahead(pActtab, i);
  3527. if( la<0 ) la = lemp->nsymbol;
  3528. if( j==0 ) fprintf(out," /* %5d */ ", i);
  3529. fprintf(out, " %4d,", la);
  3530. if( j==9 || i==n-1 ){
  3531. fprintf(out, "\n"); lineno++;
  3532. j = 0;
  3533. }else{
  3534. j++;
  3535. }
  3536. }
  3537. fprintf(out, "};\n"); lineno++;
  3538. /* Output the yy_shift_ofst[] table */
  3539. fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
  3540. n = lemp->nstate;
  3541. while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
  3542. fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
  3543. fprintf(out, "static const %s yy_shift_ofst[] = {\n",
  3544. minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
  3545. for(i=j=0; i<n; i++){
  3546. int ofst;
  3547. stp = lemp->sorted[i];
  3548. ofst = stp->iTknOfst;
  3549. if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
  3550. if( j==0 ) fprintf(out," /* %5d */ ", i);
  3551. fprintf(out, " %4d,", ofst);
  3552. if( j==9 || i==n-1 ){
  3553. fprintf(out, "\n"); lineno++;
  3554. j = 0;
  3555. }else{
  3556. j++;
  3557. }
  3558. }
  3559. fprintf(out, "};\n"); lineno++;
  3560. /* Output the yy_reduce_ofst[] table */
  3561. fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
  3562. n = lemp->nstate;
  3563. while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
  3564. fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
  3565. fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
  3566. minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
  3567. for(i=j=0; i<n; i++){
  3568. int ofst;
  3569. stp = lemp->sorted[i];
  3570. ofst = stp->iNtOfst;
  3571. if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
  3572. if( j==0 ) fprintf(out," /* %5d */ ", i);
  3573. fprintf(out, " %4d,", ofst);
  3574. if( j==9 || i==n-1 ){
  3575. fprintf(out, "\n"); lineno++;
  3576. j = 0;
  3577. }else{
  3578. j++;
  3579. }
  3580. }
  3581. fprintf(out, "};\n"); lineno++;
  3582. /* Output the default action table */
  3583. fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
  3584. n = lemp->nstate;
  3585. for(i=j=0; i<n; i++){
  3586. stp = lemp->sorted[i];
  3587. if( j==0 ) fprintf(out," /* %5d */ ", i);
  3588. fprintf(out, " %4d,", stp->iDflt);
  3589. if( j==9 || i==n-1 ){
  3590. fprintf(out, "\n"); lineno++;
  3591. j = 0;
  3592. }else{
  3593. j++;
  3594. }
  3595. }
  3596. fprintf(out, "};\n"); lineno++;
  3597. tplt_xfer(lemp->name,in,out,&lineno);
  3598. /* Generate the table of fallback tokens.
  3599. */
  3600. if( lemp->has_fallback ){
  3601. int mx = lemp->nterminal - 1;
  3602. while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
  3603. for(i=0; i<=mx; i++){
  3604. struct symbol *p = lemp->symbols[i];
  3605. if( p->fallback==0 ){
  3606. fprintf(out, " 0, /* %10s => nothing */\n", p->name);
  3607. }else{
  3608. fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
  3609. p->name, p->fallback->name);
  3610. }
  3611. lineno++;
  3612. }
  3613. }
  3614. tplt_xfer(lemp->name, in, out, &lineno);
  3615. /* Generate a table containing the symbolic name of every symbol
  3616. */
  3617. for(i=0; i<lemp->nsymbol; i++){
  3618. sprintf(line,"\"%s\",",lemp->symbols[i]->name);
  3619. fprintf(out," %-15s",line);
  3620. if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
  3621. }
  3622. if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
  3623. tplt_xfer(lemp->name,in,out,&lineno);
  3624. /* Generate a table containing a text string that describes every
  3625. ** rule in the rule set of the grammar. This information is used
  3626. ** when tracing REDUCE actions.
  3627. */
  3628. for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
  3629. assert( rp->index==i );
  3630. fprintf(out," /* %3d */ \"", i);
  3631. writeRuleText(out, rp);
  3632. fprintf(out,"\",\n"); lineno++;
  3633. }
  3634. tplt_xfer(lemp->name,in,out,&lineno);
  3635. /* Generate code which executes every time a symbol is popped from
  3636. ** the stack while processing errors or while destroying the parser.
  3637. ** (In other words, generate the %destructor actions)
  3638. */
  3639. if( lemp->tokendest ){
  3640. int once = 1;
  3641. for(i=0; i<lemp->nsymbol; i++){
  3642. struct symbol *sp = lemp->symbols[i];
  3643. if( sp==0 || sp->type!=TERMINAL ) continue;
  3644. if( once ){
  3645. fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
  3646. once = 0;
  3647. }
  3648. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  3649. }
  3650. for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
  3651. if( i<lemp->nsymbol ){
  3652. emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
  3653. fprintf(out," break;\n"); lineno++;
  3654. }
  3655. }
  3656. if( lemp->vardest ){
  3657. struct symbol *dflt_sp = 0;
  3658. int once = 1;
  3659. for(i=0; i<lemp->nsymbol; i++){
  3660. struct symbol *sp = lemp->symbols[i];
  3661. if( sp==0 || sp->type==TERMINAL ||
  3662. sp->index<=0 || sp->destructor!=0 ) continue;
  3663. if( once ){
  3664. fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
  3665. once = 0;
  3666. }
  3667. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  3668. dflt_sp = sp;
  3669. }
  3670. if( dflt_sp!=0 ){
  3671. emit_destructor_code(out,dflt_sp,lemp,&lineno);
  3672. }
  3673. fprintf(out," break;\n"); lineno++;
  3674. }
  3675. for(i=0; i<lemp->nsymbol; i++){
  3676. struct symbol *sp = lemp->symbols[i];
  3677. if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
  3678. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  3679. /* Combine duplicate destructors into a single case */
  3680. for(j=i+1; j<lemp->nsymbol; j++){
  3681. struct symbol *sp2 = lemp->symbols[j];
  3682. if( sp2 && sp2->type!=TERMINAL && sp2->destructor
  3683. && sp2->dtnum==sp->dtnum
  3684. && strcmp(sp->destructor,sp2->destructor)==0 ){
  3685. fprintf(out," case %d: /* %s */\n",
  3686. sp2->index, sp2->name); lineno++;
  3687. sp2->destructor = 0;
  3688. }
  3689. }
  3690. emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
  3691. fprintf(out," break;\n"); lineno++;
  3692. }
  3693. tplt_xfer(lemp->name,in,out,&lineno);
  3694. /* Generate code which executes whenever the parser stack overflows */
  3695. tplt_print(out,lemp,lemp->overflow,&lineno);
  3696. tplt_xfer(lemp->name,in,out,&lineno);
  3697. /* Generate the table of rule information
  3698. **
  3699. ** Note: This code depends on the fact that rules are number
  3700. ** sequentually beginning with 0.
  3701. */
  3702. for(rp=lemp->rule; rp; rp=rp->next){
  3703. fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
  3704. }
  3705. tplt_xfer(lemp->name,in,out,&lineno);
  3706. /* Generate code which execution during each REDUCE action */
  3707. for(rp=lemp->rule; rp; rp=rp->next){
  3708. translate_code(lemp, rp);
  3709. }
  3710. /* First output rules other than the default: rule */
  3711. for(rp=lemp->rule; rp; rp=rp->next){
  3712. struct rule *rp2; /* Other rules with the same action */
  3713. if( rp->code==0 ) continue;
  3714. if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
  3715. fprintf(out," case %d: /* ", rp->index);
  3716. writeRuleText(out, rp);
  3717. fprintf(out, " */\n"); lineno++;
  3718. for(rp2=rp->next; rp2; rp2=rp2->next){
  3719. if( rp2->code==rp->code ){
  3720. fprintf(out," case %d: /* ", rp2->index);
  3721. writeRuleText(out, rp2);
  3722. fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
  3723. rp2->code = 0;
  3724. }
  3725. }
  3726. emit_code(out,rp,lemp,&lineno);
  3727. fprintf(out," break;\n"); lineno++;
  3728. rp->code = 0;
  3729. }
  3730. /* Finally, output the default: rule. We choose as the default: all
  3731. ** empty actions. */
  3732. fprintf(out," default:\n"); lineno++;
  3733. for(rp=lemp->rule; rp; rp=rp->next){
  3734. if( rp->code==0 ) continue;
  3735. assert( rp->code[0]=='\n' && rp->code[1]==0 );
  3736. fprintf(out," /* (%d) ", rp->index);
  3737. writeRuleText(out, rp);
  3738. fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
  3739. }
  3740. fprintf(out," break;\n"); lineno++;
  3741. tplt_xfer(lemp->name,in,out,&lineno);
  3742. /* Generate code which executes if a parse fails */
  3743. tplt_print(out,lemp,lemp->failure,&lineno);
  3744. tplt_xfer(lemp->name,in,out,&lineno);
  3745. /* Generate code which executes when a syntax error occurs */
  3746. tplt_print(out,lemp,lemp->error,&lineno);
  3747. tplt_xfer(lemp->name,in,out,&lineno);
  3748. /* Generate code which executes when the parser accepts its input */
  3749. tplt_print(out,lemp,lemp->accept,&lineno);
  3750. tplt_xfer(lemp->name,in,out,&lineno);
  3751. /* Append any addition code the user desires */
  3752. tplt_print(out,lemp,lemp->extracode,&lineno);
  3753. fclose(in);
  3754. fclose(out);
  3755. return;
  3756. }
  3757. /* Generate a header file for the parser */
  3758. void ReportHeader(lemp)
  3759. struct lemon *lemp;
  3760. {
  3761. FILE *out, *in;
  3762. char *prefix;
  3763. char line[LINESIZE];
  3764. char pattern[LINESIZE];
  3765. int i;
  3766. if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
  3767. else prefix = "";
  3768. in = file_open(lemp,".h","rb");
  3769. if( in ){
  3770. for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
  3771. sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
  3772. if( strcmp(line,pattern) ) break;
  3773. }
  3774. fclose(in);
  3775. if( i==lemp->nterminal ){
  3776. /* No change in the file. Don't rewrite it. */
  3777. return;
  3778. }
  3779. }
  3780. out = file_open(lemp,".h","wb");
  3781. if( out ){
  3782. for(i=1; i<lemp->nterminal; i++){
  3783. fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
  3784. }
  3785. fclose(out);
  3786. }
  3787. return;
  3788. }
  3789. /* Reduce the size of the action tables, if possible, by making use
  3790. ** of defaults.
  3791. **
  3792. ** In this version, we take the most frequent REDUCE action and make
  3793. ** it the default. Except, there is no default if the wildcard token
  3794. ** is a possible look-ahead.
  3795. */
  3796. void CompressTables(lemp)
  3797. struct lemon *lemp;
  3798. {
  3799. struct state *stp;
  3800. struct action *ap, *ap2;
  3801. struct rule *rp, *rp2, *rbest;
  3802. int nbest, n;
  3803. int i;
  3804. int usesWildcard;
  3805. for(i=0; i<lemp->nstate; i++){
  3806. stp = lemp->sorted[i];
  3807. nbest = 0;
  3808. rbest = 0;
  3809. usesWildcard = 0;
  3810. for(ap=stp->ap; ap; ap=ap->next){
  3811. if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
  3812. usesWildcard = 1;
  3813. }
  3814. if( ap->type!=REDUCE ) continue;
  3815. rp = ap->x.rp;
  3816. if( rp->lhsStart ) continue;
  3817. if( rp==rbest ) continue;
  3818. n = 1;
  3819. for(ap2=ap->next; ap2; ap2=ap2->next){
  3820. if( ap2->type!=REDUCE ) continue;
  3821. rp2 = ap2->x.rp;
  3822. if( rp2==rbest ) continue;
  3823. if( rp2==rp ) n++;
  3824. }
  3825. if( n>nbest ){
  3826. nbest = n;
  3827. rbest = rp;
  3828. }
  3829. }
  3830. /* Do not make a default if the number of rules to default
  3831. ** is not at least 1 or if the wildcard token is a possible
  3832. ** lookahead.
  3833. */
  3834. if( nbest<1 || usesWildcard ) continue;
  3835. /* Combine matching REDUCE actions into a single default */
  3836. for(ap=stp->ap; ap; ap=ap->next){
  3837. if( ap->type==REDUCE && ap->x.rp==rbest ) break;
  3838. }
  3839. assert( ap );
  3840. ap->sp = Symbol_new("{default}");
  3841. for(ap=ap->next; ap; ap=ap->next){
  3842. if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
  3843. }
  3844. stp->ap = Action_sort(stp->ap);
  3845. }
  3846. }
  3847. /*
  3848. ** Compare two states for sorting purposes. The smaller state is the
  3849. ** one with the most non-terminal actions. If they have the same number
  3850. ** of non-terminal actions, then the smaller is the one with the most
  3851. ** token actions.
  3852. */
  3853. static int stateResortCompare(const void *a, const void *b){
  3854. const struct state *pA = *(const struct state**)a;
  3855. const struct state *pB = *(const struct state**)b;
  3856. int n;
  3857. n = pB->nNtAct - pA->nNtAct;
  3858. if( n==0 ){
  3859. n = pB->nTknAct - pA->nTknAct;
  3860. }
  3861. return n;
  3862. }
  3863. /*
  3864. ** Renumber and resort states so that states with fewer choices
  3865. ** occur at the end. Except, keep state 0 as the first state.
  3866. */
  3867. void ResortStates(lemp)
  3868. struct lemon *lemp;
  3869. {
  3870. int i;
  3871. struct state *stp;
  3872. struct action *ap;
  3873. for(i=0; i<lemp->nstate; i++){
  3874. stp = lemp->sorted[i];
  3875. stp->nTknAct = stp->nNtAct = 0;
  3876. stp->iDflt = lemp->nstate + lemp->nrule;
  3877. stp->iTknOfst = NO_OFFSET;
  3878. stp->iNtOfst = NO_OFFSET;
  3879. for(ap=stp->ap; ap; ap=ap->next){
  3880. if( compute_action(lemp,ap)>=0 ){
  3881. if( ap->sp->index<lemp->nterminal ){
  3882. stp->nTknAct++;
  3883. }else if( ap->sp->index<lemp->nsymbol ){
  3884. stp->nNtAct++;
  3885. }else{
  3886. stp->iDflt = compute_action(lemp, ap);
  3887. }
  3888. }
  3889. }
  3890. }
  3891. qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
  3892. stateResortCompare);
  3893. for(i=0; i<lemp->nstate; i++){
  3894. lemp->sorted[i]->statenum = i;
  3895. }
  3896. }
  3897. /***************** From the file "set.c" ************************************/
  3898. /*
  3899. ** Set manipulation routines for the LEMON parser generator.
  3900. */
  3901. static int size = 0;
  3902. /* Set the set size */
  3903. void SetSize(n)
  3904. int n;
  3905. {
  3906. size = n+1;
  3907. }
  3908. /* Allocate a new set */
  3909. char *SetNew(){
  3910. char *s;
  3911. s = (char*)calloc( size, 1);
  3912. if( s==0 ){
  3913. extern void memory_error();
  3914. memory_error();
  3915. }
  3916. return s;
  3917. }
  3918. /* Deallocate a set */
  3919. void SetFree(s)
  3920. char *s;
  3921. {
  3922. free(s);
  3923. }
  3924. /* Add a new element to the set. Return TRUE if the element was added
  3925. ** and FALSE if it was already there. */
  3926. int SetAdd(s,e)
  3927. char *s;
  3928. int e;
  3929. {
  3930. int rv;
  3931. assert( e>=0 && e<size );
  3932. rv = s[e];
  3933. s[e] = 1;
  3934. return !rv;
  3935. }
  3936. /* Add every element of s2 to s1. Return TRUE if s1 changes. */
  3937. int SetUnion(s1,s2)
  3938. char *s1;
  3939. char *s2;
  3940. {
  3941. int i, progress;
  3942. progress = 0;
  3943. for(i=0; i<size; i++){
  3944. if( s2[i]==0 ) continue;
  3945. if( s1[i]==0 ){
  3946. progress = 1;
  3947. s1[i] = 1;
  3948. }
  3949. }
  3950. return progress;
  3951. }
  3952. /********************** From the file "table.c" ****************************/
  3953. /*
  3954. ** All code in this file has been automatically generated
  3955. ** from a specification in the file
  3956. ** "table.q"
  3957. ** by the associative array code building program "aagen".
  3958. ** Do not edit this file! Instead, edit the specification
  3959. ** file, then rerun aagen.
  3960. */
  3961. /*
  3962. ** Code for processing tables in the LEMON parser generator.
  3963. */
  3964. PRIVATE int strhash(x)
  3965. char *x;
  3966. {
  3967. int h = 0;
  3968. while( *x) h = h*13 + *(x++);
  3969. return h;
  3970. }
  3971. /* Works like strdup, sort of. Save a string in malloced memory, but
  3972. ** keep strings in a table so that the same string is not in more
  3973. ** than one place.
  3974. */
  3975. char *Strsafe(y)
  3976. char *y;
  3977. {
  3978. char *z;
  3979. if( y==0 ) return 0;
  3980. z = Strsafe_find(y);
  3981. if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
  3982. strcpy(z,y);
  3983. Strsafe_insert(z);
  3984. }
  3985. MemoryCheck(z);
  3986. return z;
  3987. }
  3988. /* There is one instance of the following structure for each
  3989. ** associative array of type "x1".
  3990. */
  3991. struct s_x1 {
  3992. int size; /* The number of available slots. */
  3993. /* Must be a power of 2 greater than or */
  3994. /* equal to 1 */
  3995. int count; /* Number of currently slots filled */
  3996. struct s_x1node *tbl; /* The data stored here */
  3997. struct s_x1node **ht; /* Hash table for lookups */
  3998. };
  3999. /* There is one instance of this structure for every data element
  4000. ** in an associative array of type "x1".
  4001. */
  4002. typedef struct s_x1node {
  4003. char *data; /* The data */
  4004. struct s_x1node *next; /* Next entry with the same hash */
  4005. struct s_x1node **from; /* Previous link */
  4006. } x1node;
  4007. /* There is only one instance of the array, which is the following */
  4008. static struct s_x1 *x1a;
  4009. /* Allocate a new associative array */
  4010. void Strsafe_init(){
  4011. if( x1a ) return;
  4012. x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
  4013. if( x1a ){
  4014. x1a->size = 1024;
  4015. x1a->count = 0;
  4016. x1a->tbl = (x1node*)malloc(
  4017. (sizeof(x1node) + sizeof(x1node*))*1024 );
  4018. if( x1a->tbl==0 ){
  4019. free(x1a);
  4020. x1a = 0;
  4021. }else{
  4022. int i;
  4023. x1a->ht = (x1node**)&(x1a->tbl[1024]);
  4024. for(i=0; i<1024; i++) x1a->ht[i] = 0;
  4025. }
  4026. }
  4027. }
  4028. /* Insert a new record into the array. Return TRUE if successful.
  4029. ** Prior data with the same key is NOT overwritten */
  4030. int Strsafe_insert(data)
  4031. char *data;
  4032. {
  4033. x1node *np;
  4034. int h;
  4035. int ph;
  4036. if( x1a==0 ) return 0;
  4037. ph = strhash(data);
  4038. h = ph & (x1a->size-1);
  4039. np = x1a->ht[h];
  4040. while( np ){
  4041. if( strcmp(np->data,data)==0 ){
  4042. /* An existing entry with the same key is found. */
  4043. /* Fail because overwrite is not allows. */
  4044. return 0;
  4045. }
  4046. np = np->next;
  4047. }
  4048. if( x1a->count>=x1a->size ){
  4049. /* Need to make the hash table bigger */
  4050. int i,size;
  4051. struct s_x1 array;
  4052. array.size = size = x1a->size*2;
  4053. array.count = x1a->count;
  4054. array.tbl = (x1node*)malloc(
  4055. (sizeof(x1node) + sizeof(x1node*))*size );
  4056. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  4057. array.ht = (x1node**)&(array.tbl[size]);
  4058. for(i=0; i<size; i++) array.ht[i] = 0;
  4059. for(i=0; i<x1a->count; i++){
  4060. x1node *oldnp, *newnp;
  4061. oldnp = &(x1a->tbl[i]);
  4062. h = strhash(oldnp->data) & (size-1);
  4063. newnp = &(array.tbl[i]);
  4064. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  4065. newnp->next = array.ht[h];
  4066. newnp->data = oldnp->data;
  4067. newnp->from = &(array.ht[h]);
  4068. array.ht[h] = newnp;
  4069. }
  4070. free(x1a->tbl);
  4071. *x1a = array;
  4072. }
  4073. /* Insert the new data */
  4074. h = ph & (x1a->size-1);
  4075. np = &(x1a->tbl[x1a->count++]);
  4076. np->data = data;
  4077. if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
  4078. np->next = x1a->ht[h];
  4079. x1a->ht[h] = np;
  4080. np->from = &(x1a->ht[h]);
  4081. return 1;
  4082. }
  4083. /* Return a pointer to data assigned to the given key. Return NULL
  4084. ** if no such key. */
  4085. char *Strsafe_find(key)
  4086. char *key;
  4087. {
  4088. int h;
  4089. x1node *np;
  4090. if( x1a==0 ) return 0;
  4091. h = strhash(key) & (x1a->size-1);
  4092. np = x1a->ht[h];
  4093. while( np ){
  4094. if( strcmp(np->data,key)==0 ) break;
  4095. np = np->next;
  4096. }
  4097. return np ? np->data : 0;
  4098. }
  4099. /* Return a pointer to the (terminal or nonterminal) symbol "x".
  4100. ** Create a new symbol if this is the first time "x" has been seen.
  4101. */
  4102. struct symbol *Symbol_new(x)
  4103. char *x;
  4104. {
  4105. struct symbol *sp;
  4106. sp = Symbol_find(x);
  4107. if( sp==0 ){
  4108. sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
  4109. MemoryCheck(sp);
  4110. sp->name = Strsafe(x);
  4111. sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
  4112. sp->rule = 0;
  4113. sp->fallback = 0;
  4114. sp->prec = -1;
  4115. sp->assoc = UNK;
  4116. sp->firstset = 0;
  4117. sp->lambda = LEMON_FALSE;
  4118. sp->destructor = 0;
  4119. sp->destLineno = 0;
  4120. sp->datatype = 0;
  4121. sp->useCnt = 0;
  4122. Symbol_insert(sp,sp->name);
  4123. }
  4124. sp->useCnt++;
  4125. return sp;
  4126. }
  4127. /* Compare two symbols for working purposes
  4128. **
  4129. ** Symbols that begin with upper case letters (terminals or tokens)
  4130. ** must sort before symbols that begin with lower case letters
  4131. ** (non-terminals). Other than that, the order does not matter.
  4132. **
  4133. ** We find experimentally that leaving the symbols in their original
  4134. ** order (the order they appeared in the grammar file) gives the
  4135. ** smallest parser tables in SQLite.
  4136. */
  4137. int Symbolcmpp(struct symbol **a, struct symbol **b){
  4138. int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
  4139. int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
  4140. return i1-i2;
  4141. }
  4142. /* There is one instance of the following structure for each
  4143. ** associative array of type "x2".
  4144. */
  4145. struct s_x2 {
  4146. int size; /* The number of available slots. */
  4147. /* Must be a power of 2 greater than or */
  4148. /* equal to 1 */
  4149. int count; /* Number of currently slots filled */
  4150. struct s_x2node *tbl; /* The data stored here */
  4151. struct s_x2node **ht; /* Hash table for lookups */
  4152. };
  4153. /* There is one instance of this structure for every data element
  4154. ** in an associative array of type "x2".
  4155. */
  4156. typedef struct s_x2node {
  4157. struct symbol *data; /* The data */
  4158. char *key; /* The key */
  4159. struct s_x2node *next; /* Next entry with the same hash */
  4160. struct s_x2node **from; /* Previous link */
  4161. } x2node;
  4162. /* There is only one instance of the array, which is the following */
  4163. static struct s_x2 *x2a;
  4164. /* Allocate a new associative array */
  4165. void Symbol_init(){
  4166. if( x2a ) return;
  4167. x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
  4168. if( x2a ){
  4169. x2a->size = 128;
  4170. x2a->count = 0;
  4171. x2a->tbl = (x2node*)malloc(
  4172. (sizeof(x2node) + sizeof(x2node*))*128 );
  4173. if( x2a->tbl==0 ){
  4174. free(x2a);
  4175. x2a = 0;
  4176. }else{
  4177. int i;
  4178. x2a->ht = (x2node**)&(x2a->tbl[128]);
  4179. for(i=0; i<128; i++) x2a->ht[i] = 0;
  4180. }
  4181. }
  4182. }
  4183. /* Insert a new record into the array. Return TRUE if successful.
  4184. ** Prior data with the same key is NOT overwritten */
  4185. int Symbol_insert(data,key)
  4186. struct symbol *data;
  4187. char *key;
  4188. {
  4189. x2node *np;
  4190. int h;
  4191. int ph;
  4192. if( x2a==0 ) return 0;
  4193. ph = strhash(key);
  4194. h = ph & (x2a->size-1);
  4195. np = x2a->ht[h];
  4196. while( np ){
  4197. if( strcmp(np->key,key)==0 ){
  4198. /* An existing entry with the same key is found. */
  4199. /* Fail because overwrite is not allows. */
  4200. return 0;
  4201. }
  4202. np = np->next;
  4203. }
  4204. if( x2a->count>=x2a->size ){
  4205. /* Need to make the hash table bigger */
  4206. int i,size;
  4207. struct s_x2 array;
  4208. array.size = size = x2a->size*2;
  4209. array.count = x2a->count;
  4210. array.tbl = (x2node*)malloc(
  4211. (sizeof(x2node) + sizeof(x2node*))*size );
  4212. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  4213. array.ht = (x2node**)&(array.tbl[size]);
  4214. for(i=0; i<size; i++) array.ht[i] = 0;
  4215. for(i=0; i<x2a->count; i++){
  4216. x2node *oldnp, *newnp;
  4217. oldnp = &(x2a->tbl[i]);
  4218. h = strhash(oldnp->key) & (size-1);
  4219. newnp = &(array.tbl[i]);
  4220. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  4221. newnp->next = array.ht[h];
  4222. newnp->key = oldnp->key;
  4223. newnp->data = oldnp->data;
  4224. newnp->from = &(array.ht[h]);
  4225. array.ht[h] = newnp;
  4226. }
  4227. free(x2a->tbl);
  4228. *x2a = array;
  4229. }
  4230. /* Insert the new data */
  4231. h = ph & (x2a->size-1);
  4232. np = &(x2a->tbl[x2a->count++]);
  4233. np->key = key;
  4234. np->data = data;
  4235. if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
  4236. np->next = x2a->ht[h];
  4237. x2a->ht[h] = np;
  4238. np->from = &(x2a->ht[h]);
  4239. return 1;
  4240. }
  4241. /* Return a pointer to data assigned to the given key. Return NULL
  4242. ** if no such key. */
  4243. struct symbol *Symbol_find(key)
  4244. char *key;
  4245. {
  4246. int h;
  4247. x2node *np;
  4248. if( x2a==0 ) return 0;
  4249. h = strhash(key) & (x2a->size-1);
  4250. np = x2a->ht[h];
  4251. while( np ){
  4252. if( strcmp(np->key,key)==0 ) break;
  4253. np = np->next;
  4254. }
  4255. return np ? np->data : 0;
  4256. }
  4257. /* Return the n-th data. Return NULL if n is out of range. */
  4258. struct symbol *Symbol_Nth(n)
  4259. int n;
  4260. {
  4261. struct symbol *data;
  4262. if( x2a && n>0 && n<=x2a->count ){
  4263. data = x2a->tbl[n-1].data;
  4264. }else{
  4265. data = 0;
  4266. }
  4267. return data;
  4268. }
  4269. /* Return the size of the array */
  4270. int Symbol_count()
  4271. {
  4272. return x2a ? x2a->count : 0;
  4273. }
  4274. /* Return an array of pointers to all data in the table.
  4275. ** The array is obtained from malloc. Return NULL if memory allocation
  4276. ** problems, or if the array is empty. */
  4277. struct symbol **Symbol_arrayof()
  4278. {
  4279. struct symbol **array;
  4280. int i,size;
  4281. if( x2a==0 ) return 0;
  4282. size = x2a->count;
  4283. array = (struct symbol **)calloc(size, sizeof(struct symbol *));
  4284. if( array ){
  4285. for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
  4286. }
  4287. return array;
  4288. }
  4289. /* Compare two configurations */
  4290. int Configcmp(a,b)
  4291. struct config *a;
  4292. struct config *b;
  4293. {
  4294. int x;
  4295. x = a->rp->index - b->rp->index;
  4296. if( x==0 ) x = a->dot - b->dot;
  4297. return x;
  4298. }
  4299. /* Compare two states */
  4300. PRIVATE int statecmp(a,b)
  4301. struct config *a;
  4302. struct config *b;
  4303. {
  4304. int rc;
  4305. for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
  4306. rc = a->rp->index - b->rp->index;
  4307. if( rc==0 ) rc = a->dot - b->dot;
  4308. }
  4309. if( rc==0 ){
  4310. if( a ) rc = 1;
  4311. if( b ) rc = -1;
  4312. }
  4313. return rc;
  4314. }
  4315. /* Hash a state */
  4316. PRIVATE int statehash(a)
  4317. struct config *a;
  4318. {
  4319. int h=0;
  4320. while( a ){
  4321. h = h*571 + a->rp->index*37 + a->dot;
  4322. a = a->bp;
  4323. }
  4324. return h;
  4325. }
  4326. /* Allocate a new state structure */
  4327. struct state *State_new()
  4328. {
  4329. struct state *new;
  4330. new = (struct state *)calloc(1, sizeof(struct state) );
  4331. MemoryCheck(new);
  4332. return new;
  4333. }
  4334. /* There is one instance of the following structure for each
  4335. ** associative array of type "x3".
  4336. */
  4337. struct s_x3 {
  4338. int size; /* The number of available slots. */
  4339. /* Must be a power of 2 greater than or */
  4340. /* equal to 1 */
  4341. int count; /* Number of currently slots filled */
  4342. struct s_x3node *tbl; /* The data stored here */
  4343. struct s_x3node **ht; /* Hash table for lookups */
  4344. };
  4345. /* There is one instance of this structure for every data element
  4346. ** in an associative array of type "x3".
  4347. */
  4348. typedef struct s_x3node {
  4349. struct state *data; /* The data */
  4350. struct config *key; /* The key */
  4351. struct s_x3node *next; /* Next entry with the same hash */
  4352. struct s_x3node **from; /* Previous link */
  4353. } x3node;
  4354. /* There is only one instance of the array, which is the following */
  4355. static struct s_x3 *x3a;
  4356. /* Allocate a new associative array */
  4357. void State_init(){
  4358. if( x3a ) return;
  4359. x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
  4360. if( x3a ){
  4361. x3a->size = 128;
  4362. x3a->count = 0;
  4363. x3a->tbl = (x3node*)malloc(
  4364. (sizeof(x3node) + sizeof(x3node*))*128 );
  4365. if( x3a->tbl==0 ){
  4366. free(x3a);
  4367. x3a = 0;
  4368. }else{
  4369. int i;
  4370. x3a->ht = (x3node**)&(x3a->tbl[128]);
  4371. for(i=0; i<128; i++) x3a->ht[i] = 0;
  4372. }
  4373. }
  4374. }
  4375. /* Insert a new record into the array. Return TRUE if successful.
  4376. ** Prior data with the same key is NOT overwritten */
  4377. int State_insert(data,key)
  4378. struct state *data;
  4379. struct config *key;
  4380. {
  4381. x3node *np;
  4382. int h;
  4383. int ph;
  4384. if( x3a==0 ) return 0;
  4385. ph = statehash(key);
  4386. h = ph & (x3a->size-1);
  4387. np = x3a->ht[h];
  4388. while( np ){
  4389. if( statecmp(np->key,key)==0 ){
  4390. /* An existing entry with the same key is found. */
  4391. /* Fail because overwrite is not allows. */
  4392. return 0;
  4393. }
  4394. np = np->next;
  4395. }
  4396. if( x3a->count>=x3a->size ){
  4397. /* Need to make the hash table bigger */
  4398. int i,size;
  4399. struct s_x3 array;
  4400. array.size = size = x3a->size*2;
  4401. array.count = x3a->count;
  4402. array.tbl = (x3node*)malloc(
  4403. (sizeof(x3node) + sizeof(x3node*))*size );
  4404. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  4405. array.ht = (x3node**)&(array.tbl[size]);
  4406. for(i=0; i<size; i++) array.ht[i] = 0;
  4407. for(i=0; i<x3a->count; i++){
  4408. x3node *oldnp, *newnp;
  4409. oldnp = &(x3a->tbl[i]);
  4410. h = statehash(oldnp->key) & (size-1);
  4411. newnp = &(array.tbl[i]);
  4412. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  4413. newnp->next = array.ht[h];
  4414. newnp->key = oldnp->key;
  4415. newnp->data = oldnp->data;
  4416. newnp->from = &(array.ht[h]);
  4417. array.ht[h] = newnp;
  4418. }
  4419. free(x3a->tbl);
  4420. *x3a = array;
  4421. }
  4422. /* Insert the new data */
  4423. h = ph & (x3a->size-1);
  4424. np = &(x3a->tbl[x3a->count++]);
  4425. np->key = key;
  4426. np->data = data;
  4427. if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
  4428. np->next = x3a->ht[h];
  4429. x3a->ht[h] = np;
  4430. np->from = &(x3a->ht[h]);
  4431. return 1;
  4432. }
  4433. /* Return a pointer to data assigned to the given key. Return NULL
  4434. ** if no such key. */
  4435. struct state *State_find(key)
  4436. struct config *key;
  4437. {
  4438. int h;
  4439. x3node *np;
  4440. if( x3a==0 ) return 0;
  4441. h = statehash(key) & (x3a->size-1);
  4442. np = x3a->ht[h];
  4443. while( np ){
  4444. if( statecmp(np->key,key)==0 ) break;
  4445. np = np->next;
  4446. }
  4447. return np ? np->data : 0;
  4448. }
  4449. /* Return an array of pointers to all data in the table.
  4450. ** The array is obtained from malloc. Return NULL if memory allocation
  4451. ** problems, or if the array is empty. */
  4452. struct state **State_arrayof()
  4453. {
  4454. struct state **array;
  4455. int i,size;
  4456. if( x3a==0 ) return 0;
  4457. size = x3a->count;
  4458. array = (struct state **)malloc( sizeof(struct state *)*size );
  4459. if( array ){
  4460. for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
  4461. }
  4462. return array;
  4463. }
  4464. /* Hash a configuration */
  4465. PRIVATE int confighash(a)
  4466. struct config *a;
  4467. {
  4468. int h=0;
  4469. h = h*571 + a->rp->index*37 + a->dot;
  4470. return h;
  4471. }
  4472. /* There is one instance of the following structure for each
  4473. ** associative array of type "x4".
  4474. */
  4475. struct s_x4 {
  4476. int size; /* The number of available slots. */
  4477. /* Must be a power of 2 greater than or */
  4478. /* equal to 1 */
  4479. int count; /* Number of currently slots filled */
  4480. struct s_x4node *tbl; /* The data stored here */
  4481. struct s_x4node **ht; /* Hash table for lookups */
  4482. };
  4483. /* There is one instance of this structure for every data element
  4484. ** in an associative array of type "x4".
  4485. */
  4486. typedef struct s_x4node {
  4487. struct config *data; /* The data */
  4488. struct s_x4node *next; /* Next entry with the same hash */
  4489. struct s_x4node **from; /* Previous link */
  4490. } x4node;
  4491. /* There is only one instance of the array, which is the following */
  4492. static struct s_x4 *x4a;
  4493. /* Allocate a new associative array */
  4494. void Configtable_init(){
  4495. if( x4a ) return;
  4496. x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
  4497. if( x4a ){
  4498. x4a->size = 64;
  4499. x4a->count = 0;
  4500. x4a->tbl = (x4node*)malloc(
  4501. (sizeof(x4node) + sizeof(x4node*))*64 );
  4502. if( x4a->tbl==0 ){
  4503. free(x4a);
  4504. x4a = 0;
  4505. }else{
  4506. int i;
  4507. x4a->ht = (x4node**)&(x4a->tbl[64]);
  4508. for(i=0; i<64; i++) x4a->ht[i] = 0;
  4509. }
  4510. }
  4511. }
  4512. /* Insert a new record into the array. Return TRUE if successful.
  4513. ** Prior data with the same key is NOT overwritten */
  4514. int Configtable_insert(data)
  4515. struct config *data;
  4516. {
  4517. x4node *np;
  4518. int h;
  4519. int ph;
  4520. if( x4a==0 ) return 0;
  4521. ph = confighash(data);
  4522. h = ph & (x4a->size-1);
  4523. np = x4a->ht[h];
  4524. while( np ){
  4525. if( Configcmp(np->data,data)==0 ){
  4526. /* An existing entry with the same key is found. */
  4527. /* Fail because overwrite is not allows. */
  4528. return 0;
  4529. }
  4530. np = np->next;
  4531. }
  4532. if( x4a->count>=x4a->size ){
  4533. /* Need to make the hash table bigger */
  4534. int i,size;
  4535. struct s_x4 array;
  4536. array.size = size = x4a->size*2;
  4537. array.count = x4a->count;
  4538. array.tbl = (x4node*)malloc(
  4539. (sizeof(x4node) + sizeof(x4node*))*size );
  4540. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  4541. array.ht = (x4node**)&(array.tbl[size]);
  4542. for(i=0; i<size; i++) array.ht[i] = 0;
  4543. for(i=0; i<x4a->count; i++){
  4544. x4node *oldnp, *newnp;
  4545. oldnp = &(x4a->tbl[i]);
  4546. h = confighash(oldnp->data) & (size-1);
  4547. newnp = &(array.tbl[i]);
  4548. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  4549. newnp->next = array.ht[h];
  4550. newnp->data = oldnp->data;
  4551. newnp->from = &(array.ht[h]);
  4552. array.ht[h] = newnp;
  4553. }
  4554. free(x4a->tbl);
  4555. *x4a = array;
  4556. }
  4557. /* Insert the new data */
  4558. h = ph & (x4a->size-1);
  4559. np = &(x4a->tbl[x4a->count++]);
  4560. np->data = data;
  4561. if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
  4562. np->next = x4a->ht[h];
  4563. x4a->ht[h] = np;
  4564. np->from = &(x4a->ht[h]);
  4565. return 1;
  4566. }
  4567. /* Return a pointer to data assigned to the given key. Return NULL
  4568. ** if no such key. */
  4569. struct config *Configtable_find(key)
  4570. struct config *key;
  4571. {
  4572. int h;
  4573. x4node *np;
  4574. if( x4a==0 ) return 0;
  4575. h = confighash(key) & (x4a->size-1);
  4576. np = x4a->ht[h];
  4577. while( np ){
  4578. if( Configcmp(np->data,key)==0 ) break;
  4579. np = np->next;
  4580. }
  4581. return np ? np->data : 0;
  4582. }
  4583. /* Remove all data from the table. Pass each data to the function "f"
  4584. ** as it is removed. ("f" may be null to avoid this step.) */
  4585. void Configtable_clear(f)
  4586. int(*f)(/* struct config * */);
  4587. {
  4588. int i;
  4589. if( x4a==0 || x4a->count==0 ) return;
  4590. if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
  4591. for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
  4592. x4a->count = 0;
  4593. return;
  4594. }