2 ** Copyright (c) 1991, 1994, 1997, 1998 D. Richard Hipp
4 ** This file contains all sources (including headers) to the LEMON
5 ** LALR(1) parser generator. The sources have been combined into a
6 ** single file to make it easy to include LEMON as part of another
9 ** This program is free software; you can redistribute it and/or
10 ** modify it under the terms of the GNU General Public
11 ** License as published by the Free Software Foundation; either
12 ** version 2 of the License, or (at your option) any later version.
14 ** This program is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 ** General Public License for more details.
19 ** You should have received a copy of the GNU General Public
20 ** License along with this library; if not, write to the
21 ** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ** Boston, MA 02111-1307, USA.
24 ** Author contact information:
26 ** http://www.hwaci.com/drh/
38 * Wrapper around "isupper()", "islower()", etc. to cast the argument to
39 * "unsigned char", so that they at least handle non-ASCII 8-bit characters
40 * (and don't provoke a pile of warnings from GCC).
42 #define safe_isupper(c) isupper((unsigned char)(c))
43 #define safe_islower(c) islower((unsigned char)(c))
44 #define safe_isalpha(c) isalpha((unsigned char)(c))
45 #define safe_isalnum(c) isalnum((unsigned char)(c))
46 #define safe_isspace(c) isspace((unsigned char)(c))
48 extern int access(const char *, int);
51 # if defined(_WIN32) || defined(WIN32)
56 /* #define PRIVATE static */
57 #define PRIVATE static
60 #define MAXRHS 5 /* Set low to exercise exception code */
65 char *msort(char *, char **, int (*)(const void *, const void *));
68 /********** From the file "struct.h" *************************************/
70 ** Principal data structures for the LEMON parser generator.
73 typedef enum {BOOL_FALSE=0, BOOL_TRUE} Boolean;
75 /* Symbols (terminals and nonterminals) of the grammar are stored
76 ** in the following: */
78 char *name; /* Name of the symbol */
79 int index; /* Index number for this symbol */
84 } type; /* Symbols are all either TERMINALS or NTs */
85 struct rule *rule; /* Linked list of rules of this (if an NT) */
86 struct symbol *fallback; /* fallback token in case this token doesn't parse */
87 int prec; /* Precedence if defined (-1 otherwise) */
93 } assoc; /* Associativity if predecence is defined */
94 char *firstset; /* First-set for all rules of this symbol */
95 Boolean lambda; /* True if NT and can generate an empty string */
96 char *destructor; /* Code which executes whenever this symbol is
97 ** popped from the stack during error processing */
98 int destructorln; /* Line number of destructor code */
99 char *datatype; /* The data type of information held by this
100 ** object. Only used if type==NONTERMINAL */
101 int dtnum; /* The data type number. In the parser, the value
102 ** stack is a union. The .yy%d element of this
103 ** union is the correct data type for this object */
104 /* The following fields are used by MULTITERMINALs only */
105 int nsubsym; /* Number of constituent symbols in the MULTI */
106 struct symbol **subsym; /* Array of constituent symbols */
109 /* Each production rule in the grammar is stored in the following
112 struct symbol *lhs; /* Left-hand side of the rule */
113 char *lhsalias; /* Alias for the LHS (NULL if none) */
114 int ruleline; /* Line number for the rule */
115 int nrhs; /* Number of RHS symbols */
116 struct symbol **rhs; /* The RHS symbols */
117 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
118 int line; /* Line number at which code begins */
119 char *code; /* The code executed when this rule is reduced */
120 struct symbol *precsym; /* Precedence symbol for this rule */
121 int index; /* An index number for this rule */
122 Boolean canReduce; /* True if this rule is ever reduced */
123 struct rule *nextlhs; /* Next rule with the same LHS */
124 struct rule *next; /* Next rule in the global list */
127 /* A configuration is a production rule of the grammar together with
128 ** a mark (dot) showing how much of that rule has been processed so far.
129 ** Configurations also contain a follow-set which is a list of terminal
130 ** symbols which are allowed to immediately follow the end of the rule.
131 ** Every configuration is recorded as an instance of the following: */
133 struct rule *rp; /* The rule upon which the configuration is based */
134 int dot; /* The parse point */
135 char *fws; /* Follow-set for this configuration only */
136 struct plink *fplp; /* Follow-set forward propagation links */
137 struct plink *bplp; /* Follow-set backwards propagation links */
138 struct state *stp; /* Pointer to state which contains this */
140 COMPLETE, /* The status is used during followset and */
141 INCOMPLETE /* shift computations */
143 struct config *next; /* Next configuration in the state */
144 struct config *bp; /* The next basis configuration */
147 /* Every shift or reduce operation is stored as one of the following */
149 struct symbol *sp; /* The look-ahead symbol */
155 CONFLICT, /* Was a reduce, but part of a conflict */
156 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
157 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
158 NOT_USED /* Deleted by compression */
161 struct state *stp; /* The new state, if a shift */
162 struct rule *rp; /* The rule, if a reduce */
164 struct action *next; /* Next action for this state */
165 struct action *collide; /* Next action with the same hash */
168 /* Each state of the generated parser's finite state machine
169 ** is encoded as an instance of the following structure. */
171 struct config *bp; /* The basis configurations for this state */
172 struct config *cfp; /* All configurations in this set */
173 int statenum; /* Sequencial number for this state */
174 struct action *ap; /* Array of actions for this state */
175 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
176 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
177 int iDflt; /* Default action */
179 #define NO_OFFSET (-2147483647)
181 /* A followset propagation link indicates that the contents of one
182 ** configuration followset should be propagated to another whenever
183 ** the first changes. */
185 struct config *cfp; /* The configuration to which linked */
186 struct plink *next; /* The next propagate link */
189 /* The state vector for the entire parser generator is recorded as
190 ** follows. (LEMON uses no global variables and makes little use of
191 ** static variables. Fields in the following structure can be thought
192 ** of as begin global variables in the program.) */
194 struct state **sorted; /* Table of states sorted by state number */
195 struct rule *rule; /* List of all rules */
196 int nstate; /* Number of states */
197 int nrule; /* Number of rules */
198 int nsymbol; /* Number of terminal and nonterminal symbols */
199 int nterminal; /* Number of terminal symbols */
200 struct symbol **symbols; /* Sorted array of pointers to symbols */
201 int errorcnt; /* Number of errors */
202 struct symbol *errsym; /* The error symbol */
203 char *name; /* Name of the generated parser */
204 char *arg; /* Declaration of the 3th argument to parser */
205 char *tokentype; /* Type of terminal symbols in the parser stack */
206 char *vartype; /* The default type of non-terminal symbols */
207 char *start; /* Name of the start symbol for the grammar */
208 char *stacksize; /* Size of the parser stack */
209 char *include; /* Code to put at the start of the C file */
210 int includeln; /* Line number for start of include code */
211 char *error; /* Code to execute when an error is seen */
212 int errorln; /* Line number for start of error code */
213 char *overflow; /* Code to execute on a stack overflow */
214 int overflowln; /* Line number for start of overflow code */
215 char *failure; /* Code to execute on parser failure */
216 int failureln; /* Line number for start of failure code */
217 char *accept; /* Code to execute when the parser excepts */
218 int acceptln; /* Line number for the start of accept code */
219 char *extracode; /* Code appended to the generated file */
220 int extracodeln; /* Line number for the start of the extra code */
221 char *tokendest; /* Code to execute to destroy token data */
222 int tokendestln; /* Line number for token destroyer code */
223 char *vardest; /* Code for the default non-terminal destructor */
224 int vardestln; /* Line number for default non-term destructor code*/
225 char *filename; /* Name of the input file */
226 char *basename; /* Basename of inputer file (no directory or path */
227 char *outname; /* Name of the current output file */
228 char *outdirname; /* Name of the output directory, specified by user */
229 char *templatename; /* Name of template file to use, specified by user */
230 char *tokenprefix; /* A prefix added to token names in the .h file */
231 int nconflict; /* Number of parsing conflicts */
232 int tablesize; /* Size of the parse tables */
233 int basisflag; /* Print only basis configurations */
234 int has_fallback; /* True if any %fallback is seen in the grammer */
235 char *argv0; /* Name of the program */
238 void memory_error(void);
239 #define MemoryCheck(X) if((X)==0){ \
243 /******** From the file "action.h" *************************************/
244 struct action *Action_new(void);
245 struct action *Action_sort(struct action *);
247 /********* From the file "assert.h" ************************************/
248 void myassert(const char *, int);
250 # define assert(X) if(!(X))myassert(__FILE__,__LINE__)
255 /********** From the file "build.h" ************************************/
256 void FindRulePrecedences(struct lemon *);
257 void FindFirstSets(struct lemon *);
258 void FindStates(struct lemon *);
259 void FindLinks(struct lemon *);
260 void FindFollowSets(struct lemon *);
261 void FindActions(struct lemon *);
263 /********* From the file "configlist.h" *********************************/
264 void Configlist_init(void);
265 struct config *Configlist_add(struct rule *, int);
266 struct config *Configlist_addbasis(struct rule *, int);
267 void Configlist_closure(struct lemon *);
268 void Configlist_sort(void);
269 void Configlist_sortbasis(void);
270 struct config *Configlist_return(void);
271 struct config *Configlist_basis(void);
272 void Configlist_eat(struct config *);
273 void Configlist_reset(void);
275 /********* From the file "error.h" ***************************************/
277 void ErrorMsg( const char *, int, const char *, ... )
278 __attribute__((format (printf, 3, 4)));
280 void ErrorMsg( const char *, int, const char *, ... );
283 /****** From the file "option.h" ******************************************/
285 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
286 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
291 int optinit(char**,struct s_options*,FILE*);
293 char *get_optarg(int);
294 void get_opterr(int);
297 /******** From the file "parse.h" *****************************************/
298 void Parse(struct lemon *lemp);
300 /********* From the file "plink.h" ***************************************/
301 struct plink *Plink_new(void);
302 void Plink_add(struct plink **, struct config *);
303 void Plink_copy(struct plink **, struct plink *);
304 void Plink_delete(struct plink *);
306 /********** From the file "report.h" *************************************/
307 void Reprint(struct lemon *);
308 void ReportOutput(struct lemon *);
309 void ReportTable(struct lemon *, int);
310 void ReportHeader(struct lemon *);
311 void CompressTables(struct lemon *);
312 void ResortStates(struct lemon *);
314 /********** From the file "set.h" ****************************************/
315 void SetSize(int N); /* All sets will be of size N */
316 char *SetNew(void); /* A new set for element 0..N */
317 void SetFree(char*); /* Deallocate a set */
319 int SetAdd(char*,int); /* Add element to a set */
320 int SetUnion(char *A,char *B); /* A <- A U B, thru element N */
322 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
324 /**************** From the file "table.h" *********************************/
326 ** All code in this file has been automatically generated
327 ** from a specification in the file
329 ** by the associative array code building program "aagen".
330 ** Do not edit this file! Instead, edit the specification
331 ** file, then rerun aagen.
334 ** Code for processing tables in the LEMON parser generator.
337 /* Routines for handling a strings */
339 char *Strsafe(const char *);
341 void Strsafe_init(void);
342 int Strsafe_insert(char *);
343 char *Strsafe_find(const char *);
345 /* Routines for handling symbols of the grammar */
347 struct symbol *Symbol_new(const char *x);
348 int Symbolcmpp(const void *, const void *);
349 void Symbol_init(void);
350 int Symbol_insert(struct symbol *, char *);
351 struct symbol *Symbol_find(const char *);
352 struct symbol *Symbol_Nth(int);
353 int Symbol_count(void);
354 struct symbol **Symbol_arrayof(void);
356 /* Routines to manage the state table */
358 int Configcmp(const void *, const void *);
359 struct state *State_new(void);
360 void State_init(void);
361 int State_insert(struct state *, struct config *);
362 struct state *State_find(struct config *);
363 struct state **State_arrayof(void);
365 /* Routines used for efficiency in Configlist_add */
367 void Configtable_init(void);
368 int Configtable_insert(struct config *);
369 struct config *Configtable_find(struct config *);
370 void Configtable_clear(int(*)(struct config *));
371 /****************** From the file "action.c" *******************************/
373 ** Routines processing parser actions in the LEMON parser generator.
376 /* Allocate a new parser action */
377 struct action *Action_new(void){
378 static struct action *freelist = 0;
384 freelist = (struct action *)malloc( sizeof(struct action)*amt );
386 fprintf(stderr,"Unable to allocate memory for a new parser action.");
389 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
390 freelist[amt-1].next = 0;
393 freelist = freelist->next;
397 /* Compare two actions */
398 static int actioncmp(const void *ap1_arg, const void *ap2_arg)
400 const struct action *ap1 = ap1_arg, *ap2 = ap2_arg;
402 rc = ap1->sp->index - ap2->sp->index;
403 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
405 assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
406 assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
407 rc = ap1->x.rp->index - ap2->x.rp->index;
412 /* Sort parser actions */
413 struct action *Action_sort(struct action *ap)
415 ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp);
419 void Action_add(struct action **app, enum e_action type, struct symbol *sp,
429 new->x.stp = (struct state *)arg;
431 new->x.rp = (struct rule *)arg;
434 /********************** New code to implement the "acttab" module ***********/
436 ** This module implements routines use to construct the yy_action[] table.
440 ** The state of the yy_action table under construction is an instance of
441 ** the following structure
443 typedef struct acttab acttab;
445 int nAction; /* Number of used slots in aAction[] */
446 int nActionAlloc; /* Slots allocated for aAction[] */
448 int lookahead; /* Value of the lookahead token */
449 int action; /* Action to take on the given lookahead */
450 } *aAction, /* The yy_action[] table under construction */
451 *aLookahead; /* A single new transaction set */
452 int mnLookahead; /* Minimum aLookahead[].lookahead */
453 int mnAction; /* Action associated with mnLookahead */
454 int mxLookahead; /* Maximum aLookahead[].lookahead */
455 int nLookahead; /* Used slots in aLookahead[] */
456 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
459 /* Return the number of entries in the yy_action table */
460 #define acttab_size(X) ((X)->nAction)
462 /* The value for the N-th entry in yy_action */
463 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
465 /* The value for the N-th entry in yy_lookahead */
466 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
468 /* Free all memory associated with the given acttab */
469 void acttab_free(acttab *p){
471 free( p->aLookahead );
475 /* Allocate a new acttab structure */
476 acttab *acttab_alloc(void){
477 acttab *p = malloc( sizeof(*p) );
479 fprintf(stderr,"Unable to allocate memory for a new acttab.");
482 memset(p, 0, sizeof(*p));
486 /* Add a new action to the current transaction set
488 void acttab_action(acttab *p, int lookahead, int action){
489 if( p->nLookahead>=p->nLookaheadAlloc ){
490 p->nLookaheadAlloc += 25;
491 p->aLookahead = realloc( p->aLookahead,
492 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
493 if( p->aLookahead==0 ){
494 fprintf(stderr,"malloc failed\n");
498 if( p->nLookahead==0 ){
499 p->mxLookahead = lookahead;
500 p->mnLookahead = lookahead;
501 p->mnAction = action;
503 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
504 if( p->mnLookahead>lookahead ){
505 p->mnLookahead = lookahead;
506 p->mnAction = action;
509 p->aLookahead[p->nLookahead].lookahead = lookahead;
510 p->aLookahead[p->nLookahead].action = action;
515 ** Add the transaction set built up with prior calls to acttab_action()
516 ** into the current action table. Then reset the transaction set back
517 ** to an empty set in preparation for a new round of acttab_action() calls.
519 ** Return the offset into the action table of the new transaction.
521 int acttab_insert(acttab *p){
523 assert( p->nLookahead>0 );
525 /* Make sure we have enough space to hold the expanded action table
526 ** in the worst case. The worst case occurs if the transaction set
527 ** must be appended to the current action table
529 n = p->mxLookahead + 1;
530 if( p->nAction + n >= p->nActionAlloc ){
531 int oldAlloc = p->nActionAlloc;
532 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
533 p->aAction = realloc( p->aAction,
534 sizeof(p->aAction[0])*p->nActionAlloc);
536 fprintf(stderr,"malloc failed\n");
539 for(i=oldAlloc; i<p->nActionAlloc; i++){
540 p->aAction[i].lookahead = -1;
541 p->aAction[i].action = -1;
545 /* Scan the existing action table looking for an offset where we can
546 ** insert the current transaction set. Fall out of the loop when that
547 ** offset is found. In the worst case, we fall out of the loop when
548 ** i reaches p->nAction, which means we append the new transaction set.
550 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
552 for(i=0; i<p->nAction+p->mnLookahead; i++){
553 if( p->aAction[i].lookahead<0 ){
554 for(j=0; j<p->nLookahead; j++){
555 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
557 if( p->aAction[k].lookahead>=0 ) break;
559 if( j<p->nLookahead ) continue;
560 for(j=0; j<p->nAction; j++){
561 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
564 break; /* Fits in empty slots */
566 }else if( p->aAction[i].lookahead==p->mnLookahead ){
567 if( p->aAction[i].action!=p->mnAction ) continue;
568 for(j=0; j<p->nLookahead; j++){
569 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
570 if( k<0 || k>=p->nAction ) break;
571 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
572 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
574 if( j<p->nLookahead ) continue;
576 for(j=0; j<p->nAction; j++){
577 if( p->aAction[j].lookahead<0 ) continue;
578 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
580 if( n==p->nLookahead ){
581 break; /* Same as a prior transaction set */
585 /* Insert transaction set at index i. */
586 for(j=0; j<p->nLookahead; j++){
587 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
588 p->aAction[k] = p->aLookahead[j];
589 if( k>=p->nAction ) p->nAction = k+1;
593 /* Return the offset that is added to the lookahead in order to get the
594 ** index into yy_action of the action */
595 return i - p->mnLookahead;
599 /********************** From the file "assert.c" ****************************/
601 ** A more efficient way of handling assertions.
603 void myassert(const char *file, int line)
605 fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
608 /********************** From the file "build.c" *****************************/
610 ** Routines to construction the finite state machine for the LEMON
614 /* Find a precedence symbol of every rule in the grammar.
616 ** Those rules which have a precedence symbol coded in the input
617 ** grammar using the "[symbol]" construct will already have the
618 ** rp->precsym field filled. Other rules take as their precedence
619 ** symbol the first RHS symbol with a defined precedence. If there
620 ** are not RHS symbols with a defined precedence, the precedence
621 ** symbol field is left blank.
623 void FindRulePrecedences(struct lemon *xp)
626 for(rp=xp->rule; rp; rp=rp->next){
627 if( rp->precsym==0 ){
629 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
630 struct symbol *sp = rp->rhs[i];
631 if( sp->type==MULTITERMINAL ){
632 for(j=0; j<sp->nsubsym; j++){
633 if( sp->subsym[j]->prec>=0 ){
634 rp->precsym = sp->subsym[j];
638 }else if( sp->prec>=0 ){
639 rp->precsym = rp->rhs[i];
646 /* Find all nonterminals which will generate the empty string.
647 ** Then go back and compute the first sets of every nonterminal.
648 ** The first set is the set of all terminal symbols which can begin
649 ** a string generated by that nonterminal.
651 void FindFirstSets(struct lemon *lemp)
657 for(i=0; i<lemp->nsymbol; i++){
658 lemp->symbols[i]->lambda = BOOL_FALSE;
660 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
661 lemp->symbols[i]->firstset = SetNew();
664 /* First compute all lambdas */
667 for(rp=lemp->rule; rp; rp=rp->next){
668 if( rp->lhs->lambda ) continue;
669 for(i=0; i<rp->nrhs; i++){
670 struct symbol *sp = rp->rhs[i];
671 if( sp->type!=TERMINAL || sp->lambda==BOOL_FALSE ) break;
674 rp->lhs->lambda = BOOL_TRUE;
680 /* Now compute all first sets */
682 struct symbol *s1, *s2;
684 for(rp=lemp->rule; rp; rp=rp->next){
686 for(i=0; i<rp->nrhs; i++){
688 if( s2->type==TERMINAL ){
689 progress += SetAdd(s1->firstset,s2->index);
691 }else if( s2->type==MULTITERMINAL ){
692 for(j=0; j<s2->nsubsym; j++){
693 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
697 if( s1->lambda==BOOL_FALSE ) break;
699 progress += SetUnion(s1->firstset,s2->firstset);
700 if( s2->lambda==BOOL_FALSE ) break;
708 /* Compute all LR(0) states for the grammar. Links
709 ** are added to between some states so that the LR(1) follow sets
710 ** can be computed later.
712 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
713 void FindStates(lemp)
721 /* Find the start symbol */
723 sp = Symbol_find(lemp->start);
725 ErrorMsg(lemp->filename,0,
726 "The specified start symbol \"%s\" is not \
727 in a nonterminal of the grammar. \"%s\" will be used as the start \
728 symbol instead.",lemp->start,lemp->rule->lhs->name);
730 sp = lemp->rule->lhs;
733 sp = lemp->rule->lhs;
736 /* Make sure the start symbol doesn't occur on the right-hand side of
737 ** any rule. Report an error if it does. (YACC would generate a new
738 ** start symbol in this case.) */
739 for(rp=lemp->rule; rp; rp=rp->next){
741 for(i=0; i<rp->nrhs; i++){
742 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
743 ErrorMsg(lemp->filename,0,
744 "The start symbol \"%s\" occurs on the \
745 right-hand side of a rule. This will result in a parser which \
746 does not work properly.",sp->name);
752 /* The basis configuration set for the first state
753 ** is all rules which have the start symbol as their
755 for(rp=sp->rule; rp; rp=rp->nextlhs){
756 struct config *newcfp;
757 newcfp = Configlist_addbasis(rp,0);
758 SetAdd(newcfp->fws,0);
761 /* Compute the first state. All other states will be
762 ** computed automatically during the computation of the first one.
763 ** The returned pointer to the first state is not used. */
764 (void)getstate(lemp);
768 /* Return a pointer to a state which is described by the configuration
769 ** list which has been built from calls to Configlist_add.
771 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
772 PRIVATE struct state *getstate(struct lemon *lemp)
774 struct config *cfp, *bp;
777 /* Extract the sorted basis of the new state. The basis was constructed
778 ** by prior calls to "Configlist_addbasis()". */
779 Configlist_sortbasis();
780 bp = Configlist_basis();
782 /* Get a state with the same basis */
783 stp = State_find(bp);
785 /* A state with the same basis already exists! Copy all the follow-set
786 ** propagation links from the state under construction into the
787 ** preexisting state, then return a pointer to the preexisting state */
788 struct config *x, *y;
789 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
790 Plink_copy(&y->bplp,x->bplp);
791 Plink_delete(x->fplp);
792 x->fplp = x->bplp = 0;
794 cfp = Configlist_return();
797 /* This really is a new state. Construct all the details */
798 Configlist_closure(lemp); /* Compute the configuration closure */
799 Configlist_sort(); /* Sort the configuration closure */
800 cfp = Configlist_return(); /* Get a pointer to the config list */
801 stp = State_new(); /* A new state structure */
803 stp->bp = bp; /* Remember the configuration basis */
804 stp->cfp = cfp; /* Remember the configuration closure */
805 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
806 stp->ap = 0; /* No actions, yet. */
807 State_insert(stp,stp->bp); /* Add to the state table */
808 buildshifts(lemp,stp); /* Recursively compute successor states */
814 ** Return true if two symbols are the same.
817 int same_symbol(struct symbol *a,struct symbol *b)
821 if( a->type!=MULTITERMINAL ) return 0;
822 if( b->type!=MULTITERMINAL ) return 0;
823 if( a->nsubsym!=b->nsubsym ) return 0;
824 for(i=0; i<a->nsubsym; i++){
825 if( a->subsym[i]!=b->subsym[i] ) return 0;
831 /* Construct all successor states to the given state. A "successor"
832 ** state is any state which can be reached by a shift action.
834 PRIVATE void buildshifts(
836 struct state *stp) /* The state from which successors are computed */
838 struct config *cfp; /* For looping thru the config closure of "stp" */
839 struct config *bcfp; /* For the inner loop on config closure of "stp" */
840 struct config *new; /* */
841 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
842 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
843 struct state *newstp; /* A pointer to a successor state */
845 /* Each configuration becomes complete after it contibutes to a successor
846 ** state. Initially, all configurations are incomplete */
847 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
849 /* Loop through all configurations of the state "stp" */
850 for(cfp=stp->cfp; cfp; cfp=cfp->next){
851 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
852 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
853 Configlist_reset(); /* Reset the new config set */
854 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
856 /* For every configuration in the state "stp" which has the symbol "sp"
857 ** following its dot, add the same configuration to the basis set under
858 ** construction but with the dot shifted one symbol to the right. */
859 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
860 if( bcfp->status==COMPLETE ) continue; /* Already used */
861 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
862 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
863 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
864 bcfp->status = COMPLETE; /* Mark this config as used */
865 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
866 Plink_add(&new->bplp,bcfp);
869 /* Get a pointer to the state described by the basis configuration set
870 ** constructed in the preceding loop */
871 newstp = getstate(lemp);
873 /* The state "newstp" is reached from the state "stp" by a shift action
874 ** on the symbol "sp" */
875 if( sp->type==MULTITERMINAL ){
877 for(i=0; i<sp->nsubsym; i++){
878 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
881 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
887 ** Construct the propagation links
889 void FindLinks(struct lemon *lemp)
892 struct config *cfp, *other;
896 /* Housekeeping detail:
897 ** Add to every propagate link a pointer back to the state to
898 ** which the link is attached. */
899 for(i=0; i<lemp->nstate; i++){
900 stp = lemp->sorted[i];
901 for(cfp=stp->cfp; cfp; cfp=cfp->next){
906 /* Convert all backlinks into forward links. Only the forward
907 ** links are used in the follow-set computation. */
908 for(i=0; i<lemp->nstate; i++){
909 stp = lemp->sorted[i];
910 for(cfp=stp->cfp; cfp; cfp=cfp->next){
911 for(plp=cfp->bplp; plp; plp=plp->next){
913 Plink_add(&other->fplp,cfp);
919 /* Compute all followsets.
921 ** A followset is the set of all symbols which can come immediately
922 ** after a configuration.
924 void FindFollowSets(struct lemon *lemp)
932 for(i=0; i<lemp->nstate; i++){
933 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
934 cfp->status = INCOMPLETE;
940 for(i=0; i<lemp->nstate; i++){
941 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
942 if( cfp->status==COMPLETE ) continue;
943 for(plp=cfp->fplp; plp; plp=plp->next){
944 change = SetUnion(plp->cfp->fws,cfp->fws);
946 plp->cfp->status = INCOMPLETE;
950 cfp->status = COMPLETE;
956 static int resolve_conflict(struct action *, struct action *,struct symbol *errsym);
958 /* Compute the reduce actions, and resolve conflicts.
960 void FindActions(struct lemon *lemp)
968 /* Add all of the reduce actions
969 ** A reduce action is added for each element of the followset of
970 ** a configuration which has its dot at the extreme right.
972 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
973 stp = lemp->sorted[i];
974 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
975 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
976 for(j=0; j<lemp->nterminal; j++){
977 if( SetFind(cfp->fws,j) ){
978 /* Add a reduce action to the state "stp" which will reduce by the
979 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
980 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
987 /* Add the accepting token */
989 sp = Symbol_find(lemp->start);
990 if( sp==0 ) sp = lemp->rule->lhs;
992 sp = lemp->rule->lhs;
994 /* Add to the first state (which is always the starting state of the
995 ** finite state machine) an action to ACCEPT if the lookahead is the
996 ** start nonterminal. */
997 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
999 /* Resolve conflicts */
1000 for(i=0; i<lemp->nstate; i++){
1001 struct action *ap, *nap;
1003 stp = lemp->sorted[i];
1005 stp->ap = Action_sort(stp->ap);
1006 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1007 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1008 /* The two actions "ap" and "nap" have the same lookahead.
1009 ** Figure out which one should be used */
1010 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1015 /* Report an error for each rule that can never be reduced. */
1016 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = BOOL_FALSE;
1017 for(i=0; i<lemp->nstate; i++){
1019 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1020 if( ap->type==REDUCE ) ap->x.rp->canReduce = BOOL_TRUE;
1023 for(rp=lemp->rule; rp; rp=rp->next){
1024 if( rp->canReduce ) continue;
1025 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1030 /* Resolve a conflict between the two given actions. If the
1031 ** conflict can't be resolve, return non-zero.
1034 ** To resolve a conflict, first look to see if either action
1035 ** is on an error rule. In that case, take the action which
1036 ** is not associated with the error rule. If neither or both
1037 ** actions are associated with an error rule, then try to
1038 ** use precedence to resolve the conflict.
1040 ** If either action is a SHIFT, then it must be apx. This
1041 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1043 static int resolve_conflict(
1046 struct symbol *errsym)
1048 struct symbol *spx, *spy;
1050 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1051 if( apx->type==SHIFT && apy->type==REDUCE ){
1053 spy = apy->x.rp->precsym;
1054 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1055 /* Not enough precedence information. */
1056 apy->type = CONFLICT;
1058 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1059 apy->type = RD_RESOLVED;
1060 }else if( spx->prec<spy->prec ){
1061 apx->type = SH_RESOLVED;
1062 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1063 apy->type = RD_RESOLVED; /* associativity */
1064 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1065 apx->type = SH_RESOLVED;
1067 assert( spx->prec==spy->prec && spx->assoc==NONE );
1068 apy->type = CONFLICT;
1071 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1072 spx = apx->x.rp->precsym;
1073 spy = apy->x.rp->precsym;
1074 if( spx==0 || spy==0 || spx->prec<0 ||
1075 spy->prec<0 || spx->prec==spy->prec ){
1076 apy->type = CONFLICT;
1078 }else if( spx->prec>spy->prec ){
1079 apy->type = RD_RESOLVED;
1080 }else if( spx->prec<spy->prec ){
1081 apx->type = RD_RESOLVED;
1085 apx->type==SH_RESOLVED ||
1086 apx->type==RD_RESOLVED ||
1087 apx->type==CONFLICT ||
1088 apy->type==SH_RESOLVED ||
1089 apy->type==RD_RESOLVED ||
1092 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1093 ** REDUCEs on the list. If we reach this point it must be because
1094 ** the parser conflict had already been resolved. */
1098 /********************* From the file "configlist.c" *************************/
1100 ** Routines to processing a configuration list and building a state
1101 ** in the LEMON parser generator.
1104 static struct config *freelist = 0; /* List of free configurations */
1105 static struct config *current = 0; /* Top of list of configurations */
1106 static struct config **currentend = 0; /* Last on list of configs */
1107 static struct config *basis = 0; /* Top of list of basis configs */
1108 static struct config **basisend = 0; /* End of list of basis configs */
1110 /* Return a pointer to a new configuration */
1111 PRIVATE struct config *newconfig(void){
1116 freelist = (struct config *)malloc( sizeof(struct config)*amt );
1118 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1121 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1122 freelist[amt-1].next = 0;
1125 freelist = freelist->next;
1129 /* The configuration "old" is no longer used */
1130 PRIVATE void deleteconfig(struct config *old)
1132 old->next = freelist;
1136 /* Initialized the configuration list builder */
1137 void Configlist_init(void){
1139 currentend = ¤t;
1146 /* Initialized the configuration list builder */
1147 void Configlist_reset(void){
1149 currentend = ¤t;
1152 Configtable_clear(0);
1156 /* Add another configuration to the configuration list */
1157 struct config *Configlist_add(
1158 struct rule *rp, /* The rule */
1159 int dot) /* Index into the RHS of the rule where the dot goes */
1161 struct config *cfp, model;
1163 assert( currentend!=0 );
1166 cfp = Configtable_find(&model);
1171 cfp->fws = SetNew();
1173 cfp->fplp = cfp->bplp = 0;
1177 currentend = &cfp->next;
1178 Configtable_insert(cfp);
1183 /* Add a basis configuration to the configuration list */
1184 struct config *Configlist_addbasis(struct rule *rp, int dot)
1186 struct config *cfp, model;
1188 assert( basisend!=0 );
1189 assert( currentend!=0 );
1192 cfp = Configtable_find(&model);
1197 cfp->fws = SetNew();
1199 cfp->fplp = cfp->bplp = 0;
1203 currentend = &cfp->next;
1205 basisend = &cfp->bp;
1206 Configtable_insert(cfp);
1211 /* Compute the closure of the configuration list */
1212 void Configlist_closure(struct lemon *lemp)
1214 struct config *cfp, *newcfp;
1215 struct rule *rp, *newrp;
1216 struct symbol *sp, *xsp;
1219 assert( currentend!=0 );
1220 for(cfp=current; cfp; cfp=cfp->next){
1223 if( dot>=rp->nrhs ) continue;
1225 if( sp->type==NONTERMINAL ){
1226 if( sp->rule==0 && sp!=lemp->errsym ){
1227 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1231 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1232 newcfp = Configlist_add(newrp,0);
1233 for(i=dot+1; i<rp->nrhs; i++){
1235 if( xsp->type==TERMINAL ){
1236 SetAdd(newcfp->fws,xsp->index);
1238 }else if( xsp->type==MULTITERMINAL ){
1240 for(k=0; k<xsp->nsubsym; k++){
1241 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1245 SetUnion(newcfp->fws,xsp->firstset);
1246 if( xsp->lambda==BOOL_FALSE ) break;
1249 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1256 /* Sort the configuration list */
1257 void Configlist_sort(void){
1258 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
1263 /* Sort the basis configuration list */
1264 void Configlist_sortbasis(void){
1265 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
1270 /* Return a pointer to the head of the configuration list and
1271 ** reset the list */
1272 struct config *Configlist_return(void){
1280 /* Return a pointer to the head of the configuration list and
1281 ** reset the list */
1282 struct config *Configlist_basis(void){
1290 /* Free all elements of the given configuration list */
1291 void Configlist_eat(struct config *cfp)
1293 struct config *nextcfp;
1294 for(; cfp; cfp=nextcfp){
1295 nextcfp = cfp->next;
1296 assert( cfp->fplp==0 );
1297 assert( cfp->bplp==0 );
1298 if( cfp->fws ) SetFree(cfp->fws);
1303 /***************** From the file "error.c" *********************************/
1305 ** Code for printing error message.
1308 /* Find a good place to break "msg" so that its length is at least "min"
1309 ** but no more than "max". Make the point as close to max as possible.
1311 static int findbreak(char *msg, int min, int max)
1315 for(i=spot=min; i<=max; i++){
1317 if( c=='\t' ) msg[i] = ' ';
1318 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1319 if( c==0 ){ spot = i; break; }
1320 if( c=='-' && i<max-1 ) spot = i+1;
1321 if( c==' ' ) spot = i;
1327 ** The error message is split across multiple lines if necessary. The
1328 ** splits occur at a space, if there is a space available near the end
1331 #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1332 #define LINEWIDTH 79 /* Max width of any output line */
1333 #define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1334 void ErrorMsg(const char *filename, int lineno, const char *format, ...)
1336 char errmsg[ERRMSGSIZE];
1337 char prefix[PREFIXLIMIT+10];
1342 int end, restart, base;
1344 va_start(ap, format);
1345 /* Prepare a prefix to be prepended to every output line */
1347 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1349 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1351 prefixsize = strlen(prefix);
1352 availablewidth = LINEWIDTH - prefixsize;
1354 /* Generate the error message */
1355 vsprintf(errmsg,format,ap);
1357 errmsgsize = strlen(errmsg);
1358 /* Remove trailing '\n's from the error message. */
1359 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1360 errmsg[--errmsgsize] = 0;
1363 /* Print the error message */
1365 while( errmsg[base]!=0 ){
1366 end = restart = findbreak(&errmsg[base],0,availablewidth);
1368 while( errmsg[restart]==' ' ) restart++;
1369 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1373 /**************** From the file "main.c" ************************************/
1375 ** Main program file for the LEMON parser generator.
1378 /* Report an out-of-memory condition and abort. This function
1379 ** is used mostly by the "MemoryCheck" macro in struct.h
1381 void memory_error(void){
1382 fprintf(stderr,"Out of memory. Aborting...\n");
1386 /* Locates the basename in a string possibly containing paths,
1387 * including forward-slash and backward-slash delimiters on Windows,
1388 * and allocates a new string containing just the basename.
1389 * Returns the pointer to that string.
1392 make_basename(char* fullname)
1397 /* Find the last forward slash */
1398 cp = strrchr(fullname, '/');
1401 /* On Windows, if no forward slash was found, look ofr
1404 cp = strrchr(fullname, '\\');
1408 new_string = malloc( strlen(fullname) );
1409 strcpy(new_string, fullname);
1412 /* skip the slash */
1414 new_string = malloc( strlen(cp) );
1415 strcpy(new_string, cp);
1421 static int nDefine = 0; /* Number of -D options on the command line */
1422 static char **azDefine = 0; /* Name of the -D macros */
1424 /* This routine is called with the argument to each -D command-line option.
1425 ** Add the macro defined to the azDefine array.
1427 static void handle_D_option(char *z){
1430 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1432 fprintf(stderr,"out of memory\n");
1435 paz = &azDefine[nDefine-1];
1436 *paz = malloc( strlen(z)+1 );
1438 fprintf(stderr,"out of memory\n");
1442 for(z=*paz; *z && *z!='='; z++){}
1446 /* The main program. Parse the command line and do it... */
1447 int main(int argc _U_, char **argv)
1449 static int version = 0;
1450 static int rpflag = 0;
1451 static int basisflag = 0;
1452 static int compress = 0;
1453 static int quiet = 0;
1454 static int statistics = 0;
1455 static int mhflag = 0;
1456 static char *outdirname = NULL;
1457 static char *templatename = NULL;
1458 static struct s_options options[] = {
1459 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1460 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1461 {OPT_STR, "d", (char*)&outdirname, "Output directory name."},
1462 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1463 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1464 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1465 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1466 {OPT_FLAG, "s", (char*)&statistics,
1467 "Print parser stats to standard output."},
1468 {OPT_STR, "t", (char*)&templatename, "Template file to use."},
1469 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1475 optinit(argv,options,stderr);
1477 printf("Lemon version 1.0\n"
1478 "Copyright 1991-1997 by D. Richard Hipp\n"
1479 "Freely distributable under the GNU Public License.\n"
1483 if( optnargs()!=1 ){
1484 fprintf(stderr,"Exactly one filename argument is required.\n");
1489 /* Initialize the machine */
1493 lem.argv0 = argv[0];
1494 lem.filename = get_optarg(0);
1495 lem.basisflag = basisflag;
1496 lem.has_fallback = 0;
1498 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
1501 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1502 lem.tokenprefix = lem.outname = lem.extracode = 0;
1506 lem.errsym = Symbol_new("error");
1507 lem.outdirname = outdirname;
1508 lem.templatename = templatename;
1509 lem.basename = make_basename(lem.filename);
1511 /* Parse the input file */
1513 if( lem.errorcnt ) exit(lem.errorcnt);
1515 fprintf(stderr,"Empty grammar.\n");
1519 /* Count and index the symbols of the grammar */
1520 lem.nsymbol = Symbol_count();
1521 Symbol_new("{default}");
1522 lem.symbols = Symbol_arrayof();
1523 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1524 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),Symbolcmpp);
1525 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1526 for(i=1; safe_isupper(lem.symbols[i]->name[0]); i++);
1529 /* Generate a reprint of the grammar, if requested on the command line */
1533 /* Initialize the size for all follow and first sets */
1534 SetSize(lem.nterminal);
1536 /* Find the precedence for every production rule (that has one) */
1537 FindRulePrecedences(&lem);
1539 /* Compute the lambda-nonterminals and the first-sets for every
1541 FindFirstSets(&lem);
1543 /* Compute all LR(0) states. Also record follow-set propagation
1544 ** links so that the follow-set can be computed later */
1547 lem.sorted = State_arrayof();
1549 /* Tie up loose ends on the propagation links */
1552 /* Compute the follow set of every reducible configuration */
1553 FindFollowSets(&lem);
1555 /* Compute the action tables */
1558 /* Compress the action tables */
1559 if( compress==0 ) CompressTables(&lem);
1561 /* Reorder and renumber the states so that states with fewer choices
1562 ** occur at the end. */
1565 /* Generate a report of the parser generated. (the "y.output" file) */
1566 if( !quiet ) ReportOutput(&lem);
1568 /* Generate the source code for the parser */
1569 ReportTable(&lem, mhflag);
1571 /* Produce a header file for use by the scanner. (This step is
1572 ** omitted if the "-m" option is used because makeheaders will
1573 ** generate the file for us.) */
1574 if( !mhflag ) ReportHeader(&lem);
1577 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1578 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1579 printf(" %d states, %d parser table entries, %d conflicts\n",
1580 lem.nstate, lem.tablesize, lem.nconflict);
1582 if( lem.nconflict ){
1583 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1585 exit(lem.errorcnt + lem.nconflict);
1586 return (lem.errorcnt + lem.nconflict);
1588 /******************** From the file "msort.c" *******************************/
1590 ** A generic merge-sort program.
1593 ** Let "ptr" be a pointer to some structure which is at the head of
1594 ** a null-terminated list. Then to sort the list call:
1596 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1598 ** In the above, "cmpfnc" is a pointer to a function which compares
1599 ** two instances of the structure and returns an integer, as in
1600 ** strcmp. The second argument is a pointer to the pointer to the
1601 ** second element of the linked list. This address is used to compute
1602 ** the offset to the "next" field within the structure. The offset to
1603 ** the "next" field must be constant for all structures in the list.
1605 ** The function returns a new pointer which is the head of the list
1613 ** Return a pointer to the next structure in the linked list.
1615 #define NEXT(A) (*(char**)(((char *)A)+offset))
1619 ** a: A sorted, null-terminated linked list. (May be null).
1620 ** b: A sorted, null-terminated linked list. (May be null).
1621 ** cmp: A pointer to the comparison function.
1622 ** offset: Offset in the structure to the "next" field.
1625 ** A pointer to the head of a sorted list containing the elements
1629 ** The "next" pointers for elements in the lists a and b are
1632 static char *merge(char *a, char *b, int (*cmp)(const void *, const void *),
1642 if( (*cmp)(a,b)<0 ){
1651 if( (*cmp)(a,b)<0 ){
1661 if( a ) NEXT(ptr) = a;
1669 ** list: Pointer to a singly-linked list of structures.
1670 ** next: Pointer to pointer to the second element of the list.
1671 ** cmp: A comparison function.
1674 ** A pointer to the head of a sorted list containing the elements
1675 ** orginally in list.
1678 ** The "next" pointers for elements in list are changed.
1681 char *msort(char *list, char **next, int (*cmp)(const void *, const void *))
1685 char *set[LISTSIZE];
1687 offset = (char *)next - (char *)list;
1688 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1693 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1694 ep = merge(ep,set[i],cmp,offset);
1700 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1703 /************************ From the file "option.c" **************************/
1705 static struct s_options *op;
1706 static FILE *errstream;
1708 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1711 ** Print the command line with a carrot pointing to the k-th character
1712 ** of the n-th field.
1714 static void errline(int n, int k, FILE *err)
1717 if( argv[0] ) fprintf(err,"%s",argv[0]);
1718 spcnt = strlen(argv[0]) + 1;
1719 for(i=1; i<n && argv[i]; i++){
1720 fprintf(err," %s",argv[i]);
1721 spcnt += strlen(argv[i])+1;
1724 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1726 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1728 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1733 ** Return the index of the N-th non-switch argument. Return -1
1734 ** if N is out of range.
1736 static int argindex(int n)
1740 if( argv!=0 && *argv!=0 ){
1741 for(i=1; argv[i]; i++){
1742 if( dashdash || !ISOPT(argv[i]) ){
1743 if( n==0 ) return i;
1746 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1752 static char emsg[] = "Command line syntax error: ";
1754 typedef void (opt_func_int_t)(int);
1755 typedef void (opt_func_double_t)(double);
1756 typedef void (opt_func_string_t)(char*);
1759 ** Process a flag command line argument.
1761 static int handleflags(int i, FILE *err)
1766 for(j=0; op[j].label; j++){
1767 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
1769 v = argv[i][0]=='-' ? 1 : 0;
1770 if( op[j].label==0 ){
1772 fprintf(err,"%sundefined option.\n",emsg);
1776 }else if( op[j].type==OPT_FLAG ){
1777 *((int*)op[j].arg) = v;
1778 }else if( op[j].type==OPT_FFLAG ){
1779 ((opt_func_int_t*)(op[j].arg))(v);
1780 }else if( op[j].type==OPT_FSTR ){
1781 (*(void(*)())(op[j].arg))(&argv[i][2]);
1784 fprintf(err,"%smissing argument on switch.\n",emsg);
1793 ** Process a command line switch which has an argument.
1795 static int handleswitch(int i, FILE *err)
1803 cp = strchr(argv[i],'=');
1806 for(j=0; op[j].label; j++){
1807 if( strcmp(argv[i],op[j].label)==0 ) break;
1810 if( op[j].label==0 ){
1812 fprintf(err,"%sundefined option.\n",emsg);
1818 switch( op[j].type ){
1822 fprintf(err,"%soption requires an argument.\n",emsg);
1829 dv = strtod(cp,&end);
1832 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
1833 errline(i,(int)(end-argv[i]),err);
1840 lv = strtol(cp,&end,0);
1843 fprintf(err,"%sillegal character in integer argument.\n",emsg);
1844 errline(i,(int)(end-argv[i]),err);
1854 switch( op[j].type ){
1859 *(double*)(op[j].arg) = dv;
1862 ((opt_func_double_t*)(op[j].arg))(dv);
1865 *(int*)(op[j].arg) = lv;
1868 ((opt_func_int_t*)(op[j].arg))(lv);
1871 *(char**)(op[j].arg) = sv;
1874 ((opt_func_string_t*)(op[j].arg))(sv);
1881 int optinit(char **a, struct s_options *o, FILE *err)
1887 if( argv && *argv && op ){
1889 for(i=1; argv[i]; i++){
1890 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1891 errcnt += handleflags(i,err);
1892 }else if( strchr(argv[i],'=') ){
1893 errcnt += handleswitch(i,err);
1898 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
1909 if( argv!=0 && argv[0]!=0 ){
1910 for(i=1; argv[i]; i++){
1911 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1912 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1918 char *get_optarg(int n)
1922 return i>=0 ? argv[i] : 0;
1925 void get_opterr(int n)
1929 if( i>=0 ) errline(i,0,errstream);
1932 void optprint(void){
1936 for(i=0; op[i].label; i++){
1937 len = strlen(op[i].label) + 1;
1938 switch( op[i].type ){
1944 len += 9; /* length of "<integer>" */
1948 len += 6; /* length of "<real>" */
1952 len += 8; /* length of "<string>" */
1955 if( len>max ) max = len;
1957 for(i=0; op[i].label; i++){
1958 switch( op[i].type ){
1961 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1965 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
1966 (int)(max-strlen(op[i].label)-9),"",op[i].message);
1970 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
1971 (int)(max-strlen(op[i].label)-6),"",op[i].message);
1975 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
1976 (int)(max-strlen(op[i].label)-8),"",op[i].message);
1981 /*********************** From the file "parse.c" ****************************/
1983 ** Input file parser for the LEMON parser generator.
1986 /* The state of the parser */
1988 char *filename; /* Name of the input file */
1989 int tokenlineno; /* Linenumber at which current token starts */
1990 int errorcnt; /* Number of errors so far */
1991 char *tokenstart; /* Text of current token */
1992 struct lemon *gp; /* Global state vector */
1995 WAITING_FOR_DECL_OR_RULE,
1996 WAITING_FOR_DECL_KEYWORD,
1997 WAITING_FOR_DECL_ARG,
1998 WAITING_FOR_PRECEDENCE_SYMBOL,
2008 RESYNC_AFTER_RULE_ERROR,
2009 RESYNC_AFTER_DECL_ERROR,
2010 WAITING_FOR_DESTRUCTOR_SYMBOL,
2011 WAITING_FOR_DATATYPE_SYMBOL,
2012 WAITING_FOR_FALLBACK_ID
2013 } state; /* The state of the parser */
2014 struct symbol *fallback; /* The fallback token */
2015 struct symbol *lhs; /* Left-hand side of current rule */
2016 char *lhsalias; /* Alias for the LHS */
2017 int nrhs; /* Number of right-hand side symbols seen */
2018 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2019 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2020 struct rule *prevrule; /* Previous rule parsed */
2021 char *declkeyword; /* Keyword of a declaration */
2022 char **declargslot; /* Where the declaration argument should be put */
2023 int *decllnslot; /* Where the declaration linenumber is put */
2024 enum e_assoc declassoc; /* Assign this association to decl arguments */
2025 int preccounter; /* Assign this precedence to decl arguments */
2026 struct rule *firstrule; /* Pointer to first rule in the grammar */
2027 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2030 /* Parse a single token */
2031 static void parseonetoken(struct pstate *psp)
2034 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2036 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2039 switch( psp->state ){
2042 psp->preccounter = 0;
2043 psp->firstrule = psp->lastrule = 0;
2045 /* Fall thru to next case */
2046 case WAITING_FOR_DECL_OR_RULE:
2048 psp->state = WAITING_FOR_DECL_KEYWORD;
2049 }else if( safe_islower(x[0]) ){
2050 psp->lhs = Symbol_new(x);
2053 psp->state = WAITING_FOR_ARROW;
2054 }else if( x[0]=='{' ){
2055 if( psp->prevrule==0 ){
2056 ErrorMsg(psp->filename,psp->tokenlineno,
2057 "There is not prior rule opon which to attach the code \
2058 fragment which begins on this line.");
2060 }else if( psp->prevrule->code!=0 ){
2061 ErrorMsg(psp->filename,psp->tokenlineno,
2062 "Code fragment beginning on this line is not the first \
2063 to follow the previous rule.");
2066 psp->prevrule->line = psp->tokenlineno;
2067 psp->prevrule->code = &x[1];
2069 }else if( x[0]=='[' ){
2070 psp->state = PRECEDENCE_MARK_1;
2072 ErrorMsg(psp->filename,psp->tokenlineno,
2073 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2078 case PRECEDENCE_MARK_1:
2079 if( !safe_isupper(x[0]) ){
2080 ErrorMsg(psp->filename,psp->tokenlineno,
2081 "The precedence symbol must be a terminal.");
2083 }else if( psp->prevrule==0 ){
2084 ErrorMsg(psp->filename,psp->tokenlineno,
2085 "There is no prior rule to assign precedence \"[%s]\".",x);
2087 }else if( psp->prevrule->precsym!=0 ){
2088 ErrorMsg(psp->filename,psp->tokenlineno,
2089 "Precedence mark on this line is not the first \
2090 to follow the previous rule.");
2093 psp->prevrule->precsym = Symbol_new(x);
2095 psp->state = PRECEDENCE_MARK_2;
2097 case PRECEDENCE_MARK_2:
2099 ErrorMsg(psp->filename,psp->tokenlineno,
2100 "Missing \"]\" on precedence mark.");
2103 psp->state = WAITING_FOR_DECL_OR_RULE;
2105 case WAITING_FOR_ARROW:
2106 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2107 psp->state = IN_RHS;
2108 }else if( x[0]=='(' ){
2109 psp->state = LHS_ALIAS_1;
2111 ErrorMsg(psp->filename,psp->tokenlineno,
2112 "Expected to see a \":\" following the LHS symbol \"%s\".",
2115 psp->state = RESYNC_AFTER_RULE_ERROR;
2119 if( safe_isalpha(x[0]) ){
2121 psp->state = LHS_ALIAS_2;
2123 ErrorMsg(psp->filename,psp->tokenlineno,
2124 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2127 psp->state = RESYNC_AFTER_RULE_ERROR;
2132 psp->state = LHS_ALIAS_3;
2134 ErrorMsg(psp->filename,psp->tokenlineno,
2135 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2137 psp->state = RESYNC_AFTER_RULE_ERROR;
2141 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2142 psp->state = IN_RHS;
2144 ErrorMsg(psp->filename,psp->tokenlineno,
2145 "Missing \"->\" following: \"%s(%s)\".",
2146 psp->lhs->name,psp->lhsalias);
2148 psp->state = RESYNC_AFTER_RULE_ERROR;
2154 rp = (struct rule *)malloc( sizeof(struct rule) +
2155 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Can't allocate enough memory for this rule.");
2163 rp->ruleline = psp->tokenlineno;
2164 rp->rhs = (struct symbol**)&rp[1];
2165 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2166 for(i=0; i<psp->nrhs; i++){
2167 rp->rhs[i] = psp->rhs[i];
2168 rp->rhsalias[i] = psp->alias[i];
2171 rp->lhsalias = psp->lhsalias;
2172 rp->nrhs = psp->nrhs;
2175 rp->index = psp->gp->nrule++;
2176 rp->nextlhs = rp->lhs->rule;
2179 if( psp->firstrule==0 ){
2180 psp->firstrule = psp->lastrule = rp;
2182 psp->lastrule->next = rp;
2187 psp->state = WAITING_FOR_DECL_OR_RULE;
2188 }else if( safe_isalpha(x[0]) ){
2189 if( psp->nrhs>=MAXRHS ){
2190 ErrorMsg(psp->filename,psp->tokenlineno,
2191 "Too many symbols on RHS or rule beginning at \"%s\".",
2194 psp->state = RESYNC_AFTER_RULE_ERROR;
2196 psp->rhs[psp->nrhs] = Symbol_new(x);
2197 psp->alias[psp->nrhs] = 0;
2200 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2201 struct symbol *msp = psp->rhs[psp->nrhs-1];
2202 if( msp->type!=MULTITERMINAL ){
2203 struct symbol *origsp = msp;
2204 msp = malloc(sizeof(*msp));
2205 memset(msp, 0, sizeof(*msp));
2206 msp->type = MULTITERMINAL;
2208 msp->subsym = malloc(sizeof(struct symbol*));
2209 msp->subsym[0] = origsp;
2210 msp->name = origsp->name;
2211 psp->rhs[psp->nrhs-1] = msp;
2214 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2215 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2216 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2217 ErrorMsg(psp->filename,psp->tokenlineno,
2218 "Cannot form a compound containing a non-terminal");
2221 }else if( x[0]=='(' && psp->nrhs>0 ){
2222 psp->state = RHS_ALIAS_1;
2224 ErrorMsg(psp->filename,psp->tokenlineno,
2225 "Illegal character on RHS of rule: \"%s\".",x);
2227 psp->state = RESYNC_AFTER_RULE_ERROR;
2231 if( safe_isalpha(x[0]) ){
2232 psp->alias[psp->nrhs-1] = x;
2233 psp->state = RHS_ALIAS_2;
2235 ErrorMsg(psp->filename,psp->tokenlineno,
2236 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2237 x,psp->rhs[psp->nrhs-1]->name);
2239 psp->state = RESYNC_AFTER_RULE_ERROR;
2244 psp->state = IN_RHS;
2246 ErrorMsg(psp->filename,psp->tokenlineno,
2247 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2249 psp->state = RESYNC_AFTER_RULE_ERROR;
2252 case WAITING_FOR_DECL_KEYWORD:
2253 if( safe_isalpha(x[0]) ){
2254 psp->declkeyword = x;
2255 psp->declargslot = 0;
2256 psp->decllnslot = 0;
2257 psp->state = WAITING_FOR_DECL_ARG;
2258 if( strcmp(x,"name")==0 ){
2259 psp->declargslot = &(psp->gp->name);
2260 }else if( strcmp(x,"include")==0 ){
2261 psp->declargslot = &(psp->gp->include);
2262 psp->decllnslot = &psp->gp->includeln;
2263 }else if( strcmp(x,"code")==0 ){
2264 psp->declargslot = &(psp->gp->extracode);
2265 psp->decllnslot = &psp->gp->extracodeln;
2266 }else if( strcmp(x,"token_destructor")==0 ){
2267 psp->declargslot = &psp->gp->tokendest;
2268 psp->decllnslot = &psp->gp->tokendestln;
2269 }else if( strcmp(x,"default_destructor")==0 ){
2270 psp->declargslot = &psp->gp->vardest;
2271 psp->decllnslot = &psp->gp->vardestln;
2272 }else if( strcmp(x,"token_prefix")==0 ){
2273 psp->declargslot = &psp->gp->tokenprefix;
2274 }else if( strcmp(x,"syntax_error")==0 ){
2275 psp->declargslot = &(psp->gp->error);
2276 psp->decllnslot = &psp->gp->errorln;
2277 }else if( strcmp(x,"parse_accept")==0 ){
2278 psp->declargslot = &(psp->gp->accept);
2279 psp->decllnslot = &psp->gp->acceptln;
2280 }else if( strcmp(x,"parse_failure")==0 ){
2281 psp->declargslot = &(psp->gp->failure);
2282 psp->decllnslot = &psp->gp->failureln;
2283 }else if( strcmp(x,"stack_overflow")==0 ){
2284 psp->declargslot = &(psp->gp->overflow);
2285 psp->decllnslot = &psp->gp->overflowln;
2286 }else if( strcmp(x,"extra_argument")==0 ){
2287 psp->declargslot = &(psp->gp->arg);
2288 }else if( strcmp(x,"token_type")==0 ){
2289 psp->declargslot = &(psp->gp->tokentype);
2290 }else if( strcmp(x,"default_type")==0 ){
2291 psp->declargslot = &(psp->gp->vartype);
2292 }else if( strcmp(x,"stack_size")==0 ){
2293 psp->declargslot = &(psp->gp->stacksize);
2294 }else if( strcmp(x,"start_symbol")==0 ){
2295 psp->declargslot = &(psp->gp->start);
2296 }else if( strcmp(x,"left")==0 ){
2298 psp->declassoc = LEFT;
2299 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2300 }else if( strcmp(x,"right")==0 ){
2302 psp->declassoc = RIGHT;
2303 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2304 }else if( strcmp(x,"nonassoc")==0 ){
2306 psp->declassoc = NONE;
2307 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2308 }else if( strcmp(x,"destructor")==0 ){
2309 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2310 }else if( strcmp(x,"type")==0 ){
2311 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2312 }else if( strcmp(x,"fallback")==0 ){
2314 psp->state = WAITING_FOR_FALLBACK_ID;
2316 ErrorMsg(psp->filename,psp->tokenlineno,
2317 "Unknown declaration keyword: \"%%%s\".",x);
2319 psp->state = RESYNC_AFTER_DECL_ERROR;
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Illegal declaration keyword: \"%s\".",x);
2325 psp->state = RESYNC_AFTER_DECL_ERROR;
2328 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2329 if( !safe_isalpha(x[0]) ){
2330 ErrorMsg(psp->filename,psp->tokenlineno,
2331 "Symbol name missing after %%destructor keyword");
2333 psp->state = RESYNC_AFTER_DECL_ERROR;
2335 struct symbol *sp = Symbol_new(x);
2336 psp->declargslot = &sp->destructor;
2337 psp->decllnslot = &sp->destructorln;
2338 psp->state = WAITING_FOR_DECL_ARG;
2341 case WAITING_FOR_DATATYPE_SYMBOL:
2342 if( !safe_isalpha(x[0]) ){
2343 ErrorMsg(psp->filename,psp->tokenlineno,
2344 "Symbol name missing after %%destructor keyword");
2346 psp->state = RESYNC_AFTER_DECL_ERROR;
2348 struct symbol *sp = Symbol_new(x);
2349 psp->declargslot = &sp->datatype;
2350 psp->decllnslot = 0;
2351 psp->state = WAITING_FOR_DECL_ARG;
2354 case WAITING_FOR_PRECEDENCE_SYMBOL:
2356 psp->state = WAITING_FOR_DECL_OR_RULE;
2357 }else if( safe_isupper(x[0]) ){
2361 ErrorMsg(psp->filename,psp->tokenlineno,
2362 "Symbol \"%s\" has already be given a precedence.",x);
2365 sp->prec = psp->preccounter;
2366 sp->assoc = psp->declassoc;
2369 ErrorMsg(psp->filename,psp->tokenlineno,
2370 "Can't assign a precedence to \"%s\".",x);
2374 case WAITING_FOR_DECL_ARG:
2375 if( (x[0]=='{' || x[0]=='\"' || safe_isalnum(x[0])) ){
2376 if( *(psp->declargslot)!=0 ){
2377 ErrorMsg(psp->filename,psp->tokenlineno,
2378 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2379 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2381 psp->state = RESYNC_AFTER_DECL_ERROR;
2383 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2384 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2385 psp->state = WAITING_FOR_DECL_OR_RULE;
2388 ErrorMsg(psp->filename,psp->tokenlineno,
2389 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2391 psp->state = RESYNC_AFTER_DECL_ERROR;
2394 case WAITING_FOR_FALLBACK_ID:
2396 psp->state = WAITING_FOR_DECL_OR_RULE;
2397 }else if( !safe_isupper(x[0]) ){
2398 ErrorMsg(psp->filename, psp->tokenlineno,
2399 "%%fallback argument \"%s\" should be a token", x);
2402 struct symbol *sp = Symbol_new(x);
2403 if( psp->fallback==0 ){
2405 }else if( sp->fallback ){
2406 ErrorMsg(psp->filename, psp->tokenlineno,
2407 "More than one fallback assigned to token %s", x);
2410 sp->fallback = psp->fallback;
2411 psp->gp->has_fallback = 1;
2415 case RESYNC_AFTER_RULE_ERROR:
2416 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2418 case RESYNC_AFTER_DECL_ERROR:
2419 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2420 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2425 /* Run the proprocessor over the input file text. The global variables
2426 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2427 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2428 ** comments them out. Text in between is also commented out as appropriate.
2430 static void preprocess_input(char *z){
2436 for(i=0; z[i]; i++){
2437 if( z[i]=='\n' ) lineno++;
2438 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2439 if( strncmp(&z[i],"%endif",6)==0 && safe_isspace(z[i+6]) ){
2443 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2446 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2447 }else if( (strncmp(&z[i],"%ifdef",6)==0 && safe_isspace(z[i+6]))
2448 || (strncmp(&z[i],"%ifndef",7)==0 && safe_isspace(z[i+7])) ){
2452 for(j=i+7; safe_isspace(z[j]); j++){}
2453 for(n=0; z[j+n] && !safe_isspace(z[j+n]); n++){}
2455 for(k=0; k<nDefine; k++){
2456 if( strncmp(azDefine[k],&z[j],n)==0 && (int)strlen(azDefine[k])==n ){
2461 if( z[i+3]=='n' ) exclude = !exclude;
2464 start_lineno = lineno;
2467 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2471 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2476 /* In spite of its name, this function is really a scanner. It read
2477 ** in the entire input file (all at once) then tokenizes it. Each
2478 ** token is passed to the function "parseonetoken" which builds all
2479 ** the appropriate data structures in the global state vector "gp".
2481 void Parse(struct lemon *gp)
2493 ps.filename = gp->filename;
2495 ps.state = INITIALIZE;
2497 /* Begin by reading the input file */
2498 fp = fopen(ps.filename,"rb");
2500 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2505 filesize = ftell(fp);
2507 /* XXX - what if filesize is bigger than the maximum size_t value? */
2508 filebuf = (char *)malloc( filesize+1 );
2510 ErrorMsg(ps.filename,0,"Can't allocate %ld of memory to hold this file.",
2515 if( fread(filebuf,1,filesize,fp)!=(size_t)filesize ){
2516 ErrorMsg(ps.filename,0,"Can't read in all %ld bytes of this file.",
2523 filebuf[filesize] = 0;
2525 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2526 preprocess_input(filebuf);
2528 /* Now scan the text of the input file */
2530 for(cp=filebuf; (c= *cp)!=0; ){
2531 if( c=='\n' ) lineno++; /* Keep track of the line number */
2532 if( safe_isspace(c) ){ cp++; continue; } /* Skip all white space */
2533 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2535 while( (c= *cp)!=0 && c!='\n' ) cp++;
2538 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2540 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2541 if( c=='\n' ) lineno++;
2547 ps.tokenstart = cp; /* Mark the beginning of the token */
2548 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2549 if( c=='\"' ){ /* String literals */
2551 while( (c= *cp)!=0 && c!='\"' ){
2552 if( c=='\n' ) lineno++;
2556 ErrorMsg(ps.filename,startline,
2557 "String starting on this line is not terminated before the end of the file.");
2563 }else if( c=='{' ){ /* A block of C code */
2566 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2567 if( c=='\n' ) lineno++;
2568 else if( c=='{' ) level++;
2569 else if( c=='}' ) level--;
2570 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2574 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2575 if( c=='\n' ) lineno++;
2579 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2581 while( (c= *cp)!=0 && c!='\n' ) cp++;
2583 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2584 char startchar, prevc;
2587 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2588 if( c=='\n' ) lineno++;
2589 if( prevc=='\\' ) prevc = 0;
2595 ErrorMsg(ps.filename,ps.tokenlineno,
2596 "C code starting on this line is not terminated before the end of the file.");
2602 }else if( safe_isalnum(c) ){ /* Identifiers */
2603 while( (c= *cp)!=0 && (safe_isalnum(c) || c=='_') ) cp++;
2605 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2608 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2610 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2612 }else{ /* All other (one character) operators */
2617 *cp = 0; /* Null terminate the token */
2618 parseonetoken(&ps); /* Parse the token */
2619 *cp = c; /* Restore the buffer */
2622 free(filebuf); /* Release the buffer after parsing */
2623 gp->rule = ps.firstrule;
2624 gp->errorcnt = ps.errorcnt;
2626 /*************************** From the file "plink.c" *********************/
2628 ** Routines processing configuration follow-set propagation links
2629 ** in the LEMON parser generator.
2631 static struct plink *plink_freelist = 0;
2633 /* Allocate a new plink */
2634 struct plink *Plink_new(void){
2637 if( plink_freelist==0 ){
2640 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2641 if( plink_freelist==0 ){
2643 "Unable to allocate memory for a new follow-set propagation link.\n");
2646 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2647 plink_freelist[amt-1].next = 0;
2649 new = plink_freelist;
2650 plink_freelist = plink_freelist->next;
2654 /* Add a plink to a plink list */
2655 void Plink_add(struct plink **plpp, struct config *cfp)
2664 /* Transfer every plink on the list "from" to the list "to" */
2665 void Plink_copy(struct plink **to, struct plink *from)
2667 struct plink *nextpl;
2669 nextpl = from->next;
2676 /* Delete every plink on the list */
2677 void Plink_delete(struct plink *plp)
2679 struct plink *nextpl;
2683 plp->next = plink_freelist;
2684 plink_freelist = plp;
2688 /*********************** From the file "report.c" **************************/
2690 ** Procedures for generating reports and tables in the LEMON parser generator.
2693 /* Generate a filename with the given suffix. Space to hold the
2694 ** name comes from malloc() and must be freed by the calling
2697 PRIVATE char *file_makename(char *pattern, const char *suffix)
2702 name = malloc( strlen(pattern) + strlen(suffix) + 5 );
2704 fprintf(stderr,"Can't allocate space for a filename.\n");
2707 strcpy(name,pattern);
2708 cp = strrchr(name,'.');
2710 strcat(name,suffix);
2714 /* Generate a filename with the given suffix. Uses only
2715 ** the basename of the input file, not the entire path. This
2716 ** is useful for creating output files when using outdirname.
2717 ** Space to hold this name comes from malloc() and must be
2718 ** freed by the calling function.
2720 PRIVATE char *file_makename_using_basename(struct lemon *lemp, const char *suffix)
2722 return file_makename(lemp->basename, suffix);
2725 /* Open a file with a name based on the name of the input file,
2726 ** but with a different (specified) suffix, and return a pointer
2727 ** to the stream. Prepend outdirname for both reads and writes, because
2728 ** the only time we read is when checking for an already-produced
2729 ** header file, which should exist in the output directory, not the
2730 ** input directory. If we ever need to file_open(,,"r") on the input
2731 ** side, we should add another arg to file_open() indicating which
2732 ** directory, ("input, "output", or "other") we should deal with.
2734 PRIVATE FILE *file_open(struct lemon *lemp, const char *suffix, const char *mode)
2739 if( lemp->outname ) free(lemp->outname);
2740 name = file_makename_using_basename(lemp, suffix);
2742 if ( lemp->outdirname != NULL ) {
2743 lemp->outname = malloc( strlen(lemp->outdirname) + strlen(name) + 2);
2744 if ( lemp->outname == 0 ) {
2745 fprintf(stderr, "Can't allocate space for dir/filename");
2748 strcpy(lemp->outname, lemp->outdirname);
2750 strcat(lemp->outname, "\\");
2752 strcat(lemp->outname, "/");
2754 strcat(lemp->outname, name);
2758 lemp->outname = name;
2761 fp = fopen(lemp->outname,mode);
2762 if( fp==0 && *mode=='w' ){
2763 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2770 /* Duplicate the input file without comments and without actions
2772 void Reprint(struct lemon *lemp)
2776 int i, j, maxlen, len, ncolumns, skip;
2777 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2779 for(i=0; i<lemp->nsymbol; i++){
2780 sp = lemp->symbols[i];
2781 len = strlen(sp->name);
2782 if( len>maxlen ) maxlen = len;
2784 ncolumns = 76/(maxlen+5);
2785 if( ncolumns<1 ) ncolumns = 1;
2786 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2787 for(i=0; i<skip; i++){
2789 for(j=i; j<lemp->nsymbol; j+=skip){
2790 sp = lemp->symbols[j];
2791 assert( sp->index==j );
2792 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2796 for(rp=lemp->rule; rp; rp=rp->next){
2797 printf("%s",rp->lhs->name);
2798 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2800 for(i=0; i<rp->nrhs; i++){
2802 printf(" %s", sp->name);
2803 if( sp->type==MULTITERMINAL ){
2804 for(j=1; j<sp->nsubsym; j++){
2805 printf("|%s", sp->subsym[j]->name);
2808 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2811 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2812 /* if( rp->code ) printf("\n %s",rp->code); */
2817 PRIVATE void ConfigPrint(FILE *fp, struct config *cfp)
2823 fprintf(fp,"%s ::=",rp->lhs->name);
2824 for(i=0; i<=rp->nrhs; i++){
2825 if( i==cfp->dot ) fprintf(fp," *");
2826 if( i==rp->nrhs ) break;
2828 fprintf(fp," %s", sp->name);
2829 if( sp->type==MULTITERMINAL ){
2830 for(j=1; j<sp->nsubsym; j++){
2831 fprintf(fp,"|%s",sp->subsym[j]->name);
2840 PRIVATE void SetPrint(FILE *out, char *set, struct lemon *lemp)
2845 fprintf(out,"%12s[","");
2846 for(i=0; i<lemp->nterminal; i++){
2847 if( SetFind(set,i) ){
2848 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2855 /* Print a plink chain */
2856 PRIVATE void PlinkPrint(FILE *out, struct plink *plp, char *tag)
2859 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
2860 ConfigPrint(out,plp->cfp);
2867 /* Print an action to the given file descriptor. Return FALSE if
2868 ** nothing was actually printed.
2870 PRIVATE int PrintAction(struct action *ap, FILE *fp, int indent){
2874 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
2877 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2880 fprintf(fp,"%*s accept",indent,ap->sp->name);
2883 fprintf(fp,"%*s error",indent,ap->sp->name);
2886 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2887 indent,ap->sp->name,ap->x.rp->index);
2898 /* Generate the "y.output" log file */
2899 void ReportOutput(struct lemon *lemp)
2907 fp = file_open(lemp,".out","wb");
2910 for(i=0; i<lemp->nstate; i++){
2911 stp = lemp->sorted[i];
2912 fprintf(fp,"State %d:\n",stp->statenum);
2913 if( lemp->basisflag ) cfp=stp->bp;
2917 if( cfp->dot==cfp->rp->nrhs ){
2918 sprintf(buf,"(%d)",cfp->rp->index);
2919 fprintf(fp," %5s ",buf);
2923 ConfigPrint(fp,cfp);
2926 SetPrint(fp,cfp->fws,lemp);
2927 PlinkPrint(fp,cfp->fplp,"To ");
2928 PlinkPrint(fp,cfp->bplp,"From");
2930 if( lemp->basisflag ) cfp=cfp->bp;
2934 for(ap=stp->ap; ap; ap=ap->next){
2935 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2943 /* Search for the file "name" which is in the same directory as
2944 ** the exacutable */
2945 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
2952 cp = strrchr(argv0,'\\');
2954 cp = strrchr(argv0,'/');
2959 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2960 if( path ) sprintf(path,"%s/%s",argv0,name);
2963 pathlist = getenv("PATH");
2964 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2965 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2968 cp = strchr(pathlist,':');
2969 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2972 sprintf(path,"%s/%s",pathlist,name);
2974 if( c==0 ) pathlist = "";
2975 else pathlist = &cp[1];
2976 if( access(path,modemask)==0 ) break;
2983 /* Given an action, compute the integer value for that action
2984 ** which is to be put in the action table of the generated machine.
2985 ** Return negative if no action should be generated.
2987 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
2991 case SHIFT: act = ap->x.stp->statenum; break;
2992 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2993 case ERROR: act = lemp->nstate + lemp->nrule; break;
2994 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2995 default: act = -1; break;
3000 #define LINESIZE 1000
3001 /* The next cluster of routines are for reading the template file
3002 ** and writing the results to the generated parser */
3003 /* The first function transfers data from "in" to "out" until
3004 ** a line is seen which begins with "%%". The line number is
3007 ** if name!=0, then any word that begin with "Parse" is changed to
3008 ** begin with *name instead.
3010 PRIVATE void tplt_xfer(const char *name, FILE *in, FILE *out, int *lineno)
3013 char line[LINESIZE];
3014 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3018 for(i=0; line[i] && i<LINESIZE; i++){
3019 if( line[i]=='P' && i<(LINESIZE-5) && strncmp(&line[i],"Parse",5)==0
3020 && (i==0 || !safe_isalpha(line[i-1]))
3022 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3023 fprintf(out,"%s",name);
3029 fprintf(out,"%s",&line[iStart]);
3033 /* The next function finds the template file and opens it, returning
3034 ** a pointer to the opened file. */
3035 PRIVATE FILE *tplt_open(struct lemon *lemp)
3037 static char templatename[] = "lempar.c";
3040 char *tpltname = NULL;
3043 if (lemp->templatename) {
3044 tpltname = strdup(lemp->templatename);
3047 cp = strrchr(lemp->filename,'.');
3050 sprintf(buf,"%.*s.lt",(int)(cp - lemp->filename),lemp->filename);
3052 sprintf(buf,"%s.lt",lemp->filename);
3054 if( access(buf,004)==0 ){
3056 }else if( access(templatename,004)==0 ){
3057 tpltname = templatename;
3059 tpltname = pathsearch(lemp->argv0,templatename,0);
3064 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3070 in = fopen(tpltname,"rb");
3074 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3082 /* Print a #line directive line to the output file. */
3083 PRIVATE void tplt_linedir(out,lineno,filename)
3088 fprintf(out,"#line %d \"",lineno);
3090 if( *filename == '\\' ) putc('\\',out);
3091 putc(*filename,out);
3094 fprintf(out,"\"\n");
3097 /* Print a string to the file and keep the linenumber up to date */
3098 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str,
3099 int strln, int *lineno)
3101 if( str==0 ) return;
3102 tplt_linedir(out,strln,lemp->filename);
3105 if( *str=='\n' ) (*lineno)++;
3109 if( str[-1]!='\n' ){
3113 tplt_linedir(out,*lineno+2,lemp->outname);
3119 ** The following routine emits code for the destructor for the
3122 PRIVATE void emit_destructor_code(FILE *out, struct symbol *sp, struct lemon *lemp,
3128 if( sp->type==TERMINAL ){
3129 cp = lemp->tokendest;
3131 tplt_linedir(out,lemp->tokendestln,lemp->filename);
3133 }else if( sp->destructor ){
3134 cp = sp->destructor;
3135 tplt_linedir(out,sp->destructorln,lemp->filename);
3137 }else if( lemp->vardest ){
3140 tplt_linedir(out,lemp->vardestln,lemp->filename);
3143 assert( 0 ); /* Cannot happen */
3146 if( *cp=='$' && cp[1]=='$' ){
3147 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3151 if( *cp=='\n' ) linecnt++;
3154 (*lineno) += 3 + linecnt;
3156 tplt_linedir(out,*lineno,lemp->outname);
3161 ** Return TRUE (non-zero) if the given symbol has a destructor.
3163 PRIVATE int has_destructor(struct symbol *sp, struct lemon *lemp)
3166 if( sp->type==TERMINAL ){
3167 ret = lemp->tokendest!=0;
3169 ret = lemp->vardest!=0 || sp->destructor!=0;
3175 ** Append text to a dynamically allocated string. If zText is 0 then
3176 ** reset the string to be empty again. Always return the complete text
3177 ** of the string (which is overwritten with each call).
3179 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3180 ** \000 terminator is stored. zText can contain up to two instances of
3181 ** %d. The values of p1 and p2 are written into the first and second
3184 ** If n==-1, then the previous character is overwritten.
3186 PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3188 static int alloced = 0;
3189 static int used = 0;
3204 if( n+(int)sizeof(zInt)*2+used >= alloced ){
3205 alloced = n + sizeof(zInt)*2 + used + 200;
3206 z = realloc(z, alloced);
3208 if( z==0 ) return "";
3211 if( c=='%' && zText[0]=='d' ){
3212 sprintf(zInt, "%d", p1);
3214 strcpy(&z[used], zInt);
3215 used += strlen(&z[used]);
3227 ** zCode is a string that is the action associated with a rule. Expand
3228 ** the symbols in this string so that the refer to elements of the parser
3231 PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
3234 char lhsused = 0; /* True if the LHS element has been used */
3235 char used[MAXRHS]; /* True for each RHS element which is used */
3237 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3240 append_str(0,0,0,0);
3241 for(cp=rp->code; *cp; cp++){
3242 if( safe_isalpha(*cp) && (cp==rp->code || (!safe_isalnum(cp[-1]) && cp[-1]!='_')) ){
3244 for(xp= &cp[1]; safe_isalnum(*xp) || *xp=='_'; xp++);
3247 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3248 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
3252 for(i=0; i<rp->nrhs; i++){
3253 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3254 if( cp!=rp->code && cp[-1]=='@' ){
3255 /* If the argument is of the form @X then substituted
3256 ** the token number of X, not the value of X */
3257 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3259 struct symbol *sp = rp->rhs[i];
3261 if( sp->type==MULTITERMINAL ){
3262 dtnum = sp->subsym[0]->dtnum;
3266 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3276 append_str(cp, 1, 0, 0);
3279 /* Check to make sure the LHS has been used */
3280 if( rp->lhsalias && !lhsused ){
3281 ErrorMsg(lemp->filename,rp->ruleline,
3282 "Label \"%s\" for \"%s(%s)\" is never used.",
3283 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3287 /* Generate destructor code for RHS symbols which are not used in the
3289 for(i=0; i<rp->nrhs; i++){
3290 if( rp->rhsalias[i] && !used[i] ){
3291 ErrorMsg(lemp->filename,rp->ruleline,
3292 "Label %s for \"%s(%s)\" is never used.",
3293 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3295 }else if( rp->rhsalias[i]==0 ){
3296 if( has_destructor(rp->rhs[i],lemp) ){
3297 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
3298 rp->rhs[i]->index,i-rp->nrhs+1);
3300 /* No destructor defined for this term */
3304 cp = append_str(0,0,0,0);
3305 rp->code = Strsafe(cp);
3309 ** Generate code which executes when the rule "rp" is reduced. Write
3310 ** the code to "out". Make sure lineno stays up-to-date.
3312 PRIVATE void emit_code(FILE *out, struct rule *rp, struct lemon *lemp,
3318 /* Generate code to do the reduce action */
3320 tplt_linedir(out,rp->line,lemp->filename);
3321 fprintf(out,"{%s",rp->code);
3322 for(cp=rp->code; *cp; cp++){
3323 if( *cp=='\n' ) linecnt++;
3325 (*lineno) += 3 + linecnt;
3327 tplt_linedir(out,*lineno,lemp->outname);
3328 } /* End if( rp->code ) */
3334 ** Print the definition of the union used for the parser's data stack.
3335 ** This union contains fields for every possible data type for tokens
3336 ** and nonterminals. In the process of computing and printing this
3337 ** union, also set the ".dtnum" field of every terminal and nonterminal
3340 PRIVATE void print_stack_union(
3341 FILE *out, /* The output stream */
3342 struct lemon *lemp, /* The main info structure for this parser */
3343 int *plineno, /* Pointer to the line number */
3344 int mhflag) /* True if generating makeheaders output */
3346 int lineno = *plineno; /* The line number of the output */
3347 char **types; /* A hash table of datatypes */
3348 int arraysize; /* Size of the "types" array */
3349 int maxdtlength; /* Maximum length of any ".datatype" field. */
3350 char *stddt; /* Standardized name for a datatype */
3351 int i,j; /* Loop counters */
3352 int hash; /* For hashing the name of a type */
3353 const char *name; /* Name of the parser */
3355 /* Allocate and initialize types[] and allocate stddt[] */
3356 arraysize = lemp->nsymbol * 2;
3357 types = (char**)malloc( arraysize * sizeof(char*) );
3358 for(i=0; i<arraysize; i++) types[i] = 0;
3360 if( lemp->vartype ){
3361 maxdtlength = strlen(lemp->vartype);
3363 for(i=0; i<lemp->nsymbol; i++){
3365 struct symbol *sp = lemp->symbols[i];
3366 if( sp->datatype==0 ) continue;
3367 len = strlen(sp->datatype);
3368 if( len>maxdtlength ) maxdtlength = len;
3370 stddt = (char*)malloc( maxdtlength*2 + 1 );
3371 if( types==0 || stddt==0 ){
3372 fprintf(stderr,"Out of memory.\n");
3376 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3377 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3378 ** used for terminal symbols. If there is no %default_type defined then
3379 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3380 ** a datatype using the %type directive.
3382 for(i=0; i<lemp->nsymbol; i++){
3383 struct symbol *sp = lemp->symbols[i];
3385 if( sp==lemp->errsym ){
3386 sp->dtnum = arraysize+1;
3389 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
3394 if( cp==0 ) cp = lemp->vartype;
3396 while( safe_isspace(*cp) ) cp++;
3397 while( *cp ) stddt[j++] = *cp++;
3398 while( j>0 && safe_isspace(stddt[j-1]) ) j--;
3401 for(j=0; stddt[j]; j++){
3402 hash = hash*53 + stddt[j];
3404 hash = (hash & 0x7fffffff)%arraysize;
3405 while( types[hash] ){
3406 if( strcmp(types[hash],stddt)==0 ){
3407 sp->dtnum = hash + 1;
3411 if( hash>=arraysize ) hash = 0;
3413 if( types[hash]==0 ){
3414 sp->dtnum = hash + 1;
3415 types[hash] = (char*)malloc( strlen(stddt)+1 );
3416 if( types[hash]==0 ){
3417 fprintf(stderr,"Out of memory.\n");
3420 strcpy(types[hash],stddt);
3424 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3425 name = lemp->name ? lemp->name : "Parse";
3427 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3428 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3429 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3430 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3431 fprintf(out,"typedef union {\n"); lineno++;
3432 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3433 for(i=0; i<arraysize; i++){
3434 if( types[i]==0 ) continue;
3435 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3438 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3441 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3446 ** Return the name of a C datatype able to represent values between
3447 ** lwr and upr, inclusive.
3449 static const char *minimum_size_type(int lwr, int upr){
3452 return "unsigned char";
3453 }else if( upr<65535 ){
3454 return "unsigned short int";
3456 return "unsigned int";
3458 }else if( lwr>=-127 && upr<=127 ){
3459 return "signed char";
3460 }else if( lwr>=-32767 && upr<32767 ){
3468 ** Each state contains a set of token transaction and a set of
3469 ** nonterminal transactions. Each of these sets makes an instance
3470 ** of the following structure. An array of these structures is used
3471 ** to order the creation of entries in the yy_action[] table.
3474 struct state *stp; /* A pointer to a state */
3475 int isTkn; /* True to use tokens. False for non-terminals */
3476 int nAction; /* Number of actions */
3480 ** Compare to axset structures for sorting purposes
3482 static int axset_compare(const void *a, const void *b){
3483 struct axset *p1 = (struct axset*)a;
3484 struct axset *p2 = (struct axset*)b;
3485 return p2->nAction - p1->nAction;
3488 /* Generate C source code for the parser */
3491 int mhflag) /* Output in makeheaders format if true */
3494 char line[LINESIZE];
3499 struct acttab *pActtab;
3502 int mnTknOfst, mxTknOfst;
3503 int mnNtOfst, mxNtOfst;
3506 in = tplt_open(lemp);
3508 out = file_open(lemp,".c","wb");
3514 tplt_xfer(lemp->name,in,out,&lineno);
3516 /* Generate the include code, if any */
3517 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3519 char *name = file_makename_using_basename(lemp, ".h");
3520 fprintf(out,"#include \"%s\"\n", name); lineno++;
3523 tplt_xfer(lemp->name,in,out,&lineno);
3525 /* Generate #defines for all tokens */
3528 fprintf(out,"#if INTERFACE\n"); lineno++;
3529 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3531 for(i=1; i<lemp->nterminal; i++){
3532 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3535 fprintf(out,"#endif\n"); lineno++;
3537 tplt_xfer(lemp->name,in,out,&lineno);
3539 /* Generate the defines */
3540 fprintf(out,"#define YYCODETYPE %s\n",
3541 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
3542 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3543 fprintf(out,"#define YYACTIONTYPE %s\n",
3544 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
3545 print_stack_union(out,lemp,&lineno,mhflag);
3546 if( lemp->stacksize ){
3547 if( atoi(lemp->stacksize)<=0 ){
3548 ErrorMsg(lemp->filename,0,
3549 "Illegal stack size: [%s]. The stack size should be an integer constant.",
3552 lemp->stacksize = "100";
3554 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3556 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3559 fprintf(out,"#if INTERFACE\n"); lineno++;
3561 name = lemp->name ? lemp->name : "Parse";
3562 if( lemp->arg && lemp->arg[0] ){
3564 i = strlen(lemp->arg);
3565 while( i>=1 && safe_isspace(lemp->arg[i-1]) ) i--;
3566 while( i>=1 && (safe_isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
3567 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3568 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3569 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3570 name,lemp->arg,&lemp->arg[i]); lineno++;
3571 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3572 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
3574 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3575 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3576 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3577 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
3580 fprintf(out,"#endif\n"); lineno++;
3582 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3583 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3584 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3585 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3586 if( lemp->has_fallback ){
3587 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3589 tplt_xfer(lemp->name,in,out,&lineno);
3591 /* Generate the action table and its associates:
3593 ** yy_action[] A single table containing all actions.
3594 ** yy_lookahead[] A table containing the lookahead for each entry in
3595 ** yy_action. Used to detect hash collisions.
3596 ** yy_shift_ofst[] For each state, the offset into yy_action for
3597 ** shifting terminals.
3598 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3599 ** shifting non-terminals after a reduce.
3600 ** yy_default[] Default action for each state.
3603 /* Compute the actions on all states and count them up */
3604 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3606 fprintf(stderr,"malloc failed\n");
3609 for(i=0; i<lemp->nstate; i++){
3610 stp = lemp->sorted[i];
3613 ax[i*2].nAction = stp->nTknAct;
3614 ax[i*2+1].stp = stp;
3615 ax[i*2+1].isTkn = 0;
3616 ax[i*2+1].nAction = stp->nNtAct;
3618 mxTknOfst = mnTknOfst = 0;
3619 mxNtOfst = mnNtOfst = 0;
3621 /* Compute the action table. In order to try to keep the size of the
3622 ** action table to a minimum, the heuristic of placing the largest action
3623 ** sets first is used.
3625 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
3626 pActtab = acttab_alloc();
3627 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3630 for(ap=stp->ap; ap; ap=ap->next){
3632 if( ap->sp->index>=lemp->nterminal ) continue;
3633 action = compute_action(lemp, ap);
3634 if( action<0 ) continue;
3635 acttab_action(pActtab, ap->sp->index, action);
3637 stp->iTknOfst = acttab_insert(pActtab);
3638 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3639 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3641 for(ap=stp->ap; ap; ap=ap->next){
3643 if( ap->sp->index<lemp->nterminal ) continue;
3644 if( ap->sp->index==lemp->nsymbol ) continue;
3645 action = compute_action(lemp, ap);
3646 if( action<0 ) continue;
3647 acttab_action(pActtab, ap->sp->index, action);
3649 stp->iNtOfst = acttab_insert(pActtab);
3650 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3651 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
3656 /* Output the yy_action table */
3657 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
3658 n = acttab_size(pActtab);
3659 for(i=j=0; i<n; i++){
3660 int action = acttab_yyaction(pActtab, i);
3661 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
3662 if( j==0 ) fprintf(out," /* %5d */ ", i);
3663 fprintf(out, " %4d,", action);
3664 if( j==9 || i==n-1 ){
3665 fprintf(out, "\n"); lineno++;
3671 fprintf(out, "};\n"); lineno++;
3673 /* Output the yy_lookahead table */
3674 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
3675 for(i=j=0; i<n; i++){
3676 int la = acttab_yylookahead(pActtab, i);
3677 if( la<0 ) la = lemp->nsymbol;
3678 if( j==0 ) fprintf(out," /* %5d */ ", i);
3679 fprintf(out, " %4d,", la);
3680 if( j==9 || i==n-1 ){
3681 fprintf(out, "\n"); lineno++;
3687 fprintf(out, "};\n"); lineno++;
3689 /* Output the yy_shift_ofst[] table */
3690 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
3692 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3693 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
3694 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
3695 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
3696 for(i=j=0; i<n; i++){
3698 stp = lemp->sorted[i];
3699 ofst = stp->iTknOfst;
3700 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
3701 if( j==0 ) fprintf(out," /* %5d */ ", i);
3702 fprintf(out, " %4d,", ofst);
3703 if( j==9 || i==n-1 ){
3704 fprintf(out, "\n"); lineno++;
3710 fprintf(out, "};\n"); lineno++;
3712 /* Output the yy_reduce_ofst[] table */
3713 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
3715 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3716 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
3717 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
3718 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
3719 for(i=j=0; i<n; i++){
3721 stp = lemp->sorted[i];
3722 ofst = stp->iNtOfst;
3723 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
3724 if( j==0 ) fprintf(out," /* %5d */ ", i);
3725 fprintf(out, " %4d,", ofst);
3726 if( j==9 || i==n-1 ){
3727 fprintf(out, "\n"); lineno++;
3733 fprintf(out, "};\n"); lineno++;
3735 /* Output the default action table */
3736 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
3738 for(i=j=0; i<n; i++){
3739 stp = lemp->sorted[i];
3740 if( j==0 ) fprintf(out," /* %5d */ ", i);
3741 fprintf(out, " %4d,", stp->iDflt);
3742 if( j==9 || i==n-1 ){
3743 fprintf(out, "\n"); lineno++;
3749 fprintf(out, "};\n"); lineno++;
3750 tplt_xfer(lemp->name,in,out,&lineno);
3752 /* Generate the table of fallback tokens.
3754 if( lemp->has_fallback ){
3755 for(i=0; i<lemp->nterminal; i++){
3756 struct symbol *p = lemp->symbols[i];
3757 if( p->fallback==0 ){
3758 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3760 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3761 p->name, p->fallback->name);
3766 tplt_xfer(lemp->name, in, out, &lineno);
3768 /* Generate a table containing the symbolic name of every symbol
3770 for(i=0; i<lemp->nsymbol; i++){
3771 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3772 fprintf(out," %-15s",line);
3773 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3775 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3776 tplt_xfer(lemp->name,in,out,&lineno);
3778 /* Generate a table containing a text string that describes every
3779 ** rule in the rule set of the grammer. This information is used
3780 ** when tracing REDUCE actions.
3782 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3783 assert( rp->index==i );
3784 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
3785 for(j=0; j<rp->nrhs; j++){
3786 struct symbol *sp = rp->rhs[j];
3787 fprintf(out," %s", sp->name);
3788 if( sp->type==MULTITERMINAL ){
3790 for(k=1; k<sp->nsubsym; k++){
3791 fprintf(out,"|%s",sp->subsym[k]->name);
3795 fprintf(out,"\",\n"); lineno++;
3797 tplt_xfer(lemp->name,in,out,&lineno);
3799 /* Generate code which executes every time a symbol is popped from
3800 ** the stack while processing errors or while destroying the parser.
3801 ** (In other words, generate the %destructor actions)
3803 if( lemp->tokendest ){
3804 for(i=0; i<lemp->nsymbol; i++){
3805 struct symbol *sp = lemp->symbols[i];
3806 if( sp==0 || sp->type!=TERMINAL ) continue;
3807 fprintf(out," case %d:\n",sp->index); lineno++;
3809 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3810 if( i<lemp->nsymbol ){
3811 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3812 fprintf(out," break;\n"); lineno++;
3815 if( lemp->vardest ){
3816 struct symbol *dflt_sp = 0;
3817 for(i=0; i<lemp->nsymbol; i++){
3818 struct symbol *sp = lemp->symbols[i];
3819 if( sp==0 || sp->type==TERMINAL ||
3820 sp->index<=0 || sp->destructor!=0 ) continue;
3821 fprintf(out," case %d:\n",sp->index); lineno++;
3825 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3826 fprintf(out," break;\n"); lineno++;
3829 for(i=0; i<lemp->nsymbol; i++){
3830 struct symbol *sp = lemp->symbols[i];
3831 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3832 fprintf(out," case %d:\n",sp->index); lineno++;
3834 /* Combine duplicate destructors into a single case */
3835 for(j=i+1; j<lemp->nsymbol; j++){
3836 struct symbol *sp2 = lemp->symbols[j];
3837 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3838 && sp2->dtnum==sp->dtnum
3839 && strcmp(sp->destructor,sp2->destructor)==0 ){
3840 fprintf(out," case %d:\n",sp2->index); lineno++;
3841 sp2->destructor = 0;
3845 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3846 fprintf(out," break;\n"); lineno++;
3848 tplt_xfer(lemp->name,in,out,&lineno);
3850 /* Generate code which executes whenever the parser stack overflows */
3851 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3852 tplt_xfer(lemp->name,in,out,&lineno);
3854 /* Generate the table of rule information
3856 ** Note: This code depends on the fact that rules are number
3857 ** sequentually beginning with 0.
3859 for(rp=lemp->rule; rp; rp=rp->next){
3860 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3862 tplt_xfer(lemp->name,in,out,&lineno);
3864 /* Generate code which execution during each REDUCE action */
3865 for(rp=lemp->rule; rp; rp=rp->next){
3866 if( rp->code ) translate_code(lemp, rp);
3868 for(rp=lemp->rule; rp; rp=rp->next){
3870 if( rp->code==0 ) continue;
3871 fprintf(out," case %d:\n",rp->index); lineno++;
3872 for(rp2=rp->next; rp2; rp2=rp2->next){
3873 if( rp2->code==rp->code ){
3874 fprintf(out," case %d:\n",rp2->index); lineno++;
3878 emit_code(out,rp,lemp,&lineno);
3879 fprintf(out," break;\n"); lineno++;
3881 tplt_xfer(lemp->name,in,out,&lineno);
3883 /* Generate code which executes if a parse fails */
3884 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3885 tplt_xfer(lemp->name,in,out,&lineno);
3887 /* Generate code which executes when a syntax error occurs */
3888 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3889 tplt_xfer(lemp->name,in,out,&lineno);
3891 /* Generate code which executes when the parser accepts its input */
3892 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3893 tplt_xfer(lemp->name,in,out,&lineno);
3895 /* Append any addition code the user desires */
3896 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3903 /* Generate a header file for the parser */
3904 void ReportHeader(struct lemon *lemp)
3908 char line[LINESIZE];
3909 char pattern[LINESIZE];
3912 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3914 in = file_open(lemp,".h","rb");
3916 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3917 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3918 if( strcmp(line,pattern) ) break;
3921 if( i==lemp->nterminal ){
3922 /* No change in the file. Don't rewrite it. */
3926 out = file_open(lemp,".h","wb");
3928 for(i=1; i<lemp->nterminal; i++){
3929 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3936 /* Reduce the size of the action tables, if possible, by making use
3939 ** In this version, we take the most frequent REDUCE action and make
3942 void CompressTables(struct lemon *lemp)
3945 struct action *ap, *ap2;
3946 struct rule *rp, *rp2, *rbest;
3950 for(i=0; i<lemp->nstate; i++){
3951 stp = lemp->sorted[i];
3955 for(ap=stp->ap; ap; ap=ap->next){
3956 if( ap->type!=REDUCE ) continue;
3958 if( rp==rbest ) continue;
3960 for(ap2=ap->next; ap2; ap2=ap2->next){
3961 if( ap2->type!=REDUCE ) continue;
3963 if( rp2==rbest ) continue;
3972 /* Do not make a default if the number of rules to default
3973 ** is not at least 1 */
3974 if( nbest<1 ) continue;
3977 /* Combine matching REDUCE actions into a single default */
3978 for(ap=stp->ap; ap; ap=ap->next){
3979 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3982 ap->sp = Symbol_new("{default}");
3983 for(ap=ap->next; ap; ap=ap->next){
3984 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
3986 stp->ap = Action_sort(stp->ap);
3992 ** Compare two states for sorting purposes. The smaller state is the
3993 ** one with the most non-terminal actions. If they have the same number
3994 ** of non-terminal actions, then the smaller is the one with the most
3997 static int stateResortCompare(const void *a, const void *b){
3998 const struct state *pA = *(const struct state**)a;
3999 const struct state *pB = *(const struct state**)b;
4002 n = pB->nNtAct - pA->nNtAct;
4004 n = pB->nTknAct - pA->nTknAct;
4011 ** Renumber and resort states so that states with fewer choices
4012 ** occur at the end. Except, keep state 0 as the first state.
4014 void ResortStates(lemp)
4021 for(i=0; i<lemp->nstate; i++){
4022 stp = lemp->sorted[i];
4023 stp->nTknAct = stp->nNtAct = 0;
4024 stp->iDflt = lemp->nstate + lemp->nrule;
4025 stp->iTknOfst = NO_OFFSET;
4026 stp->iNtOfst = NO_OFFSET;
4027 for(ap=stp->ap; ap; ap=ap->next){
4028 if( compute_action(lemp,ap)>=0 ){
4029 if( ap->sp->index<lemp->nterminal ){
4031 }else if( ap->sp->index<lemp->nsymbol ){
4034 stp->iDflt = compute_action(lemp, ap);
4039 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4040 stateResortCompare);
4041 for(i=0; i<lemp->nstate; i++){
4042 lemp->sorted[i]->statenum = i;
4047 /***************** From the file "set.c" ************************************/
4049 ** Set manipulation routines for the LEMON parser generator.
4052 static int size = 0;
4054 /* Set the set size */
4060 /* Allocate a new set */
4064 s = (char*)malloc( size );
4068 for(i=0; i<size; i++) s[i] = 0;
4072 /* Deallocate a set */
4073 void SetFree(char *s)
4078 /* Add a new element to the set. Return TRUE if the element was added
4079 ** and FALSE if it was already there. */
4080 int SetAdd(char *s, int e)
4088 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4089 int SetUnion(char *s1, char *s2)
4093 for(i=0; i<size; i++){
4094 if( s2[i]==0 ) continue;
4102 /********************** From the file "table.c" ****************************/
4104 ** All code in this file has been automatically generated
4105 ** from a specification in the file
4107 ** by the associative array code building program "aagen".
4108 ** Do not edit this file! Instead, edit the specification
4109 ** file, then rerun aagen.
4112 ** Code for processing tables in the LEMON parser generator.
4115 PRIVATE int strhash(const char *x)
4118 while( *x) h = h*13 + *(x++);
4122 /* Works like strdup, sort of. Save a string in malloced memory, but
4123 ** keep strings in a table so that the same string is not in more
4126 char *Strsafe(const char *y)
4130 z = Strsafe_find(y);
4131 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4139 /* There is one instance of the following structure for each
4140 ** associative array of type "x1".
4143 int size; /* The number of available slots. */
4144 /* Must be a power of 2 greater than or */
4146 int count; /* Number of currently slots filled */
4147 struct s_x1node *tbl; /* The data stored here */
4148 struct s_x1node **ht; /* Hash table for lookups */
4151 /* There is one instance of this structure for every data element
4152 ** in an associative array of type "x1".
4154 typedef struct s_x1node {
4155 char *data; /* The data */
4156 struct s_x1node *next; /* Next entry with the same hash */
4157 struct s_x1node **from; /* Previous link */
4160 /* There is only one instance of the array, which is the following */
4161 static struct s_x1 *x1a;
4163 /* Allocate a new associative array */
4164 void Strsafe_init(void){
4166 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4170 x1a->tbl = (x1node*)malloc(
4171 (sizeof(x1node) + sizeof(x1node*))*1024 );
4177 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4178 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4182 /* Insert a new record into the array. Return TRUE if successful.
4183 ** Prior data with the same key is NOT overwritten */
4184 int Strsafe_insert(char *data)
4190 if( x1a==0 ) return 0;
4192 h = ph & (x1a->size-1);
4195 if( strcmp(np->data,data)==0 ){
4196 /* An existing entry with the same key is found. */
4197 /* Fail because overwrite is not allows. */
4202 if( x1a->count>=x1a->size ){
4203 /* Need to make the hash table bigger */
4206 array.size = size = x1a->size*2;
4207 array.count = x1a->count;
4208 array.tbl = (x1node*)malloc(
4209 (sizeof(x1node) + sizeof(x1node*))*size );
4210 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4211 array.ht = (x1node**)&(array.tbl[size]);
4212 for(i=0; i<size; i++) array.ht[i] = 0;
4213 for(i=0; i<x1a->count; i++){
4214 x1node *oldnp, *newnp;
4215 oldnp = &(x1a->tbl[i]);
4216 h = strhash(oldnp->data) & (size-1);
4217 newnp = &(array.tbl[i]);
4218 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4219 newnp->next = array.ht[h];
4220 newnp->data = oldnp->data;
4221 newnp->from = &(array.ht[h]);
4222 array.ht[h] = newnp;
4227 /* Insert the new data */
4228 h = ph & (x1a->size-1);
4229 np = &(x1a->tbl[x1a->count++]);
4231 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4232 np->next = x1a->ht[h];
4234 np->from = &(x1a->ht[h]);
4238 /* Return a pointer to data assigned to the given key. Return NULL
4239 ** if no such key. */
4240 char *Strsafe_find(const char *key)
4245 if( x1a==0 ) return 0;
4246 h = strhash(key) & (x1a->size-1);
4249 if( strcmp(np->data,key)==0 ) break;
4252 return np ? np->data : 0;
4255 /* Return a pointer to the (terminal or nonterminal) symbol "x".
4256 ** Create a new symbol if this is the first time "x" has been seen.
4258 struct symbol *Symbol_new(const char *x)
4262 sp = Symbol_find(x);
4264 sp = (struct symbol *)malloc( sizeof(struct symbol) );
4266 sp->name = Strsafe(x);
4267 sp->type = safe_isupper(*x) ? TERMINAL : NONTERMINAL;
4273 sp->lambda = BOOL_FALSE;
4276 Symbol_insert(sp,sp->name);
4281 /* Compare two symbols for working purposes
4283 ** Symbols that begin with upper case letters (terminals or tokens)
4284 ** must sort before symbols that begin with lower case letters
4285 ** (non-terminals). Other than that, the order does not matter.
4287 ** We find experimentally that leaving the symbols in their original
4288 ** order (the order they appeared in the grammar file) gives the
4289 ** smallest parser tables in SQLite.
4291 int Symbolcmpp(struct symbol **a, struct symbol **b){
4292 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4293 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4297 /* There is one instance of the following structure for each
4298 ** associative array of type "x2".
4301 int size; /* The number of available slots. */
4302 /* Must be a power of 2 greater than or */
4304 int count; /* Number of currently slots filled */
4305 struct s_x2node *tbl; /* The data stored here */
4306 struct s_x2node **ht; /* Hash table for lookups */
4309 /* There is one instance of this structure for every data element
4310 ** in an associative array of type "x2".
4312 typedef struct s_x2node {
4313 struct symbol *data; /* The data */
4314 char *key; /* The key */
4315 struct s_x2node *next; /* Next entry with the same hash */
4316 struct s_x2node **from; /* Previous link */
4319 /* There is only one instance of the array, which is the following */
4320 static struct s_x2 *x2a;
4322 /* Allocate a new associative array */
4323 void Symbol_init(void){
4325 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4329 x2a->tbl = (x2node*)malloc(
4330 (sizeof(x2node) + sizeof(x2node*))*128 );
4336 x2a->ht = (x2node**)&(x2a->tbl[128]);
4337 for(i=0; i<128; i++) x2a->ht[i] = 0;
4341 /* Insert a new record into the array. Return TRUE if successful.
4342 ** Prior data with the same key is NOT overwritten */
4343 int Symbol_insert(struct symbol *data, char *key)
4349 if( x2a==0 ) return 0;
4351 h = ph & (x2a->size-1);
4354 if( strcmp(np->key,key)==0 ){
4355 /* An existing entry with the same key is found. */
4356 /* Fail because overwrite is not allows. */
4361 if( x2a->count>=x2a->size ){
4362 /* Need to make the hash table bigger */
4365 array.size = size = x2a->size*2;
4366 array.count = x2a->count;
4367 array.tbl = (x2node*)malloc(
4368 (sizeof(x2node) + sizeof(x2node*))*size );
4369 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4370 array.ht = (x2node**)&(array.tbl[size]);
4371 for(i=0; i<size; i++) array.ht[i] = 0;
4372 for(i=0; i<x2a->count; i++){
4373 x2node *oldnp, *newnp;
4374 oldnp = &(x2a->tbl[i]);
4375 h = strhash(oldnp->key) & (size-1);
4376 newnp = &(array.tbl[i]);
4377 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4378 newnp->next = array.ht[h];
4379 newnp->key = oldnp->key;
4380 newnp->data = oldnp->data;
4381 newnp->from = &(array.ht[h]);
4382 array.ht[h] = newnp;
4387 /* Insert the new data */
4388 h = ph & (x2a->size-1);
4389 np = &(x2a->tbl[x2a->count++]);
4392 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4393 np->next = x2a->ht[h];
4395 np->from = &(x2a->ht[h]);
4399 /* Return a pointer to data assigned to the given key. Return NULL
4400 ** if no such key. */
4401 struct symbol *Symbol_find(const char *key)
4406 if( x2a==0 ) return 0;
4407 h = strhash(key) & (x2a->size-1);
4410 if( strcmp(np->key,key)==0 ) break;
4413 return np ? np->data : 0;
4416 /* Return the n-th data. Return NULL if n is out of range. */
4417 struct symbol *Symbol_Nth(int n)
4419 struct symbol *data;
4420 if( x2a && n>0 && n<=x2a->count ){
4421 data = x2a->tbl[n-1].data;
4428 /* Return the size of the array */
4429 int Symbol_count(void)
4431 return x2a ? x2a->count : 0;
4434 /* Return an array of pointers to all data in the table.
4435 ** The array is obtained from malloc. Return NULL if memory allocation
4436 ** problems, or if the array is empty. */
4437 struct symbol **Symbol_arrayof(void)
4439 struct symbol **array;
4441 if( x2a==0 ) return 0;
4443 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4445 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4450 /* Compare two configurations */
4451 int Configcmp(const void *a_arg, const void *b_arg)
4453 const struct config *a = a_arg, *b = b_arg;
4455 x = a->rp->index - b->rp->index;
4456 if( x==0 ) x = a->dot - b->dot;
4460 /* Compare two states */
4461 PRIVATE int statecmp(struct config *a, struct config *b)
4464 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4465 rc = a->rp->index - b->rp->index;
4466 if( rc==0 ) rc = a->dot - b->dot;
4476 PRIVATE int statehash(struct config *a)
4480 h = h*571 + a->rp->index*37 + a->dot;
4486 /* Allocate a new state structure */
4487 struct state *State_new(void)
4490 new = (struct state *)malloc( sizeof(struct state) );
4495 /* There is one instance of the following structure for each
4496 ** associative array of type "x3".
4499 int size; /* The number of available slots. */
4500 /* Must be a power of 2 greater than or */
4502 int count; /* Number of currently slots filled */
4503 struct s_x3node *tbl; /* The data stored here */
4504 struct s_x3node **ht; /* Hash table for lookups */
4507 /* There is one instance of this structure for every data element
4508 ** in an associative array of type "x3".
4510 typedef struct s_x3node {
4511 struct state *data; /* The data */
4512 struct config *key; /* The key */
4513 struct s_x3node *next; /* Next entry with the same hash */
4514 struct s_x3node **from; /* Previous link */
4517 /* There is only one instance of the array, which is the following */
4518 static struct s_x3 *x3a;
4520 /* Allocate a new associative array */
4521 void State_init(void){
4523 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4527 x3a->tbl = (x3node*)malloc(
4528 (sizeof(x3node) + sizeof(x3node*))*128 );
4534 x3a->ht = (x3node**)&(x3a->tbl[128]);
4535 for(i=0; i<128; i++) x3a->ht[i] = 0;
4539 /* Insert a new record into the array. Return TRUE if successful.
4540 ** Prior data with the same key is NOT overwritten */
4541 int State_insert(struct state *data, struct config *key)
4547 if( x3a==0 ) return 0;
4548 ph = statehash(key);
4549 h = ph & (x3a->size-1);
4552 if( statecmp(np->key,key)==0 ){
4553 /* An existing entry with the same key is found. */
4554 /* Fail because overwrite is not allows. */
4559 if( x3a->count>=x3a->size ){
4560 /* Need to make the hash table bigger */
4563 array.size = size = x3a->size*2;
4564 array.count = x3a->count;
4565 array.tbl = (x3node*)malloc(
4566 (sizeof(x3node) + sizeof(x3node*))*size );
4567 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4568 array.ht = (x3node**)&(array.tbl[size]);
4569 for(i=0; i<size; i++) array.ht[i] = 0;
4570 for(i=0; i<x3a->count; i++){
4571 x3node *oldnp, *newnp;
4572 oldnp = &(x3a->tbl[i]);
4573 h = statehash(oldnp->key) & (size-1);
4574 newnp = &(array.tbl[i]);
4575 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4576 newnp->next = array.ht[h];
4577 newnp->key = oldnp->key;
4578 newnp->data = oldnp->data;
4579 newnp->from = &(array.ht[h]);
4580 array.ht[h] = newnp;
4585 /* Insert the new data */
4586 h = ph & (x3a->size-1);
4587 np = &(x3a->tbl[x3a->count++]);
4590 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4591 np->next = x3a->ht[h];
4593 np->from = &(x3a->ht[h]);
4597 /* Return a pointer to data assigned to the given key. Return NULL
4598 ** if no such key. */
4599 struct state *State_find(struct config *key)
4604 if( x3a==0 ) return 0;
4605 h = statehash(key) & (x3a->size-1);
4608 if( statecmp(np->key,key)==0 ) break;
4611 return np ? np->data : 0;
4614 /* Return an array of pointers to all data in the table.
4615 ** The array is obtained from malloc. Return NULL if memory allocation
4616 ** problems, or if the array is empty. */
4617 struct state **State_arrayof(void)
4619 struct state **array;
4621 if( x3a==0 ) return 0;
4623 array = (struct state **)malloc( sizeof(struct state *)*size );
4625 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4630 /* Hash a configuration */
4631 PRIVATE int confighash(struct config *a)
4634 h = h*571 + a->rp->index*37 + a->dot;
4638 /* There is one instance of the following structure for each
4639 ** associative array of type "x4".
4642 int size; /* The number of available slots. */
4643 /* Must be a power of 2 greater than or */
4645 int count; /* Number of currently slots filled */
4646 struct s_x4node *tbl; /* The data stored here */
4647 struct s_x4node **ht; /* Hash table for lookups */
4650 /* There is one instance of this structure for every data element
4651 ** in an associative array of type "x4".
4653 typedef struct s_x4node {
4654 struct config *data; /* The data */
4655 struct s_x4node *next; /* Next entry with the same hash */
4656 struct s_x4node **from; /* Previous link */
4659 /* There is only one instance of the array, which is the following */
4660 static struct s_x4 *x4a;
4662 /* Allocate a new associative array */
4663 void Configtable_init(void){
4665 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4669 x4a->tbl = (x4node*)malloc(
4670 (sizeof(x4node) + sizeof(x4node*))*64 );
4676 x4a->ht = (x4node**)&(x4a->tbl[64]);
4677 for(i=0; i<64; i++) x4a->ht[i] = 0;
4681 /* Insert a new record into the array. Return TRUE if successful.
4682 ** Prior data with the same key is NOT overwritten */
4683 int Configtable_insert(struct config *data)
4689 if( x4a==0 ) return 0;
4690 ph = confighash(data);
4691 h = ph & (x4a->size-1);
4694 if( Configcmp(np->data,data)==0 ){
4695 /* An existing entry with the same key is found. */
4696 /* Fail because overwrite is not allows. */
4701 if( x4a->count>=x4a->size ){
4702 /* Need to make the hash table bigger */
4705 array.size = size = x4a->size*2;
4706 array.count = x4a->count;
4707 array.tbl = (x4node*)malloc(
4708 (sizeof(x4node) + sizeof(x4node*))*size );
4709 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4710 array.ht = (x4node**)&(array.tbl[size]);
4711 for(i=0; i<size; i++) array.ht[i] = 0;
4712 for(i=0; i<x4a->count; i++){
4713 x4node *oldnp, *newnp;
4714 oldnp = &(x4a->tbl[i]);
4715 h = confighash(oldnp->data) & (size-1);
4716 newnp = &(array.tbl[i]);
4717 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4718 newnp->next = array.ht[h];
4719 newnp->data = oldnp->data;
4720 newnp->from = &(array.ht[h]);
4721 array.ht[h] = newnp;
4726 /* Insert the new data */
4727 h = ph & (x4a->size-1);
4728 np = &(x4a->tbl[x4a->count++]);
4730 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4731 np->next = x4a->ht[h];
4733 np->from = &(x4a->ht[h]);
4737 /* Return a pointer to data assigned to the given key. Return NULL
4738 ** if no such key. */
4739 struct config *Configtable_find(struct config *key)
4744 if( x4a==0 ) return 0;
4745 h = confighash(key) & (x4a->size-1);
4748 if( Configcmp(np->data,key)==0 ) break;
4751 return np ? np->data : 0;
4754 /* Remove all data from the table. Pass each data to the function "f"
4755 ** as it is removed. ("f" may be null to avoid this step.) */
4756 void Configtable_clear(int(*f)(struct config *))
4759 if( x4a==0 || x4a->count==0 ) return;
4760 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4761 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;