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