lemon.c 149 KB

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