2 ** This file contains all sources (including headers) to the LEMON
3 ** LALR(1) parser generator. The sources have been combined into a
4 ** single file to make it easy to include LEMON in the source tree
5 ** and Makefile of another program.
7 ** The author of this program disclaims copyright.
16 #define ISSPACE(X) isspace((unsigned char)(X))
17 #define ISDIGIT(X) isdigit((unsigned char)(X))
18 #define ISALNUM(X) isalnum((unsigned char)(X))
19 #define ISALPHA(X) isalpha((unsigned char)(X))
20 #define ISUPPER(X) isupper((unsigned char)(X))
21 #define ISLOWER(X) islower((unsigned char)(X))
25 # if defined(_WIN32) || defined(WIN32)
34 extern int access(const char *path, int mode);
42 /* #define PRIVATE static */
46 #define MAXRHS 5 /* Set low to exercise exception code */
51 static int showPrecedenceConflict = 0;
52 static char *msort(char*,char**,int(*)(const char*,const char*));
55 ** Compilers are getting increasingly pedantic about type conversions
56 ** as C evolves ever closer to Ada.... To work around the latest problems
57 ** we have to define the following variant of strlen().
59 #define lemonStrlen(X) ((int)strlen(X))
62 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
63 ** saying they are unsafe. So we define our own versions of those routines too.
65 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
66 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
67 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
68 ** buffer, making sure the buffer is always zero-terminated.
70 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
71 ** a few simply conversions:
78 static void lemon_addtext(
79 char *zBuf, /* The buffer to which text is added */
80 int *pnUsed, /* Slots of the buffer used so far */
81 const char *zIn, /* Text to add */
82 int nIn, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth /* Field width. Negative to left justify */
85 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
86 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
88 memcpy(&zBuf[*pnUsed], zIn, nIn);
90 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
93 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
99 for(i=j=0; (c = zFormat[i])!=0; i++){
102 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
104 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
106 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
107 if( c=='-' ) iWidth = -iWidth;
111 int v = va_arg(ap, int);
113 lemon_addtext(str, &nUsed, "-", 1, iWidth);
116 lemon_addtext(str, &nUsed, "0", 1, iWidth);
121 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
124 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
126 z = va_arg(ap, const char*);
127 lemon_addtext(str, &nUsed, z, -1, iWidth);
128 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
131 z = va_arg(ap, const char*);
132 lemon_addtext(str, &nUsed, z, k, iWidth);
134 lemon_addtext(str, &nUsed, "%", 1, 0);
136 fprintf(stderr, "illegal format\n");
142 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
145 static int lemon_sprintf(char *str, const char *format, ...){
148 va_start(ap, format);
149 rc = lemon_vsprintf(str, format, ap);
153 static void lemon_strcpy(char *dest, const char *src){
154 while( (*(dest++) = *(src++))!=0 ){}
156 static void lemon_strcat(char *dest, const char *src){
157 while( *dest ) dest++;
158 lemon_strcpy(dest, src);
162 /* a few forward declarations... */
167 static struct action *Action_new(void);
168 static struct action *Action_sort(struct action *);
170 /********** From the file "build.h" ************************************/
171 void FindRulePrecedences(struct lemon*);
172 void FindFirstSets(struct lemon*);
173 void FindStates(struct lemon*);
174 void FindLinks(struct lemon*);
175 void FindFollowSets(struct lemon*);
176 void FindActions(struct lemon*);
178 /********* From the file "configlist.h" *********************************/
179 void Configlist_init(void);
180 struct config *Configlist_add(struct rule *, int);
181 struct config *Configlist_addbasis(struct rule *, int);
182 void Configlist_closure(struct lemon *);
183 void Configlist_sort(void);
184 void Configlist_sortbasis(void);
185 struct config *Configlist_return(void);
186 struct config *Configlist_basis(void);
187 void Configlist_eat(struct config *);
188 void Configlist_reset(void);
190 /********* From the file "error.h" ***************************************/
191 void ErrorMsg(const char *, int,const char *, ...);
193 /****** From the file "option.h" ******************************************/
194 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
195 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
197 enum option_type type;
202 int OptInit(char**,struct s_options*,FILE*);
208 /******** From the file "parse.h" *****************************************/
209 void Parse(struct lemon *lemp);
211 /********* From the file "plink.h" ***************************************/
212 struct plink *Plink_new(void);
213 void Plink_add(struct plink **, struct config *);
214 void Plink_copy(struct plink **, struct plink *);
215 void Plink_delete(struct plink *);
217 /********** From the file "report.h" *************************************/
218 void Reprint(struct lemon *);
219 void ReportOutput(struct lemon *);
220 void ReportTable(struct lemon *, int);
221 void ReportHeader(struct lemon *);
222 void CompressTables(struct lemon *);
223 void ResortStates(struct lemon *);
225 /********** From the file "set.h" ****************************************/
226 void SetSize(int); /* All sets will be of size N */
227 char *SetNew(void); /* A new set for element 0..N */
228 void SetFree(char*); /* Deallocate a set */
229 int SetAdd(char*,int); /* Add element to a set */
230 int SetUnion(char *,char *); /* A <- A U B, thru element N */
231 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
233 /********** From the file "struct.h" *************************************/
235 ** Principal data structures for the LEMON parser generator.
238 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
240 /* Symbols (terminals and nonterminals) of the grammar are stored
241 ** in the following: */
254 const char *name; /* Name of the symbol */
255 int index; /* Index number for this symbol */
256 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
257 struct rule *rule; /* Linked list of rules of this (if an NT) */
258 struct symbol *fallback; /* fallback token in case this token doesn't parse */
259 int prec; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc; /* Associativity if precedence is defined */
261 char *firstset; /* First-set for all rules of this symbol */
262 Boolean lambda; /* True if NT and can generate an empty string */
263 int useCnt; /* Number of times used */
264 char *destructor; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
266 int destLineno; /* Line number for start of destructor. Set to
267 ** -1 for duplicate destructors. */
268 char *datatype; /* The data type of information held by this
269 ** object. Only used if type==NONTERMINAL */
270 int dtnum; /* The data type number. In the parser, the value
271 ** stack is a union. The .yy%d element of this
272 ** union is the correct data type for this object */
273 int bContent; /* True if this symbol ever carries content - if
274 ** it is ever more than just syntax */
275 /* The following fields are used by MULTITERMINALs only */
276 int nsubsym; /* Number of constituent symbols in the MULTI */
277 struct symbol **subsym; /* Array of constituent symbols */
280 /* Each production rule in the grammar is stored in the following
283 struct symbol *lhs; /* Left-hand side of the rule */
284 const char *lhsalias; /* Alias for the LHS (NULL if none) */
285 int lhsStart; /* True if left-hand side is the start symbol */
286 int ruleline; /* Line number for the rule */
287 int nrhs; /* Number of RHS symbols */
288 struct symbol **rhs; /* The RHS symbols */
289 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
290 int line; /* Line number at which code begins */
291 const char *code; /* The code executed when this rule is reduced */
292 const char *codePrefix; /* Setup code before code[] above */
293 const char *codeSuffix; /* Breakdown code after code[] above */
294 int noCode; /* True if this rule has no associated C code */
295 int codeEmitted; /* True if the code has been emitted already */
296 struct symbol *precsym; /* Precedence symbol for this rule */
297 int index; /* An index number for this rule */
298 int iRule; /* Rule number as used in the generated tables */
299 Boolean canReduce; /* True if this rule is ever reduced */
300 Boolean doesReduce; /* Reduce actions occur after optimization */
301 struct rule *nextlhs; /* Next rule with the same LHS */
302 struct rule *next; /* Next rule in the global list */
305 /* A configuration is a production rule of the grammar together with
306 ** a mark (dot) showing how much of that rule has been processed so far.
307 ** Configurations also contain a follow-set which is a list of terminal
308 ** symbols which are allowed to immediately follow the end of the rule.
309 ** Every configuration is recorded as an instance of the following: */
315 struct rule *rp; /* The rule upon which the configuration is based */
316 int dot; /* The parse point */
317 char *fws; /* Follow-set for this configuration only */
318 struct plink *fplp; /* Follow-set forward propagation links */
319 struct plink *bplp; /* Follow-set backwards propagation links */
320 struct state *stp; /* Pointer to state which contains this */
321 enum cfgstatus status; /* used during followset and shift computations */
322 struct config *next; /* Next configuration in the state */
323 struct config *bp; /* The next basis configuration */
331 SSCONFLICT, /* A shift/shift conflict */
332 SRCONFLICT, /* Was a reduce, but part of a conflict */
333 RRCONFLICT, /* Was a reduce, but part of a conflict */
334 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
335 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
336 NOT_USED, /* Deleted by compression */
337 SHIFTREDUCE /* Shift first, then reduce */
340 /* Every shift or reduce operation is stored as one of the following */
342 struct symbol *sp; /* The look-ahead symbol */
345 struct state *stp; /* The new state, if a shift */
346 struct rule *rp; /* The rule, if a reduce */
348 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
349 struct action *next; /* Next action for this state */
350 struct action *collide; /* Next action with the same hash */
353 /* Each state of the generated parser's finite state machine
354 ** is encoded as an instance of the following structure. */
356 struct config *bp; /* The basis configurations for this state */
357 struct config *cfp; /* All configurations in this set */
358 int statenum; /* Sequential number for this state */
359 struct action *ap; /* List of actions for this state */
360 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
361 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
362 int iDfltReduce; /* Default action is to REDUCE by this rule */
363 struct rule *pDfltReduce;/* The default REDUCE rule. */
364 int autoReduce; /* True if this is an auto-reduce state */
366 #define NO_OFFSET (-2147483647)
368 /* A followset propagation link indicates that the contents of one
369 ** configuration followset should be propagated to another whenever
370 ** the first changes. */
372 struct config *cfp; /* The configuration to which linked */
373 struct plink *next; /* The next propagate link */
376 /* The state vector for the entire parser generator is recorded as
377 ** follows. (LEMON uses no global variables and makes little use of
378 ** static variables. Fields in the following structure can be thought
379 ** of as begin global variables in the program.) */
381 struct state **sorted; /* Table of states sorted by state number */
382 struct rule *rule; /* List of all rules */
383 struct rule *startRule; /* First rule */
384 int nstate; /* Number of states */
385 int nxstate; /* nstate with tail degenerate states removed */
386 int nrule; /* Number of rules */
387 int nsymbol; /* Number of terminal and nonterminal symbols */
388 int nterminal; /* Number of terminal symbols */
389 int minShiftReduce; /* Minimum shift-reduce action value */
390 int errAction; /* Error action value */
391 int accAction; /* Accept action value */
392 int noAction; /* No-op action value */
393 int minReduce; /* Minimum reduce action */
394 int maxAction; /* Maximum action value of any kind */
395 struct symbol **symbols; /* Sorted array of pointers to symbols */
396 int errorcnt; /* Number of errors */
397 struct symbol *errsym; /* The error symbol */
398 struct symbol *wildcard; /* Token that matches anything */
399 char *name; /* Name of the generated parser */
400 char *arg; /* Declaration of the 3th argument to parser */
401 char *ctx; /* Declaration of 2nd argument to constructor */
402 char *tokentype; /* Type of terminal symbols in the parser stack */
403 char *vartype; /* The default type of non-terminal symbols */
404 char *start; /* Name of the start symbol for the grammar */
405 char *stacksize; /* Size of the parser stack */
406 char *include; /* Code to put at the start of the C file */
407 char *error; /* Code to execute when an error is seen */
408 char *overflow; /* Code to execute on a stack overflow */
409 char *failure; /* Code to execute on parser failure */
410 char *accept; /* Code to execute when the parser excepts */
411 char *extracode; /* Code appended to the generated file */
412 char *tokendest; /* Code to execute to destroy token data */
413 char *vardest; /* Code for the default non-terminal destructor */
414 char *filename; /* Name of the input file */
415 char *outname; /* Name of the current output file */
416 char *tokenprefix; /* A prefix added to token names in the .h file */
417 int nconflict; /* Number of parsing conflicts */
418 int nactiontab; /* Number of entries in the yy_action[] table */
419 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
420 int tablesize; /* Total table size of all tables in bytes */
421 int basisflag; /* Print only basis configurations */
422 int has_fallback; /* True if any %fallback is seen in the grammar */
423 int nolinenosflag; /* True if #line statements should not be printed */
424 char *argv0; /* Name of the program */
427 #define MemoryCheck(X) if((X)==0){ \
428 extern void memory_error(); \
432 /**************** From the file "table.h" *********************************/
434 ** All code in this file has been automatically generated
435 ** from a specification in the file
437 ** by the associative array code building program "aagen".
438 ** Do not edit this file! Instead, edit the specification
439 ** file, then rerun aagen.
442 ** Code for processing tables in the LEMON parser generator.
444 /* Routines for handling a strings */
446 const char *Strsafe(const char *);
448 void Strsafe_init(void);
449 int Strsafe_insert(const char *);
450 const char *Strsafe_find(const char *);
452 /* Routines for handling symbols of the grammar */
454 struct symbol *Symbol_new(const char *);
455 int Symbolcmpp(const void *, const void *);
456 void Symbol_init(void);
457 int Symbol_insert(struct symbol *, const char *);
458 struct symbol *Symbol_find(const char *);
459 struct symbol *Symbol_Nth(int);
460 int Symbol_count(void);
461 struct symbol **Symbol_arrayof(void);
463 /* Routines to manage the state table */
465 int Configcmp(const char *, const char *);
466 struct state *State_new(void);
467 void State_init(void);
468 int State_insert(struct state *, struct config *);
469 struct state *State_find(struct config *);
470 struct state **State_arrayof(void);
472 /* Routines used for efficiency in Configlist_add */
474 void Configtable_init(void);
475 int Configtable_insert(struct config *);
476 struct config *Configtable_find(struct config *);
477 void Configtable_clear(int(*)(struct config *));
479 /****************** From the file "action.c" *******************************/
481 ** Routines processing parser actions in the LEMON parser generator.
484 /* Allocate a new parser action */
485 static struct action *Action_new(void){
486 static struct action *freelist = 0;
487 struct action *newaction;
492 freelist = (struct action *)calloc(amt, sizeof(struct action));
494 fprintf(stderr,"Unable to allocate memory for a new parser action.");
497 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
498 freelist[amt-1].next = 0;
500 newaction = freelist;
501 freelist = freelist->next;
505 /* Compare two actions for sorting purposes. Return negative, zero, or
506 ** positive if the first action is less than, equal to, or greater than
509 static int actioncmp(
514 rc = ap1->sp->index - ap2->sp->index;
516 rc = (int)ap1->type - (int)ap2->type;
518 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
519 rc = ap1->x.rp->index - ap2->x.rp->index;
522 rc = (int) (ap2 - ap1);
527 /* Sort parser actions */
528 static struct action *Action_sort(
531 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
532 (int(*)(const char*,const char*))actioncmp);
542 struct action *newaction;
543 newaction = Action_new();
544 newaction->next = *app;
546 newaction->type = type;
548 newaction->spOpt = 0;
550 newaction->x.stp = (struct state *)arg;
552 newaction->x.rp = (struct rule *)arg;
555 /********************** New code to implement the "acttab" module ***********/
557 ** This module implements routines use to construct the yy_action[] table.
561 ** The state of the yy_action table under construction is an instance of
562 ** the following structure.
564 ** The yy_action table maps the pair (state_number, lookahead) into an
565 ** action_number. The table is an array of integers pairs. The state_number
566 ** determines an initial offset into the yy_action array. The lookahead
567 ** value is then added to this initial offset to get an index X into the
568 ** yy_action array. If the aAction[X].lookahead equals the value of the
569 ** of the lookahead input, then the value of the action_number output is
570 ** aAction[X].action. If the lookaheads do not match then the
571 ** default action for the state_number is returned.
573 ** All actions associated with a single state_number are first entered
574 ** into aLookahead[] using multiple calls to acttab_action(). Then the
575 ** actions for that single state_number are placed into the aAction[]
576 ** array with a single call to acttab_insert(). The acttab_insert() call
577 ** also resets the aLookahead[] array in preparation for the next
580 struct lookahead_action {
581 int lookahead; /* Value of the lookahead token */
582 int action; /* Action to take on the given lookahead */
584 typedef struct acttab acttab;
586 int nAction; /* Number of used slots in aAction[] */
587 int nActionAlloc; /* Slots allocated for aAction[] */
588 struct lookahead_action
589 *aAction, /* The yy_action[] table under construction */
590 *aLookahead; /* A single new transaction set */
591 int mnLookahead; /* Minimum aLookahead[].lookahead */
592 int mnAction; /* Action associated with mnLookahead */
593 int mxLookahead; /* Maximum aLookahead[].lookahead */
594 int nLookahead; /* Used slots in aLookahead[] */
595 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
596 int nterminal; /* Number of terminal symbols */
597 int nsymbol; /* total number of symbols */
600 /* Return the number of entries in the yy_action table */
601 #define acttab_lookahead_size(X) ((X)->nAction)
603 /* The value for the N-th entry in yy_action */
604 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
606 /* The value for the N-th entry in yy_lookahead */
607 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
609 /* Free all memory associated with the given acttab */
610 void acttab_free(acttab *p){
612 free( p->aLookahead );
616 /* Allocate a new acttab structure */
617 acttab *acttab_alloc(int nsymbol, int nterminal){
618 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
620 fprintf(stderr,"Unable to allocate memory for a new acttab.");
623 memset(p, 0, sizeof(*p));
624 p->nsymbol = nsymbol;
625 p->nterminal = nterminal;
629 /* Add a new action to the current transaction set.
631 ** This routine is called once for each lookahead for a particular
634 void acttab_action(acttab *p, int lookahead, int action){
635 if( p->nLookahead>=p->nLookaheadAlloc ){
636 p->nLookaheadAlloc += 25;
637 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
638 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
639 if( p->aLookahead==0 ){
640 fprintf(stderr,"malloc failed\n");
644 if( p->nLookahead==0 ){
645 p->mxLookahead = lookahead;
646 p->mnLookahead = lookahead;
647 p->mnAction = action;
649 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
650 if( p->mnLookahead>lookahead ){
651 p->mnLookahead = lookahead;
652 p->mnAction = action;
655 p->aLookahead[p->nLookahead].lookahead = lookahead;
656 p->aLookahead[p->nLookahead].action = action;
661 ** Add the transaction set built up with prior calls to acttab_action()
662 ** into the current action table. Then reset the transaction set back
663 ** to an empty set in preparation for a new round of acttab_action() calls.
665 ** Return the offset into the action table of the new transaction.
667 ** If the makeItSafe parameter is true, then the offset is chosen so that
668 ** it is impossible to overread the yy_lookaside[] table regardless of
669 ** the lookaside token. This is done for the terminal symbols, as they
670 ** come from external inputs and can contain syntax errors. When makeItSafe
671 ** is false, there is more flexibility in selecting offsets, resulting in
672 ** a smaller table. For non-terminal symbols, which are never syntax errors,
673 ** makeItSafe can be false.
675 int acttab_insert(acttab *p, int makeItSafe){
677 assert( p->nLookahead>0 );
679 /* Make sure we have enough space to hold the expanded action table
680 ** in the worst case. The worst case occurs if the transaction set
681 ** must be appended to the current action table
684 if( p->nAction + n >= p->nActionAlloc ){
685 int oldAlloc = p->nActionAlloc;
686 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
687 p->aAction = (struct lookahead_action *) realloc( p->aAction,
688 sizeof(p->aAction[0])*p->nActionAlloc);
690 fprintf(stderr,"malloc failed\n");
693 assert(oldAlloc < p->nActionAlloc); /* hint for CSA */
694 for(i=oldAlloc; i<p->nActionAlloc; i++){
695 p->aAction[i].lookahead = -1;
696 p->aAction[i].action = -1;
699 assert(p->aAction); /* Hint for CSA (for p->aAction[i] below) */
701 /* Scan the existing action table looking for an offset that is a
702 ** duplicate of the current transaction set. Fall out of the loop
703 ** if and when the duplicate is found.
705 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
707 end = makeItSafe ? p->mnLookahead : 0;
708 for(i=p->nAction-1; i>=end; i--){
709 if( p->aAction[i].lookahead==p->mnLookahead ){
710 /* All lookaheads and actions in the aLookahead[] transaction
711 ** must match against the candidate aAction[i] entry. */
712 if( p->aAction[i].action!=p->mnAction ) continue;
713 for(j=0; j<p->nLookahead; j++){
714 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
715 if( k<0 || k>=p->nAction ) break;
716 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
717 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
719 if( j<p->nLookahead ) continue;
721 /* No possible lookahead value that is not in the aLookahead[]
722 ** transaction is allowed to match aAction[i] */
724 for(j=0; j<p->nAction; j++){
725 if( p->aAction[j].lookahead<0 ) continue;
726 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
728 if( n==p->nLookahead ){
729 break; /* An exact match is found at offset i */
734 /* If no existing offsets exactly match the current transaction, find an
735 ** an empty offset in the aAction[] table in which we can add the
736 ** aLookahead[] transaction.
739 /* Look for holes in the aAction[] table that fit the current
740 ** aLookahead[] transaction. Leave i set to the offset of the hole.
741 ** If no holes are found, i is left at p->nAction, which means the
742 ** transaction will be appended. */
743 i = makeItSafe ? p->mnLookahead : 0;
744 for(; i<p->nActionAlloc - p->mxLookahead; i++){
745 if( p->aAction[i].lookahead<0 ){
746 for(j=0; j<p->nLookahead; j++){
747 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
749 if( p->aAction[k].lookahead>=0 ) break;
751 if( j<p->nLookahead ) continue;
752 for(j=0; j<p->nAction; j++){
753 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
756 break; /* Fits in empty slots */
761 /* Insert transaction set at index i. */
764 for(j=0; j<p->nLookahead; j++){
765 printf(" %d", p->aLookahead[j].lookahead);
767 printf(" inserted at %d\n", i);
769 for(j=0; j<p->nLookahead; j++){
770 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
771 p->aAction[k] = p->aLookahead[j];
772 if( k>=p->nAction ) p->nAction = k+1;
774 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
777 /* Return the offset that is added to the lookahead in order to get the
778 ** index into yy_action of the action */
779 return i - p->mnLookahead;
783 ** Return the size of the action table without the trailing syntax error
786 int acttab_action_size(acttab *p){
788 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
792 /********************** From the file "build.c" *****************************/
794 ** Routines to construction the finite state machine for the LEMON
798 /* Find a precedence symbol of every rule in the grammar.
800 ** Those rules which have a precedence symbol coded in the input
801 ** grammar using the "[symbol]" construct will already have the
802 ** rp->precsym field filled. Other rules take as their precedence
803 ** symbol the first RHS symbol with a defined precedence. If there
804 ** are not RHS symbols with a defined precedence, the precedence
805 ** symbol field is left blank.
807 void FindRulePrecedences(struct lemon *xp)
810 for(rp=xp->rule; rp; rp=rp->next){
811 if( rp->precsym==0 ){
813 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
814 struct symbol *sp = rp->rhs[i];
815 if( sp->type==MULTITERMINAL ){
816 for(j=0; j<sp->nsubsym; j++){
817 if( sp->subsym[j]->prec>=0 ){
818 rp->precsym = sp->subsym[j];
822 }else if( sp->prec>=0 ){
823 rp->precsym = rp->rhs[i];
831 /* Find all nonterminals which will generate the empty string.
832 ** Then go back and compute the first sets of every nonterminal.
833 ** The first set is the set of all terminal symbols which can begin
834 ** a string generated by that nonterminal.
836 void FindFirstSets(struct lemon *lemp)
842 for(i=0; i<lemp->nsymbol; i++){
843 lemp->symbols[i]->lambda = LEMON_FALSE;
845 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
846 lemp->symbols[i]->firstset = SetNew();
849 /* First compute all lambdas */
852 for(rp=lemp->rule; rp; rp=rp->next){
853 if( rp->lhs->lambda ) continue;
854 for(i=0; i<rp->nrhs; i++){
855 struct symbol *sp = rp->rhs[i];
856 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
857 if( sp->lambda==LEMON_FALSE ) break;
860 rp->lhs->lambda = LEMON_TRUE;
866 /* Now compute all first sets */
868 struct symbol *s1, *s2;
870 for(rp=lemp->rule; rp; rp=rp->next){
872 for(i=0; i<rp->nrhs; i++){
874 if( s2->type==TERMINAL ){
875 progress += SetAdd(s1->firstset,s2->index);
877 }else if( s2->type==MULTITERMINAL ){
878 for(j=0; j<s2->nsubsym; j++){
879 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
883 if( s1->lambda==LEMON_FALSE ) break;
885 progress += SetUnion(s1->firstset,s2->firstset);
886 if( s2->lambda==LEMON_FALSE ) break;
894 /* Compute all LR(0) states for the grammar. Links
895 ** are added to between some states so that the LR(1) follow sets
896 ** can be computed later.
898 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
899 void FindStates(struct lemon *lemp)
906 /* Find the start symbol */
908 sp = Symbol_find(lemp->start);
910 ErrorMsg(lemp->filename,0,
911 "The specified start symbol \"%s\" is not \
912 in a nonterminal of the grammar. \"%s\" will be used as the start \
913 symbol instead.",lemp->start,lemp->startRule->lhs->name);
915 sp = lemp->startRule->lhs;
918 sp = lemp->startRule->lhs;
921 /* Make sure the start symbol doesn't occur on the right-hand side of
922 ** any rule. Report an error if it does. (YACC would generate a new
923 ** start symbol in this case.) */
924 for(rp=lemp->rule; rp; rp=rp->next){
926 for(i=0; i<rp->nrhs; i++){
927 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
928 ErrorMsg(lemp->filename,0,
929 "The start symbol \"%s\" occurs on the \
930 right-hand side of a rule. This will result in a parser which \
931 does not work properly.",sp->name);
937 /* The basis configuration set for the first state
938 ** is all rules which have the start symbol as their
940 for(rp=sp->rule; rp; rp=rp->nextlhs){
941 struct config *newcfp;
943 newcfp = Configlist_addbasis(rp,0);
944 SetAdd(newcfp->fws,0);
947 /* Compute the first state. All other states will be
948 ** computed automatically during the computation of the first one.
949 ** The returned pointer to the first state is not used. */
950 (void)getstate(lemp);
954 /* Return a pointer to a state which is described by the configuration
955 ** list which has been built from calls to Configlist_add.
957 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
958 PRIVATE struct state *getstate(struct lemon *lemp)
960 struct config *cfp, *bp;
963 /* Extract the sorted basis of the new state. The basis was constructed
964 ** by prior calls to "Configlist_addbasis()". */
965 Configlist_sortbasis();
966 bp = Configlist_basis();
968 /* Get a state with the same basis */
969 stp = State_find(bp);
971 /* A state with the same basis already exists! Copy all the follow-set
972 ** propagation links from the state under construction into the
973 ** preexisting state, then return a pointer to the preexisting state */
974 struct config *x, *y;
975 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
976 Plink_copy(&y->bplp,x->bplp);
977 Plink_delete(x->fplp);
978 x->fplp = x->bplp = 0;
980 cfp = Configlist_return();
983 /* This really is a new state. Construct all the details */
984 Configlist_closure(lemp); /* Compute the configuration closure */
985 Configlist_sort(); /* Sort the configuration closure */
986 cfp = Configlist_return(); /* Get a pointer to the config list */
987 stp = State_new(); /* A new state structure */
989 stp->bp = bp; /* Remember the configuration basis */
990 stp->cfp = cfp; /* Remember the configuration closure */
991 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
992 stp->ap = 0; /* No actions, yet. */
996 State_insert(stp,stp->bp); /* Add to the state table */
997 assert(ret == 1); /* CSA hint: stp did not leak, it has escaped. */
998 buildshifts(lemp,stp); /* Recursively compute successor states */
1004 ** Return true if two symbols are the same.
1006 int same_symbol(struct symbol *a, struct symbol *b)
1009 if( a==b ) return 1;
1010 if( a->type!=MULTITERMINAL ) return 0;
1011 if( b->type!=MULTITERMINAL ) return 0;
1012 if( a->nsubsym!=b->nsubsym ) return 0;
1013 for(i=0; i<a->nsubsym; i++){
1014 if( a->subsym[i]!=b->subsym[i] ) return 0;
1019 /* Construct all successor states to the given state. A "successor"
1020 ** state is any state which can be reached by a shift action.
1022 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
1024 struct config *cfp; /* For looping thru the config closure of "stp" */
1025 struct config *bcfp; /* For the inner loop on config closure of "stp" */
1026 struct config *newcfg; /* */
1027 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1028 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1029 struct state *newstp; /* A pointer to a successor state */
1031 /* Each configuration becomes complete after it contibutes to a successor
1032 ** state. Initially, all configurations are incomplete */
1033 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1035 /* Loop through all configurations of the state "stp" */
1036 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1037 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1038 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1039 Configlist_reset(); /* Reset the new config set */
1040 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1042 /* For every configuration in the state "stp" which has the symbol "sp"
1043 ** following its dot, add the same configuration to the basis set under
1044 ** construction but with the dot shifted one symbol to the right. */
1045 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1046 if( bcfp->status==COMPLETE ) continue; /* Already used */
1047 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1048 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
1049 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
1050 bcfp->status = COMPLETE; /* Mark this config as used */
1051 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1052 Plink_add(&newcfg->bplp,bcfp);
1055 /* Get a pointer to the state described by the basis configuration set
1056 ** constructed in the preceding loop */
1057 newstp = getstate(lemp);
1059 /* The state "newstp" is reached from the state "stp" by a shift action
1060 ** on the symbol "sp" */
1061 if( sp->type==MULTITERMINAL ){
1063 for(i=0; i<sp->nsubsym; i++){
1064 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1067 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1073 ** Construct the propagation links
1075 void FindLinks(struct lemon *lemp)
1078 struct config *cfp, *other;
1082 /* Housekeeping detail:
1083 ** Add to every propagate link a pointer back to the state to
1084 ** which the link is attached. */
1085 for(i=0; i<lemp->nstate; i++){
1086 stp = lemp->sorted[i];
1087 assert(stp); /* Hint for CSA */
1088 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1093 /* Convert all backlinks into forward links. Only the forward
1094 ** links are used in the follow-set computation. */
1095 for(i=0; i<lemp->nstate; i++){
1096 stp = lemp->sorted[i];
1097 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1098 for(plp=cfp->bplp; plp; plp=plp->next){
1100 Plink_add(&other->fplp,cfp);
1106 /* Compute all followsets.
1108 ** A followset is the set of all symbols which can come immediately
1109 ** after a configuration.
1111 void FindFollowSets(struct lemon *lemp)
1119 for(i=0; i<lemp->nstate; i++){
1120 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1121 cfp->status = INCOMPLETE;
1127 for(i=0; i<lemp->nstate; i++){
1128 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1129 if( cfp->status==COMPLETE ) continue;
1130 for(plp=cfp->fplp; plp; plp=plp->next){
1131 change = SetUnion(plp->cfp->fws,cfp->fws);
1133 plp->cfp->status = INCOMPLETE;
1137 cfp->status = COMPLETE;
1143 static int resolve_conflict(struct action *,struct action *);
1145 /* Compute the reduce actions, and resolve conflicts.
1147 void FindActions(struct lemon *lemp)
1155 /* Add all of the reduce actions
1156 ** A reduce action is added for each element of the followset of
1157 ** a configuration which has its dot at the extreme right.
1159 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1160 stp = lemp->sorted[i];
1161 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1162 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1163 for(j=0; j<lemp->nterminal; j++){
1164 if( SetFind(cfp->fws,j) ){
1165 /* Add a reduce action to the state "stp" which will reduce by the
1166 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1167 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1174 /* Add the accepting token */
1176 sp = Symbol_find(lemp->start);
1177 if( sp==0 ) sp = lemp->startRule->lhs;
1179 sp = lemp->startRule->lhs;
1181 /* Add to the first state (which is always the starting state of the
1182 ** finite state machine) an action to ACCEPT if the lookahead is the
1183 ** start nonterminal. */
1184 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1186 /* Resolve conflicts */
1187 for(i=0; i<lemp->nstate; i++){
1188 struct action *ap, *nap;
1189 stp = lemp->sorted[i];
1190 /* assert( stp->ap ); */
1191 stp->ap = Action_sort(stp->ap);
1192 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1193 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1194 /* The two actions "ap" and "nap" have the same lookahead.
1195 ** Figure out which one should be used */
1196 lemp->nconflict += resolve_conflict(ap,nap);
1201 /* Report an error for each rule that can never be reduced. */
1202 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1203 for(i=0; i<lemp->nstate; i++){
1205 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1206 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1209 for(rp=lemp->rule; rp; rp=rp->next){
1210 if( rp->canReduce ) continue;
1211 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1216 /* Resolve a conflict between the two given actions. If the
1217 ** conflict can't be resolved, return non-zero.
1220 ** To resolve a conflict, first look to see if either action
1221 ** is on an error rule. In that case, take the action which
1222 ** is not associated with the error rule. If neither or both
1223 ** actions are associated with an error rule, then try to
1224 ** use precedence to resolve the conflict.
1226 ** If either action is a SHIFT, then it must be apx. This
1227 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1229 static int resolve_conflict(
1233 struct symbol *spx, *spy;
1235 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1236 if( apx->type==SHIFT && apy->type==SHIFT ){
1237 apy->type = SSCONFLICT;
1240 if( apx->type==SHIFT && apy->type==REDUCE ){
1242 spy = apy->x.rp->precsym;
1243 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1244 /* Not enough precedence information. */
1245 apy->type = SRCONFLICT;
1247 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1248 apy->type = RD_RESOLVED;
1249 }else if( spx->prec<spy->prec ){
1250 apx->type = SH_RESOLVED;
1251 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1252 apy->type = RD_RESOLVED; /* associativity */
1253 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1254 apx->type = SH_RESOLVED;
1256 assert( spx->prec==spy->prec && spx->assoc==NONE );
1259 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1260 spx = apx->x.rp->precsym;
1261 spy = apy->x.rp->precsym;
1262 if( spx==0 || spy==0 || spx->prec<0 ||
1263 spy->prec<0 || spx->prec==spy->prec ){
1264 apy->type = RRCONFLICT;
1266 }else if( spx->prec>spy->prec ){
1267 apy->type = RD_RESOLVED;
1268 }else if( spx->prec<spy->prec ){
1269 apx->type = RD_RESOLVED;
1273 apx->type==SH_RESOLVED ||
1274 apx->type==RD_RESOLVED ||
1275 apx->type==SSCONFLICT ||
1276 apx->type==SRCONFLICT ||
1277 apx->type==RRCONFLICT ||
1278 apy->type==SH_RESOLVED ||
1279 apy->type==RD_RESOLVED ||
1280 apy->type==SSCONFLICT ||
1281 apy->type==SRCONFLICT ||
1282 apy->type==RRCONFLICT
1284 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1285 ** REDUCEs on the list. If we reach this point it must be because
1286 ** the parser conflict had already been resolved. */
1290 /********************* From the file "configlist.c" *************************/
1292 ** Routines to processing a configuration list and building a state
1293 ** in the LEMON parser generator.
1296 static struct config *freelist = 0; /* List of free configurations */
1297 static struct config *current = 0; /* Top of list of configurations */
1298 static struct config **currentend = 0; /* Last on list of configs */
1299 static struct config *basis = 0; /* Top of list of basis configs */
1300 static struct config **basisend = 0; /* End of list of basis configs */
1302 /* Return a pointer to a new configuration */
1303 PRIVATE struct config *newconfig(void){
1304 struct config *newcfg;
1308 freelist = (struct config *)calloc( amt, sizeof(struct config) );
1310 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1313 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1314 freelist[amt-1].next = 0;
1317 freelist = freelist->next;
1321 /* The configuration "old" is no longer used */
1322 PRIVATE void deleteconfig(struct config *old)
1324 old->next = freelist;
1328 /* Initialized the configuration list builder */
1329 void Configlist_init(void){
1331 currentend = ¤t;
1338 /* Initialized the configuration list builder */
1339 void Configlist_reset(void){
1341 currentend = ¤t;
1344 Configtable_clear(0);
1348 /* Add another configuration to the configuration list */
1349 struct config *Configlist_add(
1350 struct rule *rp, /* The rule */
1351 int dot /* Index into the RHS of the rule where the dot goes */
1353 struct config *cfp, model;
1355 assert( currentend!=0 );
1358 cfp = Configtable_find(&model);
1363 cfp->fws = SetNew();
1365 cfp->fplp = cfp->bplp = 0;
1369 currentend = &cfp->next;
1370 Configtable_insert(cfp);
1375 /* Add a basis configuration to the configuration list */
1376 struct config *Configlist_addbasis(struct rule *rp, int dot)
1378 struct config *cfp, model;
1380 assert( basisend!=0 );
1381 assert( currentend!=0 );
1384 cfp = Configtable_find(&model);
1389 cfp->fws = SetNew();
1391 cfp->fplp = cfp->bplp = 0;
1395 currentend = &cfp->next;
1397 basisend = &cfp->bp;
1398 Configtable_insert(cfp);
1403 /* Compute the closure of the configuration list */
1404 void Configlist_closure(struct lemon *lemp)
1406 struct config *cfp, *newcfp;
1407 struct rule *rp, *newrp;
1408 struct symbol *sp, *xsp;
1411 assert( currentend!=0 );
1412 for(cfp=current; cfp; cfp=cfp->next){
1415 if( dot>=rp->nrhs ) continue;
1417 if( sp->type==NONTERMINAL ){
1418 if( sp->rule==0 && sp!=lemp->errsym ){
1419 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1423 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1424 newcfp = Configlist_add(newrp,0);
1425 for(i=dot+1; i<rp->nrhs; i++){
1427 if( xsp->type==TERMINAL ){
1428 SetAdd(newcfp->fws,xsp->index);
1430 }else if( xsp->type==MULTITERMINAL ){
1432 for(k=0; k<xsp->nsubsym; k++){
1433 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1437 SetUnion(newcfp->fws,xsp->firstset);
1438 if( xsp->lambda==LEMON_FALSE ) break;
1441 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1448 /* Sort the configuration list */
1449 void Configlist_sort(void){
1450 current = (struct config*)msort((char*)current,(char**)&(current->next),
1456 /* Sort the basis configuration list */
1457 void Configlist_sortbasis(void){
1458 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1464 /* Return a pointer to the head of the configuration list and
1465 ** reset the list */
1466 struct config *Configlist_return(void){
1474 /* Return a pointer to the head of the configuration list and
1475 ** reset the list */
1476 struct config *Configlist_basis(void){
1484 /* Free all elements of the given configuration list */
1485 void Configlist_eat(struct config *cfp)
1487 struct config *nextcfp;
1488 for(; cfp; cfp=nextcfp){
1489 nextcfp = cfp->next;
1490 assert( cfp->fplp==0 );
1491 assert( cfp->bplp==0 );
1492 if( cfp->fws ) SetFree(cfp->fws);
1497 /***************** From the file "error.c" *********************************/
1499 ** Code for printing error message.
1502 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1504 fprintf(stderr, "%s:%d: ", filename, lineno);
1505 va_start(ap, format);
1506 vfprintf(stderr,format,ap);
1508 fprintf(stderr, "\n");
1510 /**************** From the file "main.c" ************************************/
1512 ** Main program file for the LEMON parser generator.
1515 /* Report an out-of-memory condition and abort. This function
1516 ** is used mostly by the "MemoryCheck" macro in struct.h
1518 void memory_error(void){
1519 fprintf(stderr,"Out of memory. Aborting...\n");
1523 static int nDefine = 0; /* Number of -D options on the command line */
1524 static char **azDefine = 0; /* Name of the -D macros */
1526 /* This routine is called with the argument to each -D command-line option.
1527 ** Add the macro defined to the azDefine array.
1529 static void handle_D_option(char *z){
1532 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
1534 fprintf(stderr,"out of memory\n");
1537 paz = &azDefine[nDefine-1];
1538 *paz = (char *) malloc( lemonStrlen(z)+1 );
1540 fprintf(stderr,"out of memory\n");
1543 lemon_strcpy(*paz, z);
1544 for(z=*paz; *z && *z!='='; z++){}
1548 /* Rember the name of the output directory
1550 static char *outputDir = NULL;
1551 static void handle_d_option(char *z){
1552 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1554 fprintf(stderr,"out of memory\n");
1557 lemon_strcpy(outputDir, z);
1560 static char *user_templatename = NULL;
1561 static void handle_T_option(char *z){
1562 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
1563 if( user_templatename==0 ){
1566 lemon_strcpy(user_templatename, z);
1569 /* Merge together to lists of rules ordered by rule.iRule */
1570 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1571 struct rule *pFirst = 0;
1572 struct rule **ppPrev = &pFirst;
1574 if( pA->iRule<pB->iRule ){
1593 ** Sort a list of rules in order of increasing iRule value
1595 static struct rule *Rule_sort(struct rule *rp){
1599 memset(x, 0, sizeof(x));
1603 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1604 rp = Rule_merge(x[i], rp);
1611 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1612 rp = Rule_merge(x[i], rp);
1617 /* forward reference */
1618 static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1620 /* Print a single line of the "Parser Stats" output
1622 static void stats_line(const char *zLabel, int iValue){
1623 int nLabel = lemonStrlen(zLabel);
1624 printf(" %s%.*s %5d\n", zLabel,
1625 35-nLabel, "................................",
1629 /* The main program. Parse the command line and do it... */
1630 int main(int argc, char **argv)
1632 static int version = 0;
1633 static int rpflag = 0;
1634 static int basisflag = 0;
1635 static int compress = 0;
1636 static int quiet = 0;
1637 static int statistics = 0;
1638 static int mhflag = 0;
1639 static int nolinenosflag = 0;
1640 static int noResort = 0;
1642 static struct s_options options[] = {
1643 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1644 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1645 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
1646 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1647 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1648 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1649 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1650 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1651 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
1652 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1653 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1654 "Show conflicts resolved by precedence rules"},
1655 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1656 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
1657 {OPT_FLAG, "s", (char*)&statistics,
1658 "Print parser stats to standard output."},
1659 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1660 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1661 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1669 OptInit(argv,options,stderr);
1671 printf("Lemon version 1.0\n");
1674 if( OptNArgs()!=1 ){
1675 fprintf(stderr,"Exactly one filename argument is required.\n");
1678 memset(&lem, 0, sizeof(lem));
1681 /* Initialize the machine */
1685 lem.argv0 = argv[0];
1686 lem.filename = OptArg(0);
1687 lem.basisflag = basisflag;
1688 lem.nolinenosflag = nolinenosflag;
1691 /* Parse the input file */
1693 if( lem.errorcnt ) exit(lem.errorcnt);
1694 assert(lem.rule); /* Hint for CSA (no errors => rule found). */
1696 fprintf(stderr,"Empty grammar.\n");
1699 lem.errsym = Symbol_find("error");
1701 /* Count and index the symbols of the grammar */
1702 Symbol_new("{default}");
1703 lem.nsymbol = Symbol_count();
1704 lem.symbols = Symbol_arrayof();
1705 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1706 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1707 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1708 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1709 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1710 lem.nsymbol = i - 1;
1711 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
1714 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1715 ** reduce action C-code associated with them last, so that the switch()
1716 ** statement that selects reduction actions will have a smaller jump table.
1718 for(i=0, rp=lem.rule; rp; rp=rp->next){
1719 rp->iRule = rp->code ? i++ : -1;
1721 for(rp=lem.rule; rp; rp=rp->next){
1722 if( rp->iRule<0 ) rp->iRule = i++;
1724 lem.startRule = lem.rule;
1725 lem.rule = Rule_sort(lem.rule);
1727 /* Generate a reprint of the grammar, if requested on the command line */
1731 /* Initialize the size for all follow and first sets */
1732 SetSize(lem.nterminal+1);
1734 /* Find the precedence for every production rule (that has one) */
1735 FindRulePrecedences(&lem);
1737 /* Compute the lambda-nonterminals and the first-sets for every
1739 FindFirstSets(&lem);
1741 /* Compute all LR(0) states. Also record follow-set propagation
1742 ** links so that the follow-set can be computed later */
1745 lem.sorted = State_arrayof();
1747 /* Tie up loose ends on the propagation links */
1750 /* Compute the follow set of every reducible configuration */
1751 FindFollowSets(&lem);
1753 /* Compute the action tables */
1756 /* Compress the action tables */
1757 if( compress==0 ) CompressTables(&lem);
1759 /* Reorder and renumber the states so that states with fewer choices
1760 ** occur at the end. This is an optimization that helps make the
1761 ** generated parser tables smaller. */
1762 if( noResort==0 ) ResortStates(&lem);
1764 /* Generate a report of the parser generated. (the "y.output" file) */
1765 if( !quiet ) ReportOutput(&lem);
1767 /* Generate the source code for the parser */
1768 ReportTable(&lem, mhflag);
1770 /* Produce a header file for use by the scanner. (This step is
1771 ** omitted if the "-m" option is used because makeheaders will
1772 ** generate the file for us.) */
1773 if( !mhflag ) ReportHeader(&lem);
1776 printf("Parser statistics:\n");
1777 stats_line("terminal symbols", lem.nterminal);
1778 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1779 stats_line("total symbols", lem.nsymbol);
1780 stats_line("rules", lem.nrule);
1781 stats_line("states", lem.nxstate);
1782 stats_line("conflicts", lem.nconflict);
1783 stats_line("action table entries", lem.nactiontab);
1784 stats_line("lookahead table entries", lem.nlookaheadtab);
1785 stats_line("total table size (bytes)", lem.tablesize);
1787 if( lem.nconflict > 0 ){
1788 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1791 /* return 0 on success, 1 on failure. */
1792 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1796 /******************** From the file "msort.c" *******************************/
1798 ** A generic merge-sort program.
1801 ** Let "ptr" be a pointer to some structure which is at the head of
1802 ** a null-terminated list. Then to sort the list call:
1804 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1806 ** In the above, "cmpfnc" is a pointer to a function which compares
1807 ** two instances of the structure and returns an integer, as in
1808 ** strcmp. The second argument is a pointer to the pointer to the
1809 ** second element of the linked list. This address is used to compute
1810 ** the offset to the "next" field within the structure. The offset to
1811 ** the "next" field must be constant for all structures in the list.
1813 ** The function returns a new pointer which is the head of the list
1821 ** Return a pointer to the next structure in the linked list.
1823 #define NEXT(A) (*(char**)(((char*)A)+offset))
1827 ** a: A sorted, null-terminated linked list. (May be null).
1828 ** b: A sorted, null-terminated linked list. (May be null).
1829 ** cmp: A pointer to the comparison function.
1830 ** offset: Offset in the structure to the "next" field.
1833 ** A pointer to the head of a sorted list containing the elements
1837 ** The "next" pointers for elements in the lists a and b are
1843 int (*cmp)(const char*,const char*),
1853 if( (*cmp)(a,b)<=0 ){
1862 if( (*cmp)(a,b)<=0 ){
1872 if( a ) NEXT(ptr) = a;
1880 ** list: Pointer to a singly-linked list of structures.
1881 ** next: Pointer to pointer to the second element of the list.
1882 ** cmp: A comparison function.
1885 ** A pointer to the head of a sorted list containing the elements
1886 ** orginally in list.
1889 ** The "next" pointers for elements in list are changed.
1895 int (*cmp)(const char*,const char*)
1897 unsigned long offset;
1899 char *set[LISTSIZE];
1901 offset = (unsigned long)((char*)next - (char*)list);
1902 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1907 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1908 ep = merge(ep,set[i],cmp,offset);
1914 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
1917 /************************ From the file "option.c" **************************/
1919 static struct s_options *op;
1920 static FILE *errstream;
1922 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1925 ** Print the command line with a carrot pointing to the k-th character
1926 ** of the n-th field.
1928 static void errline(int n, int k, FILE *err)
1931 if( argv[0] ) fprintf(err,"%s",argv[0]);
1932 spcnt = lemonStrlen(argv[0]) + 1;
1933 for(i=1; i<n && argv[i]; i++){
1934 fprintf(err," %s",argv[i]);
1935 spcnt += lemonStrlen(argv[i])+1;
1938 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1940 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1942 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1947 ** Return the index of the N-th non-switch argument. Return -1
1948 ** if N is out of range.
1950 static int argindex(int n)
1954 if( argv!=0 && *argv!=0 ){
1955 for(i=1; argv[i]; i++){
1956 if( dashdash || !ISOPT(argv[i]) ){
1957 if( n==0 ) return i;
1960 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1966 static char emsg[] = "Command line syntax error: ";
1969 ** Process a flag command line argument.
1971 static int handleflags(int i, FILE *err)
1976 for(j=0; op[j].label; j++){
1977 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
1979 v = argv[i][0]=='-' ? 1 : 0;
1980 if( op[j].label==0 ){
1982 fprintf(err,"%sundefined option.\n",emsg);
1986 }else if( op[j].arg==0 ){
1987 /* Ignore this option */
1988 }else if( op[j].type==OPT_FLAG ){
1989 *((int*)op[j].arg) = v;
1990 }else if( op[j].type==OPT_FFLAG ){
1991 (*(void(*)(int))(op[j].arg))(v);
1992 }else if( op[j].type==OPT_FSTR ){
1993 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
1996 fprintf(err,"%smissing argument on switch.\n",emsg);
2005 ** Process a command line switch which has an argument.
2007 static int handleswitch(int i, FILE *err)
2015 cp = strchr(argv[i],'=');
2018 for(j=0; op[j].label; j++){
2019 if( strcmp(argv[i],op[j].label)==0 ) break;
2022 if( op[j].label==0 ){
2024 fprintf(err,"%sundefined option.\n",emsg);
2030 switch( op[j].type ){
2034 fprintf(err,"%soption requires an argument.\n",emsg);
2041 dv = strtod(cp,&end);
2045 "%sillegal character in floating-point argument.\n",emsg);
2046 errline(i,(int)((char*)end-(char*)argv[i]),err);
2053 lv = strtol(cp,&end,0);
2056 fprintf(err,"%sillegal character in integer argument.\n",emsg);
2057 errline(i,(int)((char*)end-(char*)argv[i]),err);
2067 switch( op[j].type ){
2072 *(double*)(op[j].arg) = dv;
2075 (*(void(*)(double))(op[j].arg))(dv);
2078 *(int*)(op[j].arg) = lv;
2081 (*(void(*)(int))(op[j].arg))((int)lv);
2084 *(char**)(op[j].arg) = sv;
2087 (*(void(*)(char *))(op[j].arg))(sv);
2094 int OptInit(char **a, struct s_options *o, FILE *err)
2100 if( argv && *argv && op ){
2102 for(i=1; argv[i]; i++){
2103 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2104 errcnt += handleflags(i,err);
2105 }else if( strchr(argv[i],'=') ){
2106 errcnt += handleswitch(i,err);
2111 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
2122 if( argv!=0 && argv[0]!=0 ){
2123 for(i=1; argv[i]; i++){
2124 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2125 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2135 return i>=0 ? argv[i] : 0;
2142 if( i>=0 ) errline(i,0,errstream);
2145 void OptPrint(void){
2149 for(i=0; op[i].label; i++){
2150 len = lemonStrlen(op[i].label) + 1;
2151 switch( op[i].type ){
2157 len += 9; /* length of "<integer>" */
2161 len += 6; /* length of "<real>" */
2165 len += 8; /* length of "<string>" */
2168 if( len>max ) max = len;
2170 for(i=0; op[i].label; i++){
2171 switch( op[i].type ){
2174 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2178 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
2179 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2183 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
2184 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2188 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
2189 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2194 /*********************** From the file "parse.c" ****************************/
2196 ** Input file parser for the LEMON parser generator.
2199 /* The state of the parser */
2202 WAITING_FOR_DECL_OR_RULE,
2203 WAITING_FOR_DECL_KEYWORD,
2204 WAITING_FOR_DECL_ARG,
2205 WAITING_FOR_PRECEDENCE_SYMBOL,
2215 RESYNC_AFTER_RULE_ERROR,
2216 RESYNC_AFTER_DECL_ERROR,
2217 WAITING_FOR_DESTRUCTOR_SYMBOL,
2218 WAITING_FOR_DATATYPE_SYMBOL,
2219 WAITING_FOR_FALLBACK_ID,
2220 WAITING_FOR_WILDCARD_ID,
2221 WAITING_FOR_CLASS_ID,
2222 WAITING_FOR_CLASS_TOKEN,
2223 WAITING_FOR_TOKEN_NAME
2226 char *filename; /* Name of the input file */
2227 int tokenlineno; /* Linenumber at which current token starts */
2228 int errorcnt; /* Number of errors so far */
2229 char *tokenstart; /* Text of current token */
2230 struct lemon *gp; /* Global state vector */
2231 enum e_state state; /* The state of the parser */
2232 struct symbol *fallback; /* The fallback token */
2233 struct symbol *tkclass; /* Token class symbol */
2234 struct symbol *lhs; /* Left-hand side of current rule */
2235 const char *lhsalias; /* Alias for the LHS */
2236 int nrhs; /* Number of right-hand side symbols seen */
2237 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2238 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2239 struct rule *prevrule; /* Previous rule parsed */
2240 const char *declkeyword; /* Keyword of a declaration */
2241 char **declargslot; /* Where the declaration argument should be put */
2242 int insertLineMacro; /* Add #line before declaration insert */
2243 int *decllinenoslot; /* Where to write declaration line number */
2244 enum e_assoc declassoc; /* Assign this association to decl arguments */
2245 int preccounter; /* Assign this precedence to decl arguments */
2246 struct rule *firstrule; /* Pointer to first rule in the grammar */
2247 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2250 /* Parse a single token */
2251 static void parseonetoken(struct pstate *psp)
2254 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2256 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2259 switch( psp->state ){
2262 psp->preccounter = 0;
2263 psp->firstrule = psp->lastrule = 0;
2265 /* Fall thru to next case */
2266 case WAITING_FOR_DECL_OR_RULE:
2268 psp->state = WAITING_FOR_DECL_KEYWORD;
2269 }else if( ISLOWER(x[0]) ){
2270 psp->lhs = Symbol_new(x);
2273 psp->state = WAITING_FOR_ARROW;
2274 }else if( x[0]=='{' ){
2275 if( psp->prevrule==0 ){
2276 ErrorMsg(psp->filename,psp->tokenlineno,
2277 "There is no prior rule upon which to attach the code \
2278 fragment which begins on this line.");
2280 }else if( psp->prevrule->code!=0 ){
2281 ErrorMsg(psp->filename,psp->tokenlineno,
2282 "Code fragment beginning on this line is not the first \
2283 to follow the previous rule.");
2286 psp->prevrule->line = psp->tokenlineno;
2287 psp->prevrule->code = &x[1];
2288 psp->prevrule->noCode = 0;
2290 }else if( x[0]=='[' ){
2291 psp->state = PRECEDENCE_MARK_1;
2293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2299 case PRECEDENCE_MARK_1:
2300 if( !ISUPPER(x[0]) ){
2301 ErrorMsg(psp->filename,psp->tokenlineno,
2302 "The precedence symbol must be a terminal.");
2304 }else if( psp->prevrule==0 ){
2305 ErrorMsg(psp->filename,psp->tokenlineno,
2306 "There is no prior rule to assign precedence \"[%s]\".",x);
2308 }else if( psp->prevrule->precsym!=0 ){
2309 ErrorMsg(psp->filename,psp->tokenlineno,
2310 "Precedence mark on this line is not the first \
2311 to follow the previous rule.");
2314 psp->prevrule->precsym = Symbol_new(x);
2316 psp->state = PRECEDENCE_MARK_2;
2318 case PRECEDENCE_MARK_2:
2320 ErrorMsg(psp->filename,psp->tokenlineno,
2321 "Missing \"]\" on precedence mark.");
2324 psp->state = WAITING_FOR_DECL_OR_RULE;
2326 case WAITING_FOR_ARROW:
2327 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2328 psp->state = IN_RHS;
2329 }else if( x[0]=='(' ){
2330 psp->state = LHS_ALIAS_1;
2332 ErrorMsg(psp->filename,psp->tokenlineno,
2333 "Expected to see a \":\" following the LHS symbol \"%s\".",
2336 psp->state = RESYNC_AFTER_RULE_ERROR;
2340 if( ISALPHA(x[0]) ){
2342 psp->state = LHS_ALIAS_2;
2344 ErrorMsg(psp->filename,psp->tokenlineno,
2345 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2348 psp->state = RESYNC_AFTER_RULE_ERROR;
2353 psp->state = LHS_ALIAS_3;
2355 ErrorMsg(psp->filename,psp->tokenlineno,
2356 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2358 psp->state = RESYNC_AFTER_RULE_ERROR;
2362 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2363 psp->state = IN_RHS;
2365 ErrorMsg(psp->filename,psp->tokenlineno,
2366 "Missing \"->\" following: \"%s(%s)\".",
2367 psp->lhs->name,psp->lhsalias);
2369 psp->state = RESYNC_AFTER_RULE_ERROR;
2375 rp = (struct rule *)calloc( sizeof(struct rule) +
2376 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2378 ErrorMsg(psp->filename,psp->tokenlineno,
2379 "Can't allocate enough memory for this rule.");
2384 rp->ruleline = psp->tokenlineno;
2385 rp->rhs = (struct symbol**)&rp[1];
2386 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2387 for(i=0; i<psp->nrhs; i++){
2388 rp->rhs[i] = psp->rhs[i];
2389 rp->rhsalias[i] = psp->alias[i];
2390 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
2393 rp->lhsalias = psp->lhsalias;
2394 rp->nrhs = psp->nrhs;
2398 rp->index = psp->gp->nrule++;
2399 rp->nextlhs = rp->lhs->rule;
2402 if( psp->firstrule==0 ){
2403 psp->firstrule = psp->lastrule = rp;
2405 psp->lastrule->next = rp;
2410 psp->state = WAITING_FOR_DECL_OR_RULE;
2411 }else if( ISALPHA(x[0]) ){
2412 if( psp->nrhs>=MAXRHS ){
2413 ErrorMsg(psp->filename,psp->tokenlineno,
2414 "Too many symbols on RHS of rule beginning at \"%s\".",
2417 psp->state = RESYNC_AFTER_RULE_ERROR;
2419 psp->rhs[psp->nrhs] = Symbol_new(x);
2420 psp->alias[psp->nrhs] = 0;
2423 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2424 struct symbol *msp = psp->rhs[psp->nrhs-1];
2425 if( msp->type!=MULTITERMINAL ){
2426 struct symbol *origsp = msp;
2427 msp = (struct symbol *) calloc(1,sizeof(*msp));
2428 memset(msp, 0, sizeof(*msp));
2429 msp->type = MULTITERMINAL;
2431 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
2432 msp->subsym[0] = origsp;
2433 msp->name = origsp->name;
2434 psp->rhs[psp->nrhs-1] = msp;
2437 msp->subsym = (struct symbol **) realloc(msp->subsym,
2438 sizeof(struct symbol*)*msp->nsubsym);
2439 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2440 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
2441 ErrorMsg(psp->filename,psp->tokenlineno,
2442 "Cannot form a compound containing a non-terminal");
2445 }else if( x[0]=='(' && psp->nrhs>0 ){
2446 psp->state = RHS_ALIAS_1;
2448 ErrorMsg(psp->filename,psp->tokenlineno,
2449 "Illegal character on RHS of rule: \"%s\".",x);
2451 psp->state = RESYNC_AFTER_RULE_ERROR;
2455 if( ISALPHA(x[0]) ){
2456 psp->alias[psp->nrhs-1] = x;
2457 psp->state = RHS_ALIAS_2;
2459 ErrorMsg(psp->filename,psp->tokenlineno,
2460 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2461 x,psp->rhs[psp->nrhs-1]->name);
2463 psp->state = RESYNC_AFTER_RULE_ERROR;
2468 psp->state = IN_RHS;
2470 ErrorMsg(psp->filename,psp->tokenlineno,
2471 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2473 psp->state = RESYNC_AFTER_RULE_ERROR;
2476 case WAITING_FOR_DECL_KEYWORD:
2477 if( ISALPHA(x[0]) ){
2478 psp->declkeyword = x;
2479 psp->declargslot = 0;
2480 psp->decllinenoslot = 0;
2481 psp->insertLineMacro = 1;
2482 psp->state = WAITING_FOR_DECL_ARG;
2483 if( strcmp(x,"name")==0 ){
2484 psp->declargslot = &(psp->gp->name);
2485 psp->insertLineMacro = 0;
2486 }else if( strcmp(x,"include")==0 ){
2487 psp->declargslot = &(psp->gp->include);
2488 }else if( strcmp(x,"code")==0 ){
2489 psp->declargslot = &(psp->gp->extracode);
2490 }else if( strcmp(x,"token_destructor")==0 ){
2491 psp->declargslot = &psp->gp->tokendest;
2492 }else if( strcmp(x,"default_destructor")==0 ){
2493 psp->declargslot = &psp->gp->vardest;
2494 }else if( strcmp(x,"token_prefix")==0 ){
2495 psp->declargslot = &psp->gp->tokenprefix;
2496 psp->insertLineMacro = 0;
2497 }else if( strcmp(x,"syntax_error")==0 ){
2498 psp->declargslot = &(psp->gp->error);
2499 }else if( strcmp(x,"parse_accept")==0 ){
2500 psp->declargslot = &(psp->gp->accept);
2501 }else if( strcmp(x,"parse_failure")==0 ){
2502 psp->declargslot = &(psp->gp->failure);
2503 }else if( strcmp(x,"stack_overflow")==0 ){
2504 psp->declargslot = &(psp->gp->overflow);
2505 }else if( strcmp(x,"extra_argument")==0 ){
2506 psp->declargslot = &(psp->gp->arg);
2507 psp->insertLineMacro = 0;
2508 }else if( strcmp(x,"extra_context")==0 ){
2509 psp->declargslot = &(psp->gp->ctx);
2510 psp->insertLineMacro = 0;
2511 }else if( strcmp(x,"token_type")==0 ){
2512 psp->declargslot = &(psp->gp->tokentype);
2513 psp->insertLineMacro = 0;
2514 }else if( strcmp(x,"default_type")==0 ){
2515 psp->declargslot = &(psp->gp->vartype);
2516 psp->insertLineMacro = 0;
2517 }else if( strcmp(x,"stack_size")==0 ){
2518 psp->declargslot = &(psp->gp->stacksize);
2519 psp->insertLineMacro = 0;
2520 }else if( strcmp(x,"start_symbol")==0 ){
2521 psp->declargslot = &(psp->gp->start);
2522 psp->insertLineMacro = 0;
2523 }else if( strcmp(x,"left")==0 ){
2525 psp->declassoc = LEFT;
2526 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2527 }else if( strcmp(x,"right")==0 ){
2529 psp->declassoc = RIGHT;
2530 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2531 }else if( strcmp(x,"nonassoc")==0 ){
2533 psp->declassoc = NONE;
2534 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2535 }else if( strcmp(x,"destructor")==0 ){
2536 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2537 }else if( strcmp(x,"type")==0 ){
2538 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2539 }else if( strcmp(x,"fallback")==0 ){
2541 psp->state = WAITING_FOR_FALLBACK_ID;
2542 }else if( strcmp(x,"token")==0 ){
2543 psp->state = WAITING_FOR_TOKEN_NAME;
2544 }else if( strcmp(x,"wildcard")==0 ){
2545 psp->state = WAITING_FOR_WILDCARD_ID;
2546 }else if( strcmp(x,"token_class")==0 ){
2547 psp->state = WAITING_FOR_CLASS_ID;
2549 ErrorMsg(psp->filename,psp->tokenlineno,
2550 "Unknown declaration keyword: \"%%%s\".",x);
2552 psp->state = RESYNC_AFTER_DECL_ERROR;
2555 ErrorMsg(psp->filename,psp->tokenlineno,
2556 "Illegal declaration keyword: \"%s\".",x);
2558 psp->state = RESYNC_AFTER_DECL_ERROR;
2561 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2562 if( !ISALPHA(x[0]) ){
2563 ErrorMsg(psp->filename,psp->tokenlineno,
2564 "Symbol name missing after %%destructor keyword");
2566 psp->state = RESYNC_AFTER_DECL_ERROR;
2568 struct symbol *sp = Symbol_new(x);
2569 psp->declargslot = &sp->destructor;
2570 psp->decllinenoslot = &sp->destLineno;
2571 psp->insertLineMacro = 1;
2572 psp->state = WAITING_FOR_DECL_ARG;
2575 case WAITING_FOR_DATATYPE_SYMBOL:
2576 if( !ISALPHA(x[0]) ){
2577 ErrorMsg(psp->filename,psp->tokenlineno,
2578 "Symbol name missing after %%type keyword");
2580 psp->state = RESYNC_AFTER_DECL_ERROR;
2582 struct symbol *sp = Symbol_find(x);
2583 if((sp) && (sp->datatype)){
2584 ErrorMsg(psp->filename,psp->tokenlineno,
2585 "Symbol %%type \"%s\" already defined", x);
2587 psp->state = RESYNC_AFTER_DECL_ERROR;
2592 psp->declargslot = &sp->datatype;
2593 psp->insertLineMacro = 0;
2594 psp->state = WAITING_FOR_DECL_ARG;
2598 case WAITING_FOR_PRECEDENCE_SYMBOL:
2600 psp->state = WAITING_FOR_DECL_OR_RULE;
2601 }else if( ISUPPER(x[0]) ){
2605 ErrorMsg(psp->filename,psp->tokenlineno,
2606 "Symbol \"%s\" has already be given a precedence.",x);
2609 sp->prec = psp->preccounter;
2610 sp->assoc = psp->declassoc;
2613 ErrorMsg(psp->filename,psp->tokenlineno,
2614 "Can't assign a precedence to \"%s\".",x);
2618 case WAITING_FOR_DECL_ARG:
2619 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
2620 const char *zOld, *zNew;
2622 int nOld, n, nLine = 0, nNew, nBack;
2626 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2627 nNew = lemonStrlen(zNew);
2628 if( *psp->declargslot ){
2629 zOld = *psp->declargslot;
2633 nOld = lemonStrlen(zOld);
2634 n = nOld + nNew + 20;
2635 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
2636 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2638 for(z=psp->filename, nBack=0; *z; z++){
2639 if( *z=='\\' ) nBack++;
2641 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2642 nLine = lemonStrlen(zLine);
2643 n += nLine + lemonStrlen(psp->filename) + nBack;
2645 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2646 zBuf = *psp->declargslot + nOld;
2648 if( nOld && zBuf[-1]!='\n' ){
2651 memcpy(zBuf, zLine, nLine);
2654 for(z=psp->filename; *z; z++){
2663 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2664 psp->decllinenoslot[0] = psp->tokenlineno;
2666 memcpy(zBuf, zNew, nNew);
2669 psp->state = WAITING_FOR_DECL_OR_RULE;
2671 ErrorMsg(psp->filename,psp->tokenlineno,
2672 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2674 psp->state = RESYNC_AFTER_DECL_ERROR;
2677 case WAITING_FOR_FALLBACK_ID:
2679 psp->state = WAITING_FOR_DECL_OR_RULE;
2680 }else if( !ISUPPER(x[0]) ){
2681 ErrorMsg(psp->filename, psp->tokenlineno,
2682 "%%fallback argument \"%s\" should be a token", x);
2685 struct symbol *sp = Symbol_new(x);
2686 if( psp->fallback==0 ){
2688 }else if( sp->fallback ){
2689 ErrorMsg(psp->filename, psp->tokenlineno,
2690 "More than one fallback assigned to token %s", x);
2693 sp->fallback = psp->fallback;
2694 psp->gp->has_fallback = 1;
2698 case WAITING_FOR_TOKEN_NAME:
2699 /* Tokens do not have to be declared before use. But they can be
2700 ** in order to control their assigned integer number. The number for
2701 ** each token is assigned when it is first seen. So by including
2703 ** %token ONE TWO THREE
2705 ** early in the grammar file, that assigns small consecutive values
2706 ** to each of the tokens ONE TWO and THREE.
2709 psp->state = WAITING_FOR_DECL_OR_RULE;
2710 }else if( !ISUPPER(x[0]) ){
2711 ErrorMsg(psp->filename, psp->tokenlineno,
2712 "%%token argument \"%s\" should be a token", x);
2715 (void)Symbol_new(x);
2718 case WAITING_FOR_WILDCARD_ID:
2720 psp->state = WAITING_FOR_DECL_OR_RULE;
2721 }else if( !ISUPPER(x[0]) ){
2722 ErrorMsg(psp->filename, psp->tokenlineno,
2723 "%%wildcard argument \"%s\" should be a token", x);
2726 struct symbol *sp = Symbol_new(x);
2727 if( psp->gp->wildcard==0 ){
2728 psp->gp->wildcard = sp;
2730 ErrorMsg(psp->filename, psp->tokenlineno,
2731 "Extra wildcard to token: %s", x);
2736 case WAITING_FOR_CLASS_ID:
2737 if( !ISLOWER(x[0]) ){
2738 ErrorMsg(psp->filename, psp->tokenlineno,
2739 "%%token_class must be followed by an identifier: ", x);
2741 psp->state = RESYNC_AFTER_DECL_ERROR;
2742 }else if( Symbol_find(x) ){
2743 ErrorMsg(psp->filename, psp->tokenlineno,
2744 "Symbol \"%s\" already used", x);
2746 psp->state = RESYNC_AFTER_DECL_ERROR;
2748 psp->tkclass = Symbol_new(x);
2749 psp->tkclass->type = MULTITERMINAL;
2750 psp->state = WAITING_FOR_CLASS_TOKEN;
2753 case WAITING_FOR_CLASS_TOKEN:
2755 psp->state = WAITING_FOR_DECL_OR_RULE;
2756 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
2757 struct symbol *msp = psp->tkclass;
2759 msp->subsym = (struct symbol **) realloc(msp->subsym,
2760 sizeof(struct symbol*)*msp->nsubsym);
2761 if( !ISUPPER(x[0]) ) x++;
2762 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2764 ErrorMsg(psp->filename, psp->tokenlineno,
2765 "%%token_class argument \"%s\" should be a token", x);
2767 psp->state = RESYNC_AFTER_DECL_ERROR;
2770 case RESYNC_AFTER_RULE_ERROR:
2771 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2773 case RESYNC_AFTER_DECL_ERROR:
2774 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2775 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2780 /* Run the preprocessor over the input file text. The global variables
2781 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2782 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2783 ** comments them out. Text in between is also commented out as appropriate.
2785 static void preprocess_input(char *z){
2790 int start_lineno = 1;
2791 for(i=0; z[i]; i++){
2792 if( z[i]=='\n' ) lineno++;
2793 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2794 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
2798 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2801 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2802 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2803 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
2807 for(j=i+7; ISSPACE(z[j]); j++){}
2808 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
2810 for(k=0; k<nDefine; k++){
2811 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
2816 if( z[i+3]=='n' ) exclude = !exclude;
2819 start_lineno = lineno;
2822 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2826 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2831 /* In spite of its name, this function is really a scanner. It read
2832 ** in the entire input file (all at once) then tokenizes it. Each
2833 ** token is passed to the function "parseonetoken" which builds all
2834 ** the appropriate data structures in the global state vector "gp".
2836 void Parse(struct lemon *gp)
2841 unsigned int filesize;
2847 memset(&ps, '\0', sizeof(ps));
2849 ps.filename = gp->filename;
2851 ps.state = INITIALIZE;
2853 /* Begin by reading the input file */
2854 fp = fopen(ps.filename,"rb");
2856 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2861 filesize = ftell(fp);
2863 filebuf = (char *)malloc( filesize+1 );
2864 if( filesize>100000000 || filebuf==0 ){
2865 ErrorMsg(ps.filename,0,"Input file too large.");
2871 if( fread(filebuf,1,filesize,fp)!=filesize ){
2872 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2880 filebuf[filesize] = 0;
2882 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2883 preprocess_input(filebuf);
2885 /* Now scan the text of the input file */
2887 for(cp=filebuf; (c= *cp)!=0; ){
2888 if( c=='\n' ) lineno++; /* Keep track of the line number */
2889 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
2890 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2892 while( (c= *cp)!=0 && c!='\n' ) cp++;
2895 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2897 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2898 if( c=='\n' ) lineno++;
2904 ps.tokenstart = cp; /* Mark the beginning of the token */
2905 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2906 if( c=='\"' ){ /* String literals */
2908 while( (c= *cp)!=0 && c!='\"' ){
2909 if( c=='\n' ) lineno++;
2913 ErrorMsg(ps.filename,startline,
2914 "String starting on this line is not terminated before the end of the file.");
2920 }else if( c=='{' ){ /* A block of C code */
2923 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2924 if( c=='\n' ) lineno++;
2925 else if( c=='{' ) level++;
2926 else if( c=='}' ) level--;
2927 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2931 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2932 if( c=='\n' ) lineno++;
2936 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2938 while( (c= *cp)!=0 && c!='\n' ) cp++;
2940 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2941 int startchar, prevc;
2944 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2945 if( c=='\n' ) lineno++;
2946 if( prevc=='\\' ) prevc = 0;
2952 ErrorMsg(ps.filename,ps.tokenlineno,
2953 "C code starting on this line is not terminated before the end of the file.");
2959 }else if( ISALNUM(c) ){ /* Identifiers */
2960 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2962 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2965 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
2967 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2969 }else{ /* All other (one character) operators */
2974 *cp = 0; /* Null terminate the token */
2975 parseonetoken(&ps); /* Parse the token */
2976 *cp = (char)c; /* Restore the buffer */
2979 free(filebuf); /* Release the buffer after parsing */
2980 gp->rule = ps.firstrule;
2981 gp->errorcnt = ps.errorcnt;
2983 /*************************** From the file "plink.c" *********************/
2985 ** Routines processing configuration follow-set propagation links
2986 ** in the LEMON parser generator.
2988 static struct plink *plink_freelist = 0;
2990 /* Allocate a new plink */
2991 struct plink *Plink_new(void){
2992 struct plink *newlink;
2994 if( plink_freelist==0 ){
2997 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
2998 if( plink_freelist==0 ){
3000 "Unable to allocate memory for a new follow-set propagation link.\n");
3003 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3004 plink_freelist[amt-1].next = 0;
3006 newlink = plink_freelist;
3007 plink_freelist = plink_freelist->next;
3011 /* Add a plink to a plink list */
3012 void Plink_add(struct plink **plpp, struct config *cfp)
3014 struct plink *newlink;
3015 newlink = Plink_new();
3016 newlink->next = *plpp;
3021 /* Transfer every plink on the list "from" to the list "to" */
3022 void Plink_copy(struct plink **to, struct plink *from)
3024 struct plink *nextpl;
3026 nextpl = from->next;
3033 /* Delete every plink on the list */
3034 void Plink_delete(struct plink *plp)
3036 struct plink *nextpl;
3040 plp->next = plink_freelist;
3041 plink_freelist = plp;
3045 /*********************** From the file "report.c" **************************/
3047 ** Procedures for generating reports and tables in the LEMON parser generator.
3050 /* Generate a filename with the given suffix. Space to hold the
3051 ** name comes from malloc() and must be freed by the calling
3054 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
3058 char *filename = lemp->filename;
3062 cp = strrchr(filename, '/');
3063 if( cp ) filename = cp + 1;
3065 sz = lemonStrlen(filename);
3066 sz += lemonStrlen(suffix);
3067 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3069 name = (char*)malloc( sz );
3071 fprintf(stderr,"Can't allocate space for a filename.\n");
3076 lemon_strcpy(name, outputDir);
3077 lemon_strcat(name, "/");
3079 lemon_strcat(name,filename);
3080 cp = strrchr(name,'.');
3082 lemon_strcat(name,suffix);
3086 /* Open a file with a name based on the name of the input file,
3087 ** but with a different (specified) suffix, and return a pointer
3089 PRIVATE FILE *file_open(
3096 if( lemp->outname ) free(lemp->outname);
3097 lemp->outname = file_makename(lemp, suffix);
3098 fp = fopen(lemp->outname,mode);
3099 if( fp==0 && *mode=='w' ){
3100 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3107 /* Print the text of a rule
3109 void rule_print(FILE *out, struct rule *rp){
3111 fprintf(out, "%s",rp->lhs->name);
3112 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3113 fprintf(out," ::=");
3114 for(i=0; i<rp->nrhs; i++){
3115 struct symbol *sp = rp->rhs[i];
3116 if( sp->type==MULTITERMINAL ){
3117 fprintf(out," %s", sp->subsym[0]->name);
3118 for(j=1; j<sp->nsubsym; j++){
3119 fprintf(out,"|%s", sp->subsym[j]->name);
3122 fprintf(out," %s", sp->name);
3124 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3128 /* Duplicate the input file without comments and without actions
3130 void Reprint(struct lemon *lemp)
3134 int i, j, maxlen, len, ncolumns, skip;
3135 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3137 for(i=0; i<lemp->nsymbol; i++){
3138 sp = lemp->symbols[i];
3139 len = lemonStrlen(sp->name);
3140 if( len>maxlen ) maxlen = len;
3142 ncolumns = 76/(maxlen+5);
3143 if( ncolumns<1 ) ncolumns = 1;
3144 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3145 for(i=0; i<skip; i++){
3147 for(j=i; j<lemp->nsymbol; j+=skip){
3148 sp = lemp->symbols[j];
3149 assert( sp->index==j );
3150 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3154 for(rp=lemp->rule; rp; rp=rp->next){
3155 rule_print(stdout, rp);
3157 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
3158 /* if( rp->code ) printf("\n %s",rp->code); */
3163 /* Print a single rule.
3165 void RulePrint(FILE *fp, struct rule *rp, int iCursor){
3168 fprintf(fp,"%s ::=",rp->lhs->name);
3169 for(i=0; i<=rp->nrhs; i++){
3170 if( i==iCursor ) fprintf(fp," *");
3171 if( i==rp->nrhs ) break;
3173 if( sp->type==MULTITERMINAL ){
3174 fprintf(fp," %s", sp->subsym[0]->name);
3175 for(j=1; j<sp->nsubsym; j++){
3176 fprintf(fp,"|%s",sp->subsym[j]->name);
3179 fprintf(fp," %s", sp->name);
3184 /* Print the rule for a configuration.
3186 void ConfigPrint(FILE *fp, struct config *cfp){
3187 RulePrint(fp, cfp->rp, cfp->dot);
3193 PRIVATE void SetPrint(out,set,lemp)
3201 fprintf(out,"%12s[","");
3202 for(i=0; i<lemp->nterminal; i++){
3203 if( SetFind(set,i) ){
3204 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3211 /* Print a plink chain */
3212 PRIVATE void PlinkPrint(out,plp,tag)
3218 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
3219 ConfigPrint(out,plp->cfp);
3226 /* Print an action to the given file descriptor. Return FALSE if
3227 ** nothing was actually printed.
3230 struct action *ap, /* The action to print */
3231 FILE *fp, /* Print the action here */
3232 int indent /* Indent by this amount */
3237 struct state *stp = ap->x.stp;
3238 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
3242 struct rule *rp = ap->x.rp;
3243 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
3244 RulePrint(fp, rp, -1);
3248 struct rule *rp = ap->x.rp;
3249 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
3250 RulePrint(fp, rp, -1);
3254 fprintf(fp,"%*s accept",indent,ap->sp->name);
3257 fprintf(fp,"%*s error",indent,ap->sp->name);
3261 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
3262 indent,ap->sp->name,ap->x.rp->iRule);
3265 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
3266 indent,ap->sp->name,ap->x.stp->statenum);
3269 if( showPrecedenceConflict ){
3270 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
3271 indent,ap->sp->name,ap->x.stp->statenum);
3277 if( showPrecedenceConflict ){
3278 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
3279 indent,ap->sp->name,ap->x.rp->iRule);
3288 if( result && ap->spOpt ){
3289 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3294 /* Generate the "*.out" log file */
3295 void ReportOutput(struct lemon *lemp)
3304 fp = file_open(lemp,".out","wb");
3306 for(i=0; i<lemp->nxstate; i++){
3307 stp = lemp->sorted[i];
3308 fprintf(fp,"State %d:\n",stp->statenum);
3309 if( lemp->basisflag ) cfp=stp->bp;
3313 if( cfp->dot==cfp->rp->nrhs ){
3314 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
3315 fprintf(fp," %5s ",buf);
3319 ConfigPrint(fp,cfp);
3322 SetPrint(fp,cfp->fws,lemp);
3323 PlinkPrint(fp,cfp->fplp,"To ");
3324 PlinkPrint(fp,cfp->bplp,"From");
3326 if( lemp->basisflag ) cfp=cfp->bp;
3330 for(ap=stp->ap; ap; ap=ap->next){
3331 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3335 fprintf(fp, "----------------------------------------------------\n");
3336 fprintf(fp, "Symbols:\n");
3337 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
3338 for(i=0; i<lemp->nsymbol; i++){
3342 sp = lemp->symbols[i];
3343 fprintf(fp, " %3d: %s", i, sp->name);
3344 if( sp->type==NONTERMINAL ){
3347 fprintf(fp, " <lambda>");
3349 for(j=0; j<lemp->nterminal; j++){
3350 if( sp->firstset && SetFind(sp->firstset, j) ){
3351 fprintf(fp, " %s", lemp->symbols[j]->name);
3355 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
3358 fprintf(fp, "----------------------------------------------------\n");
3359 fprintf(fp, "Syntax-only Symbols:\n");
3360 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3361 for(i=n=0; i<lemp->nsymbol; i++){
3363 struct symbol *sp = lemp->symbols[i];
3364 if( sp->bContent ) continue;
3365 w = (int)strlen(sp->name);
3366 if( n>0 && n+w>75 ){
3374 fprintf(fp, "%s", sp->name);
3377 if( n>0 ) fprintf(fp, "\n");
3378 fprintf(fp, "----------------------------------------------------\n");
3379 fprintf(fp, "Rules:\n");
3380 for(rp=lemp->rule; rp; rp=rp->next){
3381 fprintf(fp, "%4d: ", rp->iRule);
3385 fprintf(fp," [%s precedence=%d]",
3386 rp->precsym->name, rp->precsym->prec);
3394 /* Search for the file "name" which is in the same directory as
3395 ** the exacutable */
3396 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3398 const char *pathlist;
3405 cp = strrchr(argv0,'\\');
3407 cp = strrchr(argv0,'/');
3412 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3413 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3416 pathlist = getenv("PATH");
3417 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3418 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
3419 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3420 MemoryCheck(pathbuf); MemoryCheck(path); /* Fail on allocation failure. */
3421 if( (pathbuf != 0) && (path!=0) ){
3422 pathbufptr = pathbuf;
3423 lemon_strcpy(pathbuf, pathlist);
3425 cp = strchr(pathbuf,':');
3426 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3429 lemon_sprintf(path,"%s/%s",pathbuf,name);
3431 if( c==0 ) pathbuf[0] = 0;
3432 else pathbuf = &cp[1];
3433 if( access(path,modemask)==0 ) break;
3441 /* Given an action, compute the integer value for that action
3442 ** which is to be put in the action table of the generated machine.
3443 ** Return negative if no action should be generated.
3445 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3449 case SHIFT: act = ap->x.stp->statenum; break;
3451 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3452 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3453 ** REDUCE action: */
3454 if( ap->sp->index>=lemp->nterminal ){
3455 act = lemp->minReduce + ap->x.rp->iRule;
3457 act = lemp->minShiftReduce + ap->x.rp->iRule;
3461 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3462 case ERROR: act = lemp->errAction; break;
3463 case ACCEPT: act = lemp->accAction; break;
3464 default: act = -1; break;
3469 #define LINESIZE 1000
3470 /* The next cluster of routines are for reading the template file
3471 ** and writing the results to the generated parser */
3472 /* The first function transfers data from "in" to "out" until
3473 ** a line is seen which begins with "%%". The line number is
3476 ** if name!=0, then any word that begin with "Parse" is changed to
3477 ** begin with *name instead.
3479 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3482 char line[LINESIZE];
3483 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3487 for(i=0; line[i]; i++){
3488 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3489 && (i==0 || !ISALPHA(line[i-1]))
3491 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3492 fprintf(out,"%s",name);
3498 fprintf(out,"%s",&line[iStart]);
3502 /* The next function finds the template file and opens it, returning
3503 ** a pointer to the opened file. */
3504 PRIVATE FILE *tplt_open(struct lemon *lemp)
3506 static char templatename[] = "lempar.c";
3512 /* We always require the -T option, avoid memleak in the other code path. */
3513 assert(user_templatename);
3515 /* first, see if user specified a template filename on the command line. */
3516 if (user_templatename != 0) {
3517 if( access(user_templatename,004)==-1 ){
3518 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3523 in = fopen(user_templatename,"rb");
3525 fprintf(stderr,"Can't open the template file \"%s\".\n",
3533 cp = strrchr(lemp->filename,'.');
3535 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3537 lemon_sprintf(buf,"%s.lt",lemp->filename);
3539 if( access(buf,004)==0 ){
3541 }else if( access(templatename,004)==0 ){
3542 tpltname = templatename;
3544 tpltname = pathsearch(lemp->argv0,templatename,0);
3547 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3552 in = fopen(tpltname,"rb");
3554 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3561 /* Print a #line directive line to the output file. */
3562 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3564 fprintf(out,"#line %d \"",lineno);
3566 if( *filename == '\\' ) putc('\\',out);
3567 putc(*filename,out);
3570 fprintf(out,"\"\n");
3573 /* Print a string to the file and keep the linenumber up to date */
3574 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3576 if( str==0 ) return;
3579 if( *str=='\n' ) (*lineno)++;
3582 if( str[-1]!='\n' ){
3586 if (!lemp->nolinenosflag) {
3587 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3593 ** The following routine emits code for the destructor for the
3596 void emit_destructor_code(
3604 if( sp->type==TERMINAL ){
3605 cp = lemp->tokendest;
3607 fprintf(out,"{\n"); (*lineno)++;
3608 }else if( sp->destructor ){
3609 cp = sp->destructor;
3610 fprintf(out,"{\n"); (*lineno)++;
3611 if( !lemp->nolinenosflag ){
3613 tplt_linedir(out,sp->destLineno,lemp->filename);
3615 }else if( lemp->vardest ){
3618 fprintf(out,"{\n"); (*lineno)++;
3620 assert( 0 ); /* Cannot happen */
3623 if( *cp=='$' && cp[1]=='$' ){
3624 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3628 if( *cp=='\n' ) (*lineno)++;
3631 fprintf(out,"\n"); (*lineno)++;
3632 if (!lemp->nolinenosflag) {
3633 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3635 fprintf(out,"}\n"); (*lineno)++;
3640 ** Return TRUE (non-zero) if the given symbol has a destructor.
3642 int has_destructor(struct symbol *sp, struct lemon *lemp)
3645 if( sp->type==TERMINAL ){
3646 ret = lemp->tokendest!=0;
3648 ret = lemp->vardest!=0 || sp->destructor!=0;
3654 ** Append text to a dynamically allocated string. If zText is 0 then
3655 ** reset the string to be empty again. Always return the complete text
3656 ** of the string (which is overwritten with each call).
3658 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3659 ** \000 terminator is stored. zText can contain up to two instances of
3660 ** %d. The values of p1 and p2 are written into the first and second
3663 ** If n==-1, then the previous character is overwritten.
3665 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3666 static char empty[1] = { 0 };
3668 static int alloced = 0;
3669 static int used = 0;
3673 if( used==0 && z!=0 ) z[0] = 0;
3682 n = lemonStrlen(zText);
3684 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3685 alloced = n + sizeof(zInt)*2 + used + 200;
3686 z = (char *) realloc(z, alloced);
3688 if( z==0 ) return empty;
3691 if( c=='%' && n>0 && zText[0]=='d' ){
3692 lemon_sprintf(zInt, "%d", p1);
3694 lemon_strcpy(&z[used], zInt);
3695 used += lemonStrlen(&z[used]);
3699 z[used++] = (char)c;
3707 ** Write and transform the rp->code string so that symbols are expanded.
3708 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3710 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3713 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
3716 int rc = 0; /* True if yylhsminor is used */
3717 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
3718 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3719 char lhsused = 0; /* True if the LHS element has been used */
3720 char lhsdirect; /* True if LHS writes directly into stack */
3721 char used[MAXRHS]; /* True for each RHS element which is used */
3722 char zLhs[50]; /* Convert the LHS symbol into this string */
3723 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
3725 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3729 static char newlinestr[2] = { '\n', '\0' };
3730 rp->code = newlinestr;
3731 rp->line = rp->ruleline;
3739 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3741 }else if( rp->rhsalias[0]==0 ){
3742 /* The left-most RHS symbol has no value. LHS direct is ok. But
3743 ** we have to call the distructor on the RHS symbol first. */
3745 if( has_destructor(rp->rhs[0],lemp) ){
3746 append_str(0,0,0,0);
3747 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3748 rp->rhs[0]->index,1-rp->nrhs);
3749 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3752 }else if( rp->lhsalias==0 ){
3753 /* There is no LHS value symbol. */
3755 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3756 /* The LHS symbol and the left-most RHS symbol are the same, so
3757 ** direct writing is allowed */
3761 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3762 ErrorMsg(lemp->filename,rp->ruleline,
3763 "%s(%s) and %s(%s) share the same label but have "
3764 "different datatypes.",
3765 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3769 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3770 rp->lhsalias, rp->rhsalias[0]);
3771 zSkip = strstr(rp->code, zOvwrt);
3773 /* The code contains a special comment that indicates that it is safe
3774 ** for the LHS label to overwrite left-most RHS label. */
3781 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3784 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3787 append_str(0,0,0,0);
3789 /* This const cast is wrong but harmless, if we're careful. */
3790 for(cp=(char *)rp->code; *cp; cp++){
3792 append_str(zOvwrt,0,0,0);
3793 cp += lemonStrlen(zOvwrt)-1;
3797 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
3799 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
3802 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3803 append_str(zLhs,0,0,0);
3807 for(i=0; i<rp->nrhs; i++){
3808 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3809 if( i==0 && dontUseRhs0 ){
3810 ErrorMsg(lemp->filename,rp->ruleline,
3811 "Label %s used after '%s'.",
3812 rp->rhsalias[0], zOvwrt);
3814 }else if( cp!=rp->code && cp[-1]=='@' ){
3815 /* If the argument is of the form @X then substituted
3816 ** the token number of X, not the value of X */
3817 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3819 struct symbol *sp = rp->rhs[i];
3821 if( sp->type==MULTITERMINAL ){
3822 dtnum = sp->subsym[0]->dtnum;
3826 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3836 append_str(cp, 1, 0, 0);
3839 /* Main code generation completed */
3840 cp = append_str(0,0,0,0);
3841 if( cp && cp[0] ) rp->code = Strsafe(cp);
3842 append_str(0,0,0,0);
3844 /* Check to make sure the LHS has been used */
3845 if( rp->lhsalias && !lhsused ){
3846 ErrorMsg(lemp->filename,rp->ruleline,
3847 "Label \"%s\" for \"%s(%s)\" is never used.",
3848 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3852 /* Generate destructor code for RHS minor values which are not referenced.
3853 ** Generate error messages for unused labels and duplicate labels.
3855 for(i=0; i<rp->nrhs; i++){
3856 if( rp->rhsalias[i] ){
3859 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3860 ErrorMsg(lemp->filename,rp->ruleline,
3861 "%s(%s) has the same label as the LHS but is not the left-most "
3862 "symbol on the RHS.",
3863 rp->rhs[i]->name, rp->rhsalias);
3867 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3868 ErrorMsg(lemp->filename,rp->ruleline,
3869 "Label %s used for multiple symbols on the RHS of a rule.",
3877 ErrorMsg(lemp->filename,rp->ruleline,
3878 "Label %s for \"%s(%s)\" is never used.",
3879 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3882 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3883 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3884 rp->rhs[i]->index,i-rp->nrhs+1);
3888 /* If unable to write LHS values directly into the stack, write the
3889 ** saved LHS value now. */
3891 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3892 append_str(zLhs, 0, 0, 0);
3893 append_str(";\n", 0, 0, 0);
3896 /* Suffix code generation complete */
3897 cp = append_str(0,0,0,0);
3899 rp->codeSuffix = Strsafe(cp);
3907 ** Generate code which executes when the rule "rp" is reduced. Write
3908 ** the code to "out". Make sure lineno stays up-to-date.
3910 PRIVATE void emit_code(
3918 /* Setup code prior to the #line directive */
3919 if( rp->codePrefix && rp->codePrefix[0] ){
3920 fprintf(out, "{%s", rp->codePrefix);
3921 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3924 /* Generate code to do the reduce action */
3926 if( !lemp->nolinenosflag ){
3928 tplt_linedir(out,rp->line,lemp->filename);
3930 fprintf(out,"{%s",rp->code);
3931 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3932 fprintf(out,"}\n"); (*lineno)++;
3933 if( !lemp->nolinenosflag ){
3935 tplt_linedir(out,*lineno,lemp->outname);
3939 /* Generate breakdown code that occurs after the #line directive */
3940 if( rp->codeSuffix && rp->codeSuffix[0] ){
3941 fprintf(out, "%s", rp->codeSuffix);
3942 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3945 if( rp->codePrefix ){
3946 fprintf(out, "}\n"); (*lineno)++;
3953 ** Print the definition of the union used for the parser's data stack.
3954 ** This union contains fields for every possible data type for tokens
3955 ** and nonterminals. In the process of computing and printing this
3956 ** union, also set the ".dtnum" field of every terminal and nonterminal
3959 void print_stack_union(
3960 FILE *out, /* The output stream */
3961 struct lemon *lemp, /* The main info structure for this parser */
3962 int *plineno, /* Pointer to the line number */
3963 int mhflag /* True if generating makeheaders output */
3965 int lineno; /* The line number of the output */
3966 char **types; /* A hash table of datatypes */
3967 int arraysize; /* Size of the "types" array */
3968 int maxdtlength; /* Maximum length of any ".datatype" field. */
3969 char *stddt; /* Standardized name for a datatype */
3970 int i,j; /* Loop counters */
3971 unsigned hash; /* For hashing the name of a type */
3972 const char *name; /* Name of the parser */
3974 /* Allocate and initialize types[] and allocate stddt[] */
3975 arraysize = lemp->nsymbol * 2;
3976 types = (char**)calloc( arraysize, sizeof(char*) );
3978 fprintf(stderr,"Out of memory.\n");
3981 for(i=0; i<arraysize; i++) types[i] = 0;
3983 if( lemp->vartype ){
3984 maxdtlength = lemonStrlen(lemp->vartype);
3986 for(i=0; i<lemp->nsymbol; i++){
3988 struct symbol *sp = lemp->symbols[i];
3989 if( sp->datatype==0 ) continue;
3990 len = lemonStrlen(sp->datatype);
3991 if( len>maxdtlength ) maxdtlength = len;
3993 stddt = (char*)malloc( maxdtlength*2 + 1 );
3995 fprintf(stderr,"Out of memory.\n");
3999 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4000 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4001 ** used for terminal symbols. If there is no %default_type defined then
4002 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4003 ** a datatype using the %type directive.
4005 for(i=0; i<lemp->nsymbol; i++){
4006 struct symbol *sp = lemp->symbols[i];
4008 if( sp==lemp->errsym ){
4009 sp->dtnum = arraysize+1;
4012 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
4017 if( cp==0 ) cp = lemp->vartype;
4019 while( ISSPACE(*cp) ) cp++;
4020 while( *cp ) stddt[j++] = *cp++;
4021 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
4023 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
4028 for(j=0; stddt[j]; j++){
4029 hash = hash*53 + stddt[j];
4031 hash = (hash & 0x7fffffff)%arraysize;
4032 while( types[hash] ){
4033 if( strcmp(types[hash],stddt)==0 ){
4034 sp->dtnum = hash + 1;
4038 if( hash>=(unsigned)arraysize ) hash = 0;
4040 if( types[hash]==0 ){
4041 sp->dtnum = hash + 1;
4042 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
4043 if( types[hash]==0 ){
4044 fprintf(stderr,"Out of memory.\n");
4047 lemon_strcpy(types[hash],stddt);
4051 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4052 name = lemp->name ? lemp->name : "Parse";
4054 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4055 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4056 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4057 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4058 fprintf(out,"typedef union {\n"); lineno++;
4059 fprintf(out," int yyinit;\n"); lineno++;
4060 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4061 for(i=0; i<arraysize; i++){
4062 if( types[i]==0 ) continue;
4063 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4066 if( lemp->errsym && lemp->errsym->useCnt ){
4067 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4071 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4076 ** Return the name of a C datatype able to represent values between
4077 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4078 ** for that type (1, 2, or 4) into *pnByte.
4080 static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4081 const char *zType = "int";
4085 zType = "unsigned char";
4087 }else if( upr<65535 ){
4088 zType = "unsigned short int";
4091 zType = "unsigned int";
4094 }else if( lwr>=-127 && upr<=127 ){
4095 zType = "signed char";
4097 }else if( lwr>=-32767 && upr<32767 ){
4101 if( pnByte ) *pnByte = nByte;
4106 ** Each state contains a set of token transaction and a set of
4107 ** nonterminal transactions. Each of these sets makes an instance
4108 ** of the following structure. An array of these structures is used
4109 ** to order the creation of entries in the yy_action[] table.
4112 struct state *stp; /* A pointer to a state */
4113 int isTkn; /* True to use tokens. False for non-terminals */
4114 int nAction; /* Number of actions */
4115 int iOrder; /* Original order of action sets */
4119 ** Compare to axset structures for sorting purposes
4121 static int axset_compare(const void *a, const void *b){
4122 struct axset *p1 = (struct axset*)a;
4123 struct axset *p2 = (struct axset*)b;
4125 c = p2->nAction - p1->nAction;
4127 c = p1->iOrder - p2->iOrder;
4129 assert( c!=0 || p1==p2 );
4134 ** Write text on "out" that describes the rule "rp".
4136 static void writeRuleText(FILE *out, struct rule *rp){
4138 fprintf(out,"%s ::=", rp->lhs->name);
4139 for(j=0; j<rp->nrhs; j++){
4140 struct symbol *sp = rp->rhs[j];
4141 if( sp->type!=MULTITERMINAL ){
4142 fprintf(out," %s", sp->name);
4145 fprintf(out," %s", sp->subsym[0]->name);
4146 for(k=1; k<sp->nsubsym; k++){
4147 fprintf(out,"|%s",sp->subsym[k]->name);
4154 /* Generate C source code for the parser */
4157 int mhflag /* Output in makeheaders format if true */
4160 char line[LINESIZE];
4165 struct acttab *pActtab;
4167 int szActionType; /* sizeof(YYACTIONTYPE) */
4168 int szCodeType; /* sizeof(YYCODETYPE) */
4170 int mnTknOfst, mxTknOfst;
4171 int mnNtOfst, mxNtOfst;
4174 lemp->minShiftReduce = lemp->nstate;
4175 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4176 lemp->accAction = lemp->errAction + 1;
4177 lemp->noAction = lemp->accAction + 1;
4178 lemp->minReduce = lemp->noAction + 1;
4179 lemp->maxAction = lemp->minReduce + lemp->nrule;
4181 in = tplt_open(lemp);
4183 out = file_open(lemp,".c","wb");
4189 tplt_xfer(lemp->name,in,out,&lineno);
4191 /* Generate the include code, if any */
4192 tplt_print(out,lemp,lemp->include,&lineno);
4194 char *incName = file_makename(lemp, ".h");
4195 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4198 tplt_xfer(lemp->name,in,out,&lineno);
4200 /* Generate #defines for all tokens */
4203 fprintf(out,"#if INTERFACE\n"); lineno++;
4204 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4206 for(i=1; i<lemp->nterminal; i++){
4207 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4210 fprintf(out,"#endif\n"); lineno++;
4212 tplt_xfer(lemp->name,in,out,&lineno);
4214 /* Generate the defines */
4215 fprintf(out,"#define YYCODETYPE %s\n",
4216 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4217 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
4218 fprintf(out,"#define YYACTIONTYPE %s\n",
4219 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
4220 if( lemp->wildcard ){
4221 fprintf(out,"#define YYWILDCARD %d\n",
4222 lemp->wildcard->index); lineno++;
4224 print_stack_union(out,lemp,&lineno,mhflag);
4225 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
4226 if( lemp->stacksize ){
4227 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4229 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4231 fprintf(out, "#endif\n"); lineno++;
4233 fprintf(out,"#if INTERFACE\n"); lineno++;
4235 name = lemp->name ? lemp->name : "Parse";
4236 if( lemp->arg && lemp->arg[0] ){
4237 i = lemonStrlen(lemp->arg);
4238 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4239 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
4240 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4241 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4242 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4243 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
4244 name,lemp->arg,&lemp->arg[i]); lineno++;
4245 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
4246 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
4248 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4249 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4250 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
4251 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4252 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
4254 if( lemp->ctx && lemp->ctx[0] ){
4255 i = lemonStrlen(lemp->ctx);
4256 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4257 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4258 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4259 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4260 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4261 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4262 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4263 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4264 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4266 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4267 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4268 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4269 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4270 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4273 fprintf(out,"#endif\n"); lineno++;
4275 if( lemp->errsym && lemp->errsym->useCnt ){
4276 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4277 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
4279 if( lemp->has_fallback ){
4280 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4283 /* Compute the action table, but do not output it yet. The action
4284 ** table must be computed before generating the YYNSTATE macro because
4285 ** we need to know how many states can be eliminated.
4287 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
4289 fprintf(stderr,"malloc failed\n");
4292 for(i=0; i<lemp->nxstate; i++){
4293 stp = lemp->sorted[i];
4296 ax[i*2].nAction = stp->nTknAct;
4297 ax[i*2+1].stp = stp;
4298 ax[i*2+1].isTkn = 0;
4299 ax[i*2+1].nAction = stp->nNtAct;
4301 mxTknOfst = mnTknOfst = 0;
4302 mxNtOfst = mnNtOfst = 0;
4303 /* In an effort to minimize the action table size, use the heuristic
4304 ** of placing the largest action sets first */
4305 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4306 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
4307 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
4308 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
4311 for(ap=stp->ap; ap; ap=ap->next){
4313 if( ap->sp->index>=lemp->nterminal ) continue;
4314 action = compute_action(lemp, ap);
4315 if( action<0 ) continue;
4316 acttab_action(pActtab, ap->sp->index, action);
4318 stp->iTknOfst = acttab_insert(pActtab, 1);
4319 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4320 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4322 for(ap=stp->ap; ap; ap=ap->next){
4324 if( ap->sp->index<lemp->nterminal ) continue;
4325 if( ap->sp->index==lemp->nsymbol ) continue;
4326 action = compute_action(lemp, ap);
4327 if( action<0 ) continue;
4328 acttab_action(pActtab, ap->sp->index, action);
4330 stp->iNtOfst = acttab_insert(pActtab, 0);
4331 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4332 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
4334 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4336 for(jj=nn=0; jj<pActtab->nAction; jj++){
4337 if( pActtab->aAction[jj].action<0 ) nn++;
4339 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4340 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4341 ax[i].nAction, pActtab->nAction, nn);
4347 /* Mark rules that are actually used for reduce actions after all
4348 ** optimizations have been applied
4350 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4351 for(i=0; i<lemp->nxstate; i++){
4352 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4353 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
4354 ap->x.rp->doesReduce = 1;
4359 /* Finish rendering the constants now that the action table has
4361 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4362 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
4363 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
4364 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
4365 i = lemp->minShiftReduce;
4366 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4368 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4369 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4370 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4371 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4372 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4373 i = lemp->minReduce + lemp->nrule;
4374 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4375 tplt_xfer(lemp->name,in,out,&lineno);
4377 /* Now output the action table and its associates:
4379 ** yy_action[] A single table containing all actions.
4380 ** yy_lookahead[] A table containing the lookahead for each entry in
4381 ** yy_action. Used to detect hash collisions.
4382 ** yy_shift_ofst[] For each state, the offset into yy_action for
4383 ** shifting terminals.
4384 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4385 ** shifting non-terminals after a reduce.
4386 ** yy_default[] Default action for each state.
4389 /* Output the yy_action table */
4390 lemp->nactiontab = n = acttab_action_size(pActtab);
4391 lemp->tablesize += n*szActionType;
4392 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4393 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
4394 for(i=j=0; i<n; i++){
4395 int action = acttab_yyaction(pActtab, i);
4396 if( action<0 ) action = lemp->noAction;
4397 if( j==0 ) fprintf(out," /* %5d */ ", i);
4398 fprintf(out, " %4d,", action);
4399 if( j==9 || i==n-1 ){
4400 fprintf(out, "\n"); lineno++;
4406 fprintf(out, "};\n"); lineno++;
4408 /* Output the yy_lookahead table */
4409 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
4410 lemp->tablesize += n*szCodeType;
4411 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
4412 for(i=j=0; i<n; i++){
4413 int la = acttab_yylookahead(pActtab, i);
4414 if( la<0 ) la = lemp->nsymbol;
4415 if( j==0 ) fprintf(out," /* %5d */ ", i);
4416 fprintf(out, " %4d,", la);
4417 if( j==9 || i==n-1 ){
4418 fprintf(out, "\n"); lineno++;
4424 fprintf(out, "};\n"); lineno++;
4425 acttab_free(pActtab);
4427 /* Output the yy_shift_ofst[] table */
4429 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
4430 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4431 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4432 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
4433 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
4434 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4436 lemp->tablesize += n*sz;
4437 for(i=j=0; i<n; i++){
4439 stp = lemp->sorted[i];
4440 ofst = stp->iTknOfst;
4441 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
4442 if( j==0 ) fprintf(out," /* %5d */ ", i);
4443 fprintf(out, " %4d,", ofst);
4444 if( j==9 || i==n-1 ){
4445 fprintf(out, "\n"); lineno++;
4451 fprintf(out, "};\n"); lineno++;
4453 /* Output the yy_reduce_ofst[] table */
4455 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
4456 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4457 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4458 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
4459 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
4460 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4461 lemp->tablesize += n*sz;
4462 for(i=j=0; i<n; i++){
4464 stp = lemp->sorted[i];
4465 ofst = stp->iNtOfst;
4466 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
4467 if( j==0 ) fprintf(out," /* %5d */ ", i);
4468 fprintf(out, " %4d,", ofst);
4469 if( j==9 || i==n-1 ){
4470 fprintf(out, "\n"); lineno++;
4476 fprintf(out, "};\n"); lineno++;
4478 /* Output the default action table */
4479 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
4481 lemp->tablesize += n*szActionType;
4482 for(i=j=0; i<n; i++){
4483 stp = lemp->sorted[i];
4484 if( j==0 ) fprintf(out," /* %5d */ ", i);
4485 if( stp->iDfltReduce<0 ){
4486 fprintf(out, " %4d,", lemp->errAction);
4488 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4490 if( j==9 || i==n-1 ){
4491 fprintf(out, "\n"); lineno++;
4497 fprintf(out, "};\n"); lineno++;
4498 tplt_xfer(lemp->name,in,out,&lineno);
4500 /* Generate the table of fallback tokens.
4502 if( lemp->has_fallback ){
4503 int mx = lemp->nterminal - 1;
4504 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
4505 lemp->tablesize += (mx+1)*szCodeType;
4506 for(i=0; i<=mx; i++){
4507 struct symbol *p = lemp->symbols[i];
4508 if( p->fallback==0 ){
4509 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4511 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4512 p->name, p->fallback->name);
4517 tplt_xfer(lemp->name, in, out, &lineno);
4519 /* Generate a table containing the symbolic name of every symbol
4521 for(i=0; i<lemp->nsymbol; i++){
4522 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
4523 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
4525 tplt_xfer(lemp->name,in,out,&lineno);
4527 /* Generate a table containing a text string that describes every
4528 ** rule in the rule set of the grammar. This information is used
4529 ** when tracing REDUCE actions.
4531 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4532 assert( rp->iRule==i );
4533 fprintf(out," /* %3d */ \"", i);
4534 writeRuleText(out, rp);
4535 fprintf(out,"\",\n"); lineno++;
4537 tplt_xfer(lemp->name,in,out,&lineno);
4539 /* Generate code which executes every time a symbol is popped from
4540 ** the stack while processing errors or while destroying the parser.
4541 ** (In other words, generate the %destructor actions)
4543 if( lemp->tokendest ){
4545 for(i=0; i<lemp->nsymbol; i++){
4546 struct symbol *sp = lemp->symbols[i];
4547 if( sp==0 || sp->type!=TERMINAL ) continue;
4549 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4552 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4554 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4555 if( i<lemp->nsymbol ){
4556 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4557 fprintf(out," break;\n"); lineno++;
4560 if( lemp->vardest ){
4561 struct symbol *dflt_sp = 0;
4563 for(i=0; i<lemp->nsymbol; i++){
4564 struct symbol *sp = lemp->symbols[i];
4565 if( sp==0 || sp->type==TERMINAL ||
4566 sp->index<=0 || sp->destructor!=0 ) continue;
4568 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
4571 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4575 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4577 fprintf(out," break;\n"); lineno++;
4579 for(i=0; i<lemp->nsymbol; i++){
4580 struct symbol *sp = lemp->symbols[i];
4581 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4582 if( sp->destLineno<0 ) continue; /* Already emitted */
4583 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4585 /* Combine duplicate destructors into a single case */
4586 for(j=i+1; j<lemp->nsymbol; j++){
4587 struct symbol *sp2 = lemp->symbols[j];
4588 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4589 && sp2->dtnum==sp->dtnum
4590 && strcmp(sp->destructor,sp2->destructor)==0 ){
4591 fprintf(out," case %d: /* %s */\n",
4592 sp2->index, sp2->name); lineno++;
4593 sp2->destLineno = -1; /* Avoid emitting this destructor again */
4597 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4598 fprintf(out," break;\n"); lineno++;
4600 tplt_xfer(lemp->name,in,out,&lineno);
4602 /* Generate code which executes whenever the parser stack overflows */
4603 tplt_print(out,lemp,lemp->overflow,&lineno);
4604 tplt_xfer(lemp->name,in,out,&lineno);
4606 /* Generate the table of rule information
4608 ** Note: This code depends on the fact that rules are number
4609 ** sequentually beginning with 0.
4611 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4612 fprintf(out," { %4d, %4d }, /* (%d) ",rp->lhs->index,-rp->nrhs,i);
4613 rule_print(out, rp);
4614 fprintf(out," */\n"); lineno++;
4616 tplt_xfer(lemp->name,in,out,&lineno);
4618 /* Generate code which execution during each REDUCE action */
4620 for(rp=lemp->rule; rp; rp=rp->next){
4621 i += translate_code(lemp, rp);
4624 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
4626 /* First output rules other than the default: rule */
4627 for(rp=lemp->rule; rp; rp=rp->next){
4628 struct rule *rp2; /* Other rules with the same action */
4629 if( rp->codeEmitted ) continue;
4631 /* No C code actions, so this will be part of the "default:" rule */
4634 fprintf(out," case %d: /* ", rp->iRule);
4635 writeRuleText(out, rp);
4636 fprintf(out, " */\n"); lineno++;
4637 for(rp2=rp->next; rp2; rp2=rp2->next){
4638 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4639 && rp2->codeSuffix==rp->codeSuffix ){
4640 fprintf(out," case %d: /* ", rp2->iRule);
4641 writeRuleText(out, rp2);
4642 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
4643 rp2->codeEmitted = 1;
4646 emit_code(out,rp,lemp,&lineno);
4647 fprintf(out," break;\n"); lineno++;
4648 rp->codeEmitted = 1;
4650 /* Finally, output the default: rule. We choose as the default: all
4651 ** empty actions. */
4652 fprintf(out," default:\n"); lineno++;
4653 for(rp=lemp->rule; rp; rp=rp->next){
4654 if( rp->codeEmitted ) continue;
4655 assert( rp->noCode );
4656 fprintf(out," /* (%d) ", rp->iRule);
4657 writeRuleText(out, rp);
4658 if( rp->doesReduce ){
4659 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4661 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4662 rp->iRule); lineno++;
4665 fprintf(out," break;\n"); lineno++;
4666 tplt_xfer(lemp->name,in,out,&lineno);
4668 /* Generate code which executes if a parse fails */
4669 tplt_print(out,lemp,lemp->failure,&lineno);
4670 tplt_xfer(lemp->name,in,out,&lineno);
4672 /* Generate code which executes when a syntax error occurs */
4673 tplt_print(out,lemp,lemp->error,&lineno);
4674 tplt_xfer(lemp->name,in,out,&lineno);
4676 /* Generate code which executes when the parser accepts its input */
4677 tplt_print(out,lemp,lemp->accept,&lineno);
4678 tplt_xfer(lemp->name,in,out,&lineno);
4680 /* Append any addition code the user desires */
4681 tplt_print(out,lemp,lemp->extracode,&lineno);
4688 /* Generate a header file for the parser */
4689 void ReportHeader(struct lemon *lemp)
4693 char line[LINESIZE];
4694 char pattern[LINESIZE];
4697 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4699 in = file_open(lemp,".h","rb");
4702 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4703 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4704 prefix,lemp->symbols[i]->name,i);
4705 if( strcmp(line,pattern) ) break;
4707 nextChar = fgetc(in);
4709 if( i==lemp->nterminal && nextChar==EOF ){
4710 /* No change in the file. Don't rewrite it. */
4714 out = file_open(lemp,".h","wb");
4716 for(i=1; i<lemp->nterminal; i++){
4717 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
4724 /* Reduce the size of the action tables, if possible, by making use
4727 ** In this version, we take the most frequent REDUCE action and make
4728 ** it the default. Except, there is no default if the wildcard token
4729 ** is a possible look-ahead.
4731 void CompressTables(struct lemon *lemp)
4734 struct action *ap, *ap2, *nextap;
4735 struct rule *rp, *rp2, *rbest;
4740 for(i=0; i<lemp->nstate; i++){
4741 stp = lemp->sorted[i];
4746 for(ap=stp->ap; ap; ap=ap->next){
4747 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4750 if( ap->type!=REDUCE ) continue;
4752 if( rp->lhsStart ) continue;
4753 if( rp==rbest ) continue;
4755 for(ap2=ap->next; ap2; ap2=ap2->next){
4756 if( ap2->type!=REDUCE ) continue;
4758 if( rp2==rbest ) continue;
4767 /* Do not make a default if the number of rules to default
4768 ** is not at least 1 or if the wildcard token is a possible
4771 if( nbest<1 || usesWildcard ) continue;
4774 /* Combine matching REDUCE actions into a single default */
4775 for(ap=stp->ap; ap; ap=ap->next){
4776 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4779 ap->sp = Symbol_new("{default}");
4780 for(ap=ap->next; ap; ap=ap->next){
4781 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
4783 stp->ap = Action_sort(stp->ap);
4785 for(ap=stp->ap; ap; ap=ap->next){
4786 if( ap->type==SHIFT ) break;
4787 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4790 stp->autoReduce = 1;
4791 stp->pDfltReduce = rbest;
4795 /* Make a second pass over all states and actions. Convert
4796 ** every action that is a SHIFT to an autoReduce state into
4797 ** a SHIFTREDUCE action.
4799 for(i=0; i<lemp->nstate; i++){
4800 stp = lemp->sorted[i];
4801 for(ap=stp->ap; ap; ap=ap->next){
4802 struct state *pNextState;
4803 if( ap->type!=SHIFT ) continue;
4804 pNextState = ap->x.stp;
4805 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4806 ap->type = SHIFTREDUCE;
4807 ap->x.rp = pNextState->pDfltReduce;
4812 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4813 ** (meaning that the SHIFTREDUCE will land back in the state where it
4814 ** started) and if there is no C-code associated with the reduce action,
4815 ** then we can go ahead and convert the action to be the same as the
4816 ** action for the RHS of the rule.
4818 for(i=0; i<lemp->nstate; i++){
4819 stp = lemp->sorted[i];
4820 for(ap=stp->ap; ap; ap=nextap){
4822 if( ap->type!=SHIFTREDUCE ) continue;
4824 if( rp->noCode==0 ) continue;
4825 if( rp->nrhs!=1 ) continue;
4827 /* Only apply this optimization to non-terminals. It would be OK to
4828 ** apply it to terminal symbols too, but that makes the parser tables
4830 if( ap->sp->index<lemp->nterminal ) continue;
4832 /* If we reach this point, it means the optimization can be applied */
4834 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4836 ap->spOpt = ap2->sp;
4837 ap->type = ap2->type;
4845 ** Compare two states for sorting purposes. The smaller state is the
4846 ** one with the most non-terminal actions. If they have the same number
4847 ** of non-terminal actions, then the smaller is the one with the most
4850 static int stateResortCompare(const void *a, const void *b){
4851 const struct state *pA = *(const struct state**)a;
4852 const struct state *pB = *(const struct state**)b;
4855 n = pB->nNtAct - pA->nNtAct;
4857 n = pB->nTknAct - pA->nTknAct;
4859 n = pB->statenum - pA->statenum;
4868 ** Renumber and resort states so that states with fewer choices
4869 ** occur at the end. Except, keep state 0 as the first state.
4871 void ResortStates(struct lemon *lemp)
4877 for(i=0; i<lemp->nstate; i++){
4878 stp = lemp->sorted[i];
4879 stp->nTknAct = stp->nNtAct = 0;
4880 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
4881 stp->iTknOfst = NO_OFFSET;
4882 stp->iNtOfst = NO_OFFSET;
4883 for(ap=stp->ap; ap; ap=ap->next){
4884 int iAction = compute_action(lemp,ap);
4886 if( ap->sp->index<lemp->nterminal ){
4888 }else if( ap->sp->index<lemp->nsymbol ){
4891 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4892 stp->iDfltReduce = iAction;
4897 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4898 stateResortCompare);
4899 for(i=0; i<lemp->nstate; i++){
4900 lemp->sorted[i]->statenum = i;
4902 lemp->nxstate = lemp->nstate;
4903 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4909 /***************** From the file "set.c" ************************************/
4911 ** Set manipulation routines for the LEMON parser generator.
4914 static int size = 0;
4916 /* Set the set size */
4922 /* Allocate a new set */
4925 s = (char*)calloc( size, 1);
4927 extern void memory_error();
4933 /* Deallocate a set */
4934 void SetFree(char *s)
4939 /* Add a new element to the set. Return TRUE if the element was added
4940 ** and FALSE if it was already there. */
4941 int SetAdd(char *s, int e)
4944 assert( e>=0 && e<size );
4950 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4951 int SetUnion(char *s1, char *s2)
4955 for(i=0; i<size; i++){
4956 if( s2[i]==0 ) continue;
4964 /********************** From the file "table.c" ****************************/
4966 ** All code in this file has been automatically generated
4967 ** from a specification in the file
4969 ** by the associative array code building program "aagen".
4970 ** Do not edit this file! Instead, edit the specification
4971 ** file, then rerun aagen.
4974 ** Code for processing tables in the LEMON parser generator.
4977 PRIVATE unsigned strhash(const char *x)
4980 while( *x ) h = h*13 + *(x++);
4984 /* Works like strdup, sort of. Save a string in malloced memory, but
4985 ** keep strings in a table so that the same string is not in more
4988 const char *Strsafe(const char *y)
4993 if( y==0 ) return 0;
4994 z = Strsafe_find(y);
4995 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4996 lemon_strcpy(cpy,y);
5004 /* There is one instance of the following structure for each
5005 ** associative array of type "x1".
5008 int size; /* The number of available slots. */
5009 /* Must be a power of 2 greater than or */
5011 int count; /* Number of currently slots filled */
5012 struct s_x1node *tbl; /* The data stored here */
5013 struct s_x1node **ht; /* Hash table for lookups */
5016 /* There is one instance of this structure for every data element
5017 ** in an associative array of type "x1".
5019 typedef struct s_x1node {
5020 const char *data; /* The data */
5021 struct s_x1node *next; /* Next entry with the same hash */
5022 struct s_x1node **from; /* Previous link */
5025 /* There is only one instance of the array, which is the following */
5026 static struct s_x1 *x1a;
5028 /* Allocate a new associative array */
5029 void Strsafe_init(void){
5031 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5035 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
5041 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5042 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5046 /* Insert a new record into the array. Return TRUE if successful.
5047 ** Prior data with the same key is NOT overwritten */
5048 int Strsafe_insert(const char *data)
5054 if( x1a==0 ) return 0;
5056 h = ph & (x1a->size-1);
5059 if( strcmp(np->data,data)==0 ){
5060 /* An existing entry with the same key is found. */
5061 /* Fail because overwrite is not allows. */
5066 if( x1a->count>=x1a->size ){
5067 /* Need to make the hash table bigger */
5070 array.size = arrSize = x1a->size*2;
5071 array.count = x1a->count;
5072 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
5073 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5074 array.ht = (x1node**)&(array.tbl[arrSize]);
5075 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5076 for(i=0; i<x1a->count; i++){
5077 x1node *oldnp, *newnp;
5078 oldnp = &(x1a->tbl[i]);
5079 h = strhash(oldnp->data) & (arrSize-1);
5080 newnp = &(array.tbl[i]);
5081 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5082 newnp->next = array.ht[h];
5083 newnp->data = oldnp->data;
5084 newnp->from = &(array.ht[h]);
5085 array.ht[h] = newnp;
5088 memcpy(x1a, &array, sizeof(array)); /* *x1a = array; */
5090 /* Insert the new data */
5091 h = ph & (x1a->size-1);
5092 np = &(x1a->tbl[x1a->count++]);
5094 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5095 np->next = x1a->ht[h];
5097 np->from = &(x1a->ht[h]);
5101 /* Return a pointer to data assigned to the given key. Return NULL
5102 ** if no such key. */
5103 const char *Strsafe_find(const char *key)
5108 if( x1a==0 ) return 0;
5109 h = strhash(key) & (x1a->size-1);
5112 if( strcmp(np->data,key)==0 ) break;
5115 return np ? np->data : 0;
5118 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5119 ** Create a new symbol if this is the first time "x" has been seen.
5121 struct symbol *Symbol_new(const char *x)
5125 sp = Symbol_find(x);
5127 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
5129 sp->name = Strsafe(x);
5130 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
5136 sp->lambda = LEMON_FALSE;
5141 Symbol_insert(sp,sp->name);
5147 /* Compare two symbols for sorting purposes. Return negative,
5148 ** zero, or positive if a is less then, equal to, or greater
5151 ** Symbols that begin with upper case letters (terminals or tokens)
5152 ** must sort before symbols that begin with lower case letters
5153 ** (non-terminals). And MULTITERMINAL symbols (created using the
5154 ** %token_class directive) must sort at the very end. Other than
5155 ** that, the order does not matter.
5157 ** We find experimentally that leaving the symbols in their original
5158 ** order (the order they appeared in the grammar file) gives the
5159 ** smallest parser tables in SQLite.
5161 int Symbolcmpp(const void *_a, const void *_b)
5163 const struct symbol *a = *(const struct symbol **) _a;
5164 const struct symbol *b = *(const struct symbol **) _b;
5165 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5166 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5167 return i1==i2 ? a->index - b->index : i1 - i2;
5170 /* There is one instance of the following structure for each
5171 ** associative array of type "x2".
5174 int size; /* The number of available slots. */
5175 /* Must be a power of 2 greater than or */
5177 int count; /* Number of currently slots filled */
5178 struct s_x2node *tbl; /* The data stored here */
5179 struct s_x2node **ht; /* Hash table for lookups */
5182 /* There is one instance of this structure for every data element
5183 ** in an associative array of type "x2".
5185 typedef struct s_x2node {
5186 struct symbol *data; /* The data */
5187 const char *key; /* The key */
5188 struct s_x2node *next; /* Next entry with the same hash */
5189 struct s_x2node **from; /* Previous link */
5192 /* There is only one instance of the array, which is the following */
5193 static struct s_x2 *x2a;
5195 /* Allocate a new associative array */
5196 void Symbol_init(void){
5198 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5202 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
5208 x2a->ht = (x2node**)&(x2a->tbl[128]);
5209 for(i=0; i<128; i++) x2a->ht[i] = 0;
5213 /* Insert a new record into the array. Return TRUE if successful.
5214 ** Prior data with the same key is NOT overwritten */
5215 int Symbol_insert(struct symbol *data, const char *key)
5221 if( x2a==0 ) return 0;
5223 h = ph & (x2a->size-1);
5226 if( strcmp(np->key,key)==0 ){
5227 /* An existing entry with the same key is found. */
5228 /* Fail because overwrite is not allows. */
5233 if( x2a->count>=x2a->size ){
5234 /* Need to make the hash table bigger */
5237 array.size = arrSize = x2a->size*2;
5238 array.count = x2a->count;
5239 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
5240 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5241 array.ht = (x2node**)&(array.tbl[arrSize]);
5242 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5243 for(i=0; i<x2a->count; i++){
5244 x2node *oldnp, *newnp;
5245 oldnp = &(x2a->tbl[i]);
5246 h = strhash(oldnp->key) & (arrSize-1);
5247 newnp = &(array.tbl[i]);
5248 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5249 newnp->next = array.ht[h];
5250 newnp->key = oldnp->key;
5251 newnp->data = oldnp->data;
5252 newnp->from = &(array.ht[h]);
5253 array.ht[h] = newnp;
5256 memcpy(x2a, &array, sizeof(array)); /* *x2a = array; */
5258 /* Insert the new data */
5259 h = ph & (x2a->size-1);
5260 np = &(x2a->tbl[x2a->count++]);
5263 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5264 np->next = x2a->ht[h];
5266 np->from = &(x2a->ht[h]);
5270 /* Return a pointer to data assigned to the given key. Return NULL
5271 ** if no such key. */
5272 struct symbol *Symbol_find(const char *key)
5277 if( x2a==0 ) return 0;
5278 h = strhash(key) & (x2a->size-1);
5281 if( strcmp(np->key,key)==0 ) break;
5284 return np ? np->data : 0;
5287 /* Return the n-th data. Return NULL if n is out of range. */
5288 struct symbol *Symbol_Nth(int n)
5290 struct symbol *data;
5291 if( x2a && n>0 && n<=x2a->count ){
5292 data = x2a->tbl[n-1].data;
5299 /* Return the size of the array */
5302 return x2a ? x2a->count : 0;
5305 /* Return an array of pointers to all data in the table.
5306 ** The array is obtained from malloc. Return NULL if memory allocation
5307 ** problems, or if the array is empty. */
5308 struct symbol **Symbol_arrayof()
5310 struct symbol **array;
5312 if( x2a==0 ) return 0;
5313 arrSize = x2a->count;
5314 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
5316 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
5321 /* Compare two configurations */
5322 int Configcmp(const char *_a,const char *_b)
5324 const struct config *a = (struct config *) _a;
5325 const struct config *b = (struct config *) _b;
5327 x = a->rp->index - b->rp->index;
5328 if( x==0 ) x = a->dot - b->dot;
5332 /* Compare two states */
5333 PRIVATE int statecmp(struct config *a, struct config *b)
5336 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5337 rc = a->rp->index - b->rp->index;
5338 if( rc==0 ) rc = a->dot - b->dot;
5348 PRIVATE unsigned statehash(struct config *a)
5352 h = h*571 + a->rp->index*37 + a->dot;
5358 /* Allocate a new state structure */
5359 struct state *State_new()
5361 struct state *newstate;
5362 newstate = (struct state *)calloc(1, sizeof(struct state) );
5363 MemoryCheck(newstate);
5367 /* There is one instance of the following structure for each
5368 ** associative array of type "x3".
5371 int size; /* The number of available slots. */
5372 /* Must be a power of 2 greater than or */
5374 int count; /* Number of currently slots filled */
5375 struct s_x3node *tbl; /* The data stored here */
5376 struct s_x3node **ht; /* Hash table for lookups */
5379 /* There is one instance of this structure for every data element
5380 ** in an associative array of type "x3".
5382 typedef struct s_x3node {
5383 struct state *data; /* The data */
5384 struct config *key; /* The key */
5385 struct s_x3node *next; /* Next entry with the same hash */
5386 struct s_x3node **from; /* Previous link */
5389 /* There is only one instance of the array, which is the following */
5390 static struct s_x3 *x3a;
5392 /* Allocate a new associative array */
5393 void State_init(void){
5395 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5399 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
5405 x3a->ht = (x3node**)&(x3a->tbl[128]);
5406 for(i=0; i<128; i++) x3a->ht[i] = 0;
5410 /* Insert a new record into the array. Return TRUE if successful.
5411 ** Prior data with the same key is NOT overwritten */
5412 int State_insert(struct state *data, struct config *key)
5418 if( x3a==0 ) return 0;
5419 ph = statehash(key);
5420 h = ph & (x3a->size-1);
5423 if( statecmp(np->key,key)==0 ){
5424 /* An existing entry with the same key is found. */
5425 /* Fail because overwrite is not allows. */
5430 if( x3a->count>=x3a->size ){
5431 /* Need to make the hash table bigger */
5434 array.size = arrSize = x3a->size*2;
5435 array.count = x3a->count;
5436 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
5437 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5438 array.ht = (x3node**)&(array.tbl[arrSize]);
5439 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5440 for(i=0; i<x3a->count; i++){
5441 x3node *oldnp, *newnp;
5442 oldnp = &(x3a->tbl[i]);
5443 h = statehash(oldnp->key) & (arrSize-1);
5444 newnp = &(array.tbl[i]);
5445 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5446 newnp->next = array.ht[h];
5447 newnp->key = oldnp->key;
5448 newnp->data = oldnp->data;
5449 newnp->from = &(array.ht[h]);
5450 array.ht[h] = newnp;
5453 memcpy(x3a, &array, sizeof(array)); /* *x3a = array; */
5455 /* Insert the new data */
5456 h = ph & (x3a->size-1);
5457 np = &(x3a->tbl[x3a->count++]);
5460 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5461 np->next = x3a->ht[h];
5463 np->from = &(x3a->ht[h]);
5467 /* Return a pointer to data assigned to the given key. Return NULL
5468 ** if no such key. */
5469 struct state *State_find(struct config *key)
5474 if( x3a==0 ) return 0;
5475 h = statehash(key) & (x3a->size-1);
5478 if( statecmp(np->key,key)==0 ) break;
5481 return np ? np->data : 0;
5484 /* Return an array of pointers to all data in the table.
5485 ** The array is obtained from malloc. Return NULL if memory allocation
5486 ** problems, or if the array is empty. */
5487 struct state **State_arrayof(void)
5489 struct state **array;
5491 if( x3a==0 ) return 0;
5492 arrSize = x3a->count;
5493 array = (struct state **)calloc(arrSize, sizeof(struct state *));
5495 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
5500 /* Hash a configuration */
5501 PRIVATE unsigned confighash(struct config *a)
5504 h = h*571 + a->rp->index*37 + a->dot;
5508 /* There is one instance of the following structure for each
5509 ** associative array of type "x4".
5512 int size; /* The number of available slots. */
5513 /* Must be a power of 2 greater than or */
5515 int count; /* Number of currently slots filled */
5516 struct s_x4node *tbl; /* The data stored here */
5517 struct s_x4node **ht; /* Hash table for lookups */
5520 /* There is one instance of this structure for every data element
5521 ** in an associative array of type "x4".
5523 typedef struct s_x4node {
5524 struct config *data; /* The data */
5525 struct s_x4node *next; /* Next entry with the same hash */
5526 struct s_x4node **from; /* Previous link */
5529 /* There is only one instance of the array, which is the following */
5530 static struct s_x4 *x4a;
5532 /* Allocate a new associative array */
5533 void Configtable_init(void){
5535 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5539 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
5545 x4a->ht = (x4node**)&(x4a->tbl[64]);
5546 for(i=0; i<64; i++) x4a->ht[i] = 0;
5550 /* Insert a new record into the array. Return TRUE if successful.
5551 ** Prior data with the same key is NOT overwritten */
5552 int Configtable_insert(struct config *data)
5558 if( x4a==0 ) return 0;
5559 ph = confighash(data);
5560 h = ph & (x4a->size-1);
5563 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
5564 /* An existing entry with the same key is found. */
5565 /* Fail because overwrite is not allows. */
5570 if( x4a->count>=x4a->size ){
5571 /* Need to make the hash table bigger */
5574 array.size = arrSize = x4a->size*2;
5575 array.count = x4a->count;
5576 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
5577 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5578 array.ht = (x4node**)&(array.tbl[arrSize]);
5579 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5580 for(i=0; i<x4a->count; i++){
5581 x4node *oldnp, *newnp;
5582 oldnp = &(x4a->tbl[i]);
5583 h = confighash(oldnp->data) & (arrSize-1);
5584 newnp = &(array.tbl[i]);
5585 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5586 newnp->next = array.ht[h];
5587 newnp->data = oldnp->data;
5588 newnp->from = &(array.ht[h]);
5589 array.ht[h] = newnp;
5592 memcpy(x4a, &array, sizeof(array)); /* *x4a = array; */
5594 /* Insert the new data */
5595 h = ph & (x4a->size-1);
5596 np = &(x4a->tbl[x4a->count++]);
5598 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5599 np->next = x4a->ht[h];
5601 np->from = &(x4a->ht[h]);
5605 /* Return a pointer to data assigned to the given key. Return NULL
5606 ** if no such key. */
5607 struct config *Configtable_find(struct config *key)
5612 if( x4a==0 ) return 0;
5613 h = confighash(key) & (x4a->size-1);
5616 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
5619 return np ? np->data : 0;
5622 /* Remove all data from the table. Pass each data to the function "f"
5623 ** as it is removed. ("f" may be null to avoid this step.) */
5624 void Configtable_clear(int(*f)(struct config *))
5627 if( x4a==0 || x4a->count==0 ) return;
5628 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5629 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;