lemon.c 116 KB

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