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