[mod_cgi] fix pipe_cloexec() when no O_CLOEXEC
[lighttpd.git] / src / lemon.c
blobde627535afe0b34df3affe47bae0fc1c332080c0
1 #include "first.h"
3 /*
4 ** This file contains all sources (including headers) to the LEMON
5 ** LALR(1) parser generator. The sources have been combined into a
6 ** single file to make it easy to include LEMON in the source tree
7 ** and Makefile of another program.
8 **
9 ** The author of this program disclaims copyright.
11 #include <stdio.h>
12 #include <stdarg.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <stdlib.h>
17 #ifdef HAVE_STDINT_H
18 # include <stdint.h>
19 #endif
20 #ifdef HAVE_INTTYPES_H
21 # include <inttypes.h>
22 #endif
24 #define UNUSED(x) ( (void)(x) )
26 extern void qsort();
27 extern double strtod();
28 extern long strtol();
29 extern void free();
30 extern int access();
31 extern int atoi();
32 extern char *getenv();
34 #ifndef __WIN32__
35 # if defined(_WIN32) || defined(WIN32)
36 # define __WIN32__
37 # endif
38 #endif
40 #if __GNUC__ > 2
41 #define NORETURN __attribute__ ((__noreturn__))
42 #else
43 #define NORETURN
44 #endif
46 /* #define PRIVATE static */
47 #define PRIVATE static
49 #ifdef TEST
50 #define MAXRHS 5 /* Set low to exercise exception code */
51 #else
52 #define MAXRHS 1000
53 #endif
55 void *msort(void *list, void **next, int(*cmp)(void *, void *));
57 extern void memory_error() NORETURN;
59 /******** From the file "action.h" *************************************/
60 struct action *Action_new();
61 struct action *Action_sort();
62 void Action_add();
64 /********* From the file "assert.h" ************************************/
65 void myassert() NORETURN;
66 #ifndef NDEBUG
67 # define assert(X) if(!(X))myassert(__FILE__,__LINE__)
68 #else
69 # define assert(X)
70 #endif
72 /********** From the file "build.h" ************************************/
73 void FindRulePrecedences();
74 void FindFirstSets();
75 void FindStates();
76 void FindLinks();
77 void FindFollowSets();
78 void FindActions();
80 /********* From the file "configlist.h" *********************************/
81 void Configlist_init(/* void */);
82 struct config *Configlist_add(/* struct rule *, int */);
83 struct config *Configlist_addbasis(/* struct rule *, int */);
84 void Configlist_closure(/* void */);
85 void Configlist_sort(/* void */);
86 void Configlist_sortbasis(/* void */);
87 struct config *Configlist_return(/* void */);
88 struct config *Configlist_basis(/* void */);
89 void Configlist_eat(/* struct config * */);
90 void Configlist_reset(/* void */);
92 /********* From the file "error.h" ***************************************/
93 void ErrorMsg(const char *, int,const char *, ...);
95 /****** From the file "option.h" ******************************************/
96 struct s_options {
97 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
98 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
99 char *label;
100 void *arg;
101 const char *message;
103 int OptInit(/* char**,struct s_options*,FILE* */);
104 int OptNArgs(/* void */);
105 char *OptArg(/* int */);
106 void OptErr(/* int */);
107 void OptPrint(/* void */);
109 /******** From the file "parse.h" *****************************************/
110 void Parse(/* struct lemon *lemp */);
112 /********* From the file "plink.h" ***************************************/
113 struct plink *Plink_new(/* void */);
114 void Plink_add(/* struct plink **, struct config * */);
115 void Plink_copy(/* struct plink **, struct plink * */);
116 void Plink_delete(/* struct plink * */);
118 /********** From the file "report.h" *************************************/
119 void Reprint(/* struct lemon * */);
120 void ReportOutput(/* struct lemon * */);
121 void ReportTable(/* struct lemon * */);
122 void ReportHeader(/* struct lemon * */);
123 void CompressTables(/* struct lemon * */);
125 /********** From the file "set.h" ****************************************/
126 void SetSize(/* int N */); /* All sets will be of size N */
127 char *SetNew(/* void */); /* A new set for element 0..N */
128 void SetFree(/* char* */); /* Deallocate a set */
130 int SetAdd(/* char*,int */); /* Add element to a set */
131 int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
133 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
135 /********** From the file "struct.h" *************************************/
137 ** Principal data structures for the LEMON parser generator.
140 typedef enum {Bo_FALSE=0, Bo_TRUE} Boolean;
142 /* Symbols (terminals and nonterminals) of the grammar are stored
143 ** in the following: */
144 struct symbol {
145 char *name; /* Name of the symbol */
146 int index; /* Index number for this symbol */
147 enum {
148 TERMINAL,
149 NONTERMINAL
150 } type; /* Symbols are all either TERMINALS or NTs */
151 struct rule *rule; /* Linked list of rules of this (if an NT) */
152 struct symbol *fallback; /* fallback token in case this token doesn't parse */
153 int prec; /* Precedence if defined (-1 otherwise) */
154 enum e_assoc {
155 LEFT,
156 RIGHT,
157 NONE,
159 } assoc; /* Associativity if predecence is defined */
160 char *firstset; /* First-set for all rules of this symbol */
161 Boolean lambda; /* True if NT and can generate an empty string */
162 char *destructor; /* Code which executes whenever this symbol is
163 ** popped from the stack during error processing */
164 int destructorln; /* Line number of destructor code */
165 char *datatype; /* The data type of information held by this
166 ** object. Only used if type==NONTERMINAL */
167 int dtnum; /* The data type number. In the parser, the value
168 ** stack is a union. The .yy%d element of this
169 ** union is the correct data type for this object */
172 /* Each production rule in the grammar is stored in the following
173 ** structure. */
174 struct rule {
175 struct symbol *lhs; /* Left-hand side of the rule */
176 char *lhsalias; /* Alias for the LHS (NULL if none) */
177 int ruleline; /* Line number for the rule */
178 int nrhs; /* Number of RHS symbols */
179 struct symbol **rhs; /* The RHS symbols */
180 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
181 int line; /* Line number at which code begins */
182 char *code; /* The code executed when this rule is reduced */
183 struct symbol *precsym; /* Precedence symbol for this rule */
184 int index; /* An index number for this rule */
185 Boolean canReduce; /* True if this rule is ever reduced */
186 struct rule *nextlhs; /* Next rule with the same LHS */
187 struct rule *next; /* Next rule in the global list */
190 /* A configuration is a production rule of the grammar together with
191 ** a mark (dot) showing how much of that rule has been processed so far.
192 ** Configurations also contain a follow-set which is a list of terminal
193 ** symbols which are allowed to immediately follow the end of the rule.
194 ** Every configuration is recorded as an instance of the following: */
195 struct config {
196 struct rule *rp; /* The rule upon which the configuration is based */
197 int dot; /* The parse point */
198 char *fws; /* Follow-set for this configuration only */
199 struct plink *fplp; /* Follow-set forward propagation links */
200 struct plink *bplp; /* Follow-set backwards propagation links */
201 struct state *stp; /* Pointer to state which contains this */
202 enum {
203 COMPLETE, /* The status is used during followset and */
204 INCOMPLETE /* shift computations */
205 } status;
206 struct config *next; /* Next configuration in the state */
207 struct config *bp; /* The next basis configuration */
210 /* Every shift or reduce operation is stored as one of the following */
211 struct action {
212 struct symbol *sp; /* The look-ahead symbol */
213 enum e_action {
214 SHIFT,
215 ACCEPT,
216 REDUCE,
217 ERROR,
218 CONFLICT, /* Was a reduce, but part of a conflict */
219 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
220 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
221 NOT_USED /* Deleted by compression */
222 } type;
223 union {
224 struct state *stp; /* The new state, if a shift */
225 struct rule *rp; /* The rule, if a reduce */
226 } x;
227 struct action *next; /* Next action for this state */
228 struct action *collide; /* Next action with the same hash */
231 /* Each state of the generated parser's finite state machine
232 ** is encoded as an instance of the following structure. */
233 struct state {
234 struct config *bp; /* The basis configurations for this state */
235 struct config *cfp; /* All configurations in this set */
236 int index; /* Sequencial number for this state */
237 struct action *ap; /* Array of actions for this state */
238 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
239 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
240 int iDflt; /* Default action */
242 #define NO_OFFSET (-2147483647)
244 /* A followset propagation link indicates that the contents of one
245 ** configuration followset should be propagated to another whenever
246 ** the first changes. */
247 struct plink {
248 struct config *cfp; /* The configuration to which linked */
249 struct plink *next; /* The next propagate link */
252 /* The state vector for the entire parser generator is recorded as
253 ** follows. (LEMON uses no global variables and makes little use of
254 ** static variables. Fields in the following structure can be thought
255 ** of as begin global variables in the program.) */
256 struct lemon {
257 struct state **sorted; /* Table of states sorted by state number */
258 struct rule *rule; /* List of all rules */
259 int nstate; /* Number of states */
260 int nrule; /* Number of rules */
261 int nsymbol; /* Number of terminal and nonterminal symbols */
262 int nterminal; /* Number of terminal symbols */
263 struct symbol **symbols; /* Sorted array of pointers to symbols */
264 int errorcnt; /* Number of errors */
265 struct symbol *errsym; /* The error symbol */
266 char *name; /* Name of the generated parser */
267 char *arg; /* Declaration of the 3th argument to parser */
268 char *tokentype; /* Type of terminal symbols in the parser stack */
269 char *vartype; /* The default type of non-terminal symbols */
270 char *start; /* Name of the start symbol for the grammar */
271 char *stacksize; /* Size of the parser stack */
272 char *include; /* Code to put at the start of the C file */
273 int includeln; /* Line number for start of include code */
274 char *error; /* Code to execute when an error is seen */
275 int errorln; /* Line number for start of error code */
276 char *overflow; /* Code to execute on a stack overflow */
277 int overflowln; /* Line number for start of overflow code */
278 char *failure; /* Code to execute on parser failure */
279 int failureln; /* Line number for start of failure code */
280 char *accept; /* Code to execute when the parser excepts */
281 int acceptln; /* Line number for the start of accept code */
282 char *extracode; /* Code appended to the generated file */
283 int extracodeln; /* Line number for the start of the extra code */
284 char *tokendest; /* Code to execute to destroy token data */
285 int tokendestln; /* Line number for token destroyer code */
286 char *vardest; /* Code for the default non-terminal destructor */
287 int vardestln; /* Line number for default non-term destructor code*/
288 char *filename; /* Name of the input file */
289 char *tmplname; /* Name of the template file */
290 char *outname; /* Name of the current output file */
291 char *tokenprefix; /* A prefix added to token names in the .h file */
292 int nconflict; /* Number of parsing conflicts */
293 int tablesize; /* Size of the parse tables */
294 int basisflag; /* Print only basis configurations */
295 int has_fallback; /* True if any %fallback is seen in the grammer */
296 char *argv0; /* Name of the program */
299 #define MemoryCheck(X) if((X)==0){ \
300 memory_error(); \
303 /**************** From the file "table.h" *********************************/
305 ** All code in this file has been automatically generated
306 ** from a specification in the file
307 ** "table.q"
308 ** by the associative array code building program "aagen".
309 ** Do not edit this file! Instead, edit the specification
310 ** file, then rerun aagen.
313 ** Code for processing tables in the LEMON parser generator.
316 /* Routines for handling a strings */
318 char *Strsafe();
320 void Strsafe_init(/* void */);
321 int Strsafe_insert(/* char * */);
322 char *Strsafe_find(/* char * */);
324 /* Routines for handling symbols of the grammar */
326 struct symbol *Symbol_new();
327 int Symbolcmpp(/* struct symbol **, struct symbol ** */);
328 void Symbol_init(/* void */);
329 int Symbol_insert(/* struct symbol *, char * */);
330 struct symbol *Symbol_find(/* char * */);
331 struct symbol *Symbol_Nth(/* int */);
332 int Symbol_count(/* */);
333 int State_count(void);
334 struct symbol **Symbol_arrayof(/* */);
336 /* Routines to manage the state table */
338 int Configcmp(/* struct config *, struct config * */);
339 struct state *State_new();
340 void State_init(/* void */);
341 int State_insert(/* struct state *, struct config * */);
342 struct state *State_find(/* struct config * */);
343 struct state **State_arrayof(/* */);
345 /* Routines used for efficiency in Configlist_add */
347 void Configtable_init(/* void */);
348 int Configtable_insert(/* struct config * */);
349 struct config *Configtable_find(/* struct config * */);
350 void Configtable_clear(/* int(*)(struct config *) */);
351 /****************** From the file "action.c" *******************************/
353 ** Routines processing parser actions in the LEMON parser generator.
356 /* Allocate a new parser action */
357 struct action *Action_new(){
358 static struct action *freelist = NULL;
359 struct action *new;
361 if( freelist==NULL ){
362 int i;
363 int amt = 100;
364 freelist = (struct action *)malloc( sizeof(struct action)*amt );
365 if( freelist==0 ){
366 fprintf(stderr,"Unable to allocate memory for a new parser action.");
367 exit(1);
369 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
370 freelist[amt-1].next = 0;
372 new = freelist;
373 freelist = freelist->next;
374 return new;
377 /* Compare two actions */
378 static int actioncmp(ap1,ap2)
379 struct action *ap1;
380 struct action *ap2;
382 int rc;
383 rc = ap1->sp->index - ap2->sp->index;
384 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
385 if( rc==0 ){
386 assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
387 assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
388 rc = ap1->x.rp->index - ap2->x.rp->index;
390 return rc;
393 /* Sort parser actions */
394 struct action *Action_sort(ap)
395 struct action *ap;
397 ap = (struct action *)msort(ap,(void **)&ap->next,actioncmp);
398 return ap;
401 void Action_add(app,type,sp,arg)
402 struct action **app;
403 enum e_action type;
404 struct symbol *sp;
405 void *arg;
407 struct action *new;
408 new = Action_new();
409 new->next = *app;
410 *app = new;
411 new->type = type;
412 new->sp = sp;
413 if( type==SHIFT ){
414 new->x.stp = (struct state *)arg;
415 }else{
416 new->x.rp = (struct rule *)arg;
419 /********************** New code to implement the "acttab" module ***********/
421 ** This module implements routines use to construct the yy_action[] table.
425 ** The state of the yy_action table under construction is an instance of
426 ** the following structure
428 typedef struct acttab acttab;
429 struct acttab {
430 int nAction; /* Number of used slots in aAction[] */
431 int nActionAlloc; /* Slots allocated for aAction[] */
432 struct {
433 int lookahead; /* Value of the lookahead token */
434 int action; /* Action to take on the given lookahead */
435 } *aAction, /* The yy_action[] table under construction */
436 *aLookahead; /* A single new transaction set */
437 int mnLookahead; /* Minimum aLookahead[].lookahead */
438 int mnAction; /* Action associated with mnLookahead */
439 int mxLookahead; /* Maximum aLookahead[].lookahead */
440 int nLookahead; /* Used slots in aLookahead[] */
441 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
444 /* Return the number of entries in the yy_action table */
445 #define acttab_size(X) ((X)->nAction)
447 /* The value for the N-th entry in yy_action */
448 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
450 /* The value for the N-th entry in yy_lookahead */
451 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
453 /* Free all memory associated with the given acttab */
455 PRIVATE void acttab_free(acttab *p){
456 free( p->aAction );
457 free( p->aLookahead );
458 free( p );
462 /* Allocate a new acttab structure */
463 PRIVATE acttab *acttab_alloc(void){
464 acttab *p = malloc( sizeof(*p) );
465 if( p==0 ){
466 fprintf(stderr,"Unable to allocate memory for a new acttab.");
467 exit(1);
469 memset(p, 0, sizeof(*p));
470 return p;
473 /* Add a new action to the current transaction set
475 PRIVATE void acttab_action(acttab *p, int lookahead, int action){
476 if( p->nLookahead>=p->nLookaheadAlloc ){
477 p->nLookaheadAlloc += 25;
478 p->aLookahead = realloc( p->aLookahead,
479 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
480 if( p->aLookahead==0 ){
481 fprintf(stderr,"malloc failed\n");
482 exit(1);
485 if( p->nLookahead==0 ){
486 p->mxLookahead = lookahead;
487 p->mnLookahead = lookahead;
488 p->mnAction = action;
489 }else{
490 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
491 if( p->mnLookahead>lookahead ){
492 p->mnLookahead = lookahead;
493 p->mnAction = action;
496 p->aLookahead[p->nLookahead].lookahead = lookahead;
497 p->aLookahead[p->nLookahead].action = action;
498 p->nLookahead++;
502 ** Add the transaction set built up with prior calls to acttab_action()
503 ** into the current action table. Then reset the transaction set back
504 ** to an empty set in preparation for a new round of acttab_action() calls.
506 ** Return the offset into the action table of the new transaction.
508 PRIVATE int acttab_insert(acttab *p){
509 int i, j, k, n;
510 assert( p->nLookahead>0 );
512 /* Make sure we have enough space to hold the expanded action table
513 ** in the worst case. The worst case occurs if the transaction set
514 ** must be appended to the current action table
516 n = p->mxLookahead + 1;
517 if( p->nAction + n >= p->nActionAlloc ){
518 int oldAlloc = p->nActionAlloc;
519 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
520 p->aAction = realloc( p->aAction,
521 sizeof(p->aAction[0])*p->nActionAlloc);
522 if( p->aAction==0 ){
523 fprintf(stderr,"malloc failed\n");
524 exit(1);
526 for(i=oldAlloc; i<p->nActionAlloc; i++){
527 p->aAction[i].lookahead = -1;
528 p->aAction[i].action = -1;
532 /* Scan the existing action table looking for an offset where we can
533 ** insert the current transaction set. Fall out of the loop when that
534 ** offset is found. In the worst case, we fall out of the loop when
535 ** i reaches p->nAction, which means we append the new transaction set.
537 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
539 for(i=0; i<p->nAction+p->mnLookahead; i++){
540 if( p->aAction[i].lookahead<0 ){
541 for(j=0; j<p->nLookahead; j++){
542 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
543 if( k<0 ) break;
544 if( p->aAction[k].lookahead>=0 ) break;
546 if( j<p->nLookahead ) continue;
547 for(j=0; j<p->nAction; j++){
548 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
550 if( j==p->nAction ){
551 break; /* Fits in empty slots */
553 }else if( p->aAction[i].lookahead==p->mnLookahead ){
554 if( p->aAction[i].action!=p->mnAction ) continue;
555 for(j=0; j<p->nLookahead; j++){
556 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
557 if( k<0 || k>=p->nAction ) break;
558 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
559 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
561 if( j<p->nLookahead ) continue;
562 n = 0;
563 for(j=0; j<p->nAction; j++){
564 if( p->aAction[j].lookahead<0 ) continue;
565 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
567 if( n==p->nLookahead ){
568 break; /* Same as a prior transaction set */
572 /* Insert transaction set at index i. */
573 for(j=0; j<p->nLookahead; j++){
574 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
575 p->aAction[k] = p->aLookahead[j];
576 if( k>=p->nAction ) p->nAction = k+1;
578 p->nLookahead = 0;
580 /* Return the offset that is added to the lookahead in order to get the
581 ** index into yy_action of the action */
582 return i - p->mnLookahead;
585 /********************** From the file "assert.c" ****************************/
587 ** A more efficient way of handling assertions.
589 void myassert(file,line)
590 char *file;
591 int line;
593 fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
594 exit(1);
596 /********************** From the file "build.c" *****************************/
598 ** Routines to construction the finite state machine for the LEMON
599 ** parser generator.
602 /* Find a precedence symbol of every rule in the grammar.
604 ** Those rules which have a precedence symbol coded in the input
605 ** grammar using the "[symbol]" construct will already have the
606 ** rp->precsym field filled. Other rules take as their precedence
607 ** symbol the first RHS symbol with a defined precedence. If there
608 ** are not RHS symbols with a defined precedence, the precedence
609 ** symbol field is left blank.
611 void FindRulePrecedences(xp)
612 struct lemon *xp;
614 struct rule *rp;
615 for(rp=xp->rule; rp; rp=rp->next){
616 if( rp->precsym==0 ){
617 int i;
618 for(i=0; i<rp->nrhs; i++){
619 if( rp->rhs[i]->prec>=0 ){
620 rp->precsym = rp->rhs[i];
621 break;
626 return;
629 /* Find all nonterminals which will generate the empty string.
630 ** Then go back and compute the first sets of every nonterminal.
631 ** The first set is the set of all terminal symbols which can begin
632 ** a string generated by that nonterminal.
634 void FindFirstSets(lemp)
635 struct lemon *lemp;
637 int i;
638 struct rule *rp;
639 int progress;
641 for(i=0; i<lemp->nsymbol; i++){
642 lemp->symbols[i]->lambda = Bo_FALSE;
644 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
645 lemp->symbols[i]->firstset = SetNew();
648 /* First compute all lambdas */
650 progress = 0;
651 for(rp=lemp->rule; rp; rp=rp->next){
652 if( rp->lhs->lambda ) continue;
653 for(i=0; i<rp->nrhs; i++){
654 if( rp->rhs[i]->lambda==Bo_FALSE ) break;
656 if( i==rp->nrhs ){
657 rp->lhs->lambda = Bo_TRUE;
658 progress = 1;
661 }while( progress );
663 /* Now compute all first sets */
665 struct symbol *s1, *s2;
666 progress = 0;
667 for(rp=lemp->rule; rp; rp=rp->next){
668 s1 = rp->lhs;
669 for(i=0; i<rp->nrhs; i++){
670 s2 = rp->rhs[i];
671 if( s2->type==TERMINAL ){
672 progress += SetAdd(s1->firstset,s2->index);
673 break;
674 }else if( s1==s2 ){
675 if( s1->lambda==Bo_FALSE ) break;
676 }else{
677 progress += SetUnion(s1->firstset,s2->firstset);
678 if( s2->lambda==Bo_FALSE ) break;
682 }while( progress );
683 return;
686 /* Compute all LR(0) states for the grammar. Links
687 ** are added to between some states so that the LR(1) follow sets
688 ** can be computed later.
690 PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
691 void FindStates(lemp)
692 struct lemon *lemp;
694 struct symbol *sp;
695 struct rule *rp;
697 Configlist_init();
699 /* Find the start symbol */
700 if( lemp->start ){
701 sp = Symbol_find(lemp->start);
702 if( sp==0 ){
703 ErrorMsg(lemp->filename,0,
704 "The specified start symbol \"%s\" is not \
705 in a nonterminal of the grammar. \"%s\" will be used as the start \
706 symbol instead.",lemp->start,lemp->rule->lhs->name);
707 lemp->errorcnt++;
708 sp = lemp->rule->lhs;
710 }else{
711 sp = lemp->rule->lhs;
714 /* Make sure the start symbol doesn't occur on the right-hand side of
715 ** any rule. Report an error if it does. (YACC would generate a new
716 ** start symbol in this case.) */
717 for(rp=lemp->rule; rp; rp=rp->next){
718 int i;
719 for(i=0; i<rp->nrhs; i++){
720 if( rp->rhs[i]==sp ){
721 ErrorMsg(lemp->filename,0,
722 "The start symbol \"%s\" occurs on the \
723 right-hand side of a rule. This will result in a parser which \
724 does not work properly.",sp->name);
725 lemp->errorcnt++;
730 /* The basis configuration set for the first state
731 ** is all rules which have the start symbol as their
732 ** left-hand side */
733 for(rp=sp->rule; rp; rp=rp->nextlhs){
734 struct config *newcfp;
735 newcfp = Configlist_addbasis(rp,0);
736 SetAdd(newcfp->fws,0);
739 /* Compute the first state. All other states will be
740 ** computed automatically during the computation of the first one.
741 ** The returned pointer to the first state is not used. */
742 (void)getstate(lemp);
743 return;
746 /* Return a pointer to a state which is described by the configuration
747 ** list which has been built from calls to Configlist_add.
749 PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
750 PRIVATE struct state *getstate(lemp)
751 struct lemon *lemp;
753 struct config *cfp, *bp;
754 struct state *stp;
756 /* Extract the sorted basis of the new state. The basis was constructed
757 ** by prior calls to "Configlist_addbasis()". */
758 Configlist_sortbasis();
759 bp = Configlist_basis();
761 /* Get a state with the same basis */
762 stp = State_find(bp);
763 if( stp ){
764 /* A state with the same basis already exists! Copy all the follow-set
765 ** propagation links from the state under construction into the
766 ** preexisting state, then return a pointer to the preexisting state */
767 struct config *x, *y;
768 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
769 Plink_copy(&y->bplp,x->bplp);
770 Plink_delete(x->fplp);
771 x->fplp = x->bplp = 0;
773 cfp = Configlist_return();
774 Configlist_eat(cfp);
775 }else{
776 /* This really is a new state. Construct all the details */
777 Configlist_closure(lemp); /* Compute the configuration closure */
778 Configlist_sort(); /* Sort the configuration closure */
779 cfp = Configlist_return(); /* Get a pointer to the config list */
780 stp = State_new(); /* A new state structure */
781 MemoryCheck(stp);
782 stp->bp = bp; /* Remember the configuration basis */
783 stp->cfp = cfp; /* Remember the configuration closure */
784 stp->index = lemp->nstate++; /* Every state gets a sequence number */
785 stp->ap = 0; /* No actions, yet. */
786 State_insert(stp,stp->bp); /* Add to the state table */
787 buildshifts(lemp,stp); /* Recursively compute successor states */
789 return stp;
792 /* Construct all successor states to the given state. A "successor"
793 ** state is any state which can be reached by a shift action.
795 PRIVATE void buildshifts(lemp,stp)
796 struct lemon *lemp;
797 struct state *stp; /* The state from which successors are computed */
799 struct config *cfp; /* For looping thru the config closure of "stp" */
800 struct config *bcfp; /* For the inner loop on config closure of "stp" */
801 struct config *new; /* */
802 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
803 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
804 struct state *newstp; /* A pointer to a successor state */
806 /* Each configuration becomes complete after it contibutes to a successor
807 ** state. Initially, all configurations are incomplete */
808 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
810 /* Loop through all configurations of the state "stp" */
811 for(cfp=stp->cfp; cfp; cfp=cfp->next){
812 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
813 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
814 Configlist_reset(); /* Reset the new config set */
815 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
817 /* For every configuration in the state "stp" which has the symbol "sp"
818 ** following its dot, add the same configuration to the basis set under
819 ** construction but with the dot shifted one symbol to the right. */
820 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
821 if( bcfp->status==COMPLETE ) continue; /* Already used */
822 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
823 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
824 if( bsp!=sp ) continue; /* Must be same as for "cfp" */
825 bcfp->status = COMPLETE; /* Mark this config as used */
826 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
827 Plink_add(&new->bplp,bcfp);
830 /* Get a pointer to the state described by the basis configuration set
831 ** constructed in the preceding loop */
832 newstp = getstate(lemp);
834 /* The state "newstp" is reached from the state "stp" by a shift action
835 ** on the symbol "sp" */
836 Action_add(&stp->ap,SHIFT,sp,newstp);
841 ** Construct the propagation links
843 void FindLinks(lemp)
844 struct lemon *lemp;
846 int i;
847 struct config *cfp, *other;
848 struct state *stp;
849 struct plink *plp;
851 /* Housekeeping detail:
852 ** Add to every propagate link a pointer back to the state to
853 ** which the link is attached. */
854 for(i=0; i<lemp->nstate; i++){
855 stp = lemp->sorted[i];
856 for(cfp=stp->cfp; cfp; cfp=cfp->next){
857 cfp->stp = stp;
861 /* Convert all backlinks into forward links. Only the forward
862 ** links are used in the follow-set computation. */
863 for(i=0; i<lemp->nstate; i++){
864 stp = lemp->sorted[i];
865 for(cfp=stp->cfp; cfp; cfp=cfp->next){
866 for(plp=cfp->bplp; plp; plp=plp->next){
867 other = plp->cfp;
868 Plink_add(&other->fplp,cfp);
874 /* Compute all followsets.
876 ** A followset is the set of all symbols which can come immediately
877 ** after a configuration.
879 void FindFollowSets(lemp)
880 struct lemon *lemp;
882 int i;
883 struct config *cfp;
884 struct state *stp;
885 struct plink *plp;
886 int progress;
887 int change;
889 for(i=0; i<lemp->nstate; i++){
890 stp = lemp->sorted[i];
891 for(cfp=stp->cfp; cfp; cfp=cfp->next){
892 cfp->status = INCOMPLETE;
897 progress = 0;
898 for(i=0; i<lemp->nstate; i++){
899 stp = lemp->sorted[i];
900 for(cfp=stp->cfp; cfp; cfp=cfp->next){
901 if( cfp->status==COMPLETE ) continue;
902 for(plp=cfp->fplp; plp; plp=plp->next){
903 change = SetUnion(plp->cfp->fws,cfp->fws);
904 if( change ){
905 plp->cfp->status = INCOMPLETE;
906 progress = 1;
909 cfp->status = COMPLETE;
912 }while( progress );
915 static int resolve_conflict();
917 /* Compute the reduce actions, and resolve conflicts.
919 void FindActions(lemp)
920 struct lemon *lemp;
922 int i,j;
923 struct config *cfp;
924 struct symbol *sp;
925 struct rule *rp;
927 /* Add all of the reduce actions
928 ** A reduce action is added for each element of the followset of
929 ** a configuration which has its dot at the extreme right.
931 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
932 struct state *stp;
933 stp = lemp->sorted[i];
934 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
935 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
936 for(j=0; j<lemp->nterminal; j++){
937 if( SetFind(cfp->fws,j) ){
938 /* Add a reduce action to the state "stp" which will reduce by the
939 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
940 Action_add(&stp->ap,REDUCE,lemp->symbols[j],cfp->rp);
947 /* Add the accepting token */
948 if( lemp->start ){
949 sp = Symbol_find(lemp->start);
950 if( sp==0 ) sp = lemp->rule->lhs;
951 }else{
952 sp = lemp->rule->lhs;
954 /* Add to the first state (which is always the starting state of the
955 ** finite state machine) an action to ACCEPT if the lookahead is the
956 ** start nonterminal. */
957 if (lemp->nstate) { /*(should always be true)*/
958 struct state *stp;
959 stp = lemp->sorted[0];
960 Action_add(&stp->ap,ACCEPT,sp,0);
963 /* Resolve conflicts */
964 for(i=0; i<lemp->nstate; i++){
965 struct action *ap, *nap;
966 struct state *stp;
967 stp = lemp->sorted[i];
968 assert( stp->ap );
969 stp->ap = Action_sort(stp->ap);
970 for(ap=stp->ap; ap && ap->next; ap=ap->next){
971 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
972 /* The two actions "ap" and "nap" have the same lookahead.
973 ** Figure out which one should be used */
974 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
979 /* Report an error for each rule that can never be reduced. */
980 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = Bo_FALSE;
981 for(i=0; i<lemp->nstate; i++){
982 struct action *ap;
983 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
984 if( ap->type==REDUCE ) ap->x.rp->canReduce = Bo_TRUE;
987 for(rp=lemp->rule; rp; rp=rp->next){
988 if( rp->canReduce ) continue;
989 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
990 lemp->errorcnt++;
994 /* Resolve a conflict between the two given actions. If the
995 ** conflict can't be resolve, return non-zero.
997 ** NO LONGER TRUE:
998 ** To resolve a conflict, first look to see if either action
999 ** is on an error rule. In that case, take the action which
1000 ** is not associated with the error rule. If neither or both
1001 ** actions are associated with an error rule, then try to
1002 ** use precedence to resolve the conflict.
1004 ** If either action is a SHIFT, then it must be apx. This
1005 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1007 static int resolve_conflict(apx,apy,errsym)
1008 struct action *apx;
1009 struct action *apy;
1010 struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1012 struct symbol *spx, *spy;
1013 int errcnt = 0;
1014 UNUSED(errsym);
1015 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1016 if( apx->type==SHIFT && apy->type==REDUCE ){
1017 spx = apx->sp;
1018 spy = apy->x.rp->precsym;
1019 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1020 /* Not enough precedence information. */
1021 apy->type = CONFLICT;
1022 errcnt++;
1023 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1024 apy->type = RD_RESOLVED;
1025 }else if( spx->prec<spy->prec ){
1026 apx->type = SH_RESOLVED;
1027 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1028 apy->type = RD_RESOLVED; /* associativity */
1029 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1030 apx->type = SH_RESOLVED;
1031 }else{
1032 assert( spx->prec==spy->prec && spx->assoc==NONE );
1033 apy->type = CONFLICT;
1034 errcnt++;
1036 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1037 spx = apx->x.rp->precsym;
1038 spy = apy->x.rp->precsym;
1039 if( spx==0 || spy==0 || spx->prec<0 ||
1040 spy->prec<0 || spx->prec==spy->prec ){
1041 apy->type = CONFLICT;
1042 errcnt++;
1043 }else if( spx->prec>spy->prec ){
1044 apy->type = RD_RESOLVED;
1045 }else if( spx->prec<spy->prec ){
1046 apx->type = RD_RESOLVED;
1048 }else{
1049 assert(
1050 apx->type==SH_RESOLVED ||
1051 apx->type==RD_RESOLVED ||
1052 apx->type==CONFLICT ||
1053 apy->type==SH_RESOLVED ||
1054 apy->type==RD_RESOLVED ||
1055 apy->type==CONFLICT
1057 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1058 ** REDUCEs on the list. If we reach this point it must be because
1059 ** the parser conflict had already been resolved. */
1061 return errcnt;
1063 /********************* From the file "configlist.c" *************************/
1065 ** Routines to processing a configuration list and building a state
1066 ** in the LEMON parser generator.
1069 static struct config *freelist = 0; /* List of free configurations */
1070 static struct config *current = 0; /* Top of list of configurations */
1071 static struct config **currentend = 0; /* Last on list of configs */
1072 static struct config *basis = 0; /* Top of list of basis configs */
1073 static struct config **basisend = 0; /* End of list of basis configs */
1075 /* Return a pointer to a new configuration */
1076 PRIVATE struct config *newconfig(){
1077 struct config *new;
1078 if( freelist==0 ){
1079 int i;
1080 int amt = 3;
1081 freelist = (struct config *)malloc( sizeof(struct config)*amt );
1082 if( freelist==0 ){
1083 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1084 exit(1);
1086 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1087 freelist[amt-1].next = 0;
1089 new = freelist;
1090 freelist = freelist->next;
1091 return new;
1094 /* The configuration "old" is no longer used */
1095 PRIVATE void deleteconfig(old)
1096 struct config *old;
1098 old->next = freelist;
1099 freelist = old;
1102 /* Initialized the configuration list builder */
1103 void Configlist_init(){
1104 current = 0;
1105 currentend = &current;
1106 basis = 0;
1107 basisend = &basis;
1108 Configtable_init();
1109 return;
1112 /* Initialized the configuration list builder */
1113 void Configlist_reset(){
1114 current = 0;
1115 currentend = &current;
1116 basis = 0;
1117 basisend = &basis;
1118 Configtable_clear(0);
1119 return;
1122 /* Add another configuration to the configuration list */
1123 struct config *Configlist_add(rp,dot)
1124 struct rule *rp; /* The rule */
1125 int dot; /* Index into the RHS of the rule where the dot goes */
1127 struct config *cfp, model;
1129 assert( currentend!=0 );
1130 model.rp = rp;
1131 model.dot = dot;
1132 cfp = Configtable_find(&model);
1133 if( cfp==0 ){
1134 cfp = newconfig();
1135 cfp->rp = rp;
1136 cfp->dot = dot;
1137 cfp->fws = SetNew();
1138 cfp->stp = 0;
1139 cfp->fplp = cfp->bplp = 0;
1140 cfp->next = 0;
1141 cfp->bp = 0;
1142 *currentend = cfp;
1143 currentend = &cfp->next;
1144 Configtable_insert(cfp);
1146 return cfp;
1149 /* Add a basis configuration to the configuration list */
1150 struct config *Configlist_addbasis(rp,dot)
1151 struct rule *rp;
1152 int dot;
1154 struct config *cfp, model;
1156 assert( basisend!=0 );
1157 assert( currentend!=0 );
1158 model.rp = rp;
1159 model.dot = dot;
1160 cfp = Configtable_find(&model);
1161 if( cfp==0 ){
1162 cfp = newconfig();
1163 cfp->rp = rp;
1164 cfp->dot = dot;
1165 cfp->fws = SetNew();
1166 cfp->stp = 0;
1167 cfp->fplp = cfp->bplp = 0;
1168 cfp->next = 0;
1169 cfp->bp = 0;
1170 *currentend = cfp;
1171 currentend = &cfp->next;
1172 *basisend = cfp;
1173 basisend = &cfp->bp;
1174 Configtable_insert(cfp);
1176 return cfp;
1179 /* Compute the closure of the configuration list */
1180 void Configlist_closure(lemp)
1181 struct lemon *lemp;
1183 struct config *cfp, *newcfp;
1184 struct rule *rp, *newrp;
1185 struct symbol *sp, *xsp;
1186 int i, dot;
1188 assert( currentend!=0 );
1189 for(cfp=current; cfp; cfp=cfp->next){
1190 rp = cfp->rp;
1191 dot = cfp->dot;
1192 if( dot>=rp->nrhs ) continue;
1193 sp = rp->rhs[dot];
1194 if( sp->type==NONTERMINAL ){
1195 if( sp->rule==0 && sp!=lemp->errsym ){
1196 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1197 sp->name);
1198 lemp->errorcnt++;
1200 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1201 newcfp = Configlist_add(newrp,0);
1202 for(i=dot+1; i<rp->nrhs; i++){
1203 xsp = rp->rhs[i];
1204 if( xsp->type==TERMINAL ){
1205 SetAdd(newcfp->fws,xsp->index);
1206 break;
1207 }else{
1208 SetUnion(newcfp->fws,xsp->firstset);
1209 if( xsp->lambda==Bo_FALSE ) break;
1212 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1216 return;
1219 /* Sort the configuration list */
1220 void Configlist_sort(){
1221 current = (struct config *)msort(current,(void **)&(current->next),Configcmp);
1222 currentend = 0;
1223 return;
1226 /* Sort the basis configuration list */
1227 void Configlist_sortbasis(){
1228 basis = (struct config *)msort(current,(void **)&(current->bp),Configcmp);
1229 basisend = 0;
1230 return;
1233 /* Return a pointer to the head of the configuration list and
1234 ** reset the list */
1235 struct config *Configlist_return(){
1236 struct config *old;
1237 old = current;
1238 current = 0;
1239 currentend = 0;
1240 return old;
1243 /* Return a pointer to the head of the configuration list and
1244 ** reset the list */
1245 struct config *Configlist_basis(){
1246 struct config *old;
1247 old = basis;
1248 basis = 0;
1249 basisend = 0;
1250 return old;
1253 /* Free all elements of the given configuration list */
1254 void Configlist_eat(cfp)
1255 struct config *cfp;
1257 struct config *nextcfp;
1258 for(; cfp; cfp=nextcfp){
1259 nextcfp = cfp->next;
1260 assert( cfp->fplp==0 );
1261 assert( cfp->bplp==0 );
1262 if( cfp->fws ) SetFree(cfp->fws);
1263 deleteconfig(cfp);
1265 return;
1267 /***************** From the file "error.c" *********************************/
1269 ** Code for printing error message.
1272 /* Find a good place to break "msg" so that its length is at least "min"
1273 ** but no more than "max". Make the point as close to max as possible.
1275 static int findbreak(msg,min,max)
1276 char *msg;
1277 int min;
1278 int max;
1280 int i,spot;
1281 char c;
1282 for(i=spot=min; i<=max; i++){
1283 c = msg[i];
1284 if( c=='\t' ) msg[i] = ' ';
1285 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1286 if( c==0 ){ spot = i; break; }
1287 if( c=='-' && i<max-1 ) spot = i+1;
1288 if( c==' ' ) spot = i;
1290 return spot;
1294 ** The error message is split across multiple lines if necessary. The
1295 ** splits occur at a space, if there is a space available near the end
1296 ** of the line.
1298 #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1299 #define LINEWIDTH 79 /* Max width of any output line */
1300 #define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1301 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1302 char errmsg[ERRMSGSIZE];
1303 char prefix[PREFIXLIMIT+10];
1304 int errmsgsize;
1305 int prefixsize;
1306 int availablewidth;
1307 va_list ap;
1308 int end, restart, base;
1310 va_start(ap, format);
1311 /* Prepare a prefix to be prepended to every output line */
1312 if( lineno>0 ){
1313 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1314 }else{
1315 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1317 prefixsize = strlen(prefix);
1318 availablewidth = LINEWIDTH - prefixsize;
1320 /* Generate the error message */
1321 vsprintf(errmsg,format,ap);
1322 va_end(ap);
1323 errmsgsize = strlen(errmsg);
1324 /* Remove trailing '\n's from the error message. */
1325 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1326 errmsg[--errmsgsize] = 0;
1329 /* Print the error message */
1330 base = 0;
1331 while( errmsg[base]!=0 ){
1332 end = restart = findbreak(&errmsg[base],0,availablewidth);
1333 restart += base;
1334 while( errmsg[restart]==' ' ) restart++;
1335 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1336 base = restart;
1339 /**************** From the file "main.c" ************************************/
1341 ** Main program file for the LEMON parser generator.
1344 /* Report an out-of-memory condition and abort. This function
1345 ** is used mostly by the "MemoryCheck" macro in struct.h
1347 void memory_error() {
1348 fprintf(stderr,"Out of memory. Aborting...\n");
1349 exit(1);
1353 /* The main program. Parse the command line and do it... */
1354 int main(argc,argv)
1355 int argc;
1356 char **argv;
1358 static int version = 0;
1359 static int rpflag = 0;
1360 static int basisflag = 0;
1361 static int compress = 0;
1362 static int quiet = 0;
1363 static int statistics = 0;
1364 static int mhflag = 0;
1365 static struct s_options options[] = {
1366 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1367 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1368 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1369 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1370 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1371 {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."},
1372 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1373 {OPT_FLAG,0,0,0}
1375 int i;
1376 struct lemon lem;
1377 char *def_tmpl_name = "lempar.c";
1379 UNUSED(argc);
1380 OptInit(argv,options,stderr);
1381 if( version ){
1382 printf("Lemon version 1.0\n");
1383 exit(0);
1385 if( OptNArgs() < 1 ){
1386 fprintf(stderr,"Exactly one filename argument is required.\n");
1387 exit(1);
1389 lem.errorcnt = 0;
1391 /* Initialize the machine */
1392 Strsafe_init();
1393 Symbol_init();
1394 State_init();
1395 lem.argv0 = argv[0];
1396 lem.filename = OptArg(0);
1397 lem.tmplname = (OptNArgs() == 2) ? OptArg(1) : def_tmpl_name;
1398 lem.basisflag = basisflag;
1399 lem.has_fallback = 0;
1400 lem.nconflict = 0;
1401 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
1402 lem.vartype = 0;
1403 lem.stacksize = 0;
1404 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1405 lem.tokenprefix = lem.outname = lem.extracode = 0;
1406 lem.vardest = 0;
1407 lem.tablesize = 0;
1408 Symbol_new("$");
1409 lem.errsym = Symbol_new("error");
1411 /* Parse the input file */
1412 Parse(&lem);
1413 if( lem.errorcnt ) exit(lem.errorcnt);
1414 if( lem.rule==0 ){
1415 fprintf(stderr,"Empty grammar.\n");
1416 exit(1);
1419 /* Count and index the symbols of the grammar */
1420 Symbol_new("{default}");
1421 lem.nsymbol = Symbol_count();
1422 lem.symbols = Symbol_arrayof();
1423 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1424 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*),
1425 (int(*)())Symbolcmpp);
1426 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1427 for(i=1; i<lem.nsymbol && isupper(lem.symbols[i]->name[0]); i++);
1428 lem.nsymbol--; /*(do not count "{default}")*/
1429 lem.nterminal = i;
1431 /* Generate a reprint of the grammar, if requested on the command line */
1432 if( rpflag ){
1433 Reprint(&lem);
1434 }else{
1435 /* Initialize the size for all follow and first sets */
1436 SetSize(lem.nterminal);
1438 /* Find the precedence for every production rule (that has one) */
1439 FindRulePrecedences(&lem);
1441 /* Compute the lambda-nonterminals and the first-sets for every
1442 ** nonterminal */
1443 FindFirstSets(&lem);
1445 /* Compute all LR(0) states. Also record follow-set propagation
1446 ** links so that the follow-set can be computed later */
1447 lem.nstate = 0;
1448 FindStates(&lem);
1449 lem.nstate = State_count();
1450 lem.sorted = State_arrayof();
1452 /* Tie up loose ends on the propagation links */
1453 FindLinks(&lem);
1455 /* Compute the follow set of every reducible configuration */
1456 FindFollowSets(&lem);
1458 /* Compute the action tables */
1459 FindActions(&lem);
1461 /* Compress the action tables */
1462 if( compress==0 ) CompressTables(&lem);
1464 /* Generate a report of the parser generated. (the "y.output" file) */
1465 if( !quiet ) ReportOutput(&lem);
1467 /* Generate the source code for the parser */
1468 ReportTable(&lem, mhflag);
1470 /* Produce a header file for use by the scanner. (This step is
1471 ** omitted if the "-m" option is used because makeheaders will
1472 ** generate the file for us.) */
1473 if( !mhflag ) ReportHeader(&lem);
1475 if( statistics ){
1476 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1477 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1478 printf(" %d states, %d parser table entries, %d conflicts\n",
1479 lem.nstate, lem.tablesize, lem.nconflict);
1481 if( lem.nconflict ){
1482 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1484 exit(lem.errorcnt + lem.nconflict);
1486 /******************** From the file "msort.c" *******************************/
1488 ** A generic merge-sort program.
1490 ** USAGE:
1491 ** Let "ptr" be a pointer to some structure which is at the head of
1492 ** a null-terminated list. Then to sort the list call:
1494 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1496 ** In the above, "cmpfnc" is a pointer to a function which compares
1497 ** two instances of the structure and returns an integer, as in
1498 ** strcmp. The second argument is a pointer to the pointer to the
1499 ** second element of the linked list. This address is used to compute
1500 ** the offset to the "next" field within the structure. The offset to
1501 ** the "next" field must be constant for all structures in the list.
1503 ** The function returns a new pointer which is the head of the list
1504 ** after sorting.
1506 ** ALGORITHM:
1507 ** Merge-sort.
1511 ** Return a pointer to the next structure in the linked list.
1513 #define NEXT(A) (*(char**)(((unsigned long)A)+offset))
1516 ** Inputs:
1517 ** a: A sorted, null-terminated linked list. (May be null).
1518 ** b: A sorted, null-terminated linked list. (May be null).
1519 ** cmp: A pointer to the comparison function.
1520 ** offset: Offset in the structure to the "next" field.
1522 ** Return Value:
1523 ** A pointer to the head of a sorted list containing the elements
1524 ** of both a and b.
1526 ** Side effects:
1527 ** The "next" pointers for elements in the lists a and b are
1528 ** changed.
1530 static char *merge(a,b,cmp,offset)
1531 char *a;
1532 char *b;
1533 int (*cmp)();
1534 int offset;
1536 char *ptr, *head;
1538 if( a==0 ){
1539 head = b;
1540 }else if( b==0 ){
1541 head = a;
1542 }else{
1543 if( (*cmp)(a,b)<0 ){
1544 ptr = a;
1545 a = NEXT(a);
1546 }else{
1547 ptr = b;
1548 b = NEXT(b);
1550 head = ptr;
1551 while( a && b ){
1552 if( (*cmp)(a,b)<0 ){
1553 NEXT(ptr) = a;
1554 ptr = a;
1555 a = NEXT(a);
1556 }else{
1557 NEXT(ptr) = b;
1558 ptr = b;
1559 b = NEXT(b);
1562 if( a ) NEXT(ptr) = a;
1563 else NEXT(ptr) = b;
1565 return head;
1569 ** Inputs:
1570 ** list: Pointer to a singly-linked list of structures.
1571 ** next: Pointer to pointer to the second element of the list.
1572 ** cmp: A comparison function.
1574 ** Return Value:
1575 ** A pointer to the head of a sorted list containing the elements
1576 ** orginally in list.
1578 ** Side effects:
1579 ** The "next" pointers for elements in list are changed.
1581 #define LISTSIZE 30
1582 void *msort(void *list, void **next, int(*cmp)(void *, void *))
1584 unsigned long offset;
1585 char *ep;
1586 char *set[LISTSIZE];
1587 int i;
1588 offset = (unsigned long)next - (unsigned long)list;
1589 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1590 while( list ){
1591 ep = list;
1592 list = NEXT(list);
1593 NEXT(ep) = 0;
1594 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1595 ep = merge(ep,set[i],cmp,offset);
1596 set[i] = 0;
1598 set[i] = ep;
1600 ep = 0;
1601 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1602 return ep;
1604 /************************ From the file "option.c" **************************/
1605 static char **argv;
1606 static struct s_options *op;
1607 static FILE *errstream;
1609 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1612 ** Print the command line with a carrot pointing to the k-th character
1613 ** of the n-th field.
1615 static void errline(n,k,err)
1616 int n;
1617 int k;
1618 FILE *err;
1620 int spcnt = 0, i;
1621 if( argv[0] ) {
1622 fprintf(err,"%s",argv[0]);
1623 spcnt += strlen(argv[0]) + 1;
1625 for(i=1; i<n && argv[i]; i++){
1626 fprintf(err," %s",argv[i]);
1627 spcnt += strlen(argv[i]) + 1;
1629 spcnt += k;
1630 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1631 if( spcnt<20 ){
1632 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1633 }else{
1634 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1639 ** Return the index of the N-th non-switch argument. Return -1
1640 ** if N is out of range.
1642 static int argindex(n)
1643 int n;
1645 int i;
1646 int dashdash = 0;
1647 if( argv!=0 && *argv!=0 ){
1648 for(i=1; argv[i]; i++){
1649 if( dashdash || !ISOPT(argv[i]) ){
1650 if( n==0 ) return i;
1651 n--;
1653 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1656 return -1;
1659 static char emsg[] = "Command line syntax error: ";
1662 ** Process a flag command line argument.
1664 static int handleflags(i,err)
1665 int i;
1666 FILE *err;
1668 int v;
1669 int errcnt = 0;
1670 int j;
1671 for(j=0; op[j].label; j++){
1672 if( strcmp(&argv[i][1],op[j].label)==0 ) break;
1674 v = argv[i][0]=='-' ? 1 : 0;
1675 if( op[j].label==0 ){
1676 if( err ){
1677 fprintf(err,"%sundefined option.\n",emsg);
1678 errline(i,1,err);
1680 errcnt++;
1681 }else if( op[j].type==OPT_FLAG ){
1682 *((int*)op[j].arg) = v;
1683 }else if( op[j].type==OPT_FFLAG ){
1684 (*(void(*)())(intptr_t)(op[j].arg))(v);
1685 }else{
1686 if( err ){
1687 fprintf(err,"%smissing argument on switch.\n",emsg);
1688 errline(i,1,err);
1690 errcnt++;
1692 return errcnt;
1696 ** Process a command line switch which has an argument.
1698 static int handleswitch(i,err)
1699 int i;
1700 FILE *err;
1702 int lv = 0;
1703 double dv = 0.0;
1704 char *sv = 0, *end;
1705 char *cp;
1706 int j;
1707 int errcnt = 0;
1708 cp = strchr(argv[i],'=');
1709 *cp = 0;
1710 for(j=0; op[j].label; j++){
1711 if( strcmp(argv[i],op[j].label)==0 ) break;
1713 *cp = '=';
1714 if( op[j].label==0 ){
1715 if( err ){
1716 fprintf(err,"%sundefined option.\n",emsg);
1717 errline(i,0,err);
1719 errcnt++;
1720 }else{
1721 cp++;
1722 switch( op[j].type ){
1723 case OPT_FLAG:
1724 case OPT_FFLAG:
1725 if( err ){
1726 fprintf(err,"%soption requires an argument.\n",emsg);
1727 errline(i,0,err);
1729 errcnt++;
1730 break;
1731 case OPT_DBL:
1732 case OPT_FDBL:
1733 dv = strtod(cp,&end);
1734 if( *end ){
1735 if( err ){
1736 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
1737 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1739 errcnt++;
1741 break;
1742 case OPT_INT:
1743 case OPT_FINT:
1744 lv = strtol(cp,&end,0);
1745 if( *end ){
1746 if( err ){
1747 fprintf(err,"%sillegal character in integer argument.\n",emsg);
1748 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1750 errcnt++;
1752 break;
1753 case OPT_STR:
1754 case OPT_FSTR:
1755 sv = cp;
1756 break;
1758 switch( op[j].type ){
1759 case OPT_FLAG:
1760 case OPT_FFLAG:
1761 break;
1762 case OPT_DBL:
1763 *(double*)(op[j].arg) = dv;
1764 break;
1765 case OPT_FDBL:
1766 (*(void(*)())(intptr_t)(op[j].arg))(dv);
1767 break;
1768 case OPT_INT:
1769 *(int*)(op[j].arg) = lv;
1770 break;
1771 case OPT_FINT:
1772 (*(void(*)())(intptr_t)(op[j].arg))((int)lv);
1773 break;
1774 case OPT_STR:
1775 *(char**)(op[j].arg) = sv;
1776 break;
1777 case OPT_FSTR:
1778 (*(void(*)())(intptr_t)(op[j].arg))(sv);
1779 break;
1782 return errcnt;
1785 int OptInit(a,o,err)
1786 char **a;
1787 struct s_options *o;
1788 FILE *err;
1790 int errcnt = 0;
1791 argv = a;
1792 op = o;
1793 errstream = err;
1794 if( argv && *argv && op ){
1795 int i;
1796 for(i=1; argv[i]; i++){
1797 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1798 errcnt += handleflags(i,err);
1799 }else if( strchr(argv[i],'=') ){
1800 errcnt += handleswitch(i,err);
1804 if( errcnt>0 ){
1805 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
1806 OptPrint();
1807 exit(1);
1809 return 0;
1812 int OptNArgs(){
1813 int cnt = 0;
1814 int dashdash = 0;
1815 int i;
1816 if( argv!=0 && argv[0]!=0 ){
1817 for(i=1; argv[i]; i++){
1818 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1819 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1822 return cnt;
1825 char *OptArg(n)
1826 int n;
1828 int i;
1829 i = argindex(n);
1830 return i>=0 ? argv[i] : 0;
1833 void OptErr(n)
1834 int n;
1836 int i;
1837 i = argindex(n);
1838 if( i>=0 ) errline(i,0,errstream);
1841 void OptPrint(){
1842 int i;
1843 int max, len;
1844 max = 0;
1845 for(i=0; op[i].label; i++){
1846 len = strlen(op[i].label) + 1;
1847 switch( op[i].type ){
1848 case OPT_FLAG:
1849 case OPT_FFLAG:
1850 break;
1851 case OPT_INT:
1852 case OPT_FINT:
1853 len += 9; /* length of "<integer>" */
1854 break;
1855 case OPT_DBL:
1856 case OPT_FDBL:
1857 len += 6; /* length of "<real>" */
1858 break;
1859 case OPT_STR:
1860 case OPT_FSTR:
1861 len += 8; /* length of "<string>" */
1862 break;
1864 if( len>max ) max = len;
1866 for(i=0; op[i].label; i++){
1867 switch( op[i].type ){
1868 case OPT_FLAG:
1869 case OPT_FFLAG:
1870 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1871 break;
1872 case OPT_INT:
1873 case OPT_FINT:
1874 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
1875 (int)(max-strlen(op[i].label)-9),"",op[i].message);
1876 break;
1877 case OPT_DBL:
1878 case OPT_FDBL:
1879 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
1880 (int)(max-strlen(op[i].label)-6),"",op[i].message);
1881 break;
1882 case OPT_STR:
1883 case OPT_FSTR:
1884 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
1885 (int)(max-strlen(op[i].label)-8),"",op[i].message);
1886 break;
1890 /*********************** From the file "parse.c" ****************************/
1892 ** Input file parser for the LEMON parser generator.
1895 /* The state of the parser */
1896 struct pstate {
1897 char *filename; /* Name of the input file */
1898 int tokenlineno; /* Linenumber at which current token starts */
1899 int errorcnt; /* Number of errors so far */
1900 char *tokenstart; /* Text of current token */
1901 struct lemon *gp; /* Global state vector */
1902 enum e_state {
1903 INITIALIZE,
1904 WAITING_FOR_DECL_OR_RULE,
1905 WAITING_FOR_DECL_KEYWORD,
1906 WAITING_FOR_DECL_ARG,
1907 WAITING_FOR_PRECEDENCE_SYMBOL,
1908 WAITING_FOR_ARROW,
1909 IN_RHS,
1910 LHS_ALIAS_1,
1911 LHS_ALIAS_2,
1912 LHS_ALIAS_3,
1913 RHS_ALIAS_1,
1914 RHS_ALIAS_2,
1915 PRECEDENCE_MARK_1,
1916 PRECEDENCE_MARK_2,
1917 RESYNC_AFTER_RULE_ERROR,
1918 RESYNC_AFTER_DECL_ERROR,
1919 WAITING_FOR_DESTRUCTOR_SYMBOL,
1920 WAITING_FOR_DATATYPE_SYMBOL,
1921 WAITING_FOR_FALLBACK_ID
1922 } state; /* The state of the parser */
1923 struct symbol *fallback; /* The fallback token */
1924 struct symbol *lhs; /* Left-hand side of current rule */
1925 char *lhsalias; /* Alias for the LHS */
1926 int nrhs; /* Number of right-hand side symbols seen */
1927 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1928 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1929 struct rule *prevrule; /* Previous rule parsed */
1930 char *declkeyword; /* Keyword of a declaration */
1931 char **declargslot; /* Where the declaration argument should be put */
1932 int *decllnslot; /* Where the declaration linenumber is put */
1933 enum e_assoc declassoc; /* Assign this association to decl arguments */
1934 int preccounter; /* Assign this precedence to decl arguments */
1935 struct rule *firstrule; /* Pointer to first rule in the grammar */
1936 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1939 /* Parse a single token */
1940 static void parseonetoken(psp)
1941 struct pstate *psp;
1943 char *x;
1944 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1945 #if 0
1946 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1947 x,psp->state);
1948 #endif
1949 switch( psp->state ){
1950 case INITIALIZE:
1951 psp->prevrule = 0;
1952 psp->preccounter = 0;
1953 psp->firstrule = psp->lastrule = 0;
1954 psp->gp->nrule = 0;
1955 /* Fall thru to next case */
1956 case WAITING_FOR_DECL_OR_RULE:
1957 if( x[0]=='%' ){
1958 psp->state = WAITING_FOR_DECL_KEYWORD;
1959 }else if( islower(x[0]) ){
1960 psp->lhs = Symbol_new(x);
1961 psp->nrhs = 0;
1962 psp->lhsalias = 0;
1963 psp->state = WAITING_FOR_ARROW;
1964 }else if( x[0]=='{' ){
1965 if( psp->prevrule==0 ){
1966 ErrorMsg(psp->filename,psp->tokenlineno,
1967 "There is not prior rule opon which to attach the code \
1968 fragment which begins on this line.");
1969 psp->errorcnt++;
1970 }else if( psp->prevrule->code!=0 ){
1971 ErrorMsg(psp->filename,psp->tokenlineno,
1972 "Code fragment beginning on this line is not the first \
1973 to follow the previous rule.");
1974 psp->errorcnt++;
1975 }else{
1976 psp->prevrule->line = psp->tokenlineno;
1977 psp->prevrule->code = &x[1];
1979 }else if( x[0]=='[' ){
1980 psp->state = PRECEDENCE_MARK_1;
1981 }else{
1982 ErrorMsg(psp->filename,psp->tokenlineno,
1983 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1985 psp->errorcnt++;
1987 break;
1988 case PRECEDENCE_MARK_1:
1989 if( !isupper(x[0]) ){
1990 ErrorMsg(psp->filename,psp->tokenlineno,
1991 "The precedence symbol must be a terminal.");
1992 psp->errorcnt++;
1993 }else if( psp->prevrule==0 ){
1994 ErrorMsg(psp->filename,psp->tokenlineno,
1995 "There is no prior rule to assign precedence \"[%s]\".",x);
1996 psp->errorcnt++;
1997 }else if( psp->prevrule->precsym!=0 ){
1998 ErrorMsg(psp->filename,psp->tokenlineno,
1999 "Precedence mark on this line is not the first \
2000 to follow the previous rule.");
2001 psp->errorcnt++;
2002 }else{
2003 psp->prevrule->precsym = Symbol_new(x);
2005 psp->state = PRECEDENCE_MARK_2;
2006 break;
2007 case PRECEDENCE_MARK_2:
2008 if( x[0]!=']' ){
2009 ErrorMsg(psp->filename,psp->tokenlineno,
2010 "Missing \"]\" on precedence mark.");
2011 psp->errorcnt++;
2013 psp->state = WAITING_FOR_DECL_OR_RULE;
2014 break;
2015 case WAITING_FOR_ARROW:
2016 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2017 psp->state = IN_RHS;
2018 }else if( x[0]=='(' ){
2019 psp->state = LHS_ALIAS_1;
2020 }else{
2021 ErrorMsg(psp->filename,psp->tokenlineno,
2022 "Expected to see a \":\" following the LHS symbol \"%s\".",
2023 psp->lhs->name);
2024 psp->errorcnt++;
2025 psp->state = RESYNC_AFTER_RULE_ERROR;
2027 break;
2028 case LHS_ALIAS_1:
2029 if( isalpha(x[0]) ){
2030 psp->lhsalias = x;
2031 psp->state = LHS_ALIAS_2;
2032 }else{
2033 ErrorMsg(psp->filename,psp->tokenlineno,
2034 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2035 x,psp->lhs->name);
2036 psp->errorcnt++;
2037 psp->state = RESYNC_AFTER_RULE_ERROR;
2039 break;
2040 case LHS_ALIAS_2:
2041 if( x[0]==')' ){
2042 psp->state = LHS_ALIAS_3;
2043 }else{
2044 ErrorMsg(psp->filename,psp->tokenlineno,
2045 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2046 psp->errorcnt++;
2047 psp->state = RESYNC_AFTER_RULE_ERROR;
2049 break;
2050 case LHS_ALIAS_3:
2051 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2052 psp->state = IN_RHS;
2053 }else{
2054 ErrorMsg(psp->filename,psp->tokenlineno,
2055 "Missing \"->\" following: \"%s(%s)\".",
2056 psp->lhs->name,psp->lhsalias);
2057 psp->errorcnt++;
2058 psp->state = RESYNC_AFTER_RULE_ERROR;
2060 break;
2061 case IN_RHS:
2062 if( x[0]=='.' ){
2063 struct rule *rp;
2064 rp = (struct rule *)malloc( sizeof(struct rule) +
2065 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2066 if( rp==0 ){
2067 ErrorMsg(psp->filename,psp->tokenlineno,
2068 "Can't allocate enough memory for this rule.");
2069 psp->errorcnt++;
2070 psp->prevrule = 0;
2071 }else{
2072 int i;
2073 rp->ruleline = psp->tokenlineno;
2074 rp->rhs = (struct symbol**)&rp[1];
2075 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2076 for(i=0; i<psp->nrhs; i++){
2077 rp->rhs[i] = psp->rhs[i];
2078 rp->rhsalias[i] = psp->alias[i];
2080 rp->lhs = psp->lhs;
2081 rp->lhsalias = psp->lhsalias;
2082 rp->nrhs = psp->nrhs;
2083 rp->code = 0;
2084 rp->precsym = 0;
2085 rp->index = psp->gp->nrule++;
2086 rp->nextlhs = rp->lhs->rule;
2087 rp->lhs->rule = rp;
2088 rp->next = 0;
2089 if( psp->firstrule==0 ){
2090 psp->firstrule = psp->lastrule = rp;
2091 }else{
2092 psp->lastrule->next = rp;
2093 psp->lastrule = rp;
2095 psp->prevrule = rp;
2097 psp->state = WAITING_FOR_DECL_OR_RULE;
2098 }else if( isalpha(x[0]) ){
2099 if( psp->nrhs>=MAXRHS ){
2100 ErrorMsg(psp->filename,psp->tokenlineno,
2101 "Too many symbol on RHS or rule beginning at \"%s\".",
2103 psp->errorcnt++;
2104 psp->state = RESYNC_AFTER_RULE_ERROR;
2105 }else{
2106 psp->rhs[psp->nrhs] = Symbol_new(x);
2107 psp->alias[psp->nrhs] = 0;
2108 psp->nrhs++;
2110 }else if( x[0]=='(' && psp->nrhs>0 ){
2111 psp->state = RHS_ALIAS_1;
2112 }else{
2113 ErrorMsg(psp->filename,psp->tokenlineno,
2114 "Illegal character on RHS of rule: \"%s\".",x);
2115 psp->errorcnt++;
2116 psp->state = RESYNC_AFTER_RULE_ERROR;
2118 break;
2119 case RHS_ALIAS_1:
2120 if( isalpha(x[0]) ){
2121 psp->alias[psp->nrhs-1] = x;
2122 psp->state = RHS_ALIAS_2;
2123 }else{
2124 ErrorMsg(psp->filename,psp->tokenlineno,
2125 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2126 x,psp->rhs[psp->nrhs-1]->name);
2127 psp->errorcnt++;
2128 psp->state = RESYNC_AFTER_RULE_ERROR;
2130 break;
2131 case RHS_ALIAS_2:
2132 if( x[0]==')' ){
2133 psp->state = IN_RHS;
2134 }else{
2135 ErrorMsg(psp->filename,psp->tokenlineno,
2136 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2137 psp->errorcnt++;
2138 psp->state = RESYNC_AFTER_RULE_ERROR;
2140 break;
2141 case WAITING_FOR_DECL_KEYWORD:
2142 if( isalpha(x[0]) ){
2143 psp->declkeyword = x;
2144 psp->declargslot = 0;
2145 psp->decllnslot = 0;
2146 psp->state = WAITING_FOR_DECL_ARG;
2147 if( strcmp(x,"name")==0 ){
2148 psp->declargslot = &(psp->gp->name);
2149 }else if( strcmp(x,"include")==0 ){
2150 psp->declargslot = &(psp->gp->include);
2151 psp->decllnslot = &psp->gp->includeln;
2152 }else if( strcmp(x,"code")==0 ){
2153 psp->declargslot = &(psp->gp->extracode);
2154 psp->decllnslot = &psp->gp->extracodeln;
2155 }else if( strcmp(x,"token_destructor")==0 ){
2156 psp->declargslot = &psp->gp->tokendest;
2157 psp->decllnslot = &psp->gp->tokendestln;
2158 }else if( strcmp(x,"default_destructor")==0 ){
2159 psp->declargslot = &psp->gp->vardest;
2160 psp->decllnslot = &psp->gp->vardestln;
2161 }else if( strcmp(x,"token_prefix")==0 ){
2162 psp->declargslot = &psp->gp->tokenprefix;
2163 }else if( strcmp(x,"syntax_error")==0 ){
2164 psp->declargslot = &(psp->gp->error);
2165 psp->decllnslot = &psp->gp->errorln;
2166 }else if( strcmp(x,"parse_accept")==0 ){
2167 psp->declargslot = &(psp->gp->accept);
2168 psp->decllnslot = &psp->gp->acceptln;
2169 }else if( strcmp(x,"parse_failure")==0 ){
2170 psp->declargslot = &(psp->gp->failure);
2171 psp->decllnslot = &psp->gp->failureln;
2172 }else if( strcmp(x,"stack_overflow")==0 ){
2173 psp->declargslot = &(psp->gp->overflow);
2174 psp->decllnslot = &psp->gp->overflowln;
2175 }else if( strcmp(x,"extra_argument")==0 ){
2176 psp->declargslot = &(psp->gp->arg);
2177 }else if( strcmp(x,"token_type")==0 ){
2178 psp->declargslot = &(psp->gp->tokentype);
2179 }else if( strcmp(x,"default_type")==0 ){
2180 psp->declargslot = &(psp->gp->vartype);
2181 }else if( strcmp(x,"stack_size")==0 ){
2182 psp->declargslot = &(psp->gp->stacksize);
2183 }else if( strcmp(x,"start_symbol")==0 ){
2184 psp->declargslot = &(psp->gp->start);
2185 }else if( strcmp(x,"left")==0 ){
2186 psp->preccounter++;
2187 psp->declassoc = LEFT;
2188 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2189 }else if( strcmp(x,"right")==0 ){
2190 psp->preccounter++;
2191 psp->declassoc = RIGHT;
2192 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2193 }else if( strcmp(x,"nonassoc")==0 ){
2194 psp->preccounter++;
2195 psp->declassoc = NONE;
2196 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2197 }else if( strcmp(x,"destructor")==0 ){
2198 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2199 }else if( strcmp(x,"type")==0 ){
2200 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2201 }else if( strcmp(x,"fallback")==0 ){
2202 psp->fallback = 0;
2203 psp->state = WAITING_FOR_FALLBACK_ID;
2204 }else{
2205 ErrorMsg(psp->filename,psp->tokenlineno,
2206 "Unknown declaration keyword: \"%%%s\".",x);
2207 psp->errorcnt++;
2208 psp->state = RESYNC_AFTER_DECL_ERROR;
2210 }else{
2211 ErrorMsg(psp->filename,psp->tokenlineno,
2212 "Illegal declaration keyword: \"%s\".",x);
2213 psp->errorcnt++;
2214 psp->state = RESYNC_AFTER_DECL_ERROR;
2216 break;
2217 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2218 if( !isalpha(x[0]) ){
2219 ErrorMsg(psp->filename,psp->tokenlineno,
2220 "Symbol name missing after %destructor keyword");
2221 psp->errorcnt++;
2222 psp->state = RESYNC_AFTER_DECL_ERROR;
2223 }else{
2224 struct symbol *sp = Symbol_new(x);
2225 psp->declargslot = &sp->destructor;
2226 psp->decllnslot = &sp->destructorln;
2227 psp->state = WAITING_FOR_DECL_ARG;
2229 break;
2230 case WAITING_FOR_DATATYPE_SYMBOL:
2231 if( !isalpha(x[0]) ){
2232 ErrorMsg(psp->filename,psp->tokenlineno,
2233 "Symbol name missing after %destructor keyword");
2234 psp->errorcnt++;
2235 psp->state = RESYNC_AFTER_DECL_ERROR;
2236 }else{
2237 struct symbol *sp = Symbol_new(x);
2238 psp->declargslot = &sp->datatype;
2239 psp->decllnslot = 0;
2240 psp->state = WAITING_FOR_DECL_ARG;
2242 break;
2243 case WAITING_FOR_PRECEDENCE_SYMBOL:
2244 if( x[0]=='.' ){
2245 psp->state = WAITING_FOR_DECL_OR_RULE;
2246 }else if( isupper(x[0]) ){
2247 struct symbol *sp;
2248 sp = Symbol_new(x);
2249 if( sp->prec>=0 ){
2250 ErrorMsg(psp->filename,psp->tokenlineno,
2251 "Symbol \"%s\" has already be given a precedence.",x);
2252 psp->errorcnt++;
2253 }else{
2254 sp->prec = psp->preccounter;
2255 sp->assoc = psp->declassoc;
2257 }else{
2258 ErrorMsg(psp->filename,psp->tokenlineno,
2259 "Can't assign a precedence to \"%s\".",x);
2260 psp->errorcnt++;
2262 break;
2263 case WAITING_FOR_DECL_ARG:
2264 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2265 if( *(psp->declargslot)!=0 ){
2266 ErrorMsg(psp->filename,psp->tokenlineno,
2267 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2268 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2269 psp->errorcnt++;
2270 psp->state = RESYNC_AFTER_DECL_ERROR;
2271 }else{
2272 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2273 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2274 psp->state = WAITING_FOR_DECL_OR_RULE;
2276 }else{
2277 ErrorMsg(psp->filename,psp->tokenlineno,
2278 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2279 psp->errorcnt++;
2280 psp->state = RESYNC_AFTER_DECL_ERROR;
2282 break;
2283 case WAITING_FOR_FALLBACK_ID:
2284 if( x[0]=='.' ){
2285 psp->state = WAITING_FOR_DECL_OR_RULE;
2286 }else if( !isupper(x[0]) ){
2287 ErrorMsg(psp->filename, psp->tokenlineno,
2288 "%%fallback argument \"%s\" should be a token", x);
2289 psp->errorcnt++;
2290 }else{
2291 struct symbol *sp = Symbol_new(x);
2292 if( psp->fallback==0 ){
2293 psp->fallback = sp;
2294 }else if( sp->fallback ){
2295 ErrorMsg(psp->filename, psp->tokenlineno,
2296 "More than one fallback assigned to token %s", x);
2297 psp->errorcnt++;
2298 }else{
2299 sp->fallback = psp->fallback;
2300 psp->gp->has_fallback = 1;
2303 break;
2304 case RESYNC_AFTER_RULE_ERROR:
2305 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2306 ** break; */
2307 case RESYNC_AFTER_DECL_ERROR:
2308 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2309 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2310 break;
2314 /* In spite of its name, this function is really a scanner. It read
2315 ** in the entire input file (all at once) then tokenizes it. Each
2316 ** token is passed to the function "parseonetoken" which builds all
2317 ** the appropriate data structures in the global state vector "gp".
2319 struct pstate ps;
2320 void Parse(gp)
2321 struct lemon *gp;
2323 FILE *fp;
2324 char *filebuf;
2325 size_t filesize;
2326 int lineno;
2327 int c;
2328 char *cp, *nextcp;
2329 int startline = 0;
2331 ps.gp = gp;
2332 ps.filename = gp->filename;
2333 ps.errorcnt = 0;
2334 ps.state = INITIALIZE;
2336 /* Begin by reading the input file */
2337 fp = fopen(ps.filename,"rb");
2338 if( fp==0 ){
2339 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2340 gp->errorcnt++;
2341 return;
2343 fseek(fp,0,2);
2344 filesize = ftell(fp);
2345 rewind(fp);
2346 filebuf = (char *)malloc( filesize+1 );
2347 if( filebuf==0 ){
2348 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2349 filesize+1);
2350 fclose(fp);
2351 gp->errorcnt++;
2352 return;
2354 if( fread(filebuf,1,filesize,fp)!=filesize ){
2355 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2356 filesize);
2357 free(filebuf);
2358 fclose(fp);
2359 gp->errorcnt++;
2360 return;
2362 fclose(fp);
2363 filebuf[filesize] = 0;
2365 /* Now scan the text of the input file */
2366 lineno = 1;
2367 for(cp=filebuf; (c= *cp)!=0; ){
2368 if( c=='\n' ) lineno++; /* Keep track of the line number */
2369 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2370 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2371 cp+=2;
2372 while( (c= *cp)!=0 && c!='\n' ) cp++;
2373 continue;
2375 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2376 cp+=2;
2377 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2378 if( c=='\n' ) lineno++;
2379 cp++;
2381 if( c ) cp++;
2382 continue;
2384 ps.tokenstart = cp; /* Mark the beginning of the token */
2385 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2386 if( c=='\"' ){ /* String literals */
2387 cp++;
2388 while( (c= *cp)!=0 && c!='\"' ){
2389 if( c=='\n' ) lineno++;
2390 cp++;
2392 if( c==0 ){
2393 ErrorMsg(ps.filename,startline,
2394 "String starting on this line is not terminated before the end of the file.");
2395 ps.errorcnt++;
2396 nextcp = cp;
2397 }else{
2398 nextcp = cp+1;
2400 }else if( c=='{' ){ /* A block of C code */
2401 int level;
2402 cp++;
2403 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2404 if( c=='\n' ) lineno++;
2405 else if( c=='{' ) level++;
2406 else if( c=='}' ) level--;
2407 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2408 int prevc;
2409 cp = &cp[2];
2410 prevc = 0;
2411 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2412 if( c=='\n' ) lineno++;
2413 prevc = c;
2414 cp++;
2416 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2417 cp = &cp[2];
2418 while( (c= *cp)!=0 && c!='\n' ) cp++;
2419 if( c ) lineno++;
2420 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2421 int startchar, prevc;
2422 startchar = c;
2423 prevc = 0;
2424 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2425 if( c=='\n' ) lineno++;
2426 if( prevc=='\\' ) prevc = 0;
2427 else prevc = c;
2431 if( c==0 ){
2432 ErrorMsg(ps.filename,ps.tokenlineno,
2433 "C code starting on this line is not terminated before the end of the file.");
2434 ps.errorcnt++;
2435 nextcp = cp;
2436 }else{
2437 nextcp = cp+1;
2439 }else if( isalnum(c) ){ /* Identifiers */
2440 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2441 nextcp = cp;
2442 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2443 cp += 3;
2444 nextcp = cp;
2445 }else{ /* All other (one character) operators */
2446 cp++;
2447 nextcp = cp;
2449 c = *cp;
2450 *cp = 0; /* Null terminate the token */
2451 parseonetoken(&ps); /* Parse the token */
2452 *cp = c; /* Restore the buffer */
2453 cp = nextcp;
2455 free(filebuf); /* Release the buffer after parsing */
2456 gp->rule = ps.firstrule;
2457 gp->errorcnt = ps.errorcnt;
2459 /*************************** From the file "plink.c" *********************/
2461 ** Routines processing configuration follow-set propagation links
2462 ** in the LEMON parser generator.
2464 static struct plink *plink_freelist = 0;
2466 /* Allocate a new plink */
2467 struct plink *Plink_new(){
2468 struct plink *new;
2470 if( plink_freelist==0 ){
2471 int i;
2472 int amt = 100;
2473 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2474 if( plink_freelist==0 ){
2475 fprintf(stderr,
2476 "Unable to allocate memory for a new follow-set propagation link.\n");
2477 exit(1);
2479 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2480 plink_freelist[amt-1].next = 0;
2482 new = plink_freelist;
2483 plink_freelist = plink_freelist->next;
2484 return new;
2487 /* Add a plink to a plink list */
2488 void Plink_add(plpp,cfp)
2489 struct plink **plpp;
2490 struct config *cfp;
2492 struct plink *new;
2493 new = Plink_new();
2494 new->next = *plpp;
2495 *plpp = new;
2496 new->cfp = cfp;
2499 /* Transfer every plink on the list "from" to the list "to" */
2500 void Plink_copy(to,from)
2501 struct plink **to;
2502 struct plink *from;
2504 struct plink *nextpl;
2505 while( from ){
2506 nextpl = from->next;
2507 from->next = *to;
2508 *to = from;
2509 from = nextpl;
2513 /* Delete every plink on the list */
2514 void Plink_delete(plp)
2515 struct plink *plp;
2517 struct plink *nextpl;
2519 while( plp ){
2520 nextpl = plp->next;
2521 plp->next = plink_freelist;
2522 plink_freelist = plp;
2523 plp = nextpl;
2526 /*********************** From the file "report.c" **************************/
2528 ** Procedures for generating reports and tables in the LEMON parser generator.
2531 /* Generate a filename with the given suffix. Space to hold the
2532 ** name comes from malloc() and must be freed by the calling
2533 ** function.
2535 PRIVATE char *file_makename(lemp,suffix)
2536 struct lemon *lemp;
2537 char *suffix;
2539 char *name;
2540 char *cp;
2542 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2543 if( name==0 ){
2544 fprintf(stderr,"Can't allocate space for a filename.\n");
2545 exit(1);
2547 /* skip directory, JK */
2548 if (NULL == (cp = strrchr(lemp->filename, '/'))) {
2549 cp = lemp->filename;
2550 } else {
2551 cp++;
2553 strcpy(name,cp);
2554 cp = strrchr(name,'.');
2555 if( cp ) *cp = 0;
2556 strcat(name,suffix);
2557 return name;
2560 /* Open a file with a name based on the name of the input file,
2561 ** but with a different (specified) suffix, and return a pointer
2562 ** to the stream */
2563 PRIVATE FILE *file_open(lemp,suffix,mode)
2564 struct lemon *lemp;
2565 char *suffix;
2566 char *mode;
2568 FILE *fp;
2570 if( lemp->outname ) free(lemp->outname);
2571 lemp->outname = file_makename(lemp, suffix);
2572 fp = fopen(lemp->outname,mode);
2573 if( fp==0 && *mode=='w' ){
2574 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2575 lemp->errorcnt++;
2576 return 0;
2578 return fp;
2581 /* Duplicate the input file without comments and without actions
2582 ** on rules */
2583 void Reprint(lemp)
2584 struct lemon *lemp;
2586 struct rule *rp;
2587 struct symbol *sp;
2588 int i, j, maxlen, len, ncolumns, skip;
2589 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2590 maxlen = 10;
2591 for(i=0; i<lemp->nsymbol; i++){
2592 sp = lemp->symbols[i];
2593 len = strlen(sp->name);
2594 if( len>maxlen ) maxlen = len;
2596 ncolumns = 76/(maxlen+5);
2597 if( ncolumns<1 ) ncolumns = 1;
2598 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2599 for(i=0; i<skip; i++){
2600 printf("//");
2601 for(j=i; j<lemp->nsymbol; j+=skip){
2602 sp = lemp->symbols[j];
2603 assert( sp->index==j );
2604 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2606 printf("\n");
2608 for(rp=lemp->rule; rp; rp=rp->next){
2609 printf("%s",rp->lhs->name);
2610 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2611 printf(" ::=");
2612 for(i=0; i<rp->nrhs; i++){
2613 printf(" %s",rp->rhs[i]->name);
2614 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2616 printf(".");
2617 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2618 /* if( rp->code ) printf("\n %s",rp->code); */
2619 printf("\n");
2623 PRIVATE void ConfigPrint(fp,cfp)
2624 FILE *fp;
2625 struct config *cfp;
2627 struct rule *rp;
2628 int i;
2629 rp = cfp->rp;
2630 fprintf(fp,"%s ::=",rp->lhs->name);
2631 for(i=0; i<=rp->nrhs; i++){
2632 if( i==cfp->dot ) fprintf(fp," *");
2633 if( i==rp->nrhs ) break;
2634 fprintf(fp," %s",rp->rhs[i]->name);
2638 /* #define TEST */
2639 #ifdef TEST
2640 /* Print a set */
2641 PRIVATE void SetPrint(out,set,lemp)
2642 FILE *out;
2643 char *set;
2644 struct lemon *lemp;
2646 int i;
2647 char *spacer;
2648 spacer = "";
2649 fprintf(out,"%12s[","");
2650 for(i=0; i<lemp->nterminal; i++){
2651 if( SetFind(set,i) ){
2652 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2653 spacer = " ";
2656 fprintf(out,"]\n");
2659 /* Print a plink chain */
2660 void PlinkPrint(out,plp,tag)
2661 FILE *out;
2662 struct plink *plp;
2663 char *tag;
2665 while( plp ){
2666 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
2667 ConfigPrint(out,plp->cfp);
2668 fprintf(out,"\n");
2669 plp = plp->next;
2672 #endif
2674 /* Print an action to the given file descriptor. Return FALSE if
2675 ** nothing was actually printed.
2677 PRIVATE int PrintAction(struct action *ap, FILE *fp, int indent){
2678 int result = 1;
2679 switch( ap->type ){
2680 case SHIFT:
2681 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
2682 break;
2683 case REDUCE:
2684 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2685 break;
2686 case ACCEPT:
2687 fprintf(fp,"%*s accept",indent,ap->sp->name);
2688 break;
2689 case ERROR:
2690 fprintf(fp,"%*s error",indent,ap->sp->name);
2691 break;
2692 case CONFLICT:
2693 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2694 indent,ap->sp->name,ap->x.rp->index);
2695 break;
2696 case SH_RESOLVED:
2697 case RD_RESOLVED:
2698 case NOT_USED:
2699 result = 0;
2700 break;
2702 return result;
2705 /* Generate the "y.output" log file */
2706 void ReportOutput(lemp)
2707 struct lemon *lemp;
2709 int i;
2710 struct state *stp;
2711 struct config *cfp;
2712 struct action *ap;
2713 FILE *fp;
2715 fp = file_open(lemp,".out","w");
2716 if( fp==0 ) return;
2717 fprintf(fp," \b");
2718 for(i=0; i<lemp->nstate; i++){
2719 stp = lemp->sorted[i];
2720 fprintf(fp,"State %d:\n",stp->index);
2721 if( lemp->basisflag ) cfp=stp->bp;
2722 else cfp=stp->cfp;
2723 while( cfp ){
2724 char buf[20];
2725 if( cfp->dot==cfp->rp->nrhs ){
2726 sprintf(buf,"(%d)",cfp->rp->index);
2727 fprintf(fp," %5s ",buf);
2728 }else{
2729 fprintf(fp," ");
2731 ConfigPrint(fp,cfp);
2732 fprintf(fp,"\n");
2733 #ifdef TEST
2734 SetPrint(fp,cfp->fws,lemp);
2735 PlinkPrint(fp,cfp->fplp,"To ");
2736 PlinkPrint(fp,cfp->bplp,"From");
2737 #endif
2738 if( lemp->basisflag ) cfp=cfp->bp;
2739 else cfp=cfp->next;
2741 fprintf(fp,"\n");
2742 for(ap=stp->ap; ap; ap=ap->next){
2743 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2745 fprintf(fp,"\n");
2747 fclose(fp);
2748 return;
2751 extern int access();
2752 /* Search for the file "name" which is in the same directory as
2753 ** the exacutable */
2754 PRIVATE char *pathsearch(argv0,name,modemask)
2755 char *argv0;
2756 char *name;
2757 int modemask;
2759 char *pathlist;
2760 char *path,*cp;
2761 char c;
2763 #ifdef __WIN32__
2764 cp = strrchr(argv0,'\\');
2765 #else
2766 cp = strrchr(argv0,'/');
2767 #endif
2768 if( cp ){
2769 c = *cp;
2770 *cp = 0;
2771 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2772 if( path ) sprintf(path,"%s/%s",argv0,name);
2773 *cp = c;
2774 }else{
2775 pathlist = getenv("PATH");
2776 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2777 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2778 if( path!=0 ){
2779 while( *pathlist ){
2780 cp = strchr(pathlist,':');
2781 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2782 c = *cp;
2783 *cp = 0;
2784 sprintf(path,"%s/%s",pathlist,name);
2785 *cp = c;
2786 if( c==0 ) pathlist = "";
2787 else pathlist = &cp[1];
2788 if( access(path,modemask)==0 ) break;
2792 return path;
2795 /* Given an action, compute the integer value for that action
2796 ** which is to be put in the action table of the generated machine.
2797 ** Return negative if no action should be generated.
2799 PRIVATE int compute_action(lemp,ap)
2800 struct lemon *lemp;
2801 struct action *ap;
2803 int act;
2804 switch( ap->type ){
2805 case SHIFT: act = ap->x.stp->index; break;
2806 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2807 case ERROR: act = lemp->nstate + lemp->nrule; break;
2808 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2809 default: act = -1; break;
2811 return act;
2814 #define LINESIZE 1000
2815 /* The next cluster of routines are for reading the template file
2816 ** and writing the results to the generated parser */
2817 /* The first function transfers data from "in" to "out" until
2818 ** a line is seen which begins with "%%". The line number is
2819 ** tracked.
2821 ** if name!=0, then any word that begin with "Parse" is changed to
2822 ** begin with *name instead.
2824 PRIVATE void tplt_xfer(name,in,out,lineno)
2825 char *name;
2826 FILE *in;
2827 FILE *out;
2828 int *lineno;
2830 int i, iStart;
2831 char line[LINESIZE];
2832 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2833 (*lineno)++;
2834 iStart = 0;
2835 if( name ){
2836 for(i=0; line[i]; i++){
2837 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2838 && (i==0 || !isalpha(line[i-1]))
2840 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2841 fprintf(out,"%s",name);
2842 i += 4;
2843 iStart = i+1;
2847 fprintf(out,"%s",&line[iStart]);
2851 /* The next function finds the template file and opens it, returning
2852 ** a pointer to the opened file. */
2853 PRIVATE FILE *tplt_open(lemp)
2854 struct lemon *lemp;
2857 char buf[1000];
2858 FILE *in;
2859 char *tpltname;
2860 char *tpltname_alloc = NULL;
2861 char *cp;
2863 cp = strrchr(lemp->filename,'.');
2864 if( cp ){
2865 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
2866 }else{
2867 sprintf(buf,"%s.lt",lemp->filename);
2869 if( access(buf,004)==0 ){
2870 tpltname = buf;
2871 }else if( access(lemp->tmplname,004)==0 ){
2872 tpltname = lemp->tmplname;
2873 }else{
2874 tpltname = tpltname_alloc = pathsearch(lemp->argv0,lemp->tmplname,0);
2876 if( tpltname==0 ){
2877 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
2878 lemp->tmplname);
2879 lemp->errorcnt++;
2880 return 0;
2882 in = fopen(tpltname,"r");
2883 if( in==0 ){
2884 fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
2885 lemp->errorcnt++;
2887 if (tpltname_alloc) free(tpltname_alloc);
2888 return in;
2891 /* Print a string to the file and keep the linenumber up to date */
2892 PRIVATE void tplt_print(out,lemp,str,strln,lineno)
2893 FILE *out;
2894 struct lemon *lemp;
2895 char *str;
2896 int strln;
2897 int *lineno;
2899 if( str==0 ) return;
2900 fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
2901 while( *str ){
2902 if( *str=='\n' ) (*lineno)++;
2903 putc(*str,out);
2904 str++;
2906 fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
2907 return;
2911 ** The following routine emits code for the destructor for the
2912 ** symbol sp
2914 PRIVATE void emit_destructor_code(out,sp,lemp,lineno)
2915 FILE *out;
2916 struct symbol *sp;
2917 struct lemon *lemp;
2918 int *lineno;
2920 char *cp = 0;
2922 int linecnt = 0;
2923 if( sp->type==TERMINAL ){
2924 cp = lemp->tokendest;
2925 if( cp==0 ) return;
2926 fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
2927 }else if( sp->destructor ){
2928 cp = sp->destructor;
2929 fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
2930 }else{
2931 cp = lemp->vardest;
2932 if( cp==0 ) return;
2933 fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
2935 for(; *cp; cp++){
2936 if( *cp=='$' && cp[1]=='$' ){
2937 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
2938 cp++;
2939 continue;
2941 if( *cp=='\n' ) linecnt++;
2942 fputc(*cp,out);
2944 (*lineno) += 3 + linecnt;
2945 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2946 return;
2950 ** Return TRUE (non-zero) if the given symbol has a destructor.
2952 PRIVATE int has_destructor(sp, lemp)
2953 struct symbol *sp;
2954 struct lemon *lemp;
2956 int ret;
2957 if( sp->type==TERMINAL ){
2958 ret = lemp->tokendest!=0;
2959 }else{
2960 ret = lemp->vardest!=0 || sp->destructor!=0;
2962 return ret;
2966 ** Generate code which executes when the rule "rp" is reduced. Write
2967 ** the code to "out". Make sure lineno stays up-to-date.
2969 PRIVATE void emit_code(out,rp,lemp,lineno)
2970 FILE *out;
2971 struct rule *rp;
2972 struct lemon *lemp;
2973 int *lineno;
2975 char *cp, *xp;
2976 int linecnt = 0;
2977 int i;
2978 char lhsused = 0; /* True if the LHS element has been used */
2979 char used[MAXRHS]; /* True for each RHS element which is used */
2981 for(i=0; i<rp->nrhs; i++) used[i] = 0;
2982 lhsused = 0;
2984 /* Generate code to do the reduce action */
2985 if( rp->code ){
2986 fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
2987 for(cp=rp->code; *cp; cp++){
2988 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
2989 char saved;
2990 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
2991 saved = *xp;
2992 *xp = 0;
2993 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
2994 fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
2995 cp = xp;
2996 lhsused = 1;
2997 }else{
2998 for(i=0; i<rp->nrhs; i++){
2999 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3000 fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
3001 cp = xp;
3002 used[i] = 1;
3003 break;
3007 *xp = saved;
3009 if( *cp=='\n' ) linecnt++;
3010 fputc(*cp,out);
3011 } /* End loop */
3012 (*lineno) += 3 + linecnt;
3013 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
3014 } /* End if( rp->code ) */
3016 /* Check to make sure the LHS has been used */
3017 if( rp->lhsalias && !lhsused ){
3018 ErrorMsg(lemp->filename,rp->ruleline,
3019 "Label \"%s\" for \"%s(%s)\" is never used.",
3020 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3021 lemp->errorcnt++;
3024 /* Generate destructor code for RHS symbols which are not used in the
3025 ** reduce code */
3026 for(i=0; i<rp->nrhs; i++){
3027 if( rp->rhsalias[i] && !used[i] ){
3028 ErrorMsg(lemp->filename,rp->ruleline,
3029 "Label %s for \"%s(%s)\" is never used.",
3030 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3031 lemp->errorcnt++;
3032 }else if( rp->rhsalias[i]==0 ){
3033 if( has_destructor(rp->rhs[i],lemp) ){
3034 fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
3035 rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
3036 }else{
3037 fprintf(out," /* No destructor defined for %s */\n",
3038 rp->rhs[i]->name);
3039 (*lineno)++;
3043 return;
3047 ** Print the definition of the union used for the parser's data stack.
3048 ** This union contains fields for every possible data type for tokens
3049 ** and nonterminals. In the process of computing and printing this
3050 ** union, also set the ".dtnum" field of every terminal and nonterminal
3051 ** symbol.
3053 PRIVATE void print_stack_union(out,lemp,plineno,mhflag)
3054 FILE *out; /* The output stream */
3055 struct lemon *lemp; /* The main info structure for this parser */
3056 int *plineno; /* Pointer to the line number */
3057 int mhflag; /* True if generating makeheaders output */
3059 int lineno; /* The line number of the output */
3060 char **types; /* A hash table of datatypes */
3061 int arraysize; /* Size of the "types" array */
3062 int maxdtlength; /* Maximum length of any ".datatype" field. */
3063 char *stddt; /* Standardized name for a datatype */
3064 int i,j; /* Loop counters */
3065 int hash; /* For hashing the name of a type */
3066 char *name; /* Name of the parser */
3068 /* Allocate and initialize types[] and allocate stddt[] */
3069 arraysize = lemp->nsymbol * 2;
3070 types = (char**)malloc( arraysize * sizeof(char*) );
3071 for(i=0; i<arraysize; i++) types[i] = 0;
3072 maxdtlength = 0;
3073 if( lemp->vartype ){
3074 maxdtlength = strlen(lemp->vartype);
3076 for(i=0; i<lemp->nsymbol; i++){
3077 int len;
3078 struct symbol *sp = lemp->symbols[i];
3079 if( sp->datatype==0 ) continue;
3080 len = strlen(sp->datatype);
3081 if( len>maxdtlength ) maxdtlength = len;
3083 stddt = (char*)malloc( maxdtlength*2 + 1 );
3084 if( types==0 || stddt==0 ){
3085 fprintf(stderr,"Out of memory.\n");
3086 exit(1);
3089 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3090 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3091 ** used for terminal symbols. If there is no %default_type defined then
3092 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3093 ** a datatype using the %type directive.
3095 for(i=0; i<lemp->nsymbol; i++){
3096 struct symbol *sp = lemp->symbols[i];
3097 char *cp;
3098 if( sp==lemp->errsym ){
3099 sp->dtnum = arraysize+1;
3100 continue;
3102 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
3103 sp->dtnum = 0;
3104 continue;
3106 cp = sp->datatype;
3107 if( cp==0 ) cp = lemp->vartype;
3108 j = 0;
3109 while( isspace(*cp) ) cp++;
3110 while( *cp ) stddt[j++] = *cp++;
3111 while( j>0 && isspace(stddt[j-1]) ) j--;
3112 stddt[j] = 0;
3113 hash = 0;
3114 for(j=0; stddt[j]; j++){
3115 hash = (unsigned int)hash*53u + (unsigned int) stddt[j];
3117 hash = (hash & 0x7fffffff)%arraysize;
3118 while( types[hash] ){
3119 if( strcmp(types[hash],stddt)==0 ){
3120 sp->dtnum = hash + 1;
3121 break;
3123 hash++;
3124 if( hash>=arraysize ) hash = 0;
3126 if( types[hash]==0 ){
3127 sp->dtnum = hash + 1;
3128 types[hash] = (char*)malloc( strlen(stddt)+1 );
3129 if( types[hash]==0 ){
3130 fprintf(stderr,"Out of memory.\n");
3131 exit(1);
3133 strcpy(types[hash],stddt);
3137 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3138 name = lemp->name ? lemp->name : "Parse";
3139 lineno = *plineno;
3140 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3141 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3142 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3143 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3144 fprintf(out,"typedef union {\n"); lineno++;
3145 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3146 for(i=0; i<arraysize; i++){
3147 if( types[i]==0 ) continue;
3148 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3149 free(types[i]);
3151 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3152 free(stddt);
3153 free(types);
3154 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3155 *plineno = lineno;
3159 ** Return the name of a C datatype able to represent values between
3160 ** lwr and upr, inclusive.
3162 static const char *minimum_size_type(int lwr, int upr){
3163 if( lwr>=0 ){
3164 if( upr<=255 ){
3165 return "unsigned char";
3166 }else if( upr<65535 ){
3167 return "unsigned short int";
3168 }else{
3169 return "unsigned int";
3171 }else if( lwr>=-127 && upr<=127 ){
3172 return "signed char";
3173 }else if( lwr>=-32767 && upr<32767 ){
3174 return "short";
3175 }else{
3176 return "int";
3181 ** Each state contains a set of token transaction and a set of
3182 ** nonterminal transactions. Each of these sets makes an instance
3183 ** of the following structure. An array of these structures is used
3184 ** to order the creation of entries in the yy_action[] table.
3186 struct axset {
3187 struct state *stp; /* A pointer to a state */
3188 int isTkn; /* True to use tokens. False for non-terminals */
3189 int nAction; /* Number of actions */
3193 ** Compare to axset structures for sorting purposes
3195 static int axset_compare(const void *a, const void *b){
3196 struct axset *p1 = (struct axset*)a;
3197 struct axset *p2 = (struct axset*)b;
3198 return p2->nAction - p1->nAction;
3201 /* Generate C source code for the parser */
3202 void ReportTable(lemp, mhflag)
3203 struct lemon *lemp;
3204 int mhflag; /* Output in makeheaders format if true */
3206 FILE *out, *in;
3207 char line[LINESIZE];
3208 int lineno;
3209 struct state *stp;
3210 struct action *ap;
3211 struct rule *rp;
3212 struct acttab *pActtab;
3213 int i, j, n;
3214 int mnTknOfst, mxTknOfst;
3215 int mnNtOfst, mxNtOfst;
3216 struct axset *ax;
3217 char *name;
3219 in = tplt_open(lemp);
3220 if( in==0 ) return;
3221 out = file_open(lemp,".c","w");
3222 if( out==0 ){
3223 fclose(in);
3224 return;
3226 lineno = 1;
3227 tplt_xfer(lemp->name,in,out,&lineno);
3229 /* Generate the include code, if any */
3230 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3231 if( mhflag ){
3232 name = file_makename(lemp, ".h");
3233 fprintf(out,"#include \"%s\"\n", name); lineno++;
3234 free(name);
3236 tplt_xfer(lemp->name,in,out,&lineno);
3238 /* Generate #defines for all tokens */
3239 if( mhflag ){
3240 char *prefix;
3241 fprintf(out,"#if INTERFACE\n"); lineno++;
3242 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3243 else prefix = "";
3244 for(i=1; i<lemp->nterminal; i++){
3245 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3246 lineno++;
3248 fprintf(out,"#endif\n"); lineno++;
3250 tplt_xfer(lemp->name,in,out,&lineno);
3252 /* Generate the defines */
3253 fprintf(out,"/* \001 */\n");
3254 fprintf(out,"#define YYCODETYPE %s\n",
3255 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
3256 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3257 fprintf(out,"#define YYACTIONTYPE %s\n",
3258 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
3259 print_stack_union(out,lemp,&lineno,mhflag);
3260 if( lemp->stacksize ){
3261 if( atoi(lemp->stacksize)<=0 ){
3262 ErrorMsg(lemp->filename,0,
3263 "Illegal stack size: [%s]. The stack size should be an integer constant.",
3264 lemp->stacksize);
3265 lemp->errorcnt++;
3266 lemp->stacksize = "100";
3268 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3269 }else{
3270 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3272 if( mhflag ){
3273 fprintf(out,"#if INTERFACE\n"); lineno++;
3275 name = lemp->name ? lemp->name : "Parse";
3276 if( lemp->arg && lemp->arg[0] ){
3277 i = strlen(lemp->arg);
3278 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3279 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
3280 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3281 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3282 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3283 name,lemp->arg,&lemp->arg[i]); lineno++;
3284 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3285 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
3286 }else{
3287 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3288 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3289 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3290 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
3292 if( mhflag ){
3293 fprintf(out,"#endif\n"); lineno++;
3295 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3296 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3297 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3298 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3299 if( lemp->has_fallback ){
3300 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3302 tplt_xfer(lemp->name,in,out,&lineno);
3304 /* Generate the action table and its associates:
3306 ** yy_action[] A single table containing all actions.
3307 ** yy_lookahead[] A table containing the lookahead for each entry in
3308 ** yy_action. Used to detect hash collisions.
3309 ** yy_shift_ofst[] For each state, the offset into yy_action for
3310 ** shifting terminals.
3311 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3312 ** shifting non-terminals after a reduce.
3313 ** yy_default[] Default action for each state.
3316 /* Compute the actions on all states and count them up */
3317 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3318 if( ax==0 ){
3319 fprintf(stderr,"malloc failed\n");
3320 exit(1);
3322 for(i=0; i<lemp->nstate; i++){
3323 stp = lemp->sorted[i];
3324 stp->nTknAct = stp->nNtAct = 0;
3325 stp->iDflt = lemp->nstate + lemp->nrule;
3326 stp->iTknOfst = NO_OFFSET;
3327 stp->iNtOfst = NO_OFFSET;
3328 for(ap=stp->ap; ap; ap=ap->next){
3329 if( compute_action(lemp,ap)>=0 ){
3330 if( ap->sp->index<lemp->nterminal ){
3331 stp->nTknAct++;
3332 }else if( ap->sp->index<lemp->nsymbol ){
3333 stp->nNtAct++;
3334 }else{
3335 stp->iDflt = compute_action(lemp, ap);
3339 ax[i*2].stp = stp;
3340 ax[i*2].isTkn = 1;
3341 ax[i*2].nAction = stp->nTknAct;
3342 ax[i*2+1].stp = stp;
3343 ax[i*2+1].isTkn = 0;
3344 ax[i*2+1].nAction = stp->nNtAct;
3346 mxTknOfst = mnTknOfst = 0;
3347 mxNtOfst = mnNtOfst = 0;
3349 /* Compute the action table. In order to try to keep the size of the
3350 ** action table to a minimum, the heuristic of placing the largest action
3351 ** sets first is used.
3353 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
3354 pActtab = acttab_alloc();
3355 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3356 stp = ax[i].stp;
3357 if( ax[i].isTkn ){
3358 for(ap=stp->ap; ap; ap=ap->next){
3359 int action;
3360 if( ap->sp->index>=lemp->nterminal ) continue;
3361 action = compute_action(lemp, ap);
3362 if( action<0 ) continue;
3363 acttab_action(pActtab, ap->sp->index, action);
3365 stp->iTknOfst = acttab_insert(pActtab);
3366 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3367 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3368 }else{
3369 for(ap=stp->ap; ap; ap=ap->next){
3370 int action;
3371 if( ap->sp->index<lemp->nterminal ) continue;
3372 if( ap->sp->index==lemp->nsymbol ) continue;
3373 action = compute_action(lemp, ap);
3374 if( action<0 ) continue;
3375 acttab_action(pActtab, ap->sp->index, action);
3377 stp->iNtOfst = acttab_insert(pActtab);
3378 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3379 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
3382 free(ax);
3384 /* Output the yy_action table */
3385 fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++;
3386 n = acttab_size(pActtab);
3387 for(i=j=0; i<n; i++){
3388 int action = acttab_yyaction(pActtab, i);
3389 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
3390 if( j==0 ) fprintf(out," /* %5d */ ", i);
3391 fprintf(out, " %4d,", action);
3392 if( j==9 || i==n-1 ){
3393 fprintf(out, "\n"); lineno++;
3394 j = 0;
3395 }else{
3396 j++;
3399 fprintf(out, "};\n"); lineno++;
3401 /* Output the yy_lookahead table */
3402 fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++;
3403 for(i=j=0; i<n; i++){
3404 int la = acttab_yylookahead(pActtab, i);
3405 if( la<0 ) la = lemp->nsymbol;
3406 if( j==0 ) fprintf(out," /* %5d */ ", i);
3407 fprintf(out, " %4d,", la);
3408 if( j==9 || i==n-1 ){
3409 fprintf(out, "\n"); lineno++;
3410 j = 0;
3411 }else{
3412 j++;
3415 fprintf(out, "};\n"); lineno++;
3417 /* Output the yy_shift_ofst[] table */
3418 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
3419 fprintf(out, "static %s yy_shift_ofst[] = {\n",
3420 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
3421 n = lemp->nstate;
3422 for(i=j=0; i<n; i++){
3423 int ofst;
3424 stp = lemp->sorted[i];
3425 ofst = stp->iTknOfst;
3426 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
3427 if( j==0 ) fprintf(out," /* %5d */ ", i);
3428 fprintf(out, " %4d,", ofst);
3429 if( j==9 || i==n-1 ){
3430 fprintf(out, "\n"); lineno++;
3431 j = 0;
3432 }else{
3433 j++;
3436 fprintf(out, "};\n"); lineno++;
3438 /* Output the yy_reduce_ofst[] table */
3439 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
3440 fprintf(out, "static %s yy_reduce_ofst[] = {\n",
3441 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
3442 n = lemp->nstate;
3443 for(i=j=0; i<n; i++){
3444 int ofst;
3445 stp = lemp->sorted[i];
3446 ofst = stp->iNtOfst;
3447 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
3448 if( j==0 ) fprintf(out," /* %5d */ ", i);
3449 fprintf(out, " %4d,", ofst);
3450 if( j==9 || i==n-1 ){
3451 fprintf(out, "\n"); lineno++;
3452 j = 0;
3453 }else{
3454 j++;
3457 fprintf(out, "};\n"); lineno++;
3459 /* Output the default action table */
3460 fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++;
3461 n = lemp->nstate;
3462 for(i=j=0; i<n; i++){
3463 stp = lemp->sorted[i];
3464 if( j==0 ) fprintf(out," /* %5d */ ", i);
3465 fprintf(out, " %4d,", stp->iDflt);
3466 if( j==9 || i==n-1 ){
3467 fprintf(out, "\n"); lineno++;
3468 j = 0;
3469 }else{
3470 j++;
3473 fprintf(out, "};\n"); lineno++;
3474 tplt_xfer(lemp->name,in,out,&lineno);
3476 /* Generate the table of fallback tokens.
3478 if( lemp->has_fallback ){
3479 for(i=0; i<lemp->nterminal; i++){
3480 struct symbol *p = lemp->symbols[i];
3481 if( p->fallback==0 ){
3482 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3483 }else{
3484 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3485 p->name, p->fallback->name);
3487 lineno++;
3490 tplt_xfer(lemp->name, in, out, &lineno);
3492 /* Generate a table containing the symbolic name of every symbol
3494 for(i=0; i<lemp->nsymbol; i++){
3495 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3496 fprintf(out," %-15s",line);
3497 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3499 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3500 tplt_xfer(lemp->name,in,out,&lineno);
3502 /* Generate a table containing a text string that describes every
3503 ** rule in the rule set of the grammer. This information is used
3504 ** when tracing REDUCE actions.
3506 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3507 assert( rp->index==i );
3508 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
3509 for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
3510 fprintf(out,"\",\n"); lineno++;
3512 tplt_xfer(lemp->name,in,out,&lineno);
3514 /* Generate code which executes every time a symbol is popped from
3515 ** the stack while processing errors or while destroying the parser.
3516 ** (In other words, generate the %destructor actions)
3518 if( lemp->tokendest ){
3519 for(i=0; i<lemp->nsymbol; i++){
3520 struct symbol *sp = lemp->symbols[i];
3521 if( sp==0 || sp->type!=TERMINAL ) continue;
3522 fprintf(out," case %d:\n",sp->index); lineno++;
3524 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3525 if( i<lemp->nsymbol ){
3526 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3527 fprintf(out," break;\n"); lineno++;
3530 for(i=0; i<lemp->nsymbol; i++){
3531 struct symbol *sp = lemp->symbols[i];
3532 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3533 fprintf(out," case %d:\n",sp->index); lineno++;
3534 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3535 fprintf(out," break;\n"); lineno++;
3537 if( lemp->vardest ){
3538 struct symbol *dflt_sp = 0;
3539 for(i=0; i<lemp->nsymbol; i++){
3540 struct symbol *sp = lemp->symbols[i];
3541 if( sp==0 || sp->type==TERMINAL ||
3542 sp->index<=0 || sp->destructor!=0 ) continue;
3543 fprintf(out," case %d:\n",sp->index); lineno++;
3544 dflt_sp = sp;
3546 if( dflt_sp!=0 ){
3547 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3548 fprintf(out," break;\n"); lineno++;
3551 tplt_xfer(lemp->name,in,out,&lineno);
3553 /* Generate code which executes whenever the parser stack overflows */
3554 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3555 tplt_xfer(lemp->name,in,out,&lineno);
3557 /* Generate the table of rule information
3559 ** Note: This code depends on the fact that rules are number
3560 ** sequentually beginning with 0.
3562 for(rp=lemp->rule; rp; rp=rp->next){
3563 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3565 tplt_xfer(lemp->name,in,out,&lineno);
3567 /* Generate code which execution during each REDUCE action */
3568 for(rp=lemp->rule; rp; rp=rp->next){
3569 fprintf(out," case %d:\n",rp->index); lineno++;
3570 emit_code(out,rp,lemp,&lineno);
3571 fprintf(out," break;\n"); lineno++;
3573 tplt_xfer(lemp->name,in,out,&lineno);
3575 /* Generate code which executes if a parse fails */
3576 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3577 tplt_xfer(lemp->name,in,out,&lineno);
3579 /* Generate code which executes when a syntax error occurs */
3580 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3581 tplt_xfer(lemp->name,in,out,&lineno);
3583 /* Generate code which executes when the parser accepts its input */
3584 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3585 tplt_xfer(lemp->name,in,out,&lineno);
3587 /* Append any addition code the user desires */
3588 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3590 fclose(in);
3591 fclose(out);
3592 return;
3595 /* Generate a header file for the parser */
3596 void ReportHeader(lemp)
3597 struct lemon *lemp;
3599 FILE *out, *in;
3600 char *prefix;
3601 char line[LINESIZE];
3602 char pattern[LINESIZE];
3603 int i;
3605 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3606 else prefix = "";
3607 in = file_open(lemp,".h","r");
3608 if( in ){
3609 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3610 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3611 if( strcmp(line,pattern) ) break;
3613 fclose(in);
3614 if( i==lemp->nterminal ){
3615 /* No change in the file. Don't rewrite it. */
3616 return;
3619 out = file_open(lemp,".h","w");
3620 if( out ){
3621 for(i=1; i<lemp->nterminal; i++){
3622 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3624 fclose(out);
3626 return;
3629 /* Reduce the size of the action tables, if possible, by making use
3630 ** of defaults.
3632 ** In this version, we take the most frequent REDUCE action and make
3633 ** it the default. Only default a reduce if there are more than one.
3635 void CompressTables(lemp)
3636 struct lemon *lemp;
3638 struct state *stp;
3639 struct action *ap, *ap2;
3640 struct rule *rp, *rp2, *rbest;
3641 int nbest, n;
3642 int i;
3644 for(i=0; i<lemp->nstate; i++){
3645 stp = lemp->sorted[i];
3646 nbest = 0;
3647 rbest = 0;
3649 for(ap=stp->ap; ap; ap=ap->next){
3650 if( ap->type!=REDUCE ) continue;
3651 rp = ap->x.rp;
3652 if( rp==rbest ) continue;
3653 n = 1;
3654 for(ap2=ap->next; ap2; ap2=ap2->next){
3655 if( ap2->type!=REDUCE ) continue;
3656 rp2 = ap2->x.rp;
3657 if( rp2==rbest ) continue;
3658 if( rp2==rp ) n++;
3660 if( n>nbest ){
3661 nbest = n;
3662 rbest = rp;
3666 /* Do not make a default if the number of rules to default
3667 ** is not at least 2 */
3668 if( nbest<2 ) continue;
3671 /* Combine matching REDUCE actions into a single default */
3672 for(ap=stp->ap; ap; ap=ap->next){
3673 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3675 assert( ap );
3676 ap->sp = Symbol_new("{default}");
3677 for(ap=ap->next; ap; ap=ap->next){
3678 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
3680 stp->ap = Action_sort(stp->ap);
3684 /***************** From the file "set.c" ************************************/
3686 ** Set manipulation routines for the LEMON parser generator.
3689 static int global_size = 0;
3691 /* Set the set size */
3692 void SetSize(n)
3693 int n;
3695 global_size = n+1;
3698 /* Allocate a new set */
3699 char *SetNew(){
3700 char *s;
3701 int i;
3702 s = (char*)malloc( global_size );
3703 if( s==0 ){
3704 memory_error();
3706 for(i=0; i<global_size; i++) s[i] = 0;
3707 return s;
3710 /* Deallocate a set */
3711 void SetFree(s)
3712 char *s;
3714 free(s);
3717 /* Add a new element to the set. Return TRUE if the element was added
3718 ** and FALSE if it was already there. */
3719 int SetAdd(s,e)
3720 char *s;
3721 int e;
3723 int rv;
3724 rv = s[e];
3725 s[e] = 1;
3726 return !rv;
3729 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
3730 int SetUnion(s1,s2)
3731 char *s1;
3732 char *s2;
3734 int i, progress;
3735 progress = 0;
3736 for(i=0; i<global_size; i++){
3737 if( s2[i]==0 ) continue;
3738 if( s1[i]==0 ){
3739 progress = 1;
3740 s1[i] = 1;
3743 return progress;
3745 /********************** From the file "table.c" ****************************/
3747 ** All code in this file has been automatically generated
3748 ** from a specification in the file
3749 ** "table.q"
3750 ** by the associative array code building program "aagen".
3751 ** Do not edit this file! Instead, edit the specification
3752 ** file, then rerun aagen.
3755 ** Code for processing tables in the LEMON parser generator.
3758 PRIVATE int strhash(x)
3759 char *x;
3761 unsigned int h = 0;
3762 while( *x) h = h*13u + (unsigned int) *(x++);
3763 return h;
3766 /* Works like strdup, sort of. Save a string in malloced memory, but
3767 ** keep strings in a table so that the same string is not in more
3768 ** than one place.
3770 char *Strsafe(y)
3771 char *y;
3773 char *z;
3775 z = Strsafe_find(y);
3776 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3777 strcpy(z,y);
3778 Strsafe_insert(z);
3780 MemoryCheck(z);
3781 return z;
3784 /* There is one instance of the following structure for each
3785 ** associative array of type "x1".
3787 struct s_x1 {
3788 int size; /* The number of available slots. */
3789 /* Must be a power of 2 greater than or */
3790 /* equal to 1 */
3791 int count; /* Number of currently slots filled */
3792 struct s_x1node *tbl; /* The data stored here */
3793 struct s_x1node **ht; /* Hash table for lookups */
3796 /* There is one instance of this structure for every data element
3797 ** in an associative array of type "x1".
3799 typedef struct s_x1node {
3800 char *data; /* The data */
3801 struct s_x1node *next; /* Next entry with the same hash */
3802 struct s_x1node **from; /* Previous link */
3803 } x1node;
3805 /* There is only one instance of the array, which is the following */
3806 static struct s_x1 *x1a;
3808 /* Allocate a new associative array */
3809 void Strsafe_init(){
3810 if( x1a ) return;
3811 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
3812 if( x1a ){
3813 x1a->size = 1024;
3814 x1a->count = 0;
3815 x1a->tbl = (x1node*)malloc(
3816 (sizeof(x1node) + sizeof(x1node*))*1024 );
3817 if( x1a->tbl==0 ){
3818 free(x1a);
3819 x1a = 0;
3820 }else{
3821 int i;
3822 x1a->ht = (x1node**)&(x1a->tbl[1024]);
3823 for(i=0; i<1024; i++) x1a->ht[i] = 0;
3827 /* Insert a new record into the array. Return TRUE if successful.
3828 ** Prior data with the same key is NOT overwritten */
3829 int Strsafe_insert(data)
3830 char *data;
3832 x1node *np;
3833 int h;
3834 int ph;
3836 if( x1a==0 ) return 0;
3837 ph = strhash(data);
3838 h = ph & (x1a->size-1);
3839 np = x1a->ht[h];
3840 while( np ){
3841 if( strcmp(np->data,data)==0 ){
3842 /* An existing entry with the same key is found. */
3843 /* Fail because overwrite is not allows. */
3844 return 0;
3846 np = np->next;
3848 if( x1a->count>=x1a->size ){
3849 /* Need to make the hash table bigger */
3850 int i,size;
3851 struct s_x1 array;
3852 array.size = size = x1a->size*2;
3853 array.count = x1a->count;
3854 array.tbl = (x1node*)malloc(
3855 (sizeof(x1node) + sizeof(x1node*))*size );
3856 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3857 array.ht = (x1node**)&(array.tbl[size]);
3858 for(i=0; i<size; i++) array.ht[i] = 0;
3859 for(i=0; i<x1a->count; i++){
3860 x1node *oldnp, *newnp;
3861 oldnp = &(x1a->tbl[i]);
3862 h = strhash(oldnp->data) & (size-1);
3863 newnp = &(array.tbl[i]);
3864 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3865 newnp->next = array.ht[h];
3866 newnp->data = oldnp->data;
3867 newnp->from = &(array.ht[h]);
3868 array.ht[h] = newnp;
3870 free(x1a->tbl);
3871 /* *x1a = array; *//* copy 'array' */
3872 memcpy(x1a, &array, sizeof(array));
3874 /* Insert the new data */
3875 h = ph & (x1a->size-1);
3876 np = &(x1a->tbl[x1a->count++]);
3877 np->data = data;
3878 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
3879 np->next = x1a->ht[h];
3880 x1a->ht[h] = np;
3881 np->from = &(x1a->ht[h]);
3882 return 1;
3885 /* Return a pointer to data assigned to the given key. Return NULL
3886 ** if no such key. */
3887 char *Strsafe_find(key)
3888 char *key;
3890 int h;
3891 x1node *np;
3893 if( x1a==0 ) return 0;
3894 h = strhash(key) & (x1a->size-1);
3895 np = x1a->ht[h];
3896 while( np ){
3897 if( strcmp(np->data,key)==0 ) break;
3898 np = np->next;
3900 return np ? np->data : 0;
3903 /* Return a pointer to the (terminal or nonterminal) symbol "x".
3904 ** Create a new symbol if this is the first time "x" has been seen.
3906 struct symbol *Symbol_new(x)
3907 char *x;
3909 struct symbol *sp;
3911 sp = Symbol_find(x);
3912 if( sp==0 ){
3913 sp = (struct symbol *)malloc( sizeof(struct symbol) );
3914 MemoryCheck(sp);
3915 sp->name = Strsafe(x);
3916 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
3917 sp->rule = 0;
3918 sp->fallback = 0;
3919 sp->prec = -1;
3920 sp->assoc = UNK;
3921 sp->firstset = 0;
3922 sp->lambda = Bo_FALSE;
3923 sp->destructor = 0;
3924 sp->datatype = 0;
3925 Symbol_insert(sp,sp->name);
3927 return sp;
3930 /* Compare two symbols for working purposes
3932 ** Symbols that begin with upper case letters (terminals or tokens)
3933 ** must sort before symbols that begin with lower case letters
3934 ** (non-terminals). Other than that, the order does not matter.
3936 ** We find experimentally that leaving the symbols in their original
3937 ** order (the order they appeared in the grammar file) gives the
3938 ** smallest parser tables in SQLite.
3940 int Symbolcmpp(struct symbol **a, struct symbol **b){
3941 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
3942 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
3943 return i1-i2;
3946 /* There is one instance of the following structure for each
3947 ** associative array of type "x2".
3949 struct s_x2 {
3950 int size; /* The number of available slots. */
3951 /* Must be a power of 2 greater than or */
3952 /* equal to 1 */
3953 int count; /* Number of currently slots filled */
3954 struct s_x2node *tbl; /* The data stored here */
3955 struct s_x2node **ht; /* Hash table for lookups */
3958 /* There is one instance of this structure for every data element
3959 ** in an associative array of type "x2".
3961 typedef struct s_x2node {
3962 struct symbol *data; /* The data */
3963 char *key; /* The key */
3964 struct s_x2node *next; /* Next entry with the same hash */
3965 struct s_x2node **from; /* Previous link */
3966 } x2node;
3968 /* There is only one instance of the array, which is the following */
3969 static struct s_x2 *x2a;
3971 /* Allocate a new associative array */
3972 void Symbol_init(){
3973 if( x2a ) return;
3974 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
3975 if( x2a ){
3976 x2a->size = 128;
3977 x2a->count = 0;
3978 x2a->tbl = (x2node*)malloc(
3979 (sizeof(x2node) + sizeof(x2node*))*128 );
3980 if( x2a->tbl==0 ){
3981 free(x2a);
3982 x2a = 0;
3983 }else{
3984 int i;
3985 x2a->ht = (x2node**)&(x2a->tbl[128]);
3986 for(i=0; i<128; i++) x2a->ht[i] = 0;
3990 /* Insert a new record into the array. Return TRUE if successful.
3991 ** Prior data with the same key is NOT overwritten */
3992 int Symbol_insert(data,key)
3993 struct symbol *data;
3994 char *key;
3996 x2node *np;
3997 int h;
3998 int ph;
4000 if( x2a==0 ) return 0;
4001 ph = strhash(key);
4002 h = ph & (x2a->size-1);
4003 np = x2a->ht[h];
4004 while( np ){
4005 if( strcmp(np->key,key)==0 ){
4006 /* An existing entry with the same key is found. */
4007 /* Fail because overwrite is not allows. */
4008 return 0;
4010 np = np->next;
4012 if( x2a->count>=x2a->size ){
4013 /* Need to make the hash table bigger */
4014 int i,size;
4015 struct s_x2 array;
4016 array.size = size = x2a->size*2;
4017 array.count = x2a->count;
4018 array.tbl = (x2node*)malloc(
4019 (sizeof(x2node) + sizeof(x2node*))*size );
4020 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4021 array.ht = (x2node**)&(array.tbl[size]);
4022 for(i=0; i<size; i++) array.ht[i] = 0;
4023 for(i=0; i<x2a->count; i++){
4024 x2node *oldnp, *newnp;
4025 oldnp = &(x2a->tbl[i]);
4026 h = strhash(oldnp->key) & (size-1);
4027 newnp = &(array.tbl[i]);
4028 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4029 newnp->next = array.ht[h];
4030 newnp->key = oldnp->key;
4031 newnp->data = oldnp->data;
4032 newnp->from = &(array.ht[h]);
4033 array.ht[h] = newnp;
4035 free(x2a->tbl);
4036 /* *x2a = array; *//* copy 'array' */
4037 memcpy(x2a, &array, sizeof(array));
4039 /* Insert the new data */
4040 h = ph & (x2a->size-1);
4041 np = &(x2a->tbl[x2a->count++]);
4042 np->key = key;
4043 np->data = data;
4044 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4045 np->next = x2a->ht[h];
4046 x2a->ht[h] = np;
4047 np->from = &(x2a->ht[h]);
4048 return 1;
4051 /* Return a pointer to data assigned to the given key. Return NULL
4052 ** if no such key. */
4053 struct symbol *Symbol_find(key)
4054 char *key;
4056 int h;
4057 x2node *np;
4059 if( x2a==0 ) return 0;
4060 h = strhash(key) & (x2a->size-1);
4061 np = x2a->ht[h];
4062 while( np ){
4063 if( strcmp(np->key,key)==0 ) break;
4064 np = np->next;
4066 return np ? np->data : 0;
4069 /* Return the n-th data. Return NULL if n is out of range. */
4070 struct symbol *Symbol_Nth(n)
4071 int n;
4073 struct symbol *data;
4074 if( x2a && n>0 && n<=x2a->count ){
4075 data = x2a->tbl[n-1].data;
4076 }else{
4077 data = 0;
4079 return data;
4082 /* Return the size of the array */
4083 int Symbol_count()
4085 return x2a ? x2a->count : 0;
4088 /* Return an array of pointers to all data in the table.
4089 ** The array is obtained from malloc. Return NULL if memory allocation
4090 ** problems, or if the array is empty. */
4091 struct symbol **Symbol_arrayof()
4093 struct symbol **array;
4094 int i,size;
4095 if( x2a==0 ) return 0;
4096 size = x2a->count;
4097 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4098 if( array ){
4099 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4101 return array;
4104 /* Compare two configurations */
4105 int Configcmp(a,b)
4106 struct config *a;
4107 struct config *b;
4109 int x;
4110 x = a->rp->index - b->rp->index;
4111 if( x==0 ) x = a->dot - b->dot;
4112 return x;
4115 /* Compare two states */
4116 PRIVATE int statecmp(a,b)
4117 struct config *a;
4118 struct config *b;
4120 int rc;
4121 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4122 rc = a->rp->index - b->rp->index;
4123 if( rc==0 ) rc = a->dot - b->dot;
4125 if( rc==0 ){
4126 if( a ) rc = 1;
4127 if( b ) rc = -1;
4129 return rc;
4132 /* Hash a state */
4133 PRIVATE int statehash(a)
4134 struct config *a;
4136 unsigned int h=0;
4137 while( a ){
4138 h = h*571u + (unsigned int)a->rp->index*37u + (unsigned int)a->dot;
4139 a = a->bp;
4141 return h;
4144 /* Allocate a new state structure */
4145 struct state *State_new()
4147 struct state *new;
4148 new = (struct state *)malloc( sizeof(struct state) );
4149 MemoryCheck(new);
4150 return new;
4153 /* There is one instance of the following structure for each
4154 ** associative array of type "x3".
4156 struct s_x3 {
4157 int size; /* The number of available slots. */
4158 /* Must be a power of 2 greater than or */
4159 /* equal to 1 */
4160 int count; /* Number of currently slots filled */
4161 struct s_x3node *tbl; /* The data stored here */
4162 struct s_x3node **ht; /* Hash table for lookups */
4165 /* There is one instance of this structure for every data element
4166 ** in an associative array of type "x3".
4168 typedef struct s_x3node {
4169 struct state *data; /* The data */
4170 struct config *key; /* The key */
4171 struct s_x3node *next; /* Next entry with the same hash */
4172 struct s_x3node **from; /* Previous link */
4173 } x3node;
4175 /* There is only one instance of the array, which is the following */
4176 static struct s_x3 *x3a;
4178 /* Allocate a new associative array */
4179 void State_init(){
4180 if( x3a ) return;
4181 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4182 if( x3a ){
4183 x3a->size = 128;
4184 x3a->count = 0;
4185 x3a->tbl = (x3node*)malloc(
4186 (sizeof(x3node) + sizeof(x3node*))*128 );
4187 if( x3a->tbl==0 ){
4188 free(x3a);
4189 x3a = 0;
4190 }else{
4191 int i;
4192 x3a->ht = (x3node**)&(x3a->tbl[128]);
4193 for(i=0; i<128; i++) x3a->ht[i] = 0;
4197 /* Insert a new record into the array. Return TRUE if successful.
4198 ** Prior data with the same key is NOT overwritten */
4199 int State_insert(data,key)
4200 struct state *data;
4201 struct config *key;
4203 x3node *np;
4204 int h;
4205 int ph;
4207 if( x3a==0 ) return 0;
4208 ph = statehash(key);
4209 h = ph & (x3a->size-1);
4210 np = x3a->ht[h];
4211 while( np ){
4212 if( statecmp(np->key,key)==0 ){
4213 /* An existing entry with the same key is found. */
4214 /* Fail because overwrite is not allows. */
4215 return 0;
4217 np = np->next;
4219 if( x3a->count>=x3a->size ){
4220 /* Need to make the hash table bigger */
4221 int i,size;
4222 struct s_x3 array;
4223 array.size = size = x3a->size*2;
4224 array.count = x3a->count;
4225 array.tbl = (x3node*)malloc(
4226 (sizeof(x3node) + sizeof(x3node*))*size );
4227 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4228 array.ht = (x3node**)&(array.tbl[size]);
4229 for(i=0; i<size; i++) array.ht[i] = 0;
4230 for(i=0; i<x3a->count; i++){
4231 x3node *oldnp, *newnp;
4232 oldnp = &(x3a->tbl[i]);
4233 h = statehash(oldnp->key) & (size-1);
4234 newnp = &(array.tbl[i]);
4235 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4236 newnp->next = array.ht[h];
4237 newnp->key = oldnp->key;
4238 newnp->data = oldnp->data;
4239 newnp->from = &(array.ht[h]);
4240 array.ht[h] = newnp;
4242 free(x3a->tbl);
4243 /* *x3a = array; *//* copy 'array' */
4244 memcpy(x3a, &array, sizeof(array));
4246 /* Insert the new data */
4247 h = ph & (x3a->size-1);
4248 np = &(x3a->tbl[x3a->count++]);
4249 np->key = key;
4250 np->data = data;
4251 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4252 np->next = x3a->ht[h];
4253 x3a->ht[h] = np;
4254 np->from = &(x3a->ht[h]);
4255 return 1;
4258 /* Return a pointer to data assigned to the given key. Return NULL
4259 ** if no such key. */
4260 struct state *State_find(key)
4261 struct config *key;
4263 int h;
4264 x3node *np;
4266 if( x3a==0 ) return 0;
4267 h = statehash(key) & (x3a->size-1);
4268 np = x3a->ht[h];
4269 while( np ){
4270 if( statecmp(np->key,key)==0 ) break;
4271 np = np->next;
4273 return np ? np->data : 0;
4276 /* Return the size of the array */
4277 int State_count(void)
4279 return x3a ? x3a->count : 0;
4282 /* Return an array of pointers to all data in the table.
4283 ** The array is obtained from malloc. Return NULL if memory allocation
4284 ** problems, or if the array is empty. */
4285 struct state **State_arrayof()
4287 struct state **array;
4288 int i,size;
4289 if( x3a==0 ) return 0;
4290 size = x3a->count;
4291 array = (struct state **)malloc( sizeof(struct state *)*size );
4292 if( array ){
4293 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4295 return array;
4298 /* Hash a configuration */
4299 PRIVATE int confighash(a)
4300 struct config *a;
4302 int h=0;
4303 h = h*571 + a->rp->index*37 + a->dot;
4304 return h;
4307 /* There is one instance of the following structure for each
4308 ** associative array of type "x4".
4310 struct s_x4 {
4311 int size; /* The number of available slots. */
4312 /* Must be a power of 2 greater than or */
4313 /* equal to 1 */
4314 int count; /* Number of currently slots filled */
4315 struct s_x4node *tbl; /* The data stored here */
4316 struct s_x4node **ht; /* Hash table for lookups */
4319 /* There is one instance of this structure for every data element
4320 ** in an associative array of type "x4".
4322 typedef struct s_x4node {
4323 struct config *data; /* The data */
4324 struct s_x4node *next; /* Next entry with the same hash */
4325 struct s_x4node **from; /* Previous link */
4326 } x4node;
4328 /* There is only one instance of the array, which is the following */
4329 static struct s_x4 *x4a;
4331 /* Allocate a new associative array */
4332 void Configtable_init(){
4333 if( x4a ) return;
4334 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4335 if( x4a ){
4336 x4a->size = 64;
4337 x4a->count = 0;
4338 x4a->tbl = (x4node*)malloc(
4339 (sizeof(x4node) + sizeof(x4node*))*64 );
4340 if( x4a->tbl==0 ){
4341 free(x4a);
4342 x4a = 0;
4343 }else{
4344 int i;
4345 x4a->ht = (x4node**)&(x4a->tbl[64]);
4346 for(i=0; i<64; i++) x4a->ht[i] = 0;
4350 /* Insert a new record into the array. Return TRUE if successful.
4351 ** Prior data with the same key is NOT overwritten */
4352 int Configtable_insert(data)
4353 struct config *data;
4355 x4node *np;
4356 int h;
4357 int ph;
4359 if( x4a==0 ) return 0;
4360 ph = confighash(data);
4361 h = ph & (x4a->size-1);
4362 np = x4a->ht[h];
4363 while( np ){
4364 if( Configcmp(np->data,data)==0 ){
4365 /* An existing entry with the same key is found. */
4366 /* Fail because overwrite is not allows. */
4367 return 0;
4369 np = np->next;
4371 if( x4a->count>=x4a->size ){
4372 /* Need to make the hash table bigger */
4373 int i,size;
4374 struct s_x4 array;
4375 array.size = size = x4a->size*2;
4376 array.count = x4a->count;
4377 array.tbl = (x4node*)malloc(
4378 (sizeof(x4node) + sizeof(x4node*))*size );
4379 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4380 array.ht = (x4node**)&(array.tbl[size]);
4381 for(i=0; i<size; i++) array.ht[i] = 0;
4382 for(i=0; i<x4a->count; i++){
4383 x4node *oldnp, *newnp;
4384 oldnp = &(x4a->tbl[i]);
4385 h = confighash(oldnp->data) & (size-1);
4386 newnp = &(array.tbl[i]);
4387 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4388 newnp->next = array.ht[h];
4389 newnp->data = oldnp->data;
4390 newnp->from = &(array.ht[h]);
4391 array.ht[h] = newnp;
4393 free(x4a->tbl);
4394 /* *x4a = array; *//* copy 'array' */
4395 memcpy(x4a, &array, sizeof(array));
4397 /* Insert the new data */
4398 h = ph & (x4a->size-1);
4399 np = &(x4a->tbl[x4a->count++]);
4400 np->data = data;
4401 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4402 np->next = x4a->ht[h];
4403 x4a->ht[h] = np;
4404 np->from = &(x4a->ht[h]);
4405 return 1;
4408 /* Return a pointer to data assigned to the given key. Return NULL
4409 ** if no such key. */
4410 struct config *Configtable_find(key)
4411 struct config *key;
4413 int h;
4414 x4node *np;
4416 if( x4a==0 ) return 0;
4417 h = confighash(key) & (x4a->size-1);
4418 np = x4a->ht[h];
4419 while( np ){
4420 if( Configcmp(np->data,key)==0 ) break;
4421 np = np->next;
4423 return np ? np->data : 0;
4426 /* Remove all data from the table. Pass each data to the function "f"
4427 ** as it is removed. ("f" may be null to avoid this step.) */
4428 void Configtable_clear(f)
4429 int(*f)(/* struct config * */);
4431 int i;
4432 if( x4a==0 || x4a->count==0 ) return;
4433 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4434 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4435 x4a->count = 0;
4436 return;