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.
17 # if defined(_WIN32) || defined(WIN32)
26 extern int access(const char *path, int mode);
34 /* #define PRIVATE static */
38 #define MAXRHS 5 /* Set low to exercise exception code */
43 static int showPrecedenceConflict = 0;
44 static char *msort(char*,char**,int(*)(const char*,const char*));
47 ** Compilers are getting increasingly pedantic about type conversions
48 ** as C evolves ever closer to Ada.... To work around the latest problems
49 ** we have to define the following variant of strlen().
51 #define lemonStrlen(X) ((int)strlen(X))
54 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
55 ** saying they are unsafe. So we define our own versions of those routines too.
57 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
58 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
59 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
60 ** buffer, making sure the buffer is always zero-terminated.
62 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
63 ** a few simply conversions:
70 static void lemon_addtext(
71 char *zBuf, /* The buffer to which text is added */
72 int *pnUsed, /* Slots of the buffer used so far */
73 const char *zIn, /* Text to add */
74 int nIn, /* Bytes of text to add. -1 to use strlen() */
75 int iWidth /* Field width. Negative to left justify */
77 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
78 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
80 memcpy(&zBuf[*pnUsed], zIn, nIn);
82 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
85 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
91 for(i=j=0; (c = zFormat[i])!=0; i++){
94 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
96 if( isdigit(c) || (c=='-' && isdigit(zFormat[i+1])) ){
98 while( isdigit(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
99 if( c=='-' ) iWidth = -iWidth;
103 int v = va_arg(ap, int);
105 lemon_addtext(str, &nUsed, "-", 1, iWidth);
108 lemon_addtext(str, &nUsed, "0", 1, iWidth);
113 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
116 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
118 z = va_arg(ap, const char*);
119 lemon_addtext(str, &nUsed, z, -1, iWidth);
120 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
123 z = va_arg(ap, const char*);
124 lemon_addtext(str, &nUsed, z, k, iWidth);
126 lemon_addtext(str, &nUsed, "%", 1, 0);
128 fprintf(stderr, "illegal format\n");
134 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
137 static int lemon_sprintf(char *str, const char *format, ...){
140 va_start(ap, format);
141 rc = lemon_vsprintf(str, format, ap);
145 static void lemon_strcpy(char *dest, const char *src){
146 while( (*(dest++) = *(src++))!=0 ){}
148 static void lemon_strcat(char *dest, const char *src){
149 while( *dest ) dest++;
150 lemon_strcpy(dest, src);
154 /* a few forward declarations... */
159 static struct action *Action_new(void);
160 static struct action *Action_sort(struct action *);
162 /********** From the file "build.h" ************************************/
163 void FindRulePrecedences();
164 void FindFirstSets();
167 void FindFollowSets();
170 /********* From the file "configlist.h" *********************************/
171 void Configlist_init(void);
172 struct config *Configlist_add(struct rule *, int);
173 struct config *Configlist_addbasis(struct rule *, int);
174 void Configlist_closure(struct lemon *);
175 void Configlist_sort(void);
176 void Configlist_sortbasis(void);
177 struct config *Configlist_return(void);
178 struct config *Configlist_basis(void);
179 void Configlist_eat(struct config *);
180 void Configlist_reset(void);
182 /********* From the file "error.h" ***************************************/
183 void ErrorMsg(const char *, int,const char *, ...);
185 /****** From the file "option.h" ******************************************/
186 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
187 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
189 enum option_type type;
194 int OptInit(char**,struct s_options*,FILE*);
200 /******** From the file "parse.h" *****************************************/
201 void Parse(struct lemon *lemp);
203 /********* From the file "plink.h" ***************************************/
204 struct plink *Plink_new(void);
205 void Plink_add(struct plink **, struct config *);
206 void Plink_copy(struct plink **, struct plink *);
207 void Plink_delete(struct plink *);
209 /********** From the file "report.h" *************************************/
210 void Reprint(struct lemon *);
211 void ReportOutput(struct lemon *);
212 void ReportTable(struct lemon *, int);
213 void ReportHeader(struct lemon *);
214 void CompressTables(struct lemon *);
215 void ResortStates(struct lemon *);
217 /********** From the file "set.h" ****************************************/
218 void SetSize(int); /* All sets will be of size N */
219 char *SetNew(void); /* A new set for element 0..N */
220 void SetFree(char*); /* Deallocate a set */
221 int SetAdd(char*,int); /* Add element to a set */
222 int SetUnion(char *,char *); /* A <- A U B, thru element N */
223 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
225 /********** From the file "struct.h" *************************************/
227 ** Principal data structures for the LEMON parser generator.
230 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
232 /* Symbols (terminals and nonterminals) of the grammar are stored
233 ** in the following: */
246 const char *name; /* Name of the symbol */
247 int index; /* Index number for this symbol */
248 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
249 struct rule *rule; /* Linked list of rules of this (if an NT) */
250 struct symbol *fallback; /* fallback token in case this token doesn't parse */
251 int prec; /* Precedence if defined (-1 otherwise) */
252 enum e_assoc assoc; /* Associativity if precedence is defined */
253 char *firstset; /* First-set for all rules of this symbol */
254 Boolean lambda; /* True if NT and can generate an empty string */
255 int useCnt; /* Number of times used */
256 char *destructor; /* Code which executes whenever this symbol is
257 ** popped from the stack during error processing */
258 int destLineno; /* Line number for start of destructor */
259 char *datatype; /* The data type of information held by this
260 ** object. Only used if type==NONTERMINAL */
261 int dtnum; /* The data type number. In the parser, the value
262 ** stack is a union. The .yy%d element of this
263 ** union is the correct data type for this object */
264 /* The following fields are used by MULTITERMINALs only */
265 int nsubsym; /* Number of constituent symbols in the MULTI */
266 struct symbol **subsym; /* Array of constituent symbols */
269 /* Each production rule in the grammar is stored in the following
272 struct symbol *lhs; /* Left-hand side of the rule */
273 const char *lhsalias; /* Alias for the LHS (NULL if none) */
274 int lhsStart; /* True if left-hand side is the start symbol */
275 int ruleline; /* Line number for the rule */
276 int nrhs; /* Number of RHS symbols */
277 struct symbol **rhs; /* The RHS symbols */
278 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
279 int line; /* Line number at which code begins */
280 const char *code; /* The code executed when this rule is reduced */
281 struct symbol *precsym; /* Precedence symbol for this rule */
282 int index; /* An index number for this rule */
283 Boolean canReduce; /* True if this rule is ever reduced */
284 struct rule *nextlhs; /* Next rule with the same LHS */
285 struct rule *next; /* Next rule in the global list */
288 /* A configuration is a production rule of the grammar together with
289 ** a mark (dot) showing how much of that rule has been processed so far.
290 ** Configurations also contain a follow-set which is a list of terminal
291 ** symbols which are allowed to immediately follow the end of the rule.
292 ** Every configuration is recorded as an instance of the following: */
298 struct rule *rp; /* The rule upon which the configuration is based */
299 int dot; /* The parse point */
300 char *fws; /* Follow-set for this configuration only */
301 struct plink *fplp; /* Follow-set forward propagation links */
302 struct plink *bplp; /* Follow-set backwards propagation links */
303 struct state *stp; /* Pointer to state which contains this */
304 enum cfgstatus status; /* used during followset and shift computations */
305 struct config *next; /* Next configuration in the state */
306 struct config *bp; /* The next basis configuration */
314 SSCONFLICT, /* A shift/shift conflict */
315 SRCONFLICT, /* Was a reduce, but part of a conflict */
316 RRCONFLICT, /* Was a reduce, but part of a conflict */
317 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
318 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
319 NOT_USED /* Deleted by compression */
322 /* Every shift or reduce operation is stored as one of the following */
324 struct symbol *sp; /* The look-ahead symbol */
327 struct state *stp; /* The new state, if a shift */
328 struct rule *rp; /* The rule, if a reduce */
330 struct action *next; /* Next action for this state */
331 struct action *collide; /* Next action with the same hash */
334 /* Each state of the generated parser's finite state machine
335 ** is encoded as an instance of the following structure. */
337 struct config *bp; /* The basis configurations for this state */
338 struct config *cfp; /* All configurations in this set */
339 int statenum; /* Sequential number for this state */
340 struct action *ap; /* Array of actions for this state */
341 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
342 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
343 int iDflt; /* Default action */
345 #define NO_OFFSET (-2147483647)
347 /* A followset propagation link indicates that the contents of one
348 ** configuration followset should be propagated to another whenever
349 ** the first changes. */
351 struct config *cfp; /* The configuration to which linked */
352 struct plink *next; /* The next propagate link */
355 /* The state vector for the entire parser generator is recorded as
356 ** follows. (LEMON uses no global variables and makes little use of
357 ** static variables. Fields in the following structure can be thought
358 ** of as begin global variables in the program.) */
360 struct state **sorted; /* Table of states sorted by state number */
361 struct rule *rule; /* List of all rules */
362 int nstate; /* Number of states */
363 int nrule; /* Number of rules */
364 int nsymbol; /* Number of terminal and nonterminal symbols */
365 int nterminal; /* Number of terminal symbols */
366 struct symbol **symbols; /* Sorted array of pointers to symbols */
367 int errorcnt; /* Number of errors */
368 struct symbol *errsym; /* The error symbol */
369 struct symbol *wildcard; /* Token that matches anything */
370 char *name; /* Name of the generated parser */
371 char *arg; /* Declaration of the 3th argument to parser */
372 char *tokentype; /* Type of terminal symbols in the parser stack */
373 char *vartype; /* The default type of non-terminal symbols */
374 char *start; /* Name of the start symbol for the grammar */
375 char *stacksize; /* Size of the parser stack */
376 char *include; /* Code to put at the start of the C file */
377 char *error; /* Code to execute when an error is seen */
378 char *overflow; /* Code to execute on a stack overflow */
379 char *failure; /* Code to execute on parser failure */
380 char *accept; /* Code to execute when the parser excepts */
381 char *extracode; /* Code appended to the generated file */
382 char *tokendest; /* Code to execute to destroy token data */
383 char *vardest; /* Code for the default non-terminal destructor */
384 char *filename; /* Name of the input file */
385 char *outname; /* Name of the current output file */
386 char *tokenprefix; /* A prefix added to token names in the .h file */
387 int nconflict; /* Number of parsing conflicts */
388 int tablesize; /* Size of the parse tables */
389 int basisflag; /* Print only basis configurations */
390 int has_fallback; /* True if any %fallback is seen in the grammar */
391 int nolinenosflag; /* True if #line statements should not be printed */
392 char *argv0; /* Name of the program */
395 #define MemoryCheck(X) if((X)==0){ \
396 extern void memory_error(); \
400 /**************** From the file "table.h" *********************************/
402 ** All code in this file has been automatically generated
403 ** from a specification in the file
405 ** by the associative array code building program "aagen".
406 ** Do not edit this file! Instead, edit the specification
407 ** file, then rerun aagen.
410 ** Code for processing tables in the LEMON parser generator.
412 /* Routines for handling a strings */
414 const char *Strsafe(const char *);
416 void Strsafe_init(void);
417 int Strsafe_insert(const char *);
418 const char *Strsafe_find(const char *);
420 /* Routines for handling symbols of the grammar */
422 struct symbol *Symbol_new(const char *);
423 int Symbolcmpp(const void *, const void *);
424 void Symbol_init(void);
425 int Symbol_insert(struct symbol *, const char *);
426 struct symbol *Symbol_find(const char *);
427 struct symbol *Symbol_Nth(int);
428 int Symbol_count(void);
429 struct symbol **Symbol_arrayof(void);
431 /* Routines to manage the state table */
433 int Configcmp(const char *, const char *);
434 struct state *State_new(void);
435 void State_init(void);
436 int State_insert(struct state *, struct config *);
437 struct state *State_find(struct config *);
438 struct state **State_arrayof(/* */);
440 /* Routines used for efficiency in Configlist_add */
442 void Configtable_init(void);
443 int Configtable_insert(struct config *);
444 struct config *Configtable_find(struct config *);
445 void Configtable_clear(int(*)(struct config *));
447 /****************** From the file "action.c" *******************************/
449 ** Routines processing parser actions in the LEMON parser generator.
452 /* Allocate a new parser action */
453 static struct action *Action_new(void){
454 static struct action *freelist = 0;
455 struct action *newaction;
460 freelist = (struct action *)calloc(amt, sizeof(struct action));
462 fprintf(stderr,"Unable to allocate memory for a new parser action.");
465 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
466 freelist[amt-1].next = 0;
468 newaction = freelist;
469 freelist = freelist->next;
473 /* Compare two actions for sorting purposes. Return negative, zero, or
474 ** positive if the first action is less than, equal to, or greater than
477 static int actioncmp(
482 rc = ap1->sp->index - ap2->sp->index;
484 rc = (int)ap1->type - (int)ap2->type;
486 if( rc==0 && ap1->type==REDUCE ){
487 rc = ap1->x.rp->index - ap2->x.rp->index;
490 rc = (int) (ap2 - ap1);
495 /* Sort parser actions */
496 static struct action *Action_sort(
499 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
500 (int(*)(const char*,const char*))actioncmp);
510 struct action *newaction;
511 newaction = Action_new();
512 newaction->next = *app;
514 newaction->type = type;
517 newaction->x.stp = (struct state *)arg;
519 newaction->x.rp = (struct rule *)arg;
522 /********************** New code to implement the "acttab" module ***********/
524 ** This module implements routines use to construct the yy_action[] table.
528 ** The state of the yy_action table under construction is an instance of
529 ** the following structure.
531 ** The yy_action table maps the pair (state_number, lookahead) into an
532 ** action_number. The table is an array of integers pairs. The state_number
533 ** determines an initial offset into the yy_action array. The lookahead
534 ** value is then added to this initial offset to get an index X into the
535 ** yy_action array. If the aAction[X].lookahead equals the value of the
536 ** of the lookahead input, then the value of the action_number output is
537 ** aAction[X].action. If the lookaheads do not match then the
538 ** default action for the state_number is returned.
540 ** All actions associated with a single state_number are first entered
541 ** into aLookahead[] using multiple calls to acttab_action(). Then the
542 ** actions for that single state_number are placed into the aAction[]
543 ** array with a single call to acttab_insert(). The acttab_insert() call
544 ** also resets the aLookahead[] array in preparation for the next
547 struct lookahead_action {
548 int lookahead; /* Value of the lookahead token */
549 int action; /* Action to take on the given lookahead */
551 typedef struct acttab acttab;
553 int nAction; /* Number of used slots in aAction[] */
554 int nActionAlloc; /* Slots allocated for aAction[] */
555 struct lookahead_action
556 *aAction, /* The yy_action[] table under construction */
557 *aLookahead; /* A single new transaction set */
558 int mnLookahead; /* Minimum aLookahead[].lookahead */
559 int mnAction; /* Action associated with mnLookahead */
560 int mxLookahead; /* Maximum aLookahead[].lookahead */
561 int nLookahead; /* Used slots in aLookahead[] */
562 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
565 /* Return the number of entries in the yy_action table */
566 #define acttab_size(X) ((X)->nAction)
568 /* The value for the N-th entry in yy_action */
569 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
571 /* The value for the N-th entry in yy_lookahead */
572 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
574 /* Free all memory associated with the given acttab */
575 void acttab_free(acttab *p){
577 free( p->aLookahead );
581 /* Allocate a new acttab structure */
582 acttab *acttab_alloc(void){
583 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
585 fprintf(stderr,"Unable to allocate memory for a new acttab.");
588 memset(p, 0, sizeof(*p));
592 /* Add a new action to the current transaction set.
594 ** This routine is called once for each lookahead for a particular
597 void acttab_action(acttab *p, int lookahead, int action){
598 if( p->nLookahead>=p->nLookaheadAlloc ){
599 p->nLookaheadAlloc += 25;
600 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
601 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
602 if( p->aLookahead==0 ){
603 fprintf(stderr,"malloc failed\n");
607 if( p->nLookahead==0 ){
608 p->mxLookahead = lookahead;
609 p->mnLookahead = lookahead;
610 p->mnAction = action;
612 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
613 if( p->mnLookahead>lookahead ){
614 p->mnLookahead = lookahead;
615 p->mnAction = action;
618 p->aLookahead[p->nLookahead].lookahead = lookahead;
619 p->aLookahead[p->nLookahead].action = action;
624 ** Add the transaction set built up with prior calls to acttab_action()
625 ** into the current action table. Then reset the transaction set back
626 ** to an empty set in preparation for a new round of acttab_action() calls.
628 ** Return the offset into the action table of the new transaction.
630 int acttab_insert(acttab *p){
632 assert( p->nLookahead>0 );
634 /* Make sure we have enough space to hold the expanded action table
635 ** in the worst case. The worst case occurs if the transaction set
636 ** must be appended to the current action table
638 n = p->mxLookahead + 1;
639 if( p->nAction + n >= p->nActionAlloc ){
640 int oldAlloc = p->nActionAlloc;
641 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
642 p->aAction = (struct lookahead_action *) realloc( p->aAction,
643 sizeof(p->aAction[0])*p->nActionAlloc);
645 fprintf(stderr,"malloc failed\n");
648 for(i=oldAlloc; i<p->nActionAlloc; i++){
649 p->aAction[i].lookahead = -1;
650 p->aAction[i].action = -1;
654 /* Scan the existing action table looking for an offset that is a
655 ** duplicate of the current transaction set. Fall out of the loop
656 ** if and when the duplicate is found.
658 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
660 for(i=p->nAction-1; i>=0; i--){
661 if( p->aAction[i].lookahead==p->mnLookahead ){
662 /* All lookaheads and actions in the aLookahead[] transaction
663 ** must match against the candidate aAction[i] entry. */
664 if( p->aAction[i].action!=p->mnAction ) continue;
665 for(j=0; j<p->nLookahead; j++){
666 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
667 if( k<0 || k>=p->nAction ) break;
668 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
669 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
671 if( j<p->nLookahead ) continue;
673 /* No possible lookahead value that is not in the aLookahead[]
674 ** transaction is allowed to match aAction[i] */
676 for(j=0; j<p->nAction; j++){
677 if( p->aAction[j].lookahead<0 ) continue;
678 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
680 if( n==p->nLookahead ){
681 break; /* An exact match is found at offset i */
686 /* If no existing offsets exactly match the current transaction, find an
687 ** an empty offset in the aAction[] table in which we can add the
688 ** aLookahead[] transaction.
691 /* Look for holes in the aAction[] table that fit the current
692 ** aLookahead[] transaction. Leave i set to the offset of the hole.
693 ** If no holes are found, i is left at p->nAction, which means the
694 ** transaction will be appended. */
695 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
696 if( p->aAction[i].lookahead<0 ){
697 for(j=0; j<p->nLookahead; j++){
698 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
700 if( p->aAction[k].lookahead>=0 ) break;
702 if( j<p->nLookahead ) continue;
703 for(j=0; j<p->nAction; j++){
704 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
707 break; /* Fits in empty slots */
712 /* Insert transaction set at index i. */
713 for(j=0; j<p->nLookahead; j++){
714 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
715 p->aAction[k] = p->aLookahead[j];
716 if( k>=p->nAction ) p->nAction = k+1;
720 /* Return the offset that is added to the lookahead in order to get the
721 ** index into yy_action of the action */
722 return i - p->mnLookahead;
725 /********************** From the file "build.c" *****************************/
727 ** Routines to construction the finite state machine for the LEMON
731 /* Find a precedence symbol of every rule in the grammar.
733 ** Those rules which have a precedence symbol coded in the input
734 ** grammar using the "[symbol]" construct will already have the
735 ** rp->precsym field filled. Other rules take as their precedence
736 ** symbol the first RHS symbol with a defined precedence. If there
737 ** are not RHS symbols with a defined precedence, the precedence
738 ** symbol field is left blank.
740 void FindRulePrecedences(struct lemon *xp)
743 for(rp=xp->rule; rp; rp=rp->next){
744 if( rp->precsym==0 ){
746 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
747 struct symbol *sp = rp->rhs[i];
748 if( sp->type==MULTITERMINAL ){
749 for(j=0; j<sp->nsubsym; j++){
750 if( sp->subsym[j]->prec>=0 ){
751 rp->precsym = sp->subsym[j];
755 }else if( sp->prec>=0 ){
756 rp->precsym = rp->rhs[i];
764 /* Find all nonterminals which will generate the empty string.
765 ** Then go back and compute the first sets of every nonterminal.
766 ** The first set is the set of all terminal symbols which can begin
767 ** a string generated by that nonterminal.
769 void FindFirstSets(struct lemon *lemp)
775 for(i=0; i<lemp->nsymbol; i++){
776 lemp->symbols[i]->lambda = LEMON_FALSE;
778 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
779 lemp->symbols[i]->firstset = SetNew();
782 /* First compute all lambdas */
785 for(rp=lemp->rule; rp; rp=rp->next){
786 if( rp->lhs->lambda ) continue;
787 for(i=0; i<rp->nrhs; i++){
788 struct symbol *sp = rp->rhs[i];
789 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
790 if( sp->lambda==LEMON_FALSE ) break;
793 rp->lhs->lambda = LEMON_TRUE;
799 /* Now compute all first sets */
801 struct symbol *s1, *s2;
803 for(rp=lemp->rule; rp; rp=rp->next){
805 for(i=0; i<rp->nrhs; i++){
807 if( s2->type==TERMINAL ){
808 progress += SetAdd(s1->firstset,s2->index);
810 }else if( s2->type==MULTITERMINAL ){
811 for(j=0; j<s2->nsubsym; j++){
812 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
816 if( s1->lambda==LEMON_FALSE ) break;
818 progress += SetUnion(s1->firstset,s2->firstset);
819 if( s2->lambda==LEMON_FALSE ) break;
827 /* Compute all LR(0) states for the grammar. Links
828 ** are added to between some states so that the LR(1) follow sets
829 ** can be computed later.
831 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
832 void FindStates(struct lemon *lemp)
839 /* Find the start symbol */
841 sp = Symbol_find(lemp->start);
843 ErrorMsg(lemp->filename,0,
844 "The specified start symbol \"%s\" is not \
845 in a nonterminal of the grammar. \"%s\" will be used as the start \
846 symbol instead.",lemp->start,lemp->rule->lhs->name);
848 sp = lemp->rule->lhs;
851 sp = lemp->rule->lhs;
854 /* Make sure the start symbol doesn't occur on the right-hand side of
855 ** any rule. Report an error if it does. (YACC would generate a new
856 ** start symbol in this case.) */
857 for(rp=lemp->rule; rp; rp=rp->next){
859 for(i=0; i<rp->nrhs; i++){
860 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
861 ErrorMsg(lemp->filename,0,
862 "The start symbol \"%s\" occurs on the \
863 right-hand side of a rule. This will result in a parser which \
864 does not work properly.",sp->name);
870 /* The basis configuration set for the first state
871 ** is all rules which have the start symbol as their
873 for(rp=sp->rule; rp; rp=rp->nextlhs){
874 struct config *newcfp;
876 newcfp = Configlist_addbasis(rp,0);
877 SetAdd(newcfp->fws,0);
880 /* Compute the first state. All other states will be
881 ** computed automatically during the computation of the first one.
882 ** The returned pointer to the first state is not used. */
883 (void)getstate(lemp);
887 /* Return a pointer to a state which is described by the configuration
888 ** list which has been built from calls to Configlist_add.
890 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
891 PRIVATE struct state *getstate(struct lemon *lemp)
893 struct config *cfp, *bp;
896 /* Extract the sorted basis of the new state. The basis was constructed
897 ** by prior calls to "Configlist_addbasis()". */
898 Configlist_sortbasis();
899 bp = Configlist_basis();
901 /* Get a state with the same basis */
902 stp = State_find(bp);
904 /* A state with the same basis already exists! Copy all the follow-set
905 ** propagation links from the state under construction into the
906 ** preexisting state, then return a pointer to the preexisting state */
907 struct config *x, *y;
908 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
909 Plink_copy(&y->bplp,x->bplp);
910 Plink_delete(x->fplp);
911 x->fplp = x->bplp = 0;
913 cfp = Configlist_return();
916 /* This really is a new state. Construct all the details */
917 Configlist_closure(lemp); /* Compute the configuration closure */
918 Configlist_sort(); /* Sort the configuration closure */
919 cfp = Configlist_return(); /* Get a pointer to the config list */
920 stp = State_new(); /* A new state structure */
922 stp->bp = bp; /* Remember the configuration basis */
923 stp->cfp = cfp; /* Remember the configuration closure */
924 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
925 stp->ap = 0; /* No actions, yet. */
926 State_insert(stp,stp->bp); /* Add to the state table */
927 buildshifts(lemp,stp); /* Recursively compute successor states */
933 ** Return true if two symbols are the same.
935 int same_symbol(struct symbol *a, struct symbol *b)
939 if( a->type!=MULTITERMINAL ) return 0;
940 if( b->type!=MULTITERMINAL ) return 0;
941 if( a->nsubsym!=b->nsubsym ) return 0;
942 for(i=0; i<a->nsubsym; i++){
943 if( a->subsym[i]!=b->subsym[i] ) return 0;
948 /* Construct all successor states to the given state. A "successor"
949 ** state is any state which can be reached by a shift action.
951 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
953 struct config *cfp; /* For looping thru the config closure of "stp" */
954 struct config *bcfp; /* For the inner loop on config closure of "stp" */
955 struct config *newcfg; /* */
956 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
957 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
958 struct state *newstp; /* A pointer to a successor state */
960 /* Each configuration becomes complete after it contibutes to a successor
961 ** state. Initially, all configurations are incomplete */
962 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
964 /* Loop through all configurations of the state "stp" */
965 for(cfp=stp->cfp; cfp; cfp=cfp->next){
966 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
967 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
968 Configlist_reset(); /* Reset the new config set */
969 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
971 /* For every configuration in the state "stp" which has the symbol "sp"
972 ** following its dot, add the same configuration to the basis set under
973 ** construction but with the dot shifted one symbol to the right. */
974 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
975 if( bcfp->status==COMPLETE ) continue; /* Already used */
976 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
977 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
978 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
979 bcfp->status = COMPLETE; /* Mark this config as used */
980 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
981 Plink_add(&newcfg->bplp,bcfp);
984 /* Get a pointer to the state described by the basis configuration set
985 ** constructed in the preceding loop */
986 newstp = getstate(lemp);
988 /* The state "newstp" is reached from the state "stp" by a shift action
989 ** on the symbol "sp" */
990 if( sp->type==MULTITERMINAL ){
992 for(i=0; i<sp->nsubsym; i++){
993 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
996 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1002 ** Construct the propagation links
1004 void FindLinks(struct lemon *lemp)
1007 struct config *cfp, *other;
1011 /* Housekeeping detail:
1012 ** Add to every propagate link a pointer back to the state to
1013 ** which the link is attached. */
1014 for(i=0; i<lemp->nstate; i++){
1015 stp = lemp->sorted[i];
1016 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1021 /* Convert all backlinks into forward links. Only the forward
1022 ** links are used in the follow-set computation. */
1023 for(i=0; i<lemp->nstate; i++){
1024 stp = lemp->sorted[i];
1025 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1026 for(plp=cfp->bplp; plp; plp=plp->next){
1028 Plink_add(&other->fplp,cfp);
1034 /* Compute all followsets.
1036 ** A followset is the set of all symbols which can come immediately
1037 ** after a configuration.
1039 void FindFollowSets(struct lemon *lemp)
1047 for(i=0; i<lemp->nstate; i++){
1048 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1049 cfp->status = INCOMPLETE;
1055 for(i=0; i<lemp->nstate; i++){
1056 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1057 if( cfp->status==COMPLETE ) continue;
1058 for(plp=cfp->fplp; plp; plp=plp->next){
1059 change = SetUnion(plp->cfp->fws,cfp->fws);
1061 plp->cfp->status = INCOMPLETE;
1065 cfp->status = COMPLETE;
1071 static int resolve_conflict(struct action *,struct action *);
1073 /* Compute the reduce actions, and resolve conflicts.
1075 void FindActions(struct lemon *lemp)
1083 /* Add all of the reduce actions
1084 ** A reduce action is added for each element of the followset of
1085 ** a configuration which has its dot at the extreme right.
1087 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1088 stp = lemp->sorted[i];
1089 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1090 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1091 for(j=0; j<lemp->nterminal; j++){
1092 if( SetFind(cfp->fws,j) ){
1093 /* Add a reduce action to the state "stp" which will reduce by the
1094 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1095 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1102 /* Add the accepting token */
1104 sp = Symbol_find(lemp->start);
1105 if( sp==0 ) sp = lemp->rule->lhs;
1107 sp = lemp->rule->lhs;
1109 /* Add to the first state (which is always the starting state of the
1110 ** finite state machine) an action to ACCEPT if the lookahead is the
1111 ** start nonterminal. */
1112 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1114 /* Resolve conflicts */
1115 for(i=0; i<lemp->nstate; i++){
1116 struct action *ap, *nap;
1118 stp = lemp->sorted[i];
1119 /* assert( stp->ap ); */
1120 stp->ap = Action_sort(stp->ap);
1121 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1122 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1123 /* The two actions "ap" and "nap" have the same lookahead.
1124 ** Figure out which one should be used */
1125 lemp->nconflict += resolve_conflict(ap,nap);
1130 /* Report an error for each rule that can never be reduced. */
1131 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1132 for(i=0; i<lemp->nstate; i++){
1134 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1135 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1138 for(rp=lemp->rule; rp; rp=rp->next){
1139 if( rp->canReduce ) continue;
1140 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1145 /* Resolve a conflict between the two given actions. If the
1146 ** conflict can't be resolved, return non-zero.
1149 ** To resolve a conflict, first look to see if either action
1150 ** is on an error rule. In that case, take the action which
1151 ** is not associated with the error rule. If neither or both
1152 ** actions are associated with an error rule, then try to
1153 ** use precedence to resolve the conflict.
1155 ** If either action is a SHIFT, then it must be apx. This
1156 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1158 static int resolve_conflict(
1162 struct symbol *spx, *spy;
1164 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1165 if( apx->type==SHIFT && apy->type==SHIFT ){
1166 apy->type = SSCONFLICT;
1169 if( apx->type==SHIFT && apy->type==REDUCE ){
1171 spy = apy->x.rp->precsym;
1172 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1173 /* Not enough precedence information. */
1174 apy->type = SRCONFLICT;
1176 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1177 apy->type = RD_RESOLVED;
1178 }else if( spx->prec<spy->prec ){
1179 apx->type = SH_RESOLVED;
1180 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1181 apy->type = RD_RESOLVED; /* associativity */
1182 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1183 apx->type = SH_RESOLVED;
1185 assert( spx->prec==spy->prec && spx->assoc==NONE );
1186 apy->type = SRCONFLICT;
1189 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1190 spx = apx->x.rp->precsym;
1191 spy = apy->x.rp->precsym;
1192 if( spx==0 || spy==0 || spx->prec<0 ||
1193 spy->prec<0 || spx->prec==spy->prec ){
1194 apy->type = RRCONFLICT;
1196 }else if( spx->prec>spy->prec ){
1197 apy->type = RD_RESOLVED;
1198 }else if( spx->prec<spy->prec ){
1199 apx->type = RD_RESOLVED;
1203 apx->type==SH_RESOLVED ||
1204 apx->type==RD_RESOLVED ||
1205 apx->type==SSCONFLICT ||
1206 apx->type==SRCONFLICT ||
1207 apx->type==RRCONFLICT ||
1208 apy->type==SH_RESOLVED ||
1209 apy->type==RD_RESOLVED ||
1210 apy->type==SSCONFLICT ||
1211 apy->type==SRCONFLICT ||
1212 apy->type==RRCONFLICT
1214 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1215 ** REDUCEs on the list. If we reach this point it must be because
1216 ** the parser conflict had already been resolved. */
1220 /********************* From the file "configlist.c" *************************/
1222 ** Routines to processing a configuration list and building a state
1223 ** in the LEMON parser generator.
1226 static struct config *freelist = 0; /* List of free configurations */
1227 static struct config *current = 0; /* Top of list of configurations */
1228 static struct config **currentend = 0; /* Last on list of configs */
1229 static struct config *basis = 0; /* Top of list of basis configs */
1230 static struct config **basisend = 0; /* End of list of basis configs */
1232 /* Return a pointer to a new configuration */
1233 PRIVATE struct config *newconfig(){
1234 struct config *newcfg;
1238 freelist = (struct config *)calloc( amt, sizeof(struct config) );
1240 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1243 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1244 freelist[amt-1].next = 0;
1247 freelist = freelist->next;
1251 /* The configuration "old" is no longer used */
1252 PRIVATE void deleteconfig(struct config *old)
1254 old->next = freelist;
1258 /* Initialized the configuration list builder */
1259 void Configlist_init(){
1261 currentend = ¤t;
1268 /* Initialized the configuration list builder */
1269 void Configlist_reset(){
1271 currentend = ¤t;
1274 Configtable_clear(0);
1278 /* Add another configuration to the configuration list */
1279 struct config *Configlist_add(
1280 struct rule *rp, /* The rule */
1281 int dot /* Index into the RHS of the rule where the dot goes */
1283 struct config *cfp, model;
1285 assert( currentend!=0 );
1288 cfp = Configtable_find(&model);
1293 cfp->fws = SetNew();
1295 cfp->fplp = cfp->bplp = 0;
1299 currentend = &cfp->next;
1300 Configtable_insert(cfp);
1305 /* Add a basis configuration to the configuration list */
1306 struct config *Configlist_addbasis(struct rule *rp, int dot)
1308 struct config *cfp, model;
1310 assert( basisend!=0 );
1311 assert( currentend!=0 );
1314 cfp = Configtable_find(&model);
1319 cfp->fws = SetNew();
1321 cfp->fplp = cfp->bplp = 0;
1325 currentend = &cfp->next;
1327 basisend = &cfp->bp;
1328 Configtable_insert(cfp);
1333 /* Compute the closure of the configuration list */
1334 void Configlist_closure(struct lemon *lemp)
1336 struct config *cfp, *newcfp;
1337 struct rule *rp, *newrp;
1338 struct symbol *sp, *xsp;
1341 assert( currentend!=0 );
1342 for(cfp=current; cfp; cfp=cfp->next){
1345 if( dot>=rp->nrhs ) continue;
1347 if( sp->type==NONTERMINAL ){
1348 if( sp->rule==0 && sp!=lemp->errsym ){
1349 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1353 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1354 newcfp = Configlist_add(newrp,0);
1355 for(i=dot+1; i<rp->nrhs; i++){
1357 if( xsp->type==TERMINAL ){
1358 SetAdd(newcfp->fws,xsp->index);
1360 }else if( xsp->type==MULTITERMINAL ){
1362 for(k=0; k<xsp->nsubsym; k++){
1363 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1367 SetUnion(newcfp->fws,xsp->firstset);
1368 if( xsp->lambda==LEMON_FALSE ) break;
1371 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1378 /* Sort the configuration list */
1379 void Configlist_sort(){
1380 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
1385 /* Sort the basis configuration list */
1386 void Configlist_sortbasis(){
1387 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
1392 /* Return a pointer to the head of the configuration list and
1393 ** reset the list */
1394 struct config *Configlist_return(){
1402 /* Return a pointer to the head of the configuration list and
1403 ** reset the list */
1404 struct config *Configlist_basis(){
1412 /* Free all elements of the given configuration list */
1413 void Configlist_eat(struct config *cfp)
1415 struct config *nextcfp;
1416 for(; cfp; cfp=nextcfp){
1417 nextcfp = cfp->next;
1418 assert( cfp->fplp==0 );
1419 assert( cfp->bplp==0 );
1420 if( cfp->fws ) SetFree(cfp->fws);
1425 /***************** From the file "error.c" *********************************/
1427 ** Code for printing error message.
1430 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1432 fprintf(stderr, "%s:%d: ", filename, lineno);
1433 va_start(ap, format);
1434 vfprintf(stderr,format,ap);
1436 fprintf(stderr, "\n");
1438 /**************** From the file "main.c" ************************************/
1440 ** Main program file for the LEMON parser generator.
1443 /* Report an out-of-memory condition and abort. This function
1444 ** is used mostly by the "MemoryCheck" macro in struct.h
1446 void memory_error(){
1447 fprintf(stderr,"Out of memory. Aborting...\n");
1451 static int nDefine = 0; /* Number of -D options on the command line */
1452 static char **azDefine = 0; /* Name of the -D macros */
1454 /* This routine is called with the argument to each -D command-line option.
1455 ** Add the macro defined to the azDefine array.
1457 static void handle_D_option(char *z){
1460 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
1462 fprintf(stderr,"out of memory\n");
1465 paz = &azDefine[nDefine-1];
1466 *paz = (char *) malloc( lemonStrlen(z)+1 );
1468 fprintf(stderr,"out of memory\n");
1471 lemon_strcpy(*paz, z);
1472 for(z=*paz; *z && *z!='='; z++){}
1476 static char *user_templatename = NULL;
1477 static void handle_T_option(char *z){
1478 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
1479 if( user_templatename==0 ){
1482 lemon_strcpy(user_templatename, z);
1485 /* The main program. Parse the command line and do it... */
1486 int main(int argc, char **argv)
1488 static int version = 0;
1489 static int rpflag = 0;
1490 static int basisflag = 0;
1491 static int compress = 0;
1492 static int quiet = 0;
1493 static int statistics = 0;
1494 static int mhflag = 0;
1495 static int nolinenosflag = 0;
1496 static int noResort = 0;
1497 static struct s_options options[] = {
1498 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1499 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1500 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1501 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1502 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1503 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1504 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
1505 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1506 "Show conflicts resolved by precedence rules"},
1507 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1508 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
1509 {OPT_FLAG, "s", (char*)&statistics,
1510 "Print parser stats to standard output."},
1511 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1518 OptInit(argv,options,stderr);
1520 printf("Lemon version 1.0\n");
1523 if( OptNArgs()!=1 ){
1524 fprintf(stderr,"Exactly one filename argument is required.\n");
1527 memset(&lem, 0, sizeof(lem));
1530 /* Initialize the machine */
1534 lem.argv0 = argv[0];
1535 lem.filename = OptArg(0);
1536 lem.basisflag = basisflag;
1537 lem.nolinenosflag = nolinenosflag;
1539 lem.errsym = Symbol_new("error");
1540 lem.errsym->useCnt = 0;
1542 /* Parse the input file */
1544 if( lem.errorcnt ) exit(lem.errorcnt);
1546 fprintf(stderr,"Empty grammar.\n");
1550 /* Count and index the symbols of the grammar */
1551 Symbol_new("{default}");
1552 lem.nsymbol = Symbol_count();
1553 lem.symbols = Symbol_arrayof();
1554 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1555 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1556 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1557 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1558 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1559 lem.nsymbol = i - 1;
1560 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1563 /* Generate a reprint of the grammar, if requested on the command line */
1567 /* Initialize the size for all follow and first sets */
1568 SetSize(lem.nterminal+1);
1570 /* Find the precedence for every production rule (that has one) */
1571 FindRulePrecedences(&lem);
1573 /* Compute the lambda-nonterminals and the first-sets for every
1575 FindFirstSets(&lem);
1577 /* Compute all LR(0) states. Also record follow-set propagation
1578 ** links so that the follow-set can be computed later */
1581 lem.sorted = State_arrayof();
1583 /* Tie up loose ends on the propagation links */
1586 /* Compute the follow set of every reducible configuration */
1587 FindFollowSets(&lem);
1589 /* Compute the action tables */
1592 /* Compress the action tables */
1593 if( compress==0 ) CompressTables(&lem);
1595 /* Reorder and renumber the states so that states with fewer choices
1596 ** occur at the end. This is an optimization that helps make the
1597 ** generated parser tables smaller. */
1598 if( noResort==0 ) ResortStates(&lem);
1600 /* Generate a report of the parser generated. (the "y.output" file) */
1601 if( !quiet ) ReportOutput(&lem);
1603 /* Generate the source code for the parser */
1604 ReportTable(&lem, mhflag);
1606 /* Produce a header file for use by the scanner. (This step is
1607 ** omitted if the "-m" option is used because makeheaders will
1608 ** generate the file for us.) */
1609 if( !mhflag ) ReportHeader(&lem);
1612 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1613 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1614 printf(" %d states, %d parser table entries, %d conflicts\n",
1615 lem.nstate, lem.tablesize, lem.nconflict);
1617 if( lem.nconflict > 0 ){
1618 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1621 /* return 0 on success, 1 on failure. */
1622 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1626 /******************** From the file "msort.c" *******************************/
1628 ** A generic merge-sort program.
1631 ** Let "ptr" be a pointer to some structure which is at the head of
1632 ** a null-terminated list. Then to sort the list call:
1634 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1636 ** In the above, "cmpfnc" is a pointer to a function which compares
1637 ** two instances of the structure and returns an integer, as in
1638 ** strcmp. The second argument is a pointer to the pointer to the
1639 ** second element of the linked list. This address is used to compute
1640 ** the offset to the "next" field within the structure. The offset to
1641 ** the "next" field must be constant for all structures in the list.
1643 ** The function returns a new pointer which is the head of the list
1651 ** Return a pointer to the next structure in the linked list.
1653 #define NEXT(A) (*(char**)(((char*)A)+offset))
1657 ** a: A sorted, null-terminated linked list. (May be null).
1658 ** b: A sorted, null-terminated linked list. (May be null).
1659 ** cmp: A pointer to the comparison function.
1660 ** offset: Offset in the structure to the "next" field.
1663 ** A pointer to the head of a sorted list containing the elements
1667 ** The "next" pointers for elements in the lists a and b are
1673 int (*cmp)(const char*,const char*),
1683 if( (*cmp)(a,b)<=0 ){
1692 if( (*cmp)(a,b)<=0 ){
1702 if( a ) NEXT(ptr) = a;
1710 ** list: Pointer to a singly-linked list of structures.
1711 ** next: Pointer to pointer to the second element of the list.
1712 ** cmp: A comparison function.
1715 ** A pointer to the head of a sorted list containing the elements
1716 ** orginally in list.
1719 ** The "next" pointers for elements in list are changed.
1725 int (*cmp)(const char*,const char*)
1727 unsigned long offset;
1729 char *set[LISTSIZE];
1731 offset = (unsigned long)next - (unsigned long)list;
1732 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1737 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1738 ep = merge(ep,set[i],cmp,offset);
1744 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
1747 /************************ From the file "option.c" **************************/
1749 static struct s_options *op;
1750 static FILE *errstream;
1752 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1755 ** Print the command line with a carrot pointing to the k-th character
1756 ** of the n-th field.
1758 static void errline(int n, int k, FILE *err)
1761 if( argv[0] ) fprintf(err,"%s",argv[0]);
1762 spcnt = lemonStrlen(argv[0]) + 1;
1763 for(i=1; i<n && argv[i]; i++){
1764 fprintf(err," %s",argv[i]);
1765 spcnt += lemonStrlen(argv[i])+1;
1768 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1770 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1772 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1777 ** Return the index of the N-th non-switch argument. Return -1
1778 ** if N is out of range.
1780 static int argindex(int n)
1784 if( argv!=0 && *argv!=0 ){
1785 for(i=1; argv[i]; i++){
1786 if( dashdash || !ISOPT(argv[i]) ){
1787 if( n==0 ) return i;
1790 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1796 static char emsg[] = "Command line syntax error: ";
1799 ** Process a flag command line argument.
1801 static int handleflags(int i, FILE *err)
1806 for(j=0; op[j].label; j++){
1807 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
1809 v = argv[i][0]=='-' ? 1 : 0;
1810 if( op[j].label==0 ){
1812 fprintf(err,"%sundefined option.\n",emsg);
1816 }else if( op[j].type==OPT_FLAG ){
1817 *((int*)op[j].arg) = v;
1818 }else if( op[j].type==OPT_FFLAG ){
1819 (*(void(*)(int))(op[j].arg))(v);
1820 }else if( op[j].type==OPT_FSTR ){
1821 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
1824 fprintf(err,"%smissing argument on switch.\n",emsg);
1833 ** Process a command line switch which has an argument.
1835 static int handleswitch(int i, FILE *err)
1843 cp = strchr(argv[i],'=');
1846 for(j=0; op[j].label; j++){
1847 if( strcmp(argv[i],op[j].label)==0 ) break;
1850 if( op[j].label==0 ){
1852 fprintf(err,"%sundefined option.\n",emsg);
1858 switch( op[j].type ){
1862 fprintf(err,"%soption requires an argument.\n",emsg);
1869 dv = strtod(cp,&end);
1872 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
1873 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1880 lv = strtol(cp,&end,0);
1883 fprintf(err,"%sillegal character in integer argument.\n",emsg);
1884 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1894 switch( op[j].type ){
1899 *(double*)(op[j].arg) = dv;
1902 (*(void(*)(double))(op[j].arg))(dv);
1905 *(int*)(op[j].arg) = lv;
1908 (*(void(*)(int))(op[j].arg))((int)lv);
1911 *(char**)(op[j].arg) = sv;
1914 (*(void(*)(char *))(op[j].arg))(sv);
1921 int OptInit(char **a, struct s_options *o, FILE *err)
1927 if( argv && *argv && op ){
1929 for(i=1; argv[i]; i++){
1930 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1931 errcnt += handleflags(i,err);
1932 }else if( strchr(argv[i],'=') ){
1933 errcnt += handleswitch(i,err);
1938 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
1949 if( argv!=0 && argv[0]!=0 ){
1950 for(i=1; argv[i]; i++){
1951 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1952 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1962 return i>=0 ? argv[i] : 0;
1969 if( i>=0 ) errline(i,0,errstream);
1976 for(i=0; op[i].label; i++){
1977 len = lemonStrlen(op[i].label) + 1;
1978 switch( op[i].type ){
1984 len += 9; /* length of "<integer>" */
1988 len += 6; /* length of "<real>" */
1992 len += 8; /* length of "<string>" */
1995 if( len>max ) max = len;
1997 for(i=0; op[i].label; i++){
1998 switch( op[i].type ){
2001 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2005 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
2006 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2010 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
2011 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2015 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
2016 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2021 /*********************** From the file "parse.c" ****************************/
2023 ** Input file parser for the LEMON parser generator.
2026 /* The state of the parser */
2029 WAITING_FOR_DECL_OR_RULE,
2030 WAITING_FOR_DECL_KEYWORD,
2031 WAITING_FOR_DECL_ARG,
2032 WAITING_FOR_PRECEDENCE_SYMBOL,
2042 RESYNC_AFTER_RULE_ERROR,
2043 RESYNC_AFTER_DECL_ERROR,
2044 WAITING_FOR_DESTRUCTOR_SYMBOL,
2045 WAITING_FOR_DATATYPE_SYMBOL,
2046 WAITING_FOR_FALLBACK_ID,
2047 WAITING_FOR_WILDCARD_ID,
2048 WAITING_FOR_CLASS_ID,
2049 WAITING_FOR_CLASS_TOKEN
2052 char *filename; /* Name of the input file */
2053 int tokenlineno; /* Linenumber at which current token starts */
2054 int errorcnt; /* Number of errors so far */
2055 char *tokenstart; /* Text of current token */
2056 struct lemon *gp; /* Global state vector */
2057 enum e_state state; /* The state of the parser */
2058 struct symbol *fallback; /* The fallback token */
2059 struct symbol *tkclass; /* Token class symbol */
2060 struct symbol *lhs; /* Left-hand side of current rule */
2061 const char *lhsalias; /* Alias for the LHS */
2062 int nrhs; /* Number of right-hand side symbols seen */
2063 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2064 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2065 struct rule *prevrule; /* Previous rule parsed */
2066 const char *declkeyword; /* Keyword of a declaration */
2067 char **declargslot; /* Where the declaration argument should be put */
2068 int insertLineMacro; /* Add #line before declaration insert */
2069 int *decllinenoslot; /* Where to write declaration line number */
2070 enum e_assoc declassoc; /* Assign this association to decl arguments */
2071 int preccounter; /* Assign this precedence to decl arguments */
2072 struct rule *firstrule; /* Pointer to first rule in the grammar */
2073 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2076 /* Parse a single token */
2077 static void parseonetoken(struct pstate *psp)
2080 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2082 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2085 switch( psp->state ){
2088 psp->preccounter = 0;
2089 psp->firstrule = psp->lastrule = 0;
2091 /* Fall thru to next case */
2092 case WAITING_FOR_DECL_OR_RULE:
2094 psp->state = WAITING_FOR_DECL_KEYWORD;
2095 }else if( islower(x[0]) ){
2096 psp->lhs = Symbol_new(x);
2099 psp->state = WAITING_FOR_ARROW;
2100 }else if( x[0]=='{' ){
2101 if( psp->prevrule==0 ){
2102 ErrorMsg(psp->filename,psp->tokenlineno,
2103 "There is no prior rule upon which to attach the code \
2104 fragment which begins on this line.");
2106 }else if( psp->prevrule->code!=0 ){
2107 ErrorMsg(psp->filename,psp->tokenlineno,
2108 "Code fragment beginning on this line is not the first \
2109 to follow the previous rule.");
2112 psp->prevrule->line = psp->tokenlineno;
2113 psp->prevrule->code = &x[1];
2115 }else if( x[0]=='[' ){
2116 psp->state = PRECEDENCE_MARK_1;
2118 ErrorMsg(psp->filename,psp->tokenlineno,
2119 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2124 case PRECEDENCE_MARK_1:
2125 if( !isupper(x[0]) ){
2126 ErrorMsg(psp->filename,psp->tokenlineno,
2127 "The precedence symbol must be a terminal.");
2129 }else if( psp->prevrule==0 ){
2130 ErrorMsg(psp->filename,psp->tokenlineno,
2131 "There is no prior rule to assign precedence \"[%s]\".",x);
2133 }else if( psp->prevrule->precsym!=0 ){
2134 ErrorMsg(psp->filename,psp->tokenlineno,
2135 "Precedence mark on this line is not the first \
2136 to follow the previous rule.");
2139 psp->prevrule->precsym = Symbol_new(x);
2141 psp->state = PRECEDENCE_MARK_2;
2143 case PRECEDENCE_MARK_2:
2145 ErrorMsg(psp->filename,psp->tokenlineno,
2146 "Missing \"]\" on precedence mark.");
2149 psp->state = WAITING_FOR_DECL_OR_RULE;
2151 case WAITING_FOR_ARROW:
2152 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2153 psp->state = IN_RHS;
2154 }else if( x[0]=='(' ){
2155 psp->state = LHS_ALIAS_1;
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Expected to see a \":\" following the LHS symbol \"%s\".",
2161 psp->state = RESYNC_AFTER_RULE_ERROR;
2165 if( isalpha(x[0]) ){
2167 psp->state = LHS_ALIAS_2;
2169 ErrorMsg(psp->filename,psp->tokenlineno,
2170 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2173 psp->state = RESYNC_AFTER_RULE_ERROR;
2178 psp->state = LHS_ALIAS_3;
2180 ErrorMsg(psp->filename,psp->tokenlineno,
2181 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2183 psp->state = RESYNC_AFTER_RULE_ERROR;
2187 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2188 psp->state = IN_RHS;
2190 ErrorMsg(psp->filename,psp->tokenlineno,
2191 "Missing \"->\" following: \"%s(%s)\".",
2192 psp->lhs->name,psp->lhsalias);
2194 psp->state = RESYNC_AFTER_RULE_ERROR;
2200 rp = (struct rule *)calloc( sizeof(struct rule) +
2201 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2203 ErrorMsg(psp->filename,psp->tokenlineno,
2204 "Can't allocate enough memory for this rule.");
2209 rp->ruleline = psp->tokenlineno;
2210 rp->rhs = (struct symbol**)&rp[1];
2211 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2212 for(i=0; i<psp->nrhs; i++){
2213 rp->rhs[i] = psp->rhs[i];
2214 rp->rhsalias[i] = psp->alias[i];
2217 rp->lhsalias = psp->lhsalias;
2218 rp->nrhs = psp->nrhs;
2221 rp->index = psp->gp->nrule++;
2222 rp->nextlhs = rp->lhs->rule;
2225 if( psp->firstrule==0 ){
2226 psp->firstrule = psp->lastrule = rp;
2228 psp->lastrule->next = rp;
2233 psp->state = WAITING_FOR_DECL_OR_RULE;
2234 }else if( isalpha(x[0]) ){
2235 if( psp->nrhs>=MAXRHS ){
2236 ErrorMsg(psp->filename,psp->tokenlineno,
2237 "Too many symbols on RHS of rule beginning at \"%s\".",
2240 psp->state = RESYNC_AFTER_RULE_ERROR;
2242 psp->rhs[psp->nrhs] = Symbol_new(x);
2243 psp->alias[psp->nrhs] = 0;
2246 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2247 struct symbol *msp = psp->rhs[psp->nrhs-1];
2248 if( msp->type!=MULTITERMINAL ){
2249 struct symbol *origsp = msp;
2250 msp = (struct symbol *) calloc(1,sizeof(*msp));
2251 memset(msp, 0, sizeof(*msp));
2252 msp->type = MULTITERMINAL;
2254 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
2255 msp->subsym[0] = origsp;
2256 msp->name = origsp->name;
2257 psp->rhs[psp->nrhs-1] = msp;
2260 msp->subsym = (struct symbol **) realloc(msp->subsym,
2261 sizeof(struct symbol*)*msp->nsubsym);
2262 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2263 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2264 ErrorMsg(psp->filename,psp->tokenlineno,
2265 "Cannot form a compound containing a non-terminal");
2268 }else if( x[0]=='(' && psp->nrhs>0 ){
2269 psp->state = RHS_ALIAS_1;
2271 ErrorMsg(psp->filename,psp->tokenlineno,
2272 "Illegal character on RHS of rule: \"%s\".",x);
2274 psp->state = RESYNC_AFTER_RULE_ERROR;
2278 if( isalpha(x[0]) ){
2279 psp->alias[psp->nrhs-1] = x;
2280 psp->state = RHS_ALIAS_2;
2282 ErrorMsg(psp->filename,psp->tokenlineno,
2283 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2284 x,psp->rhs[psp->nrhs-1]->name);
2286 psp->state = RESYNC_AFTER_RULE_ERROR;
2291 psp->state = IN_RHS;
2293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2296 psp->state = RESYNC_AFTER_RULE_ERROR;
2299 case WAITING_FOR_DECL_KEYWORD:
2300 if( isalpha(x[0]) ){
2301 psp->declkeyword = x;
2302 psp->declargslot = 0;
2303 psp->decllinenoslot = 0;
2304 psp->insertLineMacro = 1;
2305 psp->state = WAITING_FOR_DECL_ARG;
2306 if( strcmp(x,"name")==0 ){
2307 psp->declargslot = &(psp->gp->name);
2308 psp->insertLineMacro = 0;
2309 }else if( strcmp(x,"include")==0 ){
2310 psp->declargslot = &(psp->gp->include);
2311 }else if( strcmp(x,"code")==0 ){
2312 psp->declargslot = &(psp->gp->extracode);
2313 }else if( strcmp(x,"token_destructor")==0 ){
2314 psp->declargslot = &psp->gp->tokendest;
2315 }else if( strcmp(x,"default_destructor")==0 ){
2316 psp->declargslot = &psp->gp->vardest;
2317 }else if( strcmp(x,"token_prefix")==0 ){
2318 psp->declargslot = &psp->gp->tokenprefix;
2319 psp->insertLineMacro = 0;
2320 }else if( strcmp(x,"syntax_error")==0 ){
2321 psp->declargslot = &(psp->gp->error);
2322 }else if( strcmp(x,"parse_accept")==0 ){
2323 psp->declargslot = &(psp->gp->accept);
2324 }else if( strcmp(x,"parse_failure")==0 ){
2325 psp->declargslot = &(psp->gp->failure);
2326 }else if( strcmp(x,"stack_overflow")==0 ){
2327 psp->declargslot = &(psp->gp->overflow);
2328 }else if( strcmp(x,"extra_argument")==0 ){
2329 psp->declargslot = &(psp->gp->arg);
2330 psp->insertLineMacro = 0;
2331 }else if( strcmp(x,"token_type")==0 ){
2332 psp->declargslot = &(psp->gp->tokentype);
2333 psp->insertLineMacro = 0;
2334 }else if( strcmp(x,"default_type")==0 ){
2335 psp->declargslot = &(psp->gp->vartype);
2336 psp->insertLineMacro = 0;
2337 }else if( strcmp(x,"stack_size")==0 ){
2338 psp->declargslot = &(psp->gp->stacksize);
2339 psp->insertLineMacro = 0;
2340 }else if( strcmp(x,"start_symbol")==0 ){
2341 psp->declargslot = &(psp->gp->start);
2342 psp->insertLineMacro = 0;
2343 }else if( strcmp(x,"left")==0 ){
2345 psp->declassoc = LEFT;
2346 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2347 }else if( strcmp(x,"right")==0 ){
2349 psp->declassoc = RIGHT;
2350 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2351 }else if( strcmp(x,"nonassoc")==0 ){
2353 psp->declassoc = NONE;
2354 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2355 }else if( strcmp(x,"destructor")==0 ){
2356 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2357 }else if( strcmp(x,"type")==0 ){
2358 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2359 }else if( strcmp(x,"fallback")==0 ){
2361 psp->state = WAITING_FOR_FALLBACK_ID;
2362 }else if( strcmp(x,"wildcard")==0 ){
2363 psp->state = WAITING_FOR_WILDCARD_ID;
2364 }else if( strcmp(x,"token_class")==0 ){
2365 psp->state = WAITING_FOR_CLASS_ID;
2367 ErrorMsg(psp->filename,psp->tokenlineno,
2368 "Unknown declaration keyword: \"%%%s\".",x);
2370 psp->state = RESYNC_AFTER_DECL_ERROR;
2373 ErrorMsg(psp->filename,psp->tokenlineno,
2374 "Illegal declaration keyword: \"%s\".",x);
2376 psp->state = RESYNC_AFTER_DECL_ERROR;
2379 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2380 if( !isalpha(x[0]) ){
2381 ErrorMsg(psp->filename,psp->tokenlineno,
2382 "Symbol name missing after %%destructor keyword");
2384 psp->state = RESYNC_AFTER_DECL_ERROR;
2386 struct symbol *sp = Symbol_new(x);
2387 psp->declargslot = &sp->destructor;
2388 psp->decllinenoslot = &sp->destLineno;
2389 psp->insertLineMacro = 1;
2390 psp->state = WAITING_FOR_DECL_ARG;
2393 case WAITING_FOR_DATATYPE_SYMBOL:
2394 if( !isalpha(x[0]) ){
2395 ErrorMsg(psp->filename,psp->tokenlineno,
2396 "Symbol name missing after %%type keyword");
2398 psp->state = RESYNC_AFTER_DECL_ERROR;
2400 struct symbol *sp = Symbol_find(x);
2401 if((sp) && (sp->datatype)){
2402 ErrorMsg(psp->filename,psp->tokenlineno,
2403 "Symbol %%type \"%s\" already defined", x);
2405 psp->state = RESYNC_AFTER_DECL_ERROR;
2410 psp->declargslot = &sp->datatype;
2411 psp->insertLineMacro = 0;
2412 psp->state = WAITING_FOR_DECL_ARG;
2416 case WAITING_FOR_PRECEDENCE_SYMBOL:
2418 psp->state = WAITING_FOR_DECL_OR_RULE;
2419 }else if( isupper(x[0]) ){
2423 ErrorMsg(psp->filename,psp->tokenlineno,
2424 "Symbol \"%s\" has already be given a precedence.",x);
2427 sp->prec = psp->preccounter;
2428 sp->assoc = psp->declassoc;
2431 ErrorMsg(psp->filename,psp->tokenlineno,
2432 "Can't assign a precedence to \"%s\".",x);
2436 case WAITING_FOR_DECL_ARG:
2437 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2438 const char *zOld, *zNew;
2440 int nOld, n, nLine, nNew, nBack;
2444 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2445 nNew = lemonStrlen(zNew);
2446 if( *psp->declargslot ){
2447 zOld = *psp->declargslot;
2451 nOld = lemonStrlen(zOld);
2452 n = nOld + nNew + 20;
2453 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
2454 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2456 for(z=psp->filename, nBack=0; *z; z++){
2457 if( *z=='\\' ) nBack++;
2459 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2460 nLine = lemonStrlen(zLine);
2461 n += nLine + lemonStrlen(psp->filename) + nBack;
2463 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2464 zBuf = *psp->declargslot + nOld;
2466 if( nOld && zBuf[-1]!='\n' ){
2469 memcpy(zBuf, zLine, nLine);
2472 for(z=psp->filename; *z; z++){
2481 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2482 psp->decllinenoslot[0] = psp->tokenlineno;
2484 memcpy(zBuf, zNew, nNew);
2487 psp->state = WAITING_FOR_DECL_OR_RULE;
2489 ErrorMsg(psp->filename,psp->tokenlineno,
2490 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2492 psp->state = RESYNC_AFTER_DECL_ERROR;
2495 case WAITING_FOR_FALLBACK_ID:
2497 psp->state = WAITING_FOR_DECL_OR_RULE;
2498 }else if( !isupper(x[0]) ){
2499 ErrorMsg(psp->filename, psp->tokenlineno,
2500 "%%fallback argument \"%s\" should be a token", x);
2503 struct symbol *sp = Symbol_new(x);
2504 if( psp->fallback==0 ){
2506 }else if( sp->fallback ){
2507 ErrorMsg(psp->filename, psp->tokenlineno,
2508 "More than one fallback assigned to token %s", x);
2511 sp->fallback = psp->fallback;
2512 psp->gp->has_fallback = 1;
2516 case WAITING_FOR_WILDCARD_ID:
2518 psp->state = WAITING_FOR_DECL_OR_RULE;
2519 }else if( !isupper(x[0]) ){
2520 ErrorMsg(psp->filename, psp->tokenlineno,
2521 "%%wildcard argument \"%s\" should be a token", x);
2524 struct symbol *sp = Symbol_new(x);
2525 if( psp->gp->wildcard==0 ){
2526 psp->gp->wildcard = sp;
2528 ErrorMsg(psp->filename, psp->tokenlineno,
2529 "Extra wildcard to token: %s", x);
2534 case WAITING_FOR_CLASS_ID:
2535 if( !islower(x[0]) ){
2536 ErrorMsg(psp->filename, psp->tokenlineno,
2537 "%%token_class must be followed by an identifier: ", x);
2539 psp->state = RESYNC_AFTER_DECL_ERROR;
2540 }else if( Symbol_find(x) ){
2541 ErrorMsg(psp->filename, psp->tokenlineno,
2542 "Symbol \"%s\" already used", x);
2544 psp->state = RESYNC_AFTER_DECL_ERROR;
2546 psp->tkclass = Symbol_new(x);
2547 psp->tkclass->type = MULTITERMINAL;
2548 psp->state = WAITING_FOR_CLASS_TOKEN;
2551 case WAITING_FOR_CLASS_TOKEN:
2553 psp->state = WAITING_FOR_DECL_OR_RULE;
2554 }else if( isupper(x[0]) || ((x[0]=='|' || x[0]=='/') && isupper(x[1])) ){
2555 struct symbol *msp = psp->tkclass;
2557 msp->subsym = (struct symbol **) realloc(msp->subsym,
2558 sizeof(struct symbol*)*msp->nsubsym);
2559 if( !isupper(x[0]) ) x++;
2560 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2562 ErrorMsg(psp->filename, psp->tokenlineno,
2563 "%%token_class argument \"%s\" should be a token", x);
2565 psp->state = RESYNC_AFTER_DECL_ERROR;
2568 case RESYNC_AFTER_RULE_ERROR:
2569 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2571 case RESYNC_AFTER_DECL_ERROR:
2572 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2573 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2578 /* Run the preprocessor over the input file text. The global variables
2579 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2580 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2581 ** comments them out. Text in between is also commented out as appropriate.
2583 static void preprocess_input(char *z){
2588 int start_lineno = 1;
2589 for(i=0; z[i]; i++){
2590 if( z[i]=='\n' ) lineno++;
2591 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2592 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2596 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2599 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2600 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2601 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2605 for(j=i+7; isspace(z[j]); j++){}
2606 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2608 for(k=0; k<nDefine; k++){
2609 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
2614 if( z[i+3]=='n' ) exclude = !exclude;
2617 start_lineno = lineno;
2620 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2624 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2629 /* In spite of its name, this function is really a scanner. It read
2630 ** in the entire input file (all at once) then tokenizes it. Each
2631 ** token is passed to the function "parseonetoken" which builds all
2632 ** the appropriate data structures in the global state vector "gp".
2634 void Parse(struct lemon *gp)
2645 memset(&ps, '\0', sizeof(ps));
2647 ps.filename = gp->filename;
2649 ps.state = INITIALIZE;
2651 /* Begin by reading the input file */
2652 fp = fopen(ps.filename,"rb");
2654 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2659 filesize = ftell(fp);
2661 filebuf = (char *)malloc( filesize+1 );
2662 if( filesize>100000000 || filebuf==0 ){
2663 ErrorMsg(ps.filename,0,"Input file too large.");
2668 if( fread(filebuf,1,filesize,fp)!=filesize ){
2669 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2677 filebuf[filesize] = 0;
2679 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2680 preprocess_input(filebuf);
2682 /* Now scan the text of the input file */
2684 for(cp=filebuf; (c= *cp)!=0; ){
2685 if( c=='\n' ) lineno++; /* Keep track of the line number */
2686 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2687 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2689 while( (c= *cp)!=0 && c!='\n' ) cp++;
2692 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2694 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2695 if( c=='\n' ) lineno++;
2701 ps.tokenstart = cp; /* Mark the beginning of the token */
2702 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2703 if( c=='\"' ){ /* String literals */
2705 while( (c= *cp)!=0 && c!='\"' ){
2706 if( c=='\n' ) lineno++;
2710 ErrorMsg(ps.filename,startline,
2711 "String starting on this line is not terminated before the end of the file.");
2717 }else if( c=='{' ){ /* A block of C code */
2720 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2721 if( c=='\n' ) lineno++;
2722 else if( c=='{' ) level++;
2723 else if( c=='}' ) level--;
2724 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2728 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2729 if( c=='\n' ) lineno++;
2733 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2735 while( (c= *cp)!=0 && c!='\n' ) cp++;
2737 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2738 int startchar, prevc;
2741 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2742 if( c=='\n' ) lineno++;
2743 if( prevc=='\\' ) prevc = 0;
2749 ErrorMsg(ps.filename,ps.tokenlineno,
2750 "C code starting on this line is not terminated before the end of the file.");
2756 }else if( isalnum(c) ){ /* Identifiers */
2757 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2759 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2762 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2764 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2766 }else{ /* All other (one character) operators */
2771 *cp = 0; /* Null terminate the token */
2772 parseonetoken(&ps); /* Parse the token */
2773 *cp = c; /* Restore the buffer */
2776 free(filebuf); /* Release the buffer after parsing */
2777 gp->rule = ps.firstrule;
2778 gp->errorcnt = ps.errorcnt;
2780 /*************************** From the file "plink.c" *********************/
2782 ** Routines processing configuration follow-set propagation links
2783 ** in the LEMON parser generator.
2785 static struct plink *plink_freelist = 0;
2787 /* Allocate a new plink */
2788 struct plink *Plink_new(){
2789 struct plink *newlink;
2791 if( plink_freelist==0 ){
2794 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
2795 if( plink_freelist==0 ){
2797 "Unable to allocate memory for a new follow-set propagation link.\n");
2800 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2801 plink_freelist[amt-1].next = 0;
2803 newlink = plink_freelist;
2804 plink_freelist = plink_freelist->next;
2808 /* Add a plink to a plink list */
2809 void Plink_add(struct plink **plpp, struct config *cfp)
2811 struct plink *newlink;
2812 newlink = Plink_new();
2813 newlink->next = *plpp;
2818 /* Transfer every plink on the list "from" to the list "to" */
2819 void Plink_copy(struct plink **to, struct plink *from)
2821 struct plink *nextpl;
2823 nextpl = from->next;
2830 /* Delete every plink on the list */
2831 void Plink_delete(struct plink *plp)
2833 struct plink *nextpl;
2837 plp->next = plink_freelist;
2838 plink_freelist = plp;
2842 /*********************** From the file "report.c" **************************/
2844 ** Procedures for generating reports and tables in the LEMON parser generator.
2847 /* Generate a filename with the given suffix. Space to hold the
2848 ** name comes from malloc() and must be freed by the calling
2851 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
2856 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
2858 fprintf(stderr,"Can't allocate space for a filename.\n");
2861 lemon_strcpy(name,lemp->filename);
2862 cp = strrchr(name,'.');
2864 lemon_strcat(name,suffix);
2868 /* Open a file with a name based on the name of the input file,
2869 ** but with a different (specified) suffix, and return a pointer
2871 PRIVATE FILE *file_open(
2878 if( lemp->outname ) free(lemp->outname);
2879 lemp->outname = file_makename(lemp, suffix);
2880 fp = fopen(lemp->outname,mode);
2881 if( fp==0 && *mode=='w' ){
2882 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2889 /* Duplicate the input file without comments and without actions
2891 void Reprint(struct lemon *lemp)
2895 int i, j, maxlen, len, ncolumns, skip;
2896 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2898 for(i=0; i<lemp->nsymbol; i++){
2899 sp = lemp->symbols[i];
2900 len = lemonStrlen(sp->name);
2901 if( len>maxlen ) maxlen = len;
2903 ncolumns = 76/(maxlen+5);
2904 if( ncolumns<1 ) ncolumns = 1;
2905 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2906 for(i=0; i<skip; i++){
2908 for(j=i; j<lemp->nsymbol; j+=skip){
2909 sp = lemp->symbols[j];
2910 assert( sp->index==j );
2911 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2915 for(rp=lemp->rule; rp; rp=rp->next){
2916 printf("%s",rp->lhs->name);
2917 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2919 for(i=0; i<rp->nrhs; i++){
2921 if( sp->type==MULTITERMINAL ){
2922 printf(" %s", sp->subsym[0]->name);
2923 for(j=1; j<sp->nsubsym; j++){
2924 printf("|%s", sp->subsym[j]->name);
2927 printf(" %s", sp->name);
2929 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2932 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2933 /* if( rp->code ) printf("\n %s",rp->code); */
2938 void ConfigPrint(FILE *fp, struct config *cfp)
2944 fprintf(fp,"%s ::=",rp->lhs->name);
2945 for(i=0; i<=rp->nrhs; i++){
2946 if( i==cfp->dot ) fprintf(fp," *");
2947 if( i==rp->nrhs ) break;
2949 if( sp->type==MULTITERMINAL ){
2950 fprintf(fp," %s", sp->subsym[0]->name);
2951 for(j=1; j<sp->nsubsym; j++){
2952 fprintf(fp,"|%s",sp->subsym[j]->name);
2955 fprintf(fp," %s", sp->name);
2963 PRIVATE void SetPrint(out,set,lemp)
2971 fprintf(out,"%12s[","");
2972 for(i=0; i<lemp->nterminal; i++){
2973 if( SetFind(set,i) ){
2974 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2981 /* Print a plink chain */
2982 PRIVATE void PlinkPrint(out,plp,tag)
2988 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
2989 ConfigPrint(out,plp->cfp);
2996 /* Print an action to the given file descriptor. Return FALSE if
2997 ** nothing was actually printed.
2999 int PrintAction(struct action *ap, FILE *fp, int indent){
3003 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
3006 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
3009 fprintf(fp,"%*s accept",indent,ap->sp->name);
3012 fprintf(fp,"%*s error",indent,ap->sp->name);
3015 fprintf(fp,"%*s reduce %-3d ** SR Parsing conflict **",
3016 indent,ap->sp->name,ap->x.rp->index);
3019 fprintf(fp,"%*s reduce %-3d ** RR Parsing conflict **",
3020 indent,ap->sp->name,ap->x.rp->index);
3023 fprintf(fp,"%*s shift %-3d ** SS Parsing conflict **",
3024 indent,ap->sp->name,ap->x.stp->statenum);
3027 if( showPrecedenceConflict ){
3028 fprintf(fp,"%*s shift %-3d -- dropped by precedence",
3029 indent,ap->sp->name,ap->x.stp->statenum);
3035 if( showPrecedenceConflict ){
3036 fprintf(fp,"%*s reduce %-3d -- dropped by precedence",
3037 indent,ap->sp->name,ap->x.rp->index);
3049 /* Generate the "y.output" log file */
3050 void ReportOutput(struct lemon *lemp)
3058 fp = file_open(lemp,".out","wb");
3060 for(i=0; i<lemp->nstate; i++){
3061 stp = lemp->sorted[i];
3062 fprintf(fp,"State %d:\n",stp->statenum);
3063 if( lemp->basisflag ) cfp=stp->bp;
3067 if( cfp->dot==cfp->rp->nrhs ){
3068 lemon_sprintf(buf,"(%d)",cfp->rp->index);
3069 fprintf(fp," %5s ",buf);
3073 ConfigPrint(fp,cfp);
3076 SetPrint(fp,cfp->fws,lemp);
3077 PlinkPrint(fp,cfp->fplp,"To ");
3078 PlinkPrint(fp,cfp->bplp,"From");
3080 if( lemp->basisflag ) cfp=cfp->bp;
3084 for(ap=stp->ap; ap; ap=ap->next){
3085 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3089 fprintf(fp, "----------------------------------------------------\n");
3090 fprintf(fp, "Symbols:\n");
3091 for(i=0; i<lemp->nsymbol; i++){
3095 sp = lemp->symbols[i];
3096 fprintf(fp, " %3d: %s", i, sp->name);
3097 if( sp->type==NONTERMINAL ){
3100 fprintf(fp, " <lambda>");
3102 for(j=0; j<lemp->nterminal; j++){
3103 if( sp->firstset && SetFind(sp->firstset, j) ){
3104 fprintf(fp, " %s", lemp->symbols[j]->name);
3114 /* Search for the file "name" which is in the same directory as
3115 ** the exacutable */
3116 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3118 const char *pathlist;
3125 cp = strrchr(argv0,'\\');
3127 cp = strrchr(argv0,'/');
3132 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3133 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3136 pathlist = getenv("PATH");
3137 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3138 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
3139 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3140 if( (pathbuf != 0) && (path!=0) ){
3141 pathbufptr = pathbuf;
3142 lemon_strcpy(pathbuf, pathlist);
3144 cp = strchr(pathbuf,':');
3145 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3148 lemon_sprintf(path,"%s/%s",pathbuf,name);
3150 if( c==0 ) pathbuf[0] = 0;
3151 else pathbuf = &cp[1];
3152 if( access(path,modemask)==0 ) break;
3160 /* Given an action, compute the integer value for that action
3161 ** which is to be put in the action table of the generated machine.
3162 ** Return negative if no action should be generated.
3164 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3168 case SHIFT: act = ap->x.stp->statenum; break;
3169 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3170 case ERROR: act = lemp->nstate + lemp->nrule; break;
3171 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3172 default: act = -1; break;
3177 #define LINESIZE 1000
3178 /* The next cluster of routines are for reading the template file
3179 ** and writing the results to the generated parser */
3180 /* The first function transfers data from "in" to "out" until
3181 ** a line is seen which begins with "%%". The line number is
3184 ** if name!=0, then any word that begin with "Parse" is changed to
3185 ** begin with *name instead.
3187 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3190 char line[LINESIZE];
3191 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3195 for(i=0; line[i]; i++){
3196 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3197 && (i==0 || !isalpha(line[i-1]))
3199 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3200 fprintf(out,"%s",name);
3206 fprintf(out,"%s",&line[iStart]);
3210 /* The next function finds the template file and opens it, returning
3211 ** a pointer to the opened file. */
3212 PRIVATE FILE *tplt_open(struct lemon *lemp)
3214 static char templatename[] = "lempar.c";
3220 /* first, see if user specified a template filename on the command line. */
3221 if (user_templatename != 0) {
3222 if( access(user_templatename,004)==-1 ){
3223 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3228 in = fopen(user_templatename,"rb");
3230 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3237 cp = strrchr(lemp->filename,'.');
3239 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3241 lemon_sprintf(buf,"%s.lt",lemp->filename);
3243 if( access(buf,004)==0 ){
3245 }else if( access(templatename,004)==0 ){
3246 tpltname = templatename;
3248 tpltname = pathsearch(lemp->argv0,templatename,0);
3251 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3256 in = fopen(tpltname,"rb");
3258 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3265 /* Print a #line directive line to the output file. */
3266 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3268 fprintf(out,"#line %d \"",lineno);
3270 if( *filename == '\\' ) putc('\\',out);
3271 putc(*filename,out);
3274 fprintf(out,"\"\n");
3277 /* Print a string to the file and keep the linenumber up to date */
3278 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3280 if( str==0 ) return;
3283 if( *str=='\n' ) (*lineno)++;
3286 if( str[-1]!='\n' ){
3290 if (!lemp->nolinenosflag) {
3291 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3297 ** The following routine emits code for the destructor for the
3300 void emit_destructor_code(
3308 if( sp->type==TERMINAL ){
3309 cp = lemp->tokendest;
3311 fprintf(out,"{\n"); (*lineno)++;
3312 }else if( sp->destructor ){
3313 cp = sp->destructor;
3314 fprintf(out,"{\n"); (*lineno)++;
3315 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
3316 }else if( lemp->vardest ){
3319 fprintf(out,"{\n"); (*lineno)++;
3321 assert( 0 ); /* Cannot happen */
3324 if( *cp=='$' && cp[1]=='$' ){
3325 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3329 if( *cp=='\n' ) (*lineno)++;
3332 fprintf(out,"\n"); (*lineno)++;
3333 if (!lemp->nolinenosflag) {
3334 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3336 fprintf(out,"}\n"); (*lineno)++;
3341 ** Return TRUE (non-zero) if the given symbol has a destructor.
3343 int has_destructor(struct symbol *sp, struct lemon *lemp)
3346 if( sp->type==TERMINAL ){
3347 ret = lemp->tokendest!=0;
3349 ret = lemp->vardest!=0 || sp->destructor!=0;
3355 ** Append text to a dynamically allocated string. If zText is 0 then
3356 ** reset the string to be empty again. Always return the complete text
3357 ** of the string (which is overwritten with each call).
3359 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3360 ** \000 terminator is stored. zText can contain up to two instances of
3361 ** %d. The values of p1 and p2 are written into the first and second
3364 ** If n==-1, then the previous character is overwritten.
3366 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3367 static char empty[1] = { 0 };
3369 static int alloced = 0;
3370 static int used = 0;
3382 n = lemonStrlen(zText);
3384 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3385 alloced = n + sizeof(zInt)*2 + used + 200;
3386 z = (char *) realloc(z, alloced);
3388 if( z==0 ) return empty;
3391 if( c=='%' && n>0 && zText[0]=='d' ){
3392 lemon_sprintf(zInt, "%d", p1);
3394 lemon_strcpy(&z[used], zInt);
3395 used += lemonStrlen(&z[used]);
3407 ** zCode is a string that is the action associated with a rule. Expand
3408 ** the symbols in this string so that the refer to elements of the parser
3411 PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
3414 char lhsused = 0; /* True if the LHS element has been used */
3415 char used[MAXRHS]; /* True for each RHS element which is used */
3417 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3421 static char newlinestr[2] = { '\n', '\0' };
3422 rp->code = newlinestr;
3423 rp->line = rp->ruleline;
3426 append_str(0,0,0,0);
3428 /* This const cast is wrong but harmless, if we're careful. */
3429 for(cp=(char *)rp->code; *cp; cp++){
3430 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3432 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3435 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3436 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
3440 for(i=0; i<rp->nrhs; i++){
3441 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3442 if( cp!=rp->code && cp[-1]=='@' ){
3443 /* If the argument is of the form @X then substituted
3444 ** the token number of X, not the value of X */
3445 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3447 struct symbol *sp = rp->rhs[i];
3449 if( sp->type==MULTITERMINAL ){
3450 dtnum = sp->subsym[0]->dtnum;
3454 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3464 append_str(cp, 1, 0, 0);
3467 /* Check to make sure the LHS has been used */
3468 if( rp->lhsalias && !lhsused ){
3469 ErrorMsg(lemp->filename,rp->ruleline,
3470 "Label \"%s\" for \"%s(%s)\" is never used.",
3471 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3475 /* Generate destructor code for RHS symbols which are not used in the
3477 for(i=0; i<rp->nrhs; i++){
3478 if( rp->rhsalias[i] && !used[i] ){
3479 ErrorMsg(lemp->filename,rp->ruleline,
3480 "Label %s for \"%s(%s)\" is never used.",
3481 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3483 }else if( rp->rhsalias[i]==0 ){
3484 if( has_destructor(rp->rhs[i],lemp) ){
3485 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3486 rp->rhs[i]->index,i-rp->nrhs+1);
3488 /* No destructor defined for this term */
3493 cp = append_str(0,0,0,0);
3494 rp->code = Strsafe(cp?cp:"");
3499 ** Generate code which executes when the rule "rp" is reduced. Write
3500 ** the code to "out". Make sure lineno stays up-to-date.
3502 PRIVATE void emit_code(
3510 /* Generate code to do the reduce action */
3512 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
3513 fprintf(out,"{%s",rp->code);
3514 for(cp=rp->code; *cp; cp++){
3515 if( *cp=='\n' ) (*lineno)++;
3517 fprintf(out,"}\n"); (*lineno)++;
3518 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
3519 } /* End if( rp->code ) */
3525 ** Print the definition of the union used for the parser's data stack.
3526 ** This union contains fields for every possible data type for tokens
3527 ** and nonterminals. In the process of computing and printing this
3528 ** union, also set the ".dtnum" field of every terminal and nonterminal
3531 void print_stack_union(
3532 FILE *out, /* The output stream */
3533 struct lemon *lemp, /* The main info structure for this parser */
3534 int *plineno, /* Pointer to the line number */
3535 int mhflag /* True if generating makeheaders output */
3537 int lineno = *plineno; /* The line number of the output */
3538 char **types; /* A hash table of datatypes */
3539 int arraysize; /* Size of the "types" array */
3540 int maxdtlength; /* Maximum length of any ".datatype" field. */
3541 char *stddt; /* Standardized name for a datatype */
3542 int i,j; /* Loop counters */
3543 unsigned hash; /* For hashing the name of a type */
3544 const char *name; /* Name of the parser */
3546 /* Allocate and initialize types[] and allocate stddt[] */
3547 arraysize = lemp->nsymbol * 2;
3548 types = (char**)calloc( arraysize, sizeof(char*) );
3550 fprintf(stderr,"Out of memory.\n");
3553 for(i=0; i<arraysize; i++) types[i] = 0;
3555 if( lemp->vartype ){
3556 maxdtlength = lemonStrlen(lemp->vartype);
3558 for(i=0; i<lemp->nsymbol; i++){
3560 struct symbol *sp = lemp->symbols[i];
3561 if( sp->datatype==0 ) continue;
3562 len = lemonStrlen(sp->datatype);
3563 if( len>maxdtlength ) maxdtlength = len;
3565 stddt = (char*)malloc( maxdtlength*2 + 1 );
3567 fprintf(stderr,"Out of memory.\n");
3571 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3572 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3573 ** used for terminal symbols. If there is no %default_type defined then
3574 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3575 ** a datatype using the %type directive.
3577 for(i=0; i<lemp->nsymbol; i++){
3578 struct symbol *sp = lemp->symbols[i];
3580 if( sp==lemp->errsym ){
3581 sp->dtnum = arraysize+1;
3584 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
3589 if( cp==0 ) cp = lemp->vartype;
3591 while( isspace(*cp) ) cp++;
3592 while( *cp ) stddt[j++] = *cp++;
3593 while( j>0 && isspace(stddt[j-1]) ) j--;
3595 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
3600 for(j=0; stddt[j]; j++){
3601 hash = hash*53 + stddt[j];
3603 hash = (hash & 0x7fffffff)%arraysize;
3604 while( types[hash] ){
3605 if( strcmp(types[hash],stddt)==0 ){
3606 sp->dtnum = hash + 1;
3610 if( hash>=(unsigned)arraysize ) hash = 0;
3612 if( types[hash]==0 ){
3613 sp->dtnum = hash + 1;
3614 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
3615 if( types[hash]==0 ){
3616 fprintf(stderr,"Out of memory.\n");
3619 lemon_strcpy(types[hash],stddt);
3623 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3624 name = lemp->name ? lemp->name : "Parse";
3626 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3627 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3628 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3629 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3630 fprintf(out,"typedef union {\n"); lineno++;
3631 fprintf(out," int yyinit;\n"); lineno++;
3632 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3633 for(i=0; i<arraysize; i++){
3634 if( types[i]==0 ) continue;
3635 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3638 if( lemp->errsym->useCnt ){
3639 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3643 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3648 ** Return the name of a C datatype able to represent values between
3649 ** lwr and upr, inclusive.
3651 static const char *minimum_size_type(int lwr, int upr){
3654 return "unsigned char";
3655 }else if( upr<65535 ){
3656 return "unsigned short int";
3658 return "unsigned int";
3660 }else if( lwr>=-127 && upr<=127 ){
3661 return "signed char";
3662 }else if( lwr>=-32767 && upr<32767 ){
3670 ** Each state contains a set of token transaction and a set of
3671 ** nonterminal transactions. Each of these sets makes an instance
3672 ** of the following structure. An array of these structures is used
3673 ** to order the creation of entries in the yy_action[] table.
3676 struct state *stp; /* A pointer to a state */
3677 int isTkn; /* True to use tokens. False for non-terminals */
3678 int nAction; /* Number of actions */
3679 int iOrder; /* Original order of action sets */
3683 ** Compare to axset structures for sorting purposes
3685 static int axset_compare(const void *a, const void *b){
3686 struct axset *p1 = (struct axset*)a;
3687 struct axset *p2 = (struct axset*)b;
3689 c = p2->nAction - p1->nAction;
3691 c = p2->iOrder - p1->iOrder;
3693 assert( c!=0 || p1==p2 );
3698 ** Write text on "out" that describes the rule "rp".
3700 static void writeRuleText(FILE *out, struct rule *rp){
3702 fprintf(out,"%s ::=", rp->lhs->name);
3703 for(j=0; j<rp->nrhs; j++){
3704 struct symbol *sp = rp->rhs[j];
3705 if( sp->type!=MULTITERMINAL ){
3706 fprintf(out," %s", sp->name);
3709 fprintf(out," %s", sp->subsym[0]->name);
3710 for(k=1; k<sp->nsubsym; k++){
3711 fprintf(out,"|%s",sp->subsym[k]->name);
3718 /* Generate C source code for the parser */
3721 int mhflag /* Output in makeheaders format if true */
3724 char line[LINESIZE];
3729 struct acttab *pActtab;
3732 int mnTknOfst, mxTknOfst;
3733 int mnNtOfst, mxNtOfst;
3736 in = tplt_open(lemp);
3738 out = file_open(lemp,".c","wb");
3744 tplt_xfer(lemp->name,in,out,&lineno);
3746 /* Generate the include code, if any */
3747 tplt_print(out,lemp,lemp->include,&lineno);
3749 char *name = file_makename(lemp, ".h");
3750 fprintf(out,"#include \"%s\"\n", name); lineno++;
3753 tplt_xfer(lemp->name,in,out,&lineno);
3755 /* Generate #defines for all tokens */
3758 fprintf(out,"#if INTERFACE\n"); lineno++;
3759 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3761 for(i=1; i<lemp->nterminal; i++){
3762 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3765 fprintf(out,"#endif\n"); lineno++;
3767 tplt_xfer(lemp->name,in,out,&lineno);
3769 /* Generate the defines */
3770 fprintf(out,"#define YYCODETYPE %s\n",
3771 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
3772 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3773 fprintf(out,"#define YYACTIONTYPE %s\n",
3774 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
3775 if( lemp->wildcard ){
3776 fprintf(out,"#define YYWILDCARD %d\n",
3777 lemp->wildcard->index); lineno++;
3779 print_stack_union(out,lemp,&lineno,mhflag);
3780 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
3781 if( lemp->stacksize ){
3782 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3784 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3786 fprintf(out, "#endif\n"); lineno++;
3788 fprintf(out,"#if INTERFACE\n"); lineno++;
3790 name = lemp->name ? lemp->name : "Parse";
3791 if( lemp->arg && lemp->arg[0] ){
3793 i = lemonStrlen(lemp->arg);
3794 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3795 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
3796 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3797 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3798 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3799 name,lemp->arg,&lemp->arg[i]); lineno++;
3800 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3801 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
3803 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3804 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3805 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3806 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
3809 fprintf(out,"#endif\n"); lineno++;
3811 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3812 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3813 if( lemp->errsym->useCnt ){
3814 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3815 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3817 if( lemp->has_fallback ){
3818 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3820 tplt_xfer(lemp->name,in,out,&lineno);
3822 /* Generate the action table and its associates:
3824 ** yy_action[] A single table containing all actions.
3825 ** yy_lookahead[] A table containing the lookahead for each entry in
3826 ** yy_action. Used to detect hash collisions.
3827 ** yy_shift_ofst[] For each state, the offset into yy_action for
3828 ** shifting terminals.
3829 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3830 ** shifting non-terminals after a reduce.
3831 ** yy_default[] Default action for each state.
3834 /* Compute the actions on all states and count them up */
3835 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
3837 fprintf(stderr,"malloc failed\n");
3840 for(i=0; i<lemp->nstate; i++){
3841 stp = lemp->sorted[i];
3844 ax[i*2].nAction = stp->nTknAct;
3845 ax[i*2+1].stp = stp;
3846 ax[i*2+1].isTkn = 0;
3847 ax[i*2+1].nAction = stp->nNtAct;
3849 mxTknOfst = mnTknOfst = 0;
3850 mxNtOfst = mnNtOfst = 0;
3852 /* Compute the action table. In order to try to keep the size of the
3853 ** action table to a minimum, the heuristic of placing the largest action
3854 ** sets first is used.
3856 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
3857 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
3858 pActtab = acttab_alloc();
3859 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3862 for(ap=stp->ap; ap; ap=ap->next){
3864 if( ap->sp->index>=lemp->nterminal ) continue;
3865 action = compute_action(lemp, ap);
3866 if( action<0 ) continue;
3867 acttab_action(pActtab, ap->sp->index, action);
3869 stp->iTknOfst = acttab_insert(pActtab);
3870 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3871 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3873 for(ap=stp->ap; ap; ap=ap->next){
3875 if( ap->sp->index<lemp->nterminal ) continue;
3876 if( ap->sp->index==lemp->nsymbol ) continue;
3877 action = compute_action(lemp, ap);
3878 if( action<0 ) continue;
3879 acttab_action(pActtab, ap->sp->index, action);
3881 stp->iNtOfst = acttab_insert(pActtab);
3882 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3883 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
3888 /* Output the yy_action table */
3889 n = acttab_size(pActtab);
3890 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3891 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
3892 for(i=j=0; i<n; i++){
3893 int action = acttab_yyaction(pActtab, i);
3894 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
3895 if( j==0 ) fprintf(out," /* %5d */ ", i);
3896 fprintf(out, " %4d,", action);
3897 if( j==9 || i==n-1 ){
3898 fprintf(out, "\n"); lineno++;
3904 fprintf(out, "};\n"); lineno++;
3906 /* Output the yy_lookahead table */
3907 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
3908 for(i=j=0; i<n; i++){
3909 int la = acttab_yylookahead(pActtab, i);
3910 if( la<0 ) la = lemp->nsymbol;
3911 if( j==0 ) fprintf(out," /* %5d */ ", i);
3912 fprintf(out, " %4d,", la);
3913 if( j==9 || i==n-1 ){
3914 fprintf(out, "\n"); lineno++;
3920 fprintf(out, "};\n"); lineno++;
3922 /* Output the yy_shift_ofst[] table */
3923 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
3925 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3926 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3927 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3928 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
3929 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
3930 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
3931 for(i=j=0; i<n; i++){
3933 stp = lemp->sorted[i];
3934 ofst = stp->iTknOfst;
3935 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
3936 if( j==0 ) fprintf(out," /* %5d */ ", i);
3937 fprintf(out, " %4d,", ofst);
3938 if( j==9 || i==n-1 ){
3939 fprintf(out, "\n"); lineno++;
3945 fprintf(out, "};\n"); lineno++;
3947 /* Output the yy_reduce_ofst[] table */
3948 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
3950 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3951 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3952 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3953 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
3954 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
3955 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
3956 for(i=j=0; i<n; i++){
3958 stp = lemp->sorted[i];
3959 ofst = stp->iNtOfst;
3960 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
3961 if( j==0 ) fprintf(out," /* %5d */ ", i);
3962 fprintf(out, " %4d,", ofst);
3963 if( j==9 || i==n-1 ){
3964 fprintf(out, "\n"); lineno++;
3970 fprintf(out, "};\n"); lineno++;
3972 /* Output the default action table */
3973 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
3975 for(i=j=0; i<n; i++){
3976 stp = lemp->sorted[i];
3977 if( j==0 ) fprintf(out," /* %5d */ ", i);
3978 fprintf(out, " %4d,", stp->iDflt);
3979 if( j==9 || i==n-1 ){
3980 fprintf(out, "\n"); lineno++;
3986 fprintf(out, "};\n"); lineno++;
3987 tplt_xfer(lemp->name,in,out,&lineno);
3989 /* Generate the table of fallback tokens.
3991 if( lemp->has_fallback ){
3992 int mx = lemp->nterminal - 1;
3993 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3994 for(i=0; i<=mx; i++){
3995 struct symbol *p = lemp->symbols[i];
3996 if( p->fallback==0 ){
3997 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3999 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4000 p->name, p->fallback->name);
4005 tplt_xfer(lemp->name, in, out, &lineno);
4007 /* Generate a table containing the symbolic name of every symbol
4009 for(i=0; i<lemp->nsymbol; i++){
4010 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
4011 fprintf(out," %-15s",line);
4012 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4014 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4015 tplt_xfer(lemp->name,in,out,&lineno);
4017 /* Generate a table containing a text string that describes every
4018 ** rule in the rule set of the grammar. This information is used
4019 ** when tracing REDUCE actions.
4021 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4022 assert( rp->index==i );
4023 fprintf(out," /* %3d */ \"", i);
4024 writeRuleText(out, rp);
4025 fprintf(out,"\",\n"); lineno++;
4027 tplt_xfer(lemp->name,in,out,&lineno);
4029 /* Generate code which executes every time a symbol is popped from
4030 ** the stack while processing errors or while destroying the parser.
4031 ** (In other words, generate the %destructor actions)
4033 if( lemp->tokendest ){
4035 for(i=0; i<lemp->nsymbol; i++){
4036 struct symbol *sp = lemp->symbols[i];
4037 if( sp==0 || sp->type!=TERMINAL ) continue;
4039 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4042 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4044 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4045 if( i<lemp->nsymbol ){
4046 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4047 fprintf(out," break;\n"); lineno++;
4050 if( lemp->vardest ){
4051 struct symbol *dflt_sp = 0;
4053 for(i=0; i<lemp->nsymbol; i++){
4054 struct symbol *sp = lemp->symbols[i];
4055 if( sp==0 || sp->type==TERMINAL ||
4056 sp->index<=0 || sp->destructor!=0 ) continue;
4058 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4061 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4065 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4067 fprintf(out," break;\n"); lineno++;
4069 for(i=0; i<lemp->nsymbol; i++){
4070 struct symbol *sp = lemp->symbols[i];
4071 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4072 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4074 /* Combine duplicate destructors into a single case */
4075 for(j=i+1; j<lemp->nsymbol; j++){
4076 struct symbol *sp2 = lemp->symbols[j];
4077 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4078 && sp2->dtnum==sp->dtnum
4079 && strcmp(sp->destructor,sp2->destructor)==0 ){
4080 fprintf(out," case %d: /* %s */\n",
4081 sp2->index, sp2->name); lineno++;
4082 sp2->destructor = 0;
4086 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4087 fprintf(out," break;\n"); lineno++;
4089 tplt_xfer(lemp->name,in,out,&lineno);
4091 /* Generate code which executes whenever the parser stack overflows */
4092 tplt_print(out,lemp,lemp->overflow,&lineno);
4093 tplt_xfer(lemp->name,in,out,&lineno);
4095 /* Generate the table of rule information
4097 ** Note: This code depends on the fact that rules are number
4098 ** sequentually beginning with 0.
4100 for(rp=lemp->rule; rp; rp=rp->next){
4101 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4103 tplt_xfer(lemp->name,in,out,&lineno);
4105 /* Generate code which execution during each REDUCE action */
4106 for(rp=lemp->rule; rp; rp=rp->next){
4107 translate_code(lemp, rp);
4109 /* First output rules other than the default: rule */
4110 for(rp=lemp->rule; rp; rp=rp->next){
4111 struct rule *rp2; /* Other rules with the same action */
4112 if( rp->code==0 ) continue;
4113 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
4114 fprintf(out," case %d: /* ", rp->index);
4115 writeRuleText(out, rp);
4116 fprintf(out, " */\n"); lineno++;
4117 for(rp2=rp->next; rp2; rp2=rp2->next){
4118 if( rp2->code==rp->code ){
4119 fprintf(out," case %d: /* ", rp2->index);
4120 writeRuleText(out, rp2);
4121 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
4125 emit_code(out,rp,lemp,&lineno);
4126 fprintf(out," break;\n"); lineno++;
4129 /* Finally, output the default: rule. We choose as the default: all
4130 ** empty actions. */
4131 fprintf(out," default:\n"); lineno++;
4132 for(rp=lemp->rule; rp; rp=rp->next){
4133 if( rp->code==0 ) continue;
4134 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4135 fprintf(out," /* (%d) ", rp->index);
4136 writeRuleText(out, rp);
4137 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4139 fprintf(out," break;\n"); lineno++;
4140 tplt_xfer(lemp->name,in,out,&lineno);
4142 /* Generate code which executes if a parse fails */
4143 tplt_print(out,lemp,lemp->failure,&lineno);
4144 tplt_xfer(lemp->name,in,out,&lineno);
4146 /* Generate code which executes when a syntax error occurs */
4147 tplt_print(out,lemp,lemp->error,&lineno);
4148 tplt_xfer(lemp->name,in,out,&lineno);
4150 /* Generate code which executes when the parser accepts its input */
4151 tplt_print(out,lemp,lemp->accept,&lineno);
4152 tplt_xfer(lemp->name,in,out,&lineno);
4154 /* Append any addition code the user desires */
4155 tplt_print(out,lemp,lemp->extracode,&lineno);
4162 /* Generate a header file for the parser */
4163 void ReportHeader(struct lemon *lemp)
4167 char line[LINESIZE];
4168 char pattern[LINESIZE];
4171 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4173 in = file_open(lemp,".h","rb");
4176 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4177 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4178 prefix,lemp->symbols[i]->name,i);
4179 if( strcmp(line,pattern) ) break;
4181 nextChar = fgetc(in);
4183 if( i==lemp->nterminal && nextChar==EOF ){
4184 /* No change in the file. Don't rewrite it. */
4188 out = file_open(lemp,".h","wb");
4190 for(i=1; i<lemp->nterminal; i++){
4191 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
4198 /* Reduce the size of the action tables, if possible, by making use
4201 ** In this version, we take the most frequent REDUCE action and make
4202 ** it the default. Except, there is no default if the wildcard token
4203 ** is a possible look-ahead.
4205 void CompressTables(struct lemon *lemp)
4208 struct action *ap, *ap2;
4209 struct rule *rp, *rp2, *rbest;
4214 for(i=0; i<lemp->nstate; i++){
4215 stp = lemp->sorted[i];
4220 for(ap=stp->ap; ap; ap=ap->next){
4221 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4224 if( ap->type!=REDUCE ) continue;
4226 if( rp->lhsStart ) continue;
4227 if( rp==rbest ) continue;
4229 for(ap2=ap->next; ap2; ap2=ap2->next){
4230 if( ap2->type!=REDUCE ) continue;
4232 if( rp2==rbest ) continue;
4241 /* Do not make a default if the number of rules to default
4242 ** is not at least 1 or if the wildcard token is a possible
4245 if( nbest<1 || usesWildcard ) continue;
4248 /* Combine matching REDUCE actions into a single default */
4249 for(ap=stp->ap; ap; ap=ap->next){
4250 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4253 ap->sp = Symbol_new("{default}");
4254 for(ap=ap->next; ap; ap=ap->next){
4255 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
4257 stp->ap = Action_sort(stp->ap);
4263 ** Compare two states for sorting purposes. The smaller state is the
4264 ** one with the most non-terminal actions. If they have the same number
4265 ** of non-terminal actions, then the smaller is the one with the most
4268 static int stateResortCompare(const void *a, const void *b){
4269 const struct state *pA = *(const struct state**)a;
4270 const struct state *pB = *(const struct state**)b;
4273 n = pB->nNtAct - pA->nNtAct;
4275 n = pB->nTknAct - pA->nTknAct;
4277 n = pB->statenum - pA->statenum;
4286 ** Renumber and resort states so that states with fewer choices
4287 ** occur at the end. Except, keep state 0 as the first state.
4289 void ResortStates(struct lemon *lemp)
4295 for(i=0; i<lemp->nstate; i++){
4296 stp = lemp->sorted[i];
4297 stp->nTknAct = stp->nNtAct = 0;
4298 stp->iDflt = lemp->nstate + lemp->nrule;
4299 stp->iTknOfst = NO_OFFSET;
4300 stp->iNtOfst = NO_OFFSET;
4301 for(ap=stp->ap; ap; ap=ap->next){
4302 if( compute_action(lemp,ap)>=0 ){
4303 if( ap->sp->index<lemp->nterminal ){
4305 }else if( ap->sp->index<lemp->nsymbol ){
4308 stp->iDflt = compute_action(lemp, ap);
4313 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4314 stateResortCompare);
4315 for(i=0; i<lemp->nstate; i++){
4316 lemp->sorted[i]->statenum = i;
4321 /***************** From the file "set.c" ************************************/
4323 ** Set manipulation routines for the LEMON parser generator.
4326 static int size = 0;
4328 /* Set the set size */
4334 /* Allocate a new set */
4337 s = (char*)calloc( size, 1);
4339 extern void memory_error();
4345 /* Deallocate a set */
4346 void SetFree(char *s)
4351 /* Add a new element to the set. Return TRUE if the element was added
4352 ** and FALSE if it was already there. */
4353 int SetAdd(char *s, int e)
4356 assert( e>=0 && e<size );
4362 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4363 int SetUnion(char *s1, char *s2)
4367 for(i=0; i<size; i++){
4368 if( s2[i]==0 ) continue;
4376 /********************** From the file "table.c" ****************************/
4378 ** All code in this file has been automatically generated
4379 ** from a specification in the file
4381 ** by the associative array code building program "aagen".
4382 ** Do not edit this file! Instead, edit the specification
4383 ** file, then rerun aagen.
4386 ** Code for processing tables in the LEMON parser generator.
4389 PRIVATE unsigned strhash(const char *x)
4392 while( *x ) h = h*13 + *(x++);
4396 /* Works like strdup, sort of. Save a string in malloced memory, but
4397 ** keep strings in a table so that the same string is not in more
4400 const char *Strsafe(const char *y)
4405 if( y==0 ) return 0;
4406 z = Strsafe_find(y);
4407 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4408 lemon_strcpy(cpy,y);
4416 /* There is one instance of the following structure for each
4417 ** associative array of type "x1".
4420 int size; /* The number of available slots. */
4421 /* Must be a power of 2 greater than or */
4423 int count; /* Number of currently slots filled */
4424 struct s_x1node *tbl; /* The data stored here */
4425 struct s_x1node **ht; /* Hash table for lookups */
4428 /* There is one instance of this structure for every data element
4429 ** in an associative array of type "x1".
4431 typedef struct s_x1node {
4432 const char *data; /* The data */
4433 struct s_x1node *next; /* Next entry with the same hash */
4434 struct s_x1node **from; /* Previous link */
4437 /* There is only one instance of the array, which is the following */
4438 static struct s_x1 *x1a;
4440 /* Allocate a new associative array */
4441 void Strsafe_init(){
4443 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4447 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
4453 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4454 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4458 /* Insert a new record into the array. Return TRUE if successful.
4459 ** Prior data with the same key is NOT overwritten */
4460 int Strsafe_insert(const char *data)
4466 if( x1a==0 ) return 0;
4468 h = ph & (x1a->size-1);
4471 if( strcmp(np->data,data)==0 ){
4472 /* An existing entry with the same key is found. */
4473 /* Fail because overwrite is not allows. */
4478 if( x1a->count>=x1a->size ){
4479 /* Need to make the hash table bigger */
4482 array.size = size = x1a->size*2;
4483 array.count = x1a->count;
4484 array.tbl = (x1node*)calloc(size, sizeof(x1node) + sizeof(x1node*));
4485 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4486 array.ht = (x1node**)&(array.tbl[size]);
4487 for(i=0; i<size; i++) array.ht[i] = 0;
4488 for(i=0; i<x1a->count; i++){
4489 x1node *oldnp, *newnp;
4490 oldnp = &(x1a->tbl[i]);
4491 h = strhash(oldnp->data) & (size-1);
4492 newnp = &(array.tbl[i]);
4493 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4494 newnp->next = array.ht[h];
4495 newnp->data = oldnp->data;
4496 newnp->from = &(array.ht[h]);
4497 array.ht[h] = newnp;
4502 /* Insert the new data */
4503 h = ph & (x1a->size-1);
4504 np = &(x1a->tbl[x1a->count++]);
4506 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4507 np->next = x1a->ht[h];
4509 np->from = &(x1a->ht[h]);
4513 /* Return a pointer to data assigned to the given key. Return NULL
4514 ** if no such key. */
4515 const char *Strsafe_find(const char *key)
4520 if( x1a==0 ) return 0;
4521 h = strhash(key) & (x1a->size-1);
4524 if( strcmp(np->data,key)==0 ) break;
4527 return np ? np->data : 0;
4530 /* Return a pointer to the (terminal or nonterminal) symbol "x".
4531 ** Create a new symbol if this is the first time "x" has been seen.
4533 struct symbol *Symbol_new(const char *x)
4537 sp = Symbol_find(x);
4539 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
4541 sp->name = Strsafe(x);
4542 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4548 sp->lambda = LEMON_FALSE;
4553 Symbol_insert(sp,sp->name);
4559 /* Compare two symbols for sorting purposes. Return negative,
4560 ** zero, or positive if a is less then, equal to, or greater
4563 ** Symbols that begin with upper case letters (terminals or tokens)
4564 ** must sort before symbols that begin with lower case letters
4565 ** (non-terminals). And MULTITERMINAL symbols (created using the
4566 ** %token_class directive) must sort at the very end. Other than
4567 ** that, the order does not matter.
4569 ** We find experimentally that leaving the symbols in their original
4570 ** order (the order they appeared in the grammar file) gives the
4571 ** smallest parser tables in SQLite.
4573 int Symbolcmpp(const void *_a, const void *_b)
4575 const struct symbol *a = *(const struct symbol **) _a;
4576 const struct symbol *b = *(const struct symbol **) _b;
4577 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4578 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4579 return i1==i2 ? a->index - b->index : i1 - i2;
4582 /* There is one instance of the following structure for each
4583 ** associative array of type "x2".
4586 int size; /* The number of available slots. */
4587 /* Must be a power of 2 greater than or */
4589 int count; /* Number of currently slots filled */
4590 struct s_x2node *tbl; /* The data stored here */
4591 struct s_x2node **ht; /* Hash table for lookups */
4594 /* There is one instance of this structure for every data element
4595 ** in an associative array of type "x2".
4597 typedef struct s_x2node {
4598 struct symbol *data; /* The data */
4599 const char *key; /* The key */
4600 struct s_x2node *next; /* Next entry with the same hash */
4601 struct s_x2node **from; /* Previous link */
4604 /* There is only one instance of the array, which is the following */
4605 static struct s_x2 *x2a;
4607 /* Allocate a new associative array */
4610 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4614 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
4620 x2a->ht = (x2node**)&(x2a->tbl[128]);
4621 for(i=0; i<128; i++) x2a->ht[i] = 0;
4625 /* Insert a new record into the array. Return TRUE if successful.
4626 ** Prior data with the same key is NOT overwritten */
4627 int Symbol_insert(struct symbol *data, const char *key)
4633 if( x2a==0 ) return 0;
4635 h = ph & (x2a->size-1);
4638 if( strcmp(np->key,key)==0 ){
4639 /* An existing entry with the same key is found. */
4640 /* Fail because overwrite is not allows. */
4645 if( x2a->count>=x2a->size ){
4646 /* Need to make the hash table bigger */
4649 array.size = size = x2a->size*2;
4650 array.count = x2a->count;
4651 array.tbl = (x2node*)calloc(size, sizeof(x2node) + sizeof(x2node*));
4652 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4653 array.ht = (x2node**)&(array.tbl[size]);
4654 for(i=0; i<size; i++) array.ht[i] = 0;
4655 for(i=0; i<x2a->count; i++){
4656 x2node *oldnp, *newnp;
4657 oldnp = &(x2a->tbl[i]);
4658 h = strhash(oldnp->key) & (size-1);
4659 newnp = &(array.tbl[i]);
4660 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4661 newnp->next = array.ht[h];
4662 newnp->key = oldnp->key;
4663 newnp->data = oldnp->data;
4664 newnp->from = &(array.ht[h]);
4665 array.ht[h] = newnp;
4670 /* Insert the new data */
4671 h = ph & (x2a->size-1);
4672 np = &(x2a->tbl[x2a->count++]);
4675 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4676 np->next = x2a->ht[h];
4678 np->from = &(x2a->ht[h]);
4682 /* Return a pointer to data assigned to the given key. Return NULL
4683 ** if no such key. */
4684 struct symbol *Symbol_find(const char *key)
4689 if( x2a==0 ) return 0;
4690 h = strhash(key) & (x2a->size-1);
4693 if( strcmp(np->key,key)==0 ) break;
4696 return np ? np->data : 0;
4699 /* Return the n-th data. Return NULL if n is out of range. */
4700 struct symbol *Symbol_Nth(int n)
4702 struct symbol *data;
4703 if( x2a && n>0 && n<=x2a->count ){
4704 data = x2a->tbl[n-1].data;
4711 /* Return the size of the array */
4714 return x2a ? x2a->count : 0;
4717 /* Return an array of pointers to all data in the table.
4718 ** The array is obtained from malloc. Return NULL if memory allocation
4719 ** problems, or if the array is empty. */
4720 struct symbol **Symbol_arrayof()
4722 struct symbol **array;
4724 if( x2a==0 ) return 0;
4726 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
4728 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4733 /* Compare two configurations */
4734 int Configcmp(const char *_a,const char *_b)
4736 const struct config *a = (struct config *) _a;
4737 const struct config *b = (struct config *) _b;
4739 x = a->rp->index - b->rp->index;
4740 if( x==0 ) x = a->dot - b->dot;
4744 /* Compare two states */
4745 PRIVATE int statecmp(struct config *a, struct config *b)
4748 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4749 rc = a->rp->index - b->rp->index;
4750 if( rc==0 ) rc = a->dot - b->dot;
4760 PRIVATE unsigned statehash(struct config *a)
4764 h = h*571 + a->rp->index*37 + a->dot;
4770 /* Allocate a new state structure */
4771 struct state *State_new()
4773 struct state *newstate;
4774 newstate = (struct state *)calloc(1, sizeof(struct state) );
4775 MemoryCheck(newstate);
4779 /* There is one instance of the following structure for each
4780 ** associative array of type "x3".
4783 int size; /* The number of available slots. */
4784 /* Must be a power of 2 greater than or */
4786 int count; /* Number of currently slots filled */
4787 struct s_x3node *tbl; /* The data stored here */
4788 struct s_x3node **ht; /* Hash table for lookups */
4791 /* There is one instance of this structure for every data element
4792 ** in an associative array of type "x3".
4794 typedef struct s_x3node {
4795 struct state *data; /* The data */
4796 struct config *key; /* The key */
4797 struct s_x3node *next; /* Next entry with the same hash */
4798 struct s_x3node **from; /* Previous link */
4801 /* There is only one instance of the array, which is the following */
4802 static struct s_x3 *x3a;
4804 /* Allocate a new associative array */
4807 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4811 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
4817 x3a->ht = (x3node**)&(x3a->tbl[128]);
4818 for(i=0; i<128; i++) x3a->ht[i] = 0;
4822 /* Insert a new record into the array. Return TRUE if successful.
4823 ** Prior data with the same key is NOT overwritten */
4824 int State_insert(struct state *data, struct config *key)
4830 if( x3a==0 ) return 0;
4831 ph = statehash(key);
4832 h = ph & (x3a->size-1);
4835 if( statecmp(np->key,key)==0 ){
4836 /* An existing entry with the same key is found. */
4837 /* Fail because overwrite is not allows. */
4842 if( x3a->count>=x3a->size ){
4843 /* Need to make the hash table bigger */
4846 array.size = size = x3a->size*2;
4847 array.count = x3a->count;
4848 array.tbl = (x3node*)calloc(size, sizeof(x3node) + sizeof(x3node*));
4849 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4850 array.ht = (x3node**)&(array.tbl[size]);
4851 for(i=0; i<size; i++) array.ht[i] = 0;
4852 for(i=0; i<x3a->count; i++){
4853 x3node *oldnp, *newnp;
4854 oldnp = &(x3a->tbl[i]);
4855 h = statehash(oldnp->key) & (size-1);
4856 newnp = &(array.tbl[i]);
4857 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4858 newnp->next = array.ht[h];
4859 newnp->key = oldnp->key;
4860 newnp->data = oldnp->data;
4861 newnp->from = &(array.ht[h]);
4862 array.ht[h] = newnp;
4867 /* Insert the new data */
4868 h = ph & (x3a->size-1);
4869 np = &(x3a->tbl[x3a->count++]);
4872 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4873 np->next = x3a->ht[h];
4875 np->from = &(x3a->ht[h]);
4879 /* Return a pointer to data assigned to the given key. Return NULL
4880 ** if no such key. */
4881 struct state *State_find(struct config *key)
4886 if( x3a==0 ) return 0;
4887 h = statehash(key) & (x3a->size-1);
4890 if( statecmp(np->key,key)==0 ) break;
4893 return np ? np->data : 0;
4896 /* Return an array of pointers to all data in the table.
4897 ** The array is obtained from malloc. Return NULL if memory allocation
4898 ** problems, or if the array is empty. */
4899 struct state **State_arrayof()
4901 struct state **array;
4903 if( x3a==0 ) return 0;
4905 array = (struct state **)calloc(size, sizeof(struct state *));
4907 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4912 /* Hash a configuration */
4913 PRIVATE unsigned confighash(struct config *a)
4916 h = h*571 + a->rp->index*37 + a->dot;
4920 /* There is one instance of the following structure for each
4921 ** associative array of type "x4".
4924 int size; /* The number of available slots. */
4925 /* Must be a power of 2 greater than or */
4927 int count; /* Number of currently slots filled */
4928 struct s_x4node *tbl; /* The data stored here */
4929 struct s_x4node **ht; /* Hash table for lookups */
4932 /* There is one instance of this structure for every data element
4933 ** in an associative array of type "x4".
4935 typedef struct s_x4node {
4936 struct config *data; /* The data */
4937 struct s_x4node *next; /* Next entry with the same hash */
4938 struct s_x4node **from; /* Previous link */
4941 /* There is only one instance of the array, which is the following */
4942 static struct s_x4 *x4a;
4944 /* Allocate a new associative array */
4945 void Configtable_init(){
4947 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4951 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
4957 x4a->ht = (x4node**)&(x4a->tbl[64]);
4958 for(i=0; i<64; i++) x4a->ht[i] = 0;
4962 /* Insert a new record into the array. Return TRUE if successful.
4963 ** Prior data with the same key is NOT overwritten */
4964 int Configtable_insert(struct config *data)
4970 if( x4a==0 ) return 0;
4971 ph = confighash(data);
4972 h = ph & (x4a->size-1);
4975 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
4976 /* An existing entry with the same key is found. */
4977 /* Fail because overwrite is not allows. */
4982 if( x4a->count>=x4a->size ){
4983 /* Need to make the hash table bigger */
4986 array.size = size = x4a->size*2;
4987 array.count = x4a->count;
4988 array.tbl = (x4node*)calloc(size, sizeof(x4node) + sizeof(x4node*));
4989 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4990 array.ht = (x4node**)&(array.tbl[size]);
4991 for(i=0; i<size; i++) array.ht[i] = 0;
4992 for(i=0; i<x4a->count; i++){
4993 x4node *oldnp, *newnp;
4994 oldnp = &(x4a->tbl[i]);
4995 h = confighash(oldnp->data) & (size-1);
4996 newnp = &(array.tbl[i]);
4997 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4998 newnp->next = array.ht[h];
4999 newnp->data = oldnp->data;
5000 newnp->from = &(array.ht[h]);
5001 array.ht[h] = newnp;
5006 /* Insert the new data */
5007 h = ph & (x4a->size-1);
5008 np = &(x4a->tbl[x4a->count++]);
5010 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5011 np->next = x4a->ht[h];
5013 np->from = &(x4a->ht[h]);
5017 /* Return a pointer to data assigned to the given key. Return NULL
5018 ** if no such key. */
5019 struct config *Configtable_find(struct config *key)
5024 if( x4a==0 ) return 0;
5025 h = confighash(key) & (x4a->size-1);
5028 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
5031 return np ? np->data : 0;
5034 /* Remove all data from the table. Pass each data to the function "f"
5035 ** as it is removed. ("f" may be null to avoid this step.) */
5036 void Configtable_clear(int(*f)(struct config *))
5039 if( x4a==0 || x4a->count==0 ) return;
5040 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5041 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;