[ci] Enable IRC notifications from travis
[xapian.git] / xapian-core / queryparser / lemon.c
blobb57ea1ad98e23f5b309fb04fa23faa7c8e0e39f2
1 /*
2 ** This file contains all sources (including headers) to the LEMON
3 ** LALR(1) parser generator. The sources have been combined into a
4 ** single file to make it easy to include LEMON in the source tree
5 ** and Makefile of another program.
6 **
7 ** The authors of this program disclaim copyright.
8 **
9 ** Modified to add "-o" and "-h" command line options. Olly Betts 2005-02-14
10 ** Modified to fix a number of compiler warnings. Olly Betts 2007-02-20
12 ** Synced with upstream:
13 ** https://www.sqlite.org/src/artifact/c1a87d15983f96851b253707985dba8783fbe41ba21ba1b76720e06c8a262206
15 #include <stdio.h>
16 #include <stdarg.h>
17 #include <string.h>
18 #include <ctype.h>
19 #include <stdlib.h>
20 #include <assert.h>
22 #define ISSPACE(X) isspace((unsigned char)(X))
23 #define ISDIGIT(X) isdigit((unsigned char)(X))
24 #define ISALNUM(X) isalnum((unsigned char)(X))
25 #define ISALPHA(X) isalpha((unsigned char)(X))
26 #define ISUPPER(X) isupper((unsigned char)(X))
27 #define ISLOWER(X) islower((unsigned char)(X))
30 #ifndef __WIN32__
31 # if defined(_WIN32) || defined(WIN32)
32 # define __WIN32__
33 # endif
34 #endif
36 #ifdef __WIN32__
37 #ifdef __cplusplus
38 extern "C" {
39 #endif
40 extern int access(const char *path, int mode);
41 #ifdef __cplusplus
43 #endif
44 #else
45 #include <unistd.h>
46 #endif
48 #define PRIVATE static
50 #ifdef TEST
51 #define MAXRHS 5 /* Set low to exercise exception code */
52 #else
53 #define MAXRHS 1000
54 #endif
56 static int showPrecedenceConflict = 0;
57 static char *msort(char*,char**,int(*)(const char*,const char*));
60 ** Compilers are getting increasingly pedantic about type conversions
61 ** as C evolves ever closer to Ada.... To work around the latest problems
62 ** we have to define the following variant of strlen().
64 #define lemonStrlen(X) ((int)strlen(X))
67 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
68 ** saying they are unsafe. So we define our own versions of those routines too.
70 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
71 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
72 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
73 ** buffer, making sure the buffer is always zero-terminated.
75 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
76 ** a few simply conversions:
78 ** %d
79 ** %s
80 ** %.*s
83 static void lemon_addtext(
84 char *zBuf, /* The buffer to which text is added */
85 int *pnUsed, /* Slots of the buffer used so far */
86 const char *zIn, /* Text to add */
87 int nIn, /* Bytes of text to add. -1 to use strlen() */
88 int iWidth /* Field width. Negative to left justify */
90 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
91 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
92 if( nIn==0 ) return;
93 memcpy(&zBuf[*pnUsed], zIn, nIn);
94 *pnUsed += nIn;
95 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
96 zBuf[*pnUsed] = 0;
98 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
99 int i, j, k, c;
100 int nUsed = 0;
101 const char *z;
102 char zTemp[50];
103 str[0] = 0;
104 for(i=j=0; (c = zFormat[i])!=0; i++){
105 if( c=='%' ){
106 int iWidth = 0;
107 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
108 c = zFormat[++i];
109 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
110 if( c=='-' ) i++;
111 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
112 if( c=='-' ) iWidth = -iWidth;
113 c = zFormat[i];
115 if( c=='d' ){
116 int v = va_arg(ap, int);
117 if( v<0 ){
118 lemon_addtext(str, &nUsed, "-", 1, iWidth);
119 v = -v;
120 }else if( v==0 ){
121 lemon_addtext(str, &nUsed, "0", 1, iWidth);
123 k = 0;
124 while( v>0 ){
125 k++;
126 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
127 v /= 10;
129 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
130 }else if( c=='s' ){
131 z = va_arg(ap, const char*);
132 lemon_addtext(str, &nUsed, z, -1, iWidth);
133 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
134 i += 2;
135 k = va_arg(ap, int);
136 z = va_arg(ap, const char*);
137 lemon_addtext(str, &nUsed, z, k, iWidth);
138 }else if( c=='%' ){
139 lemon_addtext(str, &nUsed, "%", 1, 0);
140 }else{
141 fprintf(stderr, "illegal format\n");
142 exit(1);
144 j = i+1;
147 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
148 return nUsed;
150 static int lemon_sprintf(char *str, const char *format, ...){
151 va_list ap;
152 int rc;
153 va_start(ap, format);
154 rc = lemon_vsprintf(str, format, ap);
155 va_end(ap);
156 return rc;
158 static void lemon_strcpy(char *dest, const char *src){
159 while( (*(dest++) = *(src++))!=0 ){}
161 static void lemon_strcat(char *dest, const char *src){
162 while( *dest ) dest++;
163 lemon_strcpy(dest, src);
167 /* a few forward declarations... */
168 struct rule;
169 struct lemon;
170 struct action;
172 static struct action *Action_new(void);
173 static struct action *Action_sort(struct action *);
175 /********** From the file "build.h" ************************************/
176 void FindRulePrecedences(struct lemon*);
177 void FindFirstSets(struct lemon*);
178 void FindStates(struct lemon*);
179 void FindLinks(struct lemon*);
180 void FindFollowSets(struct lemon*);
181 void FindActions(struct lemon*);
183 /********* From the file "configlist.h" *********************************/
184 void Configlist_init(void);
185 struct config *Configlist_add(struct rule *, int);
186 struct config *Configlist_addbasis(struct rule *, int);
187 void Configlist_closure(struct lemon *);
188 void Configlist_sort(void);
189 void Configlist_sortbasis(void);
190 struct config *Configlist_return(void);
191 struct config *Configlist_basis(void);
192 void Configlist_eat(struct config *);
193 void Configlist_reset(void);
195 /********* From the file "error.h" ***************************************/
196 void ErrorMsg(const char *, int,const char *, ...);
198 /****** From the file "option.h" ******************************************/
199 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
200 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
201 struct s_options {
202 enum option_type type;
203 const char *label;
204 void *arg;
205 void(*func)();
206 const char *message;
208 int OptInit(char**,const struct s_options*,FILE*);
209 int OptNArgs(void);
210 char *OptArg(int);
211 void OptErr(int);
212 void OptPrint(void);
214 /******** From the file "parse.h" *****************************************/
215 void Parse(struct lemon *lemp);
217 /********* From the file "plink.h" ***************************************/
218 struct plink *Plink_new(void);
219 void Plink_add(struct plink **, struct config *);
220 void Plink_copy(struct plink **, struct plink *);
221 void Plink_delete(struct plink *);
223 /********** From the file "report.h" *************************************/
224 void Reprint(struct lemon *);
225 void ReportOutput(struct lemon *);
226 void ReportTable(struct lemon *, int);
227 void ReportHeader(struct lemon *);
228 void CompressTables(struct lemon *);
229 void ResortStates(struct lemon *);
231 /********** From the file "set.h" ****************************************/
232 void SetSize(int); /* All sets will be of size N */
233 char *SetNew(void); /* A new set for element 0..N */
234 void SetFree(char*); /* Deallocate a set */
235 int SetAdd(char*,int); /* Add element to a set */
236 int SetUnion(char *,char *); /* A <- A U B, thru element N */
237 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
239 /********** From the file "struct.h" *************************************/
241 ** Principal data structures for the LEMON parser generator.
244 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
246 /* Symbols (terminals and nonterminals) of the grammar are stored
247 ** in the following: */
248 enum symbol_type {
249 TERMINAL,
250 NONTERMINAL,
251 MULTITERMINAL
253 enum e_assoc {
254 LEFT,
255 RIGHT,
256 NONE,
259 struct symbol {
260 const char *name; /* Name of the symbol */
261 int index; /* Index number for this symbol */
262 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
263 struct rule *rule; /* Linked list of rules of this (if an NT) */
264 struct symbol *fallback; /* fallback token in case this token doesn't parse */
265 int prec; /* Precedence if defined (-1 otherwise) */
266 enum e_assoc assoc; /* Associativity if precedence is defined */
267 char *firstset; /* First-set for all rules of this symbol */
268 Boolean lambda; /* True if NT and can generate an empty string */
269 int useCnt; /* Number of times used */
270 char *destructor; /* Code which executes whenever this symbol is
271 ** popped from the stack during error processing */
272 int destLineno; /* Line number for start of destructor. Set to
273 ** -1 for duplicate destructors. */
274 char *datatype; /* The data type of information held by this
275 ** object. Only used if type==NONTERMINAL */
276 int dtnum; /* The data type number. In the parser, the value
277 ** stack is a union. The .yy%d element of this
278 ** union is the correct data type for this object */
279 /* The following fields are used by MULTITERMINALs only */
280 int nsubsym; /* Number of constituent symbols in the MULTI */
281 struct symbol **subsym; /* Array of constituent symbols */
284 /* Each production rule in the grammar is stored in the following
285 ** structure. */
286 struct rule {
287 struct symbol *lhs; /* Left-hand side of the rule */
288 const char *lhsalias; /* Alias for the LHS (NULL if none) */
289 int lhsStart; /* True if left-hand side is the start symbol */
290 int ruleline; /* Line number for the rule */
291 int nrhs; /* Number of RHS symbols */
292 struct symbol **rhs; /* The RHS symbols */
293 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
294 int line; /* Line number at which code begins */
295 const char *code; /* The code executed when this rule is reduced */
296 const char *codePrefix; /* Setup code before code[] above */
297 const char *codeSuffix; /* Breakdown code after code[] above */
298 int noCode; /* True if this rule has no associated C code */
299 int codeEmitted; /* True if the code has been emitted already */
300 struct symbol *precsym; /* Precedence symbol for this rule */
301 int index; /* An index number for this rule */
302 int iRule; /* Rule number as used in the generated tables */
303 Boolean canReduce; /* True if this rule is ever reduced */
304 Boolean doesReduce; /* Reduce actions occur after optimization */
305 struct rule *nextlhs; /* Next rule with the same LHS */
306 struct rule *next; /* Next rule in the global list */
309 /* A configuration is a production rule of the grammar together with
310 ** a mark (dot) showing how much of that rule has been processed so far.
311 ** Configurations also contain a follow-set which is a list of terminal
312 ** symbols which are allowed to immediately follow the end of the rule.
313 ** Every configuration is recorded as an instance of the following: */
314 enum cfgstatus {
315 COMPLETE,
316 INCOMPLETE
318 struct config {
319 struct rule *rp; /* The rule upon which the configuration is based */
320 int dot; /* The parse point */
321 char *fws; /* Follow-set for this configuration only */
322 struct plink *fplp; /* Follow-set forward propagation links */
323 struct plink *bplp; /* Follow-set backwards propagation links */
324 struct state *stp; /* Pointer to state which contains this */
325 enum cfgstatus status; /* used during followset and shift computations */
326 struct config *next; /* Next configuration in the state */
327 struct config *bp; /* The next basis configuration */
330 enum e_action {
331 SHIFT,
332 ACCEPT,
333 REDUCE,
334 ERROR,
335 SSCONFLICT, /* A shift/shift conflict */
336 SRCONFLICT, /* Was a reduce, but part of a conflict */
337 RRCONFLICT, /* Was a reduce, but part of a conflict */
338 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
339 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
340 NOT_USED, /* Deleted by compression */
341 SHIFTREDUCE /* Shift first, then reduce */
344 /* Every shift or reduce operation is stored as one of the following */
345 struct action {
346 struct symbol *sp; /* The look-ahead symbol */
347 enum e_action type;
348 union {
349 struct state *stp; /* The new state, if a shift */
350 struct rule *rp; /* The rule, if a reduce */
351 } x;
352 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
353 struct action *next; /* Next action for this state */
354 struct action *collide; /* Next action with the same hash */
357 /* Each state of the generated parser's finite state machine
358 ** is encoded as an instance of the following structure. */
359 struct state {
360 struct config *bp; /* The basis configurations for this state */
361 struct config *cfp; /* All configurations in this set */
362 int statenum; /* Sequential number for this state */
363 struct action *ap; /* List of actions for this state */
364 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
365 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
366 int iDfltReduce; /* Default action is to REDUCE by this rule */
367 struct rule *pDfltReduce;/* The default REDUCE rule. */
368 int autoReduce; /* True if this is an auto-reduce state */
370 #define NO_OFFSET (-2147483647)
372 /* A followset propagation link indicates that the contents of one
373 ** configuration followset should be propagated to another whenever
374 ** the first changes. */
375 struct plink {
376 struct config *cfp; /* The configuration to which linked */
377 struct plink *next; /* The next propagate link */
380 /* The state vector for the entire parser generator is recorded as
381 ** follows. (LEMON uses no global variables and makes little use of
382 ** static variables. Fields in the following structure can be thought
383 ** of as begin global variables in the program.) */
384 struct lemon {
385 struct state **sorted; /* Table of states sorted by state number */
386 struct rule *rule; /* List of all rules */
387 struct rule *startRule; /* First rule */
388 int nstate; /* Number of states */
389 int nxstate; /* nstate with tail degenerate states removed */
390 int nrule; /* Number of rules */
391 int nsymbol; /* Number of terminal and nonterminal symbols */
392 int nterminal; /* Number of terminal symbols */
393 int minShiftReduce; /* Minimum shift-reduce action value */
394 int errAction; /* Error action value */
395 int accAction; /* Accept action value */
396 int noAction; /* No-op action value */
397 int minReduce; /* Minimum reduce action */
398 int maxAction; /* Maximum action value of any kind */
399 struct symbol **symbols; /* Sorted array of pointers to symbols */
400 int errorcnt; /* Number of errors */
401 struct symbol *errsym; /* The error symbol */
402 struct symbol *wildcard; /* Token that matches anything */
403 char *name; /* Name of the generated parser */
404 char *arg; /* Declaration of the 3th argument to parser */
405 char *tokentype; /* Type of terminal symbols in the parser stack */
406 char *vartype; /* The default type of non-terminal symbols */
407 char *start; /* Name of the start symbol for the grammar */
408 char *stacksize; /* Size of the parser stack */
409 char *include; /* Code to put at the start of the C file */
410 char *error; /* Code to execute when an error is seen */
411 char *overflow; /* Code to execute on a stack overflow */
412 char *failure; /* Code to execute on parser failure */
413 char *accept; /* Code to execute when the parser excepts */
414 char *extracode; /* Code appended to the generated file */
415 char *tokendest; /* Code to execute to destroy token data */
416 char *vardest; /* Code for the default non-terminal destructor */
417 char *filename; /* Name of the input file */
418 char *outname; /* Name of the current output file */
419 char *tokenprefix; /* A prefix added to token names in the .h file */
420 int nconflict; /* Number of parsing conflicts */
421 int nactiontab; /* Number of entries in the yy_action[] table */
422 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
423 int tablesize; /* Total table size of all tables in bytes */
424 int basisflag; /* Print only basis configurations */
425 int has_fallback; /* True if any %fallback is seen in the grammar */
426 int nolinenosflag; /* True if #line statements should not be printed */
427 char *argv0; /* Name of the program */
430 #define MemoryCheck(X) if((X)==0){ \
431 extern void memory_error(); \
432 memory_error(); \
435 /**************** From the file "table.h" *********************************/
437 ** All code in this file has been automatically generated
438 ** from a specification in the file
439 ** "table.q"
440 ** by the associative array code building program "aagen".
441 ** Do not edit this file! Instead, edit the specification
442 ** file, then rerun aagen.
445 ** Code for processing tables in the LEMON parser generator.
447 /* Routines for handling strings */
449 const char *Strsafe(const char *);
451 void Strsafe_init(void);
452 int Strsafe_insert(const char *);
453 const char *Strsafe_find(const char *);
455 /* Routines for handling symbols of the grammar */
457 struct symbol *Symbol_new(const char *);
458 int Symbolcmpp(const void *, const void *);
459 void Symbol_init(void);
460 int Symbol_insert(struct symbol *, const char *);
461 struct symbol *Symbol_find(const char *);
462 struct symbol *Symbol_Nth(int);
463 int Symbol_count(void);
464 struct symbol **Symbol_arrayof(void);
466 /* Routines to manage the state table */
468 int Configcmp(const char *, const char *);
469 struct state *State_new(void);
470 void State_init(void);
471 int State_insert(struct state *, struct config *);
472 struct state *State_find(struct config *);
473 struct state **State_arrayof(void);
475 /* Routines used for efficiency in Configlist_add */
477 void Configtable_init(void);
478 int Configtable_insert(struct config *);
479 struct config *Configtable_find(struct config *);
480 void Configtable_clear(int(*)(struct config *));
482 /****************** From the file "action.c" *******************************/
484 ** Routines processing parser actions in the LEMON parser generator.
487 /* Allocate a new parser action */
488 static struct action *Action_new(void){
489 static struct action *freelist = 0;
490 struct action *newaction;
492 if( freelist==0 ){
493 int i;
494 int amt = 100;
495 freelist = (struct action *)calloc(amt, sizeof(struct action));
496 if( freelist==0 ){
497 fprintf(stderr,"Unable to allocate memory for a new parser action.");
498 exit(1);
500 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
501 freelist[amt-1].next = 0;
503 newaction = freelist;
504 freelist = freelist->next;
505 return newaction;
508 /* Compare two actions for sorting purposes. Return negative, zero, or
509 ** positive if the first action is less than, equal to, or greater than
510 ** the first
512 static int actioncmp(
513 const char *char_ap1,
514 const char *char_ap2
516 const struct action *ap1 = (const struct action *)char_ap1;
517 const struct action *ap2 = (const struct action *)char_ap2;
518 int rc;
519 rc = ap1->sp->index - ap2->sp->index;
520 if( rc==0 ){
521 rc = (int)ap1->type - (int)ap2->type;
523 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
524 rc = ap1->x.rp->index - ap2->x.rp->index;
526 if( rc==0 ){
527 rc = (int) (ap2 - ap1);
529 return rc;
532 /* Sort parser actions */
533 static struct action *Action_sort(
534 struct action *ap
536 /* Cast to "char **" via "void *" to avoid aliasing problems. */
537 ap = (struct action *)msort((char *)ap,(char **)(void *)&ap->next,actioncmp);
538 return ap;
541 void Action_add(
542 struct action **app,
543 enum e_action type,
544 struct symbol *sp,
545 char *arg
547 struct action *newaction;
548 newaction = Action_new();
549 newaction->next = *app;
550 *app = newaction;
551 newaction->type = type;
552 newaction->sp = sp;
553 newaction->spOpt = 0;
554 if( type==SHIFT ){
555 newaction->x.stp = (struct state *)arg;
556 }else{
557 newaction->x.rp = (struct rule *)arg;
560 /********************** New code to implement the "acttab" module ***********/
562 ** This module implements routines use to construct the yy_action[] table.
566 ** The state of the yy_action table under construction is an instance of
567 ** the following structure.
569 ** The yy_action table maps the pair (state_number, lookahead) into an
570 ** action_number. The table is an array of integers pairs. The state_number
571 ** determines an initial offset into the yy_action array. The lookahead
572 ** value is then added to this initial offset to get an index X into the
573 ** yy_action array. If the aAction[X].lookahead equals the value of the
574 ** of the lookahead input, then the value of the action_number output is
575 ** aAction[X].action. If the lookaheads do not match then the
576 ** default action for the state_number is returned.
578 ** All actions associated with a single state_number are first entered
579 ** into aLookahead[] using multiple calls to acttab_action(). Then the
580 ** actions for that single state_number are placed into the aAction[]
581 ** array with a single call to acttab_insert(). The acttab_insert() call
582 ** also resets the aLookahead[] array in preparation for the next
583 ** state number.
585 struct lookahead_action {
586 int lookahead; /* Value of the lookahead token */
587 int action; /* Action to take on the given lookahead */
589 typedef struct acttab acttab;
590 struct acttab {
591 int nAction; /* Number of used slots in aAction[] */
592 int nActionAlloc; /* Slots allocated for aAction[] */
593 struct lookahead_action
594 *aAction, /* The yy_action[] table under construction */
595 *aLookahead; /* A single new transaction set */
596 int mnLookahead; /* Minimum aLookahead[].lookahead */
597 int mnAction; /* Action associated with mnLookahead */
598 int mxLookahead; /* Maximum aLookahead[].lookahead */
599 int nLookahead; /* Used slots in aLookahead[] */
600 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
601 int nterminal; /* Number of terminal symbols */
602 int nsymbol; /* total number of symbols */
605 /* Return the number of entries in the yy_action table */
606 #define acttab_lookahead_size(X) ((X)->nAction)
608 /* The value for the N-th entry in yy_action */
609 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
611 /* The value for the N-th entry in yy_lookahead */
612 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
614 /* Free all memory associated with the given acttab */
615 void acttab_free(acttab *p){
616 free( p->aAction );
617 free( p->aLookahead );
618 free( p );
621 /* Allocate a new acttab structure */
622 acttab *acttab_alloc(int nsymbol, int nterminal){
623 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
624 if( p==0 ){
625 fprintf(stderr,"Unable to allocate memory for a new acttab.");
626 exit(1);
628 memset(p, 0, sizeof(*p));
629 p->nsymbol = nsymbol;
630 p->nterminal = nterminal;
631 return p;
634 /* Add a new action to the current transaction set.
636 ** This routine is called once for each lookahead for a particular
637 ** state.
639 void acttab_action(acttab *p, int lookahead, int action){
640 if( p->nLookahead>=p->nLookaheadAlloc ){
641 p->nLookaheadAlloc += 25;
642 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
643 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
644 if( p->aLookahead==0 ){
645 fprintf(stderr,"malloc failed\n");
646 exit(1);
649 if( p->nLookahead==0 ){
650 p->mxLookahead = lookahead;
651 p->mnLookahead = lookahead;
652 p->mnAction = action;
653 }else{
654 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
655 if( p->mnLookahead>lookahead ){
656 p->mnLookahead = lookahead;
657 p->mnAction = action;
660 p->aLookahead[p->nLookahead].lookahead = lookahead;
661 p->aLookahead[p->nLookahead].action = action;
662 p->nLookahead++;
666 ** Add the transaction set built up with prior calls to acttab_action()
667 ** into the current action table. Then reset the transaction set back
668 ** to an empty set in preparation for a new round of acttab_action() calls.
670 ** Return the offset into the action table of the new transaction.
672 ** If the makeItSafe parameter is true, then the offset is chosen so that
673 ** it is impossible to overread the yy_lookaside[] table regardless of
674 ** the lookaside token. This is done for the terminal symbols, as they
675 ** come from external inputs and can contain syntax errors. When makeItSafe
676 ** is false, there is more flexibility in selecting offsets, resulting in
677 ** a smaller table. For non-terminal symbols, which are never syntax errors,
678 ** makeItSafe can be false.
680 int acttab_insert(acttab *p, int makeItSafe){
681 int i, j, k, n, end;
682 assert( p->nLookahead>0 );
684 /* Make sure we have enough space to hold the expanded action table
685 ** in the worst case. The worst case occurs if the transaction set
686 ** must be appended to the current action table
688 n = p->nsymbol + 1;
689 if( p->nAction + n >= p->nActionAlloc ){
690 int oldAlloc = p->nActionAlloc;
691 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
692 p->aAction = (struct lookahead_action *) realloc( p->aAction,
693 sizeof(p->aAction[0])*p->nActionAlloc);
694 if( p->aAction==0 ){
695 fprintf(stderr,"malloc failed\n");
696 exit(1);
698 for(i=oldAlloc; i<p->nActionAlloc; i++){
699 p->aAction[i].lookahead = -1;
700 p->aAction[i].action = -1;
704 /* Scan the existing action table looking for an offset that is a
705 ** duplicate of the current transaction set. Fall out of the loop
706 ** if and when the duplicate is found.
708 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
710 end = makeItSafe ? p->mnLookahead : 0;
711 for(i=p->nAction-1; i>=end; i--){
712 if( p->aAction[i].lookahead==p->mnLookahead ){
713 /* All lookaheads and actions in the aLookahead[] transaction
714 ** must match against the candidate aAction[i] entry. */
715 if( p->aAction[i].action!=p->mnAction ) continue;
716 for(j=0; j<p->nLookahead; j++){
717 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
718 if( k<0 || k>=p->nAction ) break;
719 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
720 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
722 if( j<p->nLookahead ) continue;
724 /* No possible lookahead value that is not in the aLookahead[]
725 ** transaction is allowed to match aAction[i] */
726 n = 0;
727 for(j=0; j<p->nAction; j++){
728 if( p->aAction[j].lookahead<0 ) continue;
729 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
731 if( n==p->nLookahead ){
732 break; /* An exact match is found at offset i */
737 /* If no existing offsets exactly match the current transaction, find an
738 ** an empty offset in the aAction[] table in which we can add the
739 ** aLookahead[] transaction.
741 if( i<end ){
742 /* Look for holes in the aAction[] table that fit the current
743 ** aLookahead[] transaction. Leave i set to the offset of the hole.
744 ** If no holes are found, i is left at p->nAction, which means the
745 ** transaction will be appended. */
746 i = makeItSafe ? p->mnLookahead : 0;
747 for(; i<p->nActionAlloc - p->mxLookahead; i++){
748 if( p->aAction[i].lookahead<0 ){
749 for(j=0; j<p->nLookahead; j++){
750 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
751 if( k<0 ) break;
752 if( p->aAction[k].lookahead>=0 ) break;
754 if( j<p->nLookahead ) continue;
755 for(j=0; j<p->nAction; j++){
756 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
758 if( j==p->nAction ){
759 break; /* Fits in empty slots */
764 /* Insert transaction set at index i. */
765 #if 0
766 printf("Acttab:");
767 for(j=0; j<p->nLookahead; j++){
768 printf(" %d", p->aLookahead[j].lookahead);
770 printf(" inserted at %d\n", i);
771 #endif
772 for(j=0; j<p->nLookahead; j++){
773 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
774 p->aAction[k] = p->aLookahead[j];
775 if( k>=p->nAction ) p->nAction = k+1;
777 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
778 p->nLookahead = 0;
780 /* Return the offset that is added to the lookahead in order to get the
781 ** index into yy_action of the action */
782 return i - p->mnLookahead;
786 ** Return the size of the action table without the trailing syntax error
787 ** entries.
789 int acttab_action_size(acttab *p){
790 int n = p->nAction;
791 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
792 return n;
795 /********************** From the file "build.c" *****************************/
797 ** Routines to construction the finite state machine for the LEMON
798 ** parser generator.
801 /* Find a precedence symbol of every rule in the grammar.
803 ** Those rules which have a precedence symbol coded in the input
804 ** grammar using the "[symbol]" construct will already have the
805 ** rp->precsym field filled. Other rules take as their precedence
806 ** symbol the first RHS symbol with a defined precedence. If there
807 ** are not RHS symbols with a defined precedence, the precedence
808 ** symbol field is left blank.
810 void FindRulePrecedences(struct lemon *xp)
812 struct rule *rp;
813 for(rp=xp->rule; rp; rp=rp->next){
814 if( rp->precsym==0 ){
815 int i, j;
816 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
817 struct symbol *sp = rp->rhs[i];
818 if( sp->type==MULTITERMINAL ){
819 for(j=0; j<sp->nsubsym; j++){
820 if( sp->subsym[j]->prec>=0 ){
821 rp->precsym = sp->subsym[j];
822 break;
825 }else if( sp->prec>=0 ){
826 rp->precsym = rp->rhs[i];
831 return;
834 /* Find all nonterminals which will generate the empty string.
835 ** Then go back and compute the first sets of every nonterminal.
836 ** The first set is the set of all terminal symbols which can begin
837 ** a string generated by that nonterminal.
839 void FindFirstSets(struct lemon *lemp)
841 int i, j;
842 struct rule *rp;
843 int progress;
845 for(i=0; i<lemp->nsymbol; i++){
846 lemp->symbols[i]->lambda = LEMON_FALSE;
848 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
849 lemp->symbols[i]->firstset = SetNew();
852 /* First compute all lambdas */
854 progress = 0;
855 for(rp=lemp->rule; rp; rp=rp->next){
856 if( rp->lhs->lambda ) continue;
857 for(i=0; i<rp->nrhs; i++){
858 struct symbol *sp = rp->rhs[i];
859 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
860 if( sp->lambda==LEMON_FALSE ) break;
862 if( i==rp->nrhs ){
863 rp->lhs->lambda = LEMON_TRUE;
864 progress = 1;
867 }while( progress );
869 /* Now compute all first sets */
871 struct symbol *s1, *s2;
872 progress = 0;
873 for(rp=lemp->rule; rp; rp=rp->next){
874 s1 = rp->lhs;
875 for(i=0; i<rp->nrhs; i++){
876 s2 = rp->rhs[i];
877 if( s2->type==TERMINAL ){
878 progress += SetAdd(s1->firstset,s2->index);
879 break;
880 }else if( s2->type==MULTITERMINAL ){
881 for(j=0; j<s2->nsubsym; j++){
882 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
884 break;
885 }else if( s1==s2 ){
886 if( s1->lambda==LEMON_FALSE ) break;
887 }else{
888 progress += SetUnion(s1->firstset,s2->firstset);
889 if( s2->lambda==LEMON_FALSE ) break;
893 }while( progress );
894 return;
897 /* Compute all LR(0) states for the grammar. Links
898 ** are added to between some states so that the LR(1) follow sets
899 ** can be computed later.
901 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
902 void FindStates(struct lemon *lemp)
904 struct symbol *sp;
905 struct rule *rp;
907 Configlist_init();
909 /* Find the start symbol */
910 if( lemp->start ){
911 sp = Symbol_find(lemp->start);
912 if( sp==0 ){
913 ErrorMsg(lemp->filename,0,
914 "The specified start symbol \"%s\" is not "
915 "in a nonterminal of the grammar. \"%s\" will be used as the start "
916 "symbol instead.",lemp->start,lemp->startRule->lhs->name);
917 lemp->errorcnt++;
918 sp = lemp->startRule->lhs;
920 }else{
921 sp = lemp->startRule->lhs;
924 /* Make sure the start symbol doesn't occur on the right-hand side of
925 ** any rule. Report an error if it does. (YACC would generate a new
926 ** start symbol in this case.) */
927 for(rp=lemp->rule; rp; rp=rp->next){
928 int i;
929 for(i=0; i<rp->nrhs; i++){
930 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
931 ErrorMsg(lemp->filename,0,
932 "The start symbol \"%s\" occurs on the "
933 "right-hand side of a rule. This will result in a parser which "
934 "does not work properly.",sp->name);
935 lemp->errorcnt++;
940 /* The basis configuration set for the first state
941 ** is all rules which have the start symbol as their
942 ** left-hand side */
943 for(rp=sp->rule; rp; rp=rp->nextlhs){
944 struct config *newcfp;
945 rp->lhsStart = 1;
946 newcfp = Configlist_addbasis(rp,0);
947 SetAdd(newcfp->fws,0);
950 /* Compute the first state. All other states will be
951 ** computed automatically during the computation of the first one.
952 ** The returned pointer to the first state is not used. */
953 (void)getstate(lemp);
954 return;
957 /* Return a pointer to a state which is described by the configuration
958 ** list which has been built from calls to Configlist_add.
960 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
961 PRIVATE struct state *getstate(struct lemon *lemp)
963 struct config *cfp, *bp;
964 struct state *stp;
966 /* Extract the sorted basis of the new state. The basis was constructed
967 ** by prior calls to "Configlist_addbasis()". */
968 Configlist_sortbasis();
969 bp = Configlist_basis();
971 /* Get a state with the same basis */
972 stp = State_find(bp);
973 if( stp ){
974 /* A state with the same basis already exists! Copy all the follow-set
975 ** propagation links from the state under construction into the
976 ** preexisting state, then return a pointer to the preexisting state */
977 struct config *x, *y;
978 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
979 Plink_copy(&y->bplp,x->bplp);
980 Plink_delete(x->fplp);
981 x->fplp = x->bplp = 0;
983 cfp = Configlist_return();
984 Configlist_eat(cfp);
985 }else{
986 /* This really is a new state. Construct all the details */
987 Configlist_closure(lemp); /* Compute the configuration closure */
988 Configlist_sort(); /* Sort the configuration closure */
989 cfp = Configlist_return(); /* Get a pointer to the config list */
990 stp = State_new(); /* A new state structure */
991 MemoryCheck(stp);
992 stp->bp = bp; /* Remember the configuration basis */
993 stp->cfp = cfp; /* Remember the configuration closure */
994 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
995 stp->ap = 0; /* No actions, yet. */
996 State_insert(stp,stp->bp); /* Add to the state table */
997 buildshifts(lemp,stp); /* Recursively compute successor states */
999 return stp;
1003 ** Return true if two symbols are the same.
1005 int same_symbol(struct symbol *a, struct symbol *b)
1007 int i;
1008 if( a==b ) return 1;
1009 if( a->type!=MULTITERMINAL ) return 0;
1010 if( b->type!=MULTITERMINAL ) return 0;
1011 if( a->nsubsym!=b->nsubsym ) return 0;
1012 for(i=0; i<a->nsubsym; i++){
1013 if( a->subsym[i]!=b->subsym[i] ) return 0;
1015 return 1;
1018 /* Construct all successor states to the given state. A "successor"
1019 ** state is any state which can be reached by a shift action.
1021 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
1023 struct config *cfp; /* For looping thru the config closure of "stp" */
1024 struct config *bcfp; /* For the inner loop on config closure of "stp" */
1025 struct config *newcfg; /* */
1026 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1027 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1028 struct state *newstp; /* A pointer to a successor state */
1030 /* Each configuration becomes complete after it contributes to a successor
1031 ** state. Initially, all configurations are incomplete */
1032 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1034 /* Loop through all configurations of the state "stp" */
1035 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1036 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1037 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1038 Configlist_reset(); /* Reset the new config set */
1039 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1041 /* For every configuration in the state "stp" which has the symbol "sp"
1042 ** following its dot, add the same configuration to the basis set under
1043 ** construction but with the dot shifted one symbol to the right. */
1044 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1045 if( bcfp->status==COMPLETE ) continue; /* Already used */
1046 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1047 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
1048 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
1049 bcfp->status = COMPLETE; /* Mark this config as used */
1050 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1051 Plink_add(&newcfg->bplp,bcfp);
1054 /* Get a pointer to the state described by the basis configuration set
1055 ** constructed in the preceding loop */
1056 newstp = getstate(lemp);
1058 /* The state "newstp" is reached from the state "stp" by a shift action
1059 ** on the symbol "sp" */
1060 if( sp->type==MULTITERMINAL ){
1061 int i;
1062 for(i=0; i<sp->nsubsym; i++){
1063 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1065 }else{
1066 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1072 ** Construct the propagation links
1074 void FindLinks(struct lemon *lemp)
1076 int i;
1077 struct config *cfp, *other;
1078 struct state *stp;
1079 struct plink *plp;
1081 /* Housekeeping detail:
1082 ** Add to every propagate link a pointer back to the state to
1083 ** which the link is attached. */
1084 for(i=0; i<lemp->nstate; i++){
1085 stp = lemp->sorted[i];
1086 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1087 cfp->stp = stp;
1091 /* Convert all backlinks into forward links. Only the forward
1092 ** links are used in the follow-set computation. */
1093 for(i=0; i<lemp->nstate; i++){
1094 stp = lemp->sorted[i];
1095 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1096 for(plp=cfp->bplp; plp; plp=plp->next){
1097 other = plp->cfp;
1098 Plink_add(&other->fplp,cfp);
1104 /* Compute all followsets.
1106 ** A followset is the set of all symbols which can come immediately
1107 ** after a configuration.
1109 void FindFollowSets(struct lemon *lemp)
1111 int i;
1112 struct config *cfp;
1113 struct plink *plp;
1114 int progress;
1115 int change;
1117 for(i=0; i<lemp->nstate; i++){
1118 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1119 cfp->status = INCOMPLETE;
1124 progress = 0;
1125 for(i=0; i<lemp->nstate; i++){
1126 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1127 if( cfp->status==COMPLETE ) continue;
1128 for(plp=cfp->fplp; plp; plp=plp->next){
1129 change = SetUnion(plp->cfp->fws,cfp->fws);
1130 if( change ){
1131 plp->cfp->status = INCOMPLETE;
1132 progress = 1;
1135 cfp->status = COMPLETE;
1138 }while( progress );
1141 static int resolve_conflict(struct action *,struct action *);
1143 /* Compute the reduce actions, and resolve conflicts.
1145 void FindActions(struct lemon *lemp)
1147 int i,j;
1148 struct config *cfp;
1149 struct state *stp;
1150 struct symbol *sp;
1151 struct rule *rp;
1153 /* Add all of the reduce actions
1154 ** A reduce action is added for each element of the followset of
1155 ** a configuration which has its dot at the extreme right.
1157 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1158 stp = lemp->sorted[i];
1159 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1160 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1161 for(j=0; j<lemp->nterminal; j++){
1162 if( SetFind(cfp->fws,j) ){
1163 /* Add a reduce action to the state "stp" which will reduce by the
1164 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1165 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1172 /* Add the accepting token */
1173 if( lemp->start ){
1174 sp = Symbol_find(lemp->start);
1175 if( sp==0 ) sp = lemp->startRule->lhs;
1176 }else{
1177 sp = lemp->startRule->lhs;
1179 /* Add to the first state (which is always the starting state of the
1180 ** finite state machine) an action to ACCEPT if the lookahead is the
1181 ** start nonterminal. */
1182 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1184 /* Resolve conflicts */
1185 for(i=0; i<lemp->nstate; i++){
1186 struct action *ap, *nap;
1187 stp = lemp->sorted[i];
1188 /* assert( stp->ap ); */
1189 stp->ap = Action_sort(stp->ap);
1190 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1191 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1192 /* The two actions "ap" and "nap" have the same lookahead.
1193 ** Figure out which one should be used */
1194 lemp->nconflict += resolve_conflict(ap,nap);
1199 /* Report an error for each rule that can never be reduced. */
1200 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1201 for(i=0; i<lemp->nstate; i++){
1202 struct action *ap;
1203 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1204 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1207 for(rp=lemp->rule; rp; rp=rp->next){
1208 if( rp->canReduce ) continue;
1209 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1210 lemp->errorcnt++;
1214 /* Resolve a conflict between the two given actions. If the
1215 ** conflict can't be resolved, return non-zero.
1217 ** NO LONGER TRUE:
1218 ** To resolve a conflict, first look to see if either action
1219 ** is on an error rule. In that case, take the action which
1220 ** is not associated with the error rule. If neither or both
1221 ** actions are associated with an error rule, then try to
1222 ** use precedence to resolve the conflict.
1224 ** If either action is a SHIFT, then it must be apx. This
1225 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1227 static int resolve_conflict(
1228 struct action *apx,
1229 struct action *apy
1231 struct symbol *spx, *spy;
1232 int errcnt = 0;
1233 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1234 if( apx->type==SHIFT && apy->type==SHIFT ){
1235 apy->type = SSCONFLICT;
1236 errcnt++;
1238 if( apx->type==SHIFT && apy->type==REDUCE ){
1239 spx = apx->sp;
1240 spy = apy->x.rp->precsym;
1241 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1242 /* Not enough precedence information. */
1243 apy->type = SRCONFLICT;
1244 errcnt++;
1245 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1246 apy->type = RD_RESOLVED;
1247 }else if( spx->prec<spy->prec ){
1248 apx->type = SH_RESOLVED;
1249 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1250 apy->type = RD_RESOLVED; /* associativity */
1251 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1252 apx->type = SH_RESOLVED;
1253 }else{
1254 assert( spx->prec==spy->prec && spx->assoc==NONE );
1255 apx->type = ERROR;
1257 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1258 spx = apx->x.rp->precsym;
1259 spy = apy->x.rp->precsym;
1260 if( spx==0 || spy==0 || spx->prec<0 ||
1261 spy->prec<0 || spx->prec==spy->prec ){
1262 apy->type = RRCONFLICT;
1263 errcnt++;
1264 }else if( spx->prec>spy->prec ){
1265 apy->type = RD_RESOLVED;
1266 }else if( spx->prec<spy->prec ){
1267 apx->type = RD_RESOLVED;
1269 }else{
1270 assert(
1271 apx->type==SH_RESOLVED ||
1272 apx->type==RD_RESOLVED ||
1273 apx->type==SSCONFLICT ||
1274 apx->type==SRCONFLICT ||
1275 apx->type==RRCONFLICT ||
1276 apy->type==SH_RESOLVED ||
1277 apy->type==RD_RESOLVED ||
1278 apy->type==SSCONFLICT ||
1279 apy->type==SRCONFLICT ||
1280 apy->type==RRCONFLICT
1282 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1283 ** REDUCEs on the list. If we reach this point it must be because
1284 ** the parser conflict had already been resolved. */
1286 return errcnt;
1288 /********************* From the file "configlist.c" *************************/
1290 ** Routines to processing a configuration list and building a state
1291 ** in the LEMON parser generator.
1294 static struct config *freelist = 0; /* List of free configurations */
1295 static struct config *current = 0; /* Top of list of configurations */
1296 static struct config **currentend = 0; /* Last on list of configs */
1297 static struct config *basis = 0; /* Top of list of basis configs */
1298 static struct config **basisend = 0; /* End of list of basis configs */
1300 /* Return a pointer to a new configuration */
1301 PRIVATE struct config *newconfig(void){
1302 struct config *newcfg;
1303 if( freelist==0 ){
1304 int i;
1305 int amt = 3;
1306 freelist = (struct config *)calloc( amt, sizeof(struct config) );
1307 if( freelist==0 ){
1308 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1309 exit(1);
1311 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1312 freelist[amt-1].next = 0;
1314 newcfg = freelist;
1315 freelist = freelist->next;
1316 return newcfg;
1319 /* The configuration "old" is no longer used */
1320 PRIVATE void deleteconfig(struct config *old)
1322 old->next = freelist;
1323 freelist = old;
1326 /* Initialized the configuration list builder */
1327 void Configlist_init(void){
1328 current = 0;
1329 currentend = &current;
1330 basis = 0;
1331 basisend = &basis;
1332 Configtable_init();
1333 return;
1336 /* Initialized the configuration list builder */
1337 void Configlist_reset(void){
1338 current = 0;
1339 currentend = &current;
1340 basis = 0;
1341 basisend = &basis;
1342 Configtable_clear(0);
1343 return;
1346 /* Add another configuration to the configuration list */
1347 struct config *Configlist_add(
1348 struct rule *rp, /* The rule */
1349 int dot /* Index into the RHS of the rule where the dot goes */
1351 struct config *cfp, model;
1353 assert( currentend!=0 );
1354 model.rp = rp;
1355 model.dot = dot;
1356 cfp = Configtable_find(&model);
1357 if( cfp==0 ){
1358 cfp = newconfig();
1359 cfp->rp = rp;
1360 cfp->dot = dot;
1361 cfp->fws = SetNew();
1362 cfp->stp = 0;
1363 cfp->fplp = cfp->bplp = 0;
1364 cfp->next = 0;
1365 cfp->bp = 0;
1366 *currentend = cfp;
1367 currentend = &cfp->next;
1368 Configtable_insert(cfp);
1370 return cfp;
1373 /* Add a basis configuration to the configuration list */
1374 struct config *Configlist_addbasis(struct rule *rp, int dot)
1376 struct config *cfp, model;
1378 assert( basisend!=0 );
1379 assert( currentend!=0 );
1380 model.rp = rp;
1381 model.dot = dot;
1382 cfp = Configtable_find(&model);
1383 if( cfp==0 ){
1384 cfp = newconfig();
1385 cfp->rp = rp;
1386 cfp->dot = dot;
1387 cfp->fws = SetNew();
1388 cfp->stp = 0;
1389 cfp->fplp = cfp->bplp = 0;
1390 cfp->next = 0;
1391 cfp->bp = 0;
1392 *currentend = cfp;
1393 currentend = &cfp->next;
1394 *basisend = cfp;
1395 basisend = &cfp->bp;
1396 Configtable_insert(cfp);
1398 return cfp;
1401 /* Compute the closure of the configuration list */
1402 void Configlist_closure(struct lemon *lemp)
1404 struct config *cfp, *newcfp;
1405 struct rule *rp, *newrp;
1406 struct symbol *sp, *xsp;
1407 int i, dot;
1409 assert( currentend!=0 );
1410 for(cfp=current; cfp; cfp=cfp->next){
1411 rp = cfp->rp;
1412 dot = cfp->dot;
1413 if( dot>=rp->nrhs ) continue;
1414 sp = rp->rhs[dot];
1415 if( sp->type==NONTERMINAL ){
1416 if( sp->rule==0 && sp!=lemp->errsym ){
1417 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1418 sp->name);
1419 lemp->errorcnt++;
1421 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1422 newcfp = Configlist_add(newrp,0);
1423 for(i=dot+1; i<rp->nrhs; i++){
1424 xsp = rp->rhs[i];
1425 if( xsp->type==TERMINAL ){
1426 SetAdd(newcfp->fws,xsp->index);
1427 break;
1428 }else if( xsp->type==MULTITERMINAL ){
1429 int k;
1430 for(k=0; k<xsp->nsubsym; k++){
1431 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1433 break;
1434 }else{
1435 SetUnion(newcfp->fws,xsp->firstset);
1436 if( xsp->lambda==LEMON_FALSE ) break;
1439 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1443 return;
1446 /* Sort the configuration list */
1447 void Configlist_sort(void){
1448 /* Cast to "char **" via "void *" to avoid aliasing problems. */
1449 current = (struct config*)msort((char*)current,(char**)(void*)&(current->next),
1450 Configcmp);
1451 currentend = 0;
1452 return;
1455 /* Sort the basis configuration list */
1456 void Configlist_sortbasis(void){
1457 /* Cast to "char **" via "void *" to avoid aliasing problems. */
1458 basis = (struct config*)msort((char*)current,(char**)(void*)&(current->bp),
1459 Configcmp);
1460 basisend = 0;
1461 return;
1464 /* Return a pointer to the head of the configuration list and
1465 ** reset the list */
1466 struct config *Configlist_return(void){
1467 struct config *old;
1468 old = current;
1469 current = 0;
1470 currentend = 0;
1471 return old;
1474 /* Return a pointer to the head of the configuration list and
1475 ** reset the list */
1476 struct config *Configlist_basis(void){
1477 struct config *old;
1478 old = basis;
1479 basis = 0;
1480 basisend = 0;
1481 return old;
1484 /* Free all elements of the given configuration list */
1485 void Configlist_eat(struct config *cfp)
1487 struct config *nextcfp;
1488 for(; cfp; cfp=nextcfp){
1489 nextcfp = cfp->next;
1490 assert( cfp->fplp==0 );
1491 assert( cfp->bplp==0 );
1492 if( cfp->fws ) SetFree(cfp->fws);
1493 deleteconfig(cfp);
1495 return;
1497 /***************** From the file "error.c" *********************************/
1499 ** Code for printing error message.
1502 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1503 va_list ap;
1504 fprintf(stderr, "%s:%d: ", filename, lineno);
1505 va_start(ap, format);
1506 vfprintf(stderr,format,ap);
1507 va_end(ap);
1508 fprintf(stderr, "\n");
1510 /**************** From the file "main.c" ************************************/
1512 ** Main program file for the LEMON parser generator.
1515 /* Report an out-of-memory condition and abort. This function
1516 ** is used mostly by the "MemoryCheck" macro in struct.h
1518 void memory_error(void){
1519 fprintf(stderr,"Out of memory. Aborting...\n");
1520 exit(1);
1523 static int nDefine = 0; /* Number of -D options on the command line */
1524 static char **azDefine = 0; /* Name of the -D macros */
1526 /* This routine is called with the argument to each -D command-line option.
1527 ** Add the macro defined to the azDefine array.
1529 static void handle_D_option(char *z){
1530 char **paz;
1531 nDefine++;
1532 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
1533 if( azDefine==0 ){
1534 fprintf(stderr,"out of memory\n");
1535 exit(1);
1537 paz = &azDefine[nDefine-1];
1538 *paz = (char *) malloc( lemonStrlen(z)+1 );
1539 if( *paz==0 ){
1540 fprintf(stderr,"out of memory\n");
1541 exit(1);
1543 lemon_strcpy(*paz, z);
1544 for(z=*paz; *z && *z!='='; z++){}
1545 *z = 0;
1548 static char *output_filename = 0; /* Output filename from -o */
1550 /* This routine is called with the argument to any -o command-line option.
1552 static void handle_o_option(char *z){
1553 output_filename = (char *) malloc( strlen(z)+1 );
1554 if( output_filename==0 ){
1555 fprintf(stderr,"out of memory\n");
1556 exit(1);
1558 strcpy(output_filename, z);
1561 static char *output_header_filename = 0; /* Output filename from -h */
1563 /* This routine is called with the argument to any -h command-line option.
1565 static void handle_h_option(char *z){
1566 output_header_filename = (char *) malloc( strlen(z)+1 );
1567 if( output_header_filename==0 ){
1568 fprintf(stderr,"out of memory\n");
1569 exit(1);
1571 strcpy(output_header_filename, z);
1574 static char *user_templatename = NULL;
1575 static void handle_T_option(char *z){
1576 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
1577 if( user_templatename==0 ){
1578 memory_error();
1580 lemon_strcpy(user_templatename, z);
1583 /* Merge together to lists of rules ordered by rule.iRule */
1584 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1585 struct rule *pFirst = 0;
1586 struct rule **ppPrev = &pFirst;
1587 while( pA && pB ){
1588 if( pA->iRule<pB->iRule ){
1589 *ppPrev = pA;
1590 ppPrev = &pA->next;
1591 pA = pA->next;
1592 }else{
1593 *ppPrev = pB;
1594 ppPrev = &pB->next;
1595 pB = pB->next;
1598 if( pA ){
1599 *ppPrev = pA;
1600 }else{
1601 *ppPrev = pB;
1603 return pFirst;
1607 ** Sort a list of rules in order of increasing iRule value
1609 static struct rule *Rule_sort(struct rule *rp){
1610 int i;
1611 struct rule *pNext;
1612 struct rule *x[32];
1613 memset(x, 0, sizeof(x));
1614 while( rp ){
1615 pNext = rp->next;
1616 rp->next = 0;
1617 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1618 rp = Rule_merge(x[i], rp);
1619 x[i] = 0;
1621 x[i] = rp;
1622 rp = pNext;
1624 rp = 0;
1625 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1626 rp = Rule_merge(x[i], rp);
1628 return rp;
1631 /* forward reference */
1632 static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1634 /* Print a single line of the "Parser Stats" output
1636 static void stats_line(const char *zLabel, int iValue){
1637 int nLabel = lemonStrlen(zLabel);
1638 printf(" %s%.*s %5d\n", zLabel,
1639 35-nLabel, "................................",
1640 iValue);
1643 /* The main program. Parse the command line and do it... */
1644 int main(int argc, char **argv)
1646 static int version = 0;
1647 static int rpflag = 0;
1648 static int basisflag = 0;
1649 static int compress = 0;
1650 static int quiet = 0;
1651 static int statistics = 0;
1652 static int mhflag = 0;
1653 static int nolinenosflag = 0;
1654 static int noResort = 0;
1655 static const struct s_options options[] = {
1656 {OPT_FLAG, "b", (void*)&basisflag, 0, "Print only the basis in report."},
1657 {OPT_FLAG, "c", (void*)&compress, 0, "Don't compress the action table."},
1658 {OPT_FSTR, "D", 0, handle_D_option, "Define an %ifdef macro."},
1659 {OPT_FSTR, "f", 0, 0, "Ignored. (Placeholder for -f compiler options.)"},
1660 {OPT_FLAG, "g", (void*)&rpflag, 0, "Print grammar without actions."},
1661 {OPT_FSTR, "h", 0, handle_h_option, "Specify output header filename."},
1662 {OPT_FSTR, "I", 0, 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1663 {OPT_FLAG, "m", (void*)&mhflag, 0, "Output a makeheaders compatible file."},
1664 {OPT_FLAG, "l", (void*)&nolinenosflag, 0, "Do not print #line statements."},
1665 {OPT_FSTR, "O", 0, 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1666 {OPT_FSTR, "o", 0, handle_o_option, "Specify output filename."},
1667 {OPT_FLAG, "p", (void*)&showPrecedenceConflict, 0,
1668 "Show conflicts resolved by precedence rules"},
1669 {OPT_FLAG, "q", (void*)&quiet, 0, "(Quiet) Don't print the report file."},
1670 {OPT_FLAG, "r", (void*)&noResort, 0, "Do not sort or renumber states"},
1671 {OPT_FLAG, "s", (void*)&statistics, 0,
1672 "Print parser stats to standard output."},
1673 {OPT_FLAG, "x", (void*)&version, 0, "Print the version number."},
1674 {OPT_FSTR, "T", 0, handle_T_option, "Specify a template file."},
1675 {OPT_FSTR, "W", 0, 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1676 {OPT_FLAG,0,0,0,0}
1678 int i;
1679 int exitcode;
1680 struct lemon lem;
1681 struct rule *rp;
1683 (void)argc; /* Suppress "unused argument" warning. */
1684 OptInit(argv,options,stderr);
1685 if( version ){
1686 printf("Lemon version 1.0 (patched for Xapian)\n");
1687 exit(0);
1689 if( OptNArgs()!=1 ){
1690 fprintf(stderr,"Exactly one filename argument is required.\n");
1691 exit(1);
1693 memset(&lem, 0, sizeof(lem));
1694 lem.errorcnt = 0;
1696 /* Initialize the machine */
1697 Strsafe_init();
1698 Symbol_init();
1699 State_init();
1700 lem.argv0 = argv[0];
1701 lem.filename = OptArg(0);
1702 lem.basisflag = basisflag;
1703 lem.nolinenosflag = nolinenosflag;
1704 Symbol_new("$");
1705 lem.errsym = Symbol_new("error");
1706 lem.errsym->useCnt = 0;
1708 /* Parse the input file */
1709 Parse(&lem);
1710 if( lem.errorcnt ) exit(lem.errorcnt);
1711 if( lem.nrule==0 ){
1712 fprintf(stderr,"Empty grammar.\n");
1713 exit(1);
1716 /* Count and index the symbols of the grammar */
1717 Symbol_new("{default}");
1718 lem.nsymbol = Symbol_count();
1719 lem.symbols = Symbol_arrayof();
1720 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1721 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1722 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1723 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1724 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1725 lem.nsymbol = i - 1;
1726 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
1727 lem.nterminal = i;
1729 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1730 ** reduce action C-code associated with them last, so that the switch()
1731 ** statement that selects reduction actions will have a smaller jump table.
1733 for(i=0, rp=lem.rule; rp; rp=rp->next){
1734 rp->iRule = rp->code ? i++ : -1;
1736 for(rp=lem.rule; rp; rp=rp->next){
1737 if( rp->iRule<0 ) rp->iRule = i++;
1739 lem.startRule = lem.rule;
1740 lem.rule = Rule_sort(lem.rule);
1742 /* Generate a reprint of the grammar, if requested on the command line */
1743 if( rpflag ){
1744 Reprint(&lem);
1745 }else{
1746 /* Initialize the size for all follow and first sets */
1747 SetSize(lem.nterminal+1);
1749 /* Find the precedence for every production rule (that has one) */
1750 FindRulePrecedences(&lem);
1752 /* Compute the lambda-nonterminals and the first-sets for every
1753 ** nonterminal */
1754 FindFirstSets(&lem);
1756 /* Compute all LR(0) states. Also record follow-set propagation
1757 ** links so that the follow-set can be computed later */
1758 lem.nstate = 0;
1759 FindStates(&lem);
1760 lem.sorted = State_arrayof();
1762 /* Tie up loose ends on the propagation links */
1763 FindLinks(&lem);
1765 /* Compute the follow set of every reducible configuration */
1766 FindFollowSets(&lem);
1768 /* Compute the action tables */
1769 FindActions(&lem);
1771 /* Compress the action tables */
1772 if( compress==0 ) CompressTables(&lem);
1774 /* Reorder and renumber the states so that states with fewer choices
1775 ** occur at the end. This is an optimization that helps make the
1776 ** generated parser tables smaller. */
1777 if( noResort==0 ) ResortStates(&lem);
1779 /* Generate a report of the parser generated. (the "y.output" file) */
1780 if( !quiet ) ReportOutput(&lem);
1782 /* Generate the source code for the parser */
1783 ReportTable(&lem, mhflag);
1785 /* Produce a header file for use by the scanner. (This step is
1786 ** omitted if the "-m" option is used because makeheaders will
1787 ** generate the file for us.) */
1788 if( !mhflag ) ReportHeader(&lem);
1790 if( statistics ){
1791 printf("Parser statistics:\n");
1792 stats_line("terminal symbols", lem.nterminal);
1793 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1794 stats_line("total symbols", lem.nsymbol);
1795 stats_line("rules", lem.nrule);
1796 stats_line("states", lem.nxstate);
1797 stats_line("conflicts", lem.nconflict);
1798 stats_line("action table entries", lem.nactiontab);
1799 stats_line("lookahead table entries", lem.nlookaheadtab);
1800 stats_line("total table size (bytes)", lem.tablesize);
1802 if( lem.nconflict > 0 ){
1803 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1806 /* return 0 on success, 1 on failure. */
1807 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1808 exit(exitcode);
1809 return (exitcode);
1811 /******************** From the file "msort.c" *******************************/
1813 ** A generic merge-sort program.
1815 ** USAGE:
1816 ** Let "ptr" be a pointer to some structure which is at the head of
1817 ** a null-terminated list. Then to sort the list call:
1819 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1821 ** In the above, "cmpfnc" is a pointer to a function which compares
1822 ** two instances of the structure and returns an integer, as in
1823 ** strcmp. The second argument is a pointer to the pointer to the
1824 ** second element of the linked list. This address is used to compute
1825 ** the offset to the "next" field within the structure. The offset to
1826 ** the "next" field must be constant for all structures in the list.
1828 ** The function returns a new pointer which is the head of the list
1829 ** after sorting.
1831 ** ALGORITHM:
1832 ** Merge-sort.
1836 ** Return a pointer to the next structure in the linked list.
1838 #define NEXT(A) (*(char**)(((char*)A)+offset))
1841 ** Inputs:
1842 ** a: A sorted, null-terminated linked list. (May be null).
1843 ** b: A sorted, null-terminated linked list. (May be null).
1844 ** cmp: A pointer to the comparison function.
1845 ** offset: Offset in the structure to the "next" field.
1847 ** Return Value:
1848 ** A pointer to the head of a sorted list containing the elements
1849 ** of both a and b.
1851 ** Side effects:
1852 ** The "next" pointers for elements in the lists a and b are
1853 ** changed.
1855 static char *merge(
1856 char *a,
1857 char *b,
1858 int (*cmp)(const char*,const char*),
1859 int offset
1861 char *ptr, *head;
1863 if( a==0 ){
1864 head = b;
1865 }else if( b==0 ){
1866 head = a;
1867 }else{
1868 if( (*cmp)(a,b)<=0 ){
1869 ptr = a;
1870 a = NEXT(a);
1871 }else{
1872 ptr = b;
1873 b = NEXT(b);
1875 head = ptr;
1876 while( a && b ){
1877 if( (*cmp)(a,b)<=0 ){
1878 NEXT(ptr) = a;
1879 ptr = a;
1880 a = NEXT(a);
1881 }else{
1882 NEXT(ptr) = b;
1883 ptr = b;
1884 b = NEXT(b);
1887 if( a ) NEXT(ptr) = a;
1888 else NEXT(ptr) = b;
1890 return head;
1894 ** Inputs:
1895 ** list: Pointer to a singly-linked list of structures.
1896 ** next: Pointer to pointer to the second element of the list.
1897 ** cmp: A comparison function.
1899 ** Return Value:
1900 ** A pointer to the head of a sorted list containing the elements
1901 ** originally in list.
1903 ** Side effects:
1904 ** The "next" pointers for elements in list are changed.
1906 #define LISTSIZE 30
1907 static char *msort(
1908 char *list,
1909 char **next,
1910 int (*cmp)(const char*,const char*)
1912 unsigned long offset;
1913 char *ep;
1914 char *set[LISTSIZE];
1915 int i;
1916 offset = (unsigned long)((char*)next - (char*)list);
1917 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1918 while( list ){
1919 ep = list;
1920 list = NEXT(list);
1921 NEXT(ep) = 0;
1922 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1923 ep = merge(ep,set[i],cmp,offset);
1924 set[i] = 0;
1926 set[i] = ep;
1928 ep = 0;
1929 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
1930 return ep;
1932 /************************ From the file "option.c" **************************/
1933 static char **argv;
1934 static const struct s_options *op;
1935 static FILE *errstream;
1937 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1940 ** Print the command line with a carrot pointing to the k-th character
1941 ** of the n-th field.
1943 static void errline(int n, int k, FILE *err)
1945 int spcnt, i;
1946 if( argv[0] ) fprintf(err,"%s",argv[0]);
1947 spcnt = lemonStrlen(argv[0]) + 1;
1948 for(i=1; i<n && argv[i]; i++){
1949 fprintf(err," %s",argv[i]);
1950 spcnt += lemonStrlen(argv[i])+1;
1952 spcnt += k;
1953 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1954 if( spcnt<20 ){
1955 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1956 }else{
1957 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1962 ** Return the index of the N-th non-switch argument. Return -1
1963 ** if N is out of range.
1965 static int argindex(int n)
1967 int i;
1968 int dashdash = 0;
1969 if( argv!=0 && *argv!=0 ){
1970 for(i=1; argv[i]; i++){
1971 if( dashdash || !ISOPT(argv[i]) ){
1972 if( n==0 ) return i;
1973 n--;
1975 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1978 return -1;
1981 static char emsg[] = "Command line syntax error: ";
1984 ** Process a flag command line argument.
1986 static int handleflags(int i, FILE *err)
1988 int v;
1989 int errcnt = 0;
1990 int j;
1991 for(j=0; op[j].label; j++){
1992 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
1994 v = argv[i][0]=='-' ? 1 : 0;
1995 if( op[j].label==0 ){
1996 if( err ){
1997 fprintf(err,"%sundefined option.\n",emsg);
1998 errline(i,1,err);
2000 errcnt++;
2001 }else if( op[j].arg==0 && op[j].func==0 ){
2002 /* Ignore this option */
2003 }else if( op[j].type==OPT_FLAG ){
2004 *((int*)op[j].arg) = v;
2005 }else if( op[j].type==OPT_FFLAG ){
2006 (op[j].func)(v);
2007 }else if( op[j].type==OPT_FSTR ){
2008 (op[j].func)(&argv[i][2]);
2009 }else{
2010 if( err ){
2011 fprintf(err,"%smissing argument on switch.\n",emsg);
2012 errline(i,1,err);
2014 errcnt++;
2016 return errcnt;
2020 ** Process a command line switch which has an argument.
2022 static int handleswitch(int i, FILE *err)
2024 int lv = 0;
2025 double dv = 0.0;
2026 char *sv = 0, *end;
2027 char *cp;
2028 int j;
2029 int errcnt = 0;
2030 cp = strchr(argv[i],'=');
2031 assert( cp!=0 );
2032 *cp = 0;
2033 for(j=0; op[j].label; j++){
2034 if( strcmp(argv[i],op[j].label)==0 ) break;
2036 *cp = '=';
2037 if( op[j].label==0 ){
2038 if( err ){
2039 fprintf(err,"%sundefined option.\n",emsg);
2040 errline(i,0,err);
2042 errcnt++;
2043 }else{
2044 cp++;
2045 switch( op[j].type ){
2046 case OPT_FLAG:
2047 case OPT_FFLAG:
2048 if( err ){
2049 fprintf(err,"%soption requires an argument.\n",emsg);
2050 errline(i,0,err);
2052 errcnt++;
2053 break;
2054 case OPT_DBL:
2055 case OPT_FDBL:
2056 dv = strtod(cp,&end);
2057 if( *end ){
2058 if( err ){
2059 fprintf(err,
2060 "%sillegal character in floating-point argument.\n",emsg);
2061 errline(i,(int)((char*)end-(char*)argv[i]),err);
2063 errcnt++;
2065 break;
2066 case OPT_INT:
2067 case OPT_FINT:
2068 lv = strtol(cp,&end,0);
2069 if( *end ){
2070 if( err ){
2071 fprintf(err,"%sillegal character in integer argument.\n",emsg);
2072 errline(i,(int)((char*)end-(char*)argv[i]),err);
2074 errcnt++;
2076 break;
2077 case OPT_STR:
2078 case OPT_FSTR:
2079 sv = cp;
2080 break;
2082 switch( op[j].type ){
2083 case OPT_FLAG:
2084 case OPT_FFLAG:
2085 break;
2086 case OPT_DBL:
2087 *(double*)(op[j].arg) = dv;
2088 break;
2089 case OPT_FDBL:
2090 (op[j].func)(dv);
2091 break;
2092 case OPT_INT:
2093 *(int*)(op[j].arg) = lv;
2094 break;
2095 case OPT_FINT:
2096 (op[j].func)((int)lv);
2097 break;
2098 case OPT_STR:
2099 *(char**)(op[j].arg) = sv;
2100 break;
2101 case OPT_FSTR:
2102 (op[j].func)(sv);
2103 break;
2106 return errcnt;
2109 int OptInit(char **a, const struct s_options *o, FILE *err)
2111 int errcnt = 0;
2112 argv = a;
2113 op = o;
2114 errstream = err;
2115 if( argv && *argv && op ){
2116 int i;
2117 for(i=1; argv[i]; i++){
2118 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2119 errcnt += handleflags(i,err);
2120 }else if( strchr(argv[i],'=') ){
2121 errcnt += handleswitch(i,err);
2125 if( errcnt>0 ){
2126 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
2127 OptPrint();
2128 exit(1);
2130 return 0;
2133 int OptNArgs(void){
2134 int cnt = 0;
2135 int dashdash = 0;
2136 int i;
2137 if( argv!=0 && argv[0]!=0 ){
2138 for(i=1; argv[i]; i++){
2139 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2140 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2143 return cnt;
2146 char *OptArg(int n)
2148 int i;
2149 i = argindex(n);
2150 return i>=0 ? argv[i] : 0;
2153 void OptErr(int n)
2155 int i;
2156 i = argindex(n);
2157 if( i>=0 ) errline(i,0,errstream);
2160 void OptPrint(void){
2161 int i;
2162 int max, len;
2163 max = 0;
2164 for(i=0; op[i].label; i++){
2165 len = lemonStrlen(op[i].label) + 1;
2166 switch( op[i].type ){
2167 case OPT_FLAG:
2168 case OPT_FFLAG:
2169 break;
2170 case OPT_INT:
2171 case OPT_FINT:
2172 len += 9; /* length of "<integer>" */
2173 break;
2174 case OPT_DBL:
2175 case OPT_FDBL:
2176 len += 6; /* length of "<real>" */
2177 break;
2178 case OPT_STR:
2179 case OPT_FSTR:
2180 len += 8; /* length of "<string>" */
2181 break;
2183 if( len>max ) max = len;
2185 for(i=0; op[i].label; i++){
2186 switch( op[i].type ){
2187 case OPT_FLAG:
2188 case OPT_FFLAG:
2189 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2190 break;
2191 case OPT_INT:
2192 case OPT_FINT:
2193 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
2194 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2195 break;
2196 case OPT_DBL:
2197 case OPT_FDBL:
2198 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
2199 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2200 break;
2201 case OPT_STR:
2202 case OPT_FSTR:
2203 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
2204 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2205 break;
2209 /*********************** From the file "parse.c" ****************************/
2211 ** Input file parser for the LEMON parser generator.
2214 /* The state of the parser */
2215 enum e_state {
2216 INITIALIZE,
2217 WAITING_FOR_DECL_OR_RULE,
2218 WAITING_FOR_DECL_KEYWORD,
2219 WAITING_FOR_DECL_ARG,
2220 WAITING_FOR_PRECEDENCE_SYMBOL,
2221 WAITING_FOR_ARROW,
2222 IN_RHS,
2223 LHS_ALIAS_1,
2224 LHS_ALIAS_2,
2225 LHS_ALIAS_3,
2226 RHS_ALIAS_1,
2227 RHS_ALIAS_2,
2228 PRECEDENCE_MARK_1,
2229 PRECEDENCE_MARK_2,
2230 RESYNC_AFTER_RULE_ERROR,
2231 RESYNC_AFTER_DECL_ERROR,
2232 WAITING_FOR_DESTRUCTOR_SYMBOL,
2233 WAITING_FOR_DATATYPE_SYMBOL,
2234 WAITING_FOR_FALLBACK_ID,
2235 WAITING_FOR_WILDCARD_ID,
2236 WAITING_FOR_CLASS_ID,
2237 WAITING_FOR_CLASS_TOKEN,
2238 WAITING_FOR_TOKEN_NAME
2240 struct pstate {
2241 char *filename; /* Name of the input file */
2242 int tokenlineno; /* Linenumber at which current token starts */
2243 int errorcnt; /* Number of errors so far */
2244 char *tokenstart; /* Text of current token */
2245 struct lemon *gp; /* Global state vector */
2246 enum e_state state; /* The state of the parser */
2247 struct symbol *fallback; /* The fallback token */
2248 struct symbol *tkclass; /* Token class symbol */
2249 struct symbol *lhs; /* Left-hand side of current rule */
2250 const char *lhsalias; /* Alias for the LHS */
2251 int nrhs; /* Number of right-hand side symbols seen */
2252 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2253 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2254 struct rule *prevrule; /* Previous rule parsed */
2255 const char *declkeyword; /* Keyword of a declaration */
2256 char **declargslot; /* Where the declaration argument should be put */
2257 int insertLineMacro; /* Add #line before declaration insert */
2258 int *decllinenoslot; /* Where to write declaration line number */
2259 enum e_assoc declassoc; /* Assign this association to decl arguments */
2260 int preccounter; /* Assign this precedence to decl arguments */
2261 struct rule *firstrule; /* Pointer to first rule in the grammar */
2262 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2265 /* Parse a single token */
2266 static void parseonetoken(struct pstate *psp)
2268 const char *x;
2269 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2270 #if 0
2271 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2272 x,psp->state);
2273 #endif
2274 switch( psp->state ){
2275 case INITIALIZE:
2276 psp->prevrule = 0;
2277 psp->preccounter = 0;
2278 psp->firstrule = psp->lastrule = 0;
2279 psp->gp->nrule = 0;
2280 /* Fall thru to next case */
2281 case WAITING_FOR_DECL_OR_RULE:
2282 if( x[0]=='%' ){
2283 psp->state = WAITING_FOR_DECL_KEYWORD;
2284 }else if( ISLOWER(x[0]) ){
2285 psp->lhs = Symbol_new(x);
2286 psp->nrhs = 0;
2287 psp->lhsalias = 0;
2288 psp->state = WAITING_FOR_ARROW;
2289 }else if( x[0]=='{' ){
2290 if( psp->prevrule==0 ){
2291 ErrorMsg(psp->filename,psp->tokenlineno,
2292 "There is no prior rule upon which to attach the code "
2293 "fragment which begins on this line.");
2294 psp->errorcnt++;
2295 }else if( psp->prevrule->code!=0 ){
2296 ErrorMsg(psp->filename,psp->tokenlineno,
2297 "Code fragment beginning on this line is not the first "
2298 "to follow the previous rule.");
2299 psp->errorcnt++;
2300 }else{
2301 psp->prevrule->line = psp->tokenlineno;
2302 psp->prevrule->code = &x[1];
2303 psp->prevrule->noCode = 0;
2305 }else if( x[0]=='[' ){
2306 psp->state = PRECEDENCE_MARK_1;
2307 }else{
2308 ErrorMsg(psp->filename,psp->tokenlineno,
2309 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2311 psp->errorcnt++;
2313 break;
2314 case PRECEDENCE_MARK_1:
2315 if( !ISUPPER(x[0]) ){
2316 ErrorMsg(psp->filename,psp->tokenlineno,
2317 "The precedence symbol must be a terminal.");
2318 psp->errorcnt++;
2319 }else if( psp->prevrule==0 ){
2320 ErrorMsg(psp->filename,psp->tokenlineno,
2321 "There is no prior rule to assign precedence \"[%s]\".",x);
2322 psp->errorcnt++;
2323 }else if( psp->prevrule->precsym!=0 ){
2324 ErrorMsg(psp->filename,psp->tokenlineno,
2325 "Precedence mark on this line is not the first "
2326 "to follow the previous rule.");
2327 psp->errorcnt++;
2328 }else{
2329 psp->prevrule->precsym = Symbol_new(x);
2331 psp->state = PRECEDENCE_MARK_2;
2332 break;
2333 case PRECEDENCE_MARK_2:
2334 if( x[0]!=']' ){
2335 ErrorMsg(psp->filename,psp->tokenlineno,
2336 "Missing \"]\" on precedence mark.");
2337 psp->errorcnt++;
2339 psp->state = WAITING_FOR_DECL_OR_RULE;
2340 break;
2341 case WAITING_FOR_ARROW:
2342 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2343 psp->state = IN_RHS;
2344 }else if( x[0]=='(' ){
2345 psp->state = LHS_ALIAS_1;
2346 }else{
2347 ErrorMsg(psp->filename,psp->tokenlineno,
2348 "Expected to see a \":\" following the LHS symbol \"%s\".",
2349 psp->lhs->name);
2350 psp->errorcnt++;
2351 psp->state = RESYNC_AFTER_RULE_ERROR;
2353 break;
2354 case LHS_ALIAS_1:
2355 if( ISALPHA(x[0]) ){
2356 psp->lhsalias = x;
2357 psp->state = LHS_ALIAS_2;
2358 }else{
2359 ErrorMsg(psp->filename,psp->tokenlineno,
2360 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2361 x,psp->lhs->name);
2362 psp->errorcnt++;
2363 psp->state = RESYNC_AFTER_RULE_ERROR;
2365 break;
2366 case LHS_ALIAS_2:
2367 if( x[0]==')' ){
2368 psp->state = LHS_ALIAS_3;
2369 }else{
2370 ErrorMsg(psp->filename,psp->tokenlineno,
2371 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2372 psp->errorcnt++;
2373 psp->state = RESYNC_AFTER_RULE_ERROR;
2375 break;
2376 case LHS_ALIAS_3:
2377 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2378 psp->state = IN_RHS;
2379 }else{
2380 ErrorMsg(psp->filename,psp->tokenlineno,
2381 "Missing \"->\" following: \"%s(%s)\".",
2382 psp->lhs->name,psp->lhsalias);
2383 psp->errorcnt++;
2384 psp->state = RESYNC_AFTER_RULE_ERROR;
2386 break;
2387 case IN_RHS:
2388 if( x[0]=='.' ){
2389 struct rule *rp;
2390 rp = (struct rule *)calloc( sizeof(struct rule) +
2391 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2392 if( rp==0 ){
2393 ErrorMsg(psp->filename,psp->tokenlineno,
2394 "Can't allocate enough memory for this rule.");
2395 psp->errorcnt++;
2396 psp->prevrule = 0;
2397 }else{
2398 int i;
2399 rp->ruleline = psp->tokenlineno;
2400 rp->rhs = (struct symbol**)&rp[1];
2401 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2402 for(i=0; i<psp->nrhs; i++){
2403 rp->rhs[i] = psp->rhs[i];
2404 rp->rhsalias[i] = psp->alias[i];
2406 rp->lhs = psp->lhs;
2407 rp->lhsalias = psp->lhsalias;
2408 rp->nrhs = psp->nrhs;
2409 rp->code = 0;
2410 rp->noCode = 1;
2411 rp->precsym = 0;
2412 rp->index = psp->gp->nrule++;
2413 rp->nextlhs = rp->lhs->rule;
2414 rp->lhs->rule = rp;
2415 rp->next = 0;
2416 if( psp->firstrule==0 ){
2417 psp->firstrule = psp->lastrule = rp;
2418 }else{
2419 psp->lastrule->next = rp;
2420 psp->lastrule = rp;
2422 psp->prevrule = rp;
2424 psp->state = WAITING_FOR_DECL_OR_RULE;
2425 }else if( ISALPHA(x[0]) ){
2426 if( psp->nrhs>=MAXRHS ){
2427 ErrorMsg(psp->filename,psp->tokenlineno,
2428 "Too many symbols on RHS of rule beginning at \"%s\".",
2430 psp->errorcnt++;
2431 psp->state = RESYNC_AFTER_RULE_ERROR;
2432 }else{
2433 psp->rhs[psp->nrhs] = Symbol_new(x);
2434 psp->alias[psp->nrhs] = 0;
2435 psp->nrhs++;
2437 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2438 struct symbol *msp = psp->rhs[psp->nrhs-1];
2439 if( msp->type!=MULTITERMINAL ){
2440 struct symbol *origsp = msp;
2441 msp = (struct symbol *) calloc(1,sizeof(*msp));
2442 MemoryCheck(msp);
2443 memset(msp, 0, sizeof(*msp));
2444 msp->type = MULTITERMINAL;
2445 msp->nsubsym = 1;
2446 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
2447 MemoryCheck(msp->subsym);
2448 msp->subsym[0] = origsp;
2449 msp->name = origsp->name;
2450 psp->rhs[psp->nrhs-1] = msp;
2452 msp->nsubsym++;
2453 msp->subsym = (struct symbol **) realloc(msp->subsym,
2454 sizeof(struct symbol*)*msp->nsubsym);
2455 MemoryCheck(msp->subsym);
2456 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2457 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
2458 ErrorMsg(psp->filename,psp->tokenlineno,
2459 "Cannot form a compound containing a non-terminal");
2460 psp->errorcnt++;
2462 }else if( x[0]=='(' && psp->nrhs>0 ){
2463 psp->state = RHS_ALIAS_1;
2464 }else{
2465 ErrorMsg(psp->filename,psp->tokenlineno,
2466 "Illegal character on RHS of rule: \"%s\".",x);
2467 psp->errorcnt++;
2468 psp->state = RESYNC_AFTER_RULE_ERROR;
2470 break;
2471 case RHS_ALIAS_1:
2472 if( ISALPHA(x[0]) ){
2473 psp->alias[psp->nrhs-1] = x;
2474 psp->state = RHS_ALIAS_2;
2475 }else{
2476 ErrorMsg(psp->filename,psp->tokenlineno,
2477 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2478 x,psp->rhs[psp->nrhs-1]->name);
2479 psp->errorcnt++;
2480 psp->state = RESYNC_AFTER_RULE_ERROR;
2482 break;
2483 case RHS_ALIAS_2:
2484 if( x[0]==')' ){
2485 psp->state = IN_RHS;
2486 }else{
2487 ErrorMsg(psp->filename,psp->tokenlineno,
2488 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2489 psp->errorcnt++;
2490 psp->state = RESYNC_AFTER_RULE_ERROR;
2492 break;
2493 case WAITING_FOR_DECL_KEYWORD:
2494 if( ISALPHA(x[0]) ){
2495 psp->declkeyword = x;
2496 psp->declargslot = 0;
2497 psp->decllinenoslot = 0;
2498 psp->insertLineMacro = 1;
2499 psp->state = WAITING_FOR_DECL_ARG;
2500 if( strcmp(x,"name")==0 ){
2501 psp->declargslot = &(psp->gp->name);
2502 psp->insertLineMacro = 0;
2503 }else if( strcmp(x,"include")==0 ){
2504 psp->declargslot = &(psp->gp->include);
2505 }else if( strcmp(x,"code")==0 ){
2506 psp->declargslot = &(psp->gp->extracode);
2507 }else if( strcmp(x,"token_destructor")==0 ){
2508 psp->declargslot = &psp->gp->tokendest;
2509 }else if( strcmp(x,"default_destructor")==0 ){
2510 psp->declargslot = &psp->gp->vardest;
2511 }else if( strcmp(x,"token_prefix")==0 ){
2512 psp->declargslot = &psp->gp->tokenprefix;
2513 psp->insertLineMacro = 0;
2514 }else if( strcmp(x,"syntax_error")==0 ){
2515 psp->declargslot = &(psp->gp->error);
2516 }else if( strcmp(x,"parse_accept")==0 ){
2517 psp->declargslot = &(psp->gp->accept);
2518 }else if( strcmp(x,"parse_failure")==0 ){
2519 psp->declargslot = &(psp->gp->failure);
2520 }else if( strcmp(x,"stack_overflow")==0 ){
2521 psp->declargslot = &(psp->gp->overflow);
2522 }else if( strcmp(x,"extra_argument")==0 ){
2523 psp->declargslot = &(psp->gp->arg);
2524 psp->insertLineMacro = 0;
2525 }else if( strcmp(x,"token_type")==0 ){
2526 psp->declargslot = &(psp->gp->tokentype);
2527 psp->insertLineMacro = 0;
2528 }else if( strcmp(x,"default_type")==0 ){
2529 psp->declargslot = &(psp->gp->vartype);
2530 psp->insertLineMacro = 0;
2531 }else if( strcmp(x,"stack_size")==0 ){
2532 psp->declargslot = &(psp->gp->stacksize);
2533 psp->insertLineMacro = 0;
2534 }else if( strcmp(x,"start_symbol")==0 ){
2535 psp->declargslot = &(psp->gp->start);
2536 psp->insertLineMacro = 0;
2537 }else if( strcmp(x,"left")==0 ){
2538 psp->preccounter++;
2539 psp->declassoc = LEFT;
2540 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2541 }else if( strcmp(x,"right")==0 ){
2542 psp->preccounter++;
2543 psp->declassoc = RIGHT;
2544 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2545 }else if( strcmp(x,"nonassoc")==0 ){
2546 psp->preccounter++;
2547 psp->declassoc = NONE;
2548 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2549 }else if( strcmp(x,"destructor")==0 ){
2550 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2551 }else if( strcmp(x,"type")==0 ){
2552 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2553 }else if( strcmp(x,"fallback")==0 ){
2554 psp->fallback = 0;
2555 psp->state = WAITING_FOR_FALLBACK_ID;
2556 }else if( strcmp(x,"token")==0 ){
2557 psp->state = WAITING_FOR_TOKEN_NAME;
2558 }else if( strcmp(x,"wildcard")==0 ){
2559 psp->state = WAITING_FOR_WILDCARD_ID;
2560 }else if( strcmp(x,"token_class")==0 ){
2561 psp->state = WAITING_FOR_CLASS_ID;
2562 }else{
2563 ErrorMsg(psp->filename,psp->tokenlineno,
2564 "Unknown declaration keyword: \"%%%s\".",x);
2565 psp->errorcnt++;
2566 psp->state = RESYNC_AFTER_DECL_ERROR;
2568 }else{
2569 ErrorMsg(psp->filename,psp->tokenlineno,
2570 "Illegal declaration keyword: \"%s\".",x);
2571 psp->errorcnt++;
2572 psp->state = RESYNC_AFTER_DECL_ERROR;
2574 break;
2575 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2576 if( !ISALPHA(x[0]) ){
2577 ErrorMsg(psp->filename,psp->tokenlineno,
2578 "Symbol name missing after %%destructor keyword");
2579 psp->errorcnt++;
2580 psp->state = RESYNC_AFTER_DECL_ERROR;
2581 }else{
2582 struct symbol *sp = Symbol_new(x);
2583 psp->declargslot = &sp->destructor;
2584 psp->decllinenoslot = &sp->destLineno;
2585 psp->insertLineMacro = 1;
2586 psp->state = WAITING_FOR_DECL_ARG;
2588 break;
2589 case WAITING_FOR_DATATYPE_SYMBOL:
2590 if( !ISALPHA(x[0]) ){
2591 ErrorMsg(psp->filename,psp->tokenlineno,
2592 "Symbol name missing after %%type keyword");
2593 psp->errorcnt++;
2594 psp->state = RESYNC_AFTER_DECL_ERROR;
2595 }else{
2596 struct symbol *sp = Symbol_find(x);
2597 if((sp) && (sp->datatype)){
2598 ErrorMsg(psp->filename,psp->tokenlineno,
2599 "Symbol %%type \"%s\" already defined", x);
2600 psp->errorcnt++;
2601 psp->state = RESYNC_AFTER_DECL_ERROR;
2602 }else{
2603 if (!sp){
2604 sp = Symbol_new(x);
2606 psp->declargslot = &sp->datatype;
2607 psp->insertLineMacro = 0;
2608 psp->state = WAITING_FOR_DECL_ARG;
2611 break;
2612 case WAITING_FOR_PRECEDENCE_SYMBOL:
2613 if( x[0]=='.' ){
2614 psp->state = WAITING_FOR_DECL_OR_RULE;
2615 }else if( ISUPPER(x[0]) ){
2616 struct symbol *sp;
2617 sp = Symbol_new(x);
2618 if( sp->prec>=0 ){
2619 ErrorMsg(psp->filename,psp->tokenlineno,
2620 "Symbol \"%s\" has already be given a precedence.",x);
2621 psp->errorcnt++;
2622 }else{
2623 sp->prec = psp->preccounter;
2624 sp->assoc = psp->declassoc;
2626 }else{
2627 ErrorMsg(psp->filename,psp->tokenlineno,
2628 "Can't assign a precedence to \"%s\".",x);
2629 psp->errorcnt++;
2631 break;
2632 case WAITING_FOR_DECL_ARG:
2633 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
2634 const char *zOld, *zNew;
2635 char *zBuf, *z;
2636 int nOld, n, nLine = 0, nNew, nBack;
2637 int addLineMacro;
2638 char zLine[50];
2639 zNew = x;
2640 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2641 nNew = lemonStrlen(zNew);
2642 if( *psp->declargslot ){
2643 zOld = *psp->declargslot;
2644 }else{
2645 zOld = "";
2647 nOld = lemonStrlen(zOld);
2648 n = nOld + nNew + 20;
2649 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
2650 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2651 if( addLineMacro ){
2652 for(z=psp->filename, nBack=0; *z; z++){
2653 if( *z=='\\' ) nBack++;
2655 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2656 nLine = lemonStrlen(zLine);
2657 n += nLine + lemonStrlen(psp->filename) + nBack;
2659 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2660 MemoryCheck(*psp->declargslot);
2661 zBuf = *psp->declargslot + nOld;
2662 if( addLineMacro ){
2663 if( nOld && zBuf[-1]!='\n' ){
2664 *(zBuf++) = '\n';
2666 memcpy(zBuf, zLine, nLine);
2667 zBuf += nLine;
2668 *(zBuf++) = '"';
2669 for(z=psp->filename; *z; z++){
2670 if( *z=='\\' ){
2671 *(zBuf++) = '\\';
2673 *(zBuf++) = *z;
2675 *(zBuf++) = '"';
2676 *(zBuf++) = '\n';
2678 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2679 psp->decllinenoslot[0] = psp->tokenlineno;
2681 memcpy(zBuf, zNew, nNew);
2682 zBuf += nNew;
2683 *zBuf = 0;
2684 psp->state = WAITING_FOR_DECL_OR_RULE;
2685 }else{
2686 ErrorMsg(psp->filename,psp->tokenlineno,
2687 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2688 psp->errorcnt++;
2689 psp->state = RESYNC_AFTER_DECL_ERROR;
2691 break;
2692 case WAITING_FOR_FALLBACK_ID:
2693 if( x[0]=='.' ){
2694 psp->state = WAITING_FOR_DECL_OR_RULE;
2695 }else if( !ISUPPER(x[0]) ){
2696 ErrorMsg(psp->filename, psp->tokenlineno,
2697 "%%fallback argument \"%s\" should be a token", x);
2698 psp->errorcnt++;
2699 }else{
2700 struct symbol *sp = Symbol_new(x);
2701 if( psp->fallback==0 ){
2702 psp->fallback = sp;
2703 }else if( sp->fallback ){
2704 ErrorMsg(psp->filename, psp->tokenlineno,
2705 "More than one fallback assigned to token %s", x);
2706 psp->errorcnt++;
2707 }else{
2708 sp->fallback = psp->fallback;
2709 psp->gp->has_fallback = 1;
2712 break;
2713 case WAITING_FOR_TOKEN_NAME:
2714 /* Tokens do not have to be declared before use. But they can be
2715 ** in order to control their assigned integer number. The number for
2716 ** each token is assigned when it is first seen. So by including
2718 ** %token ONE TWO THREE
2720 ** early in the grammar file, that assigns small consecutive values
2721 ** to each of the tokens ONE TWO and THREE.
2723 if( x[0]=='.' ){
2724 psp->state = WAITING_FOR_DECL_OR_RULE;
2725 }else if( !ISUPPER(x[0]) ){
2726 ErrorMsg(psp->filename, psp->tokenlineno,
2727 "%%token argument \"%s\" should be a token", x);
2728 psp->errorcnt++;
2729 }else{
2730 (void)Symbol_new(x);
2732 break;
2733 case WAITING_FOR_WILDCARD_ID:
2734 if( x[0]=='.' ){
2735 psp->state = WAITING_FOR_DECL_OR_RULE;
2736 }else if( !ISUPPER(x[0]) ){
2737 ErrorMsg(psp->filename, psp->tokenlineno,
2738 "%%wildcard argument \"%s\" should be a token", x);
2739 psp->errorcnt++;
2740 }else{
2741 struct symbol *sp = Symbol_new(x);
2742 if( psp->gp->wildcard==0 ){
2743 psp->gp->wildcard = sp;
2744 }else{
2745 ErrorMsg(psp->filename, psp->tokenlineno,
2746 "Extra wildcard to token: %s", x);
2747 psp->errorcnt++;
2750 break;
2751 case WAITING_FOR_CLASS_ID:
2752 if( !ISLOWER(x[0]) ){
2753 ErrorMsg(psp->filename, psp->tokenlineno,
2754 "%%token_class must be followed by an identifier: ", x);
2755 psp->errorcnt++;
2756 psp->state = RESYNC_AFTER_DECL_ERROR;
2757 }else if( Symbol_find(x) ){
2758 ErrorMsg(psp->filename, psp->tokenlineno,
2759 "Symbol \"%s\" already used", x);
2760 psp->errorcnt++;
2761 psp->state = RESYNC_AFTER_DECL_ERROR;
2762 }else{
2763 psp->tkclass = Symbol_new(x);
2764 psp->tkclass->type = MULTITERMINAL;
2765 psp->state = WAITING_FOR_CLASS_TOKEN;
2767 break;
2768 case WAITING_FOR_CLASS_TOKEN:
2769 if( x[0]=='.' ){
2770 psp->state = WAITING_FOR_DECL_OR_RULE;
2771 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
2772 struct symbol *msp = psp->tkclass;
2773 msp->nsubsym++;
2774 msp->subsym = (struct symbol **) realloc(msp->subsym,
2775 sizeof(struct symbol*)*msp->nsubsym);
2776 MemoryCheck(msp->subsym);
2777 if( !ISUPPER(x[0]) ) x++;
2778 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2779 }else{
2780 ErrorMsg(psp->filename, psp->tokenlineno,
2781 "%%token_class argument \"%s\" should be a token", x);
2782 psp->errorcnt++;
2783 psp->state = RESYNC_AFTER_DECL_ERROR;
2785 break;
2786 case RESYNC_AFTER_RULE_ERROR:
2787 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2788 ** break; */
2789 case RESYNC_AFTER_DECL_ERROR:
2790 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2791 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2792 break;
2796 /* Run the preprocessor over the input file text. The global variables
2797 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2798 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2799 ** comments them out. Text in between is also commented out as appropriate.
2801 static void preprocess_input(char *z){
2802 int i, j, k, n;
2803 int exclude = 0;
2804 int start = 0;
2805 int lineno = 1;
2806 int start_lineno = 1;
2807 for(i=0; z[i]; i++){
2808 if( z[i]=='\n' ) lineno++;
2809 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2810 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
2811 if( exclude ){
2812 exclude--;
2813 if( exclude==0 ){
2814 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2817 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2818 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2819 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
2820 if( exclude ){
2821 exclude++;
2822 }else{
2823 for(j=i+7; ISSPACE(z[j]); j++){}
2824 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
2825 exclude = 1;
2826 for(k=0; k<nDefine; k++){
2827 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
2828 exclude = 0;
2829 break;
2832 if( z[i+3]=='n' ) exclude = !exclude;
2833 if( exclude ){
2834 start = i;
2835 start_lineno = lineno;
2838 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2841 if( exclude ){
2842 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2843 exit(1);
2847 /* In spite of its name, this function is really a scanner. It read
2848 ** in the entire input file (all at once) then tokenizes it. Each
2849 ** token is passed to the function "parseonetoken" which builds all
2850 ** the appropriate data structures in the global state vector "gp".
2852 void Parse(struct lemon *gp)
2854 struct pstate ps;
2855 FILE *fp;
2856 char *filebuf;
2857 unsigned int filesize;
2858 int lineno;
2859 int c;
2860 char *cp, *nextcp;
2861 int startline = 0;
2863 memset(&ps, '\0', sizeof(ps));
2864 ps.gp = gp;
2865 ps.filename = gp->filename;
2866 ps.errorcnt = 0;
2867 ps.state = INITIALIZE;
2869 /* Begin by reading the input file */
2870 fp = fopen(ps.filename,"rb");
2871 if( fp==0 ){
2872 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2873 gp->errorcnt++;
2874 return;
2876 fseek(fp,0,2);
2877 filesize = ftell(fp);
2878 rewind(fp);
2879 filebuf = (char *)malloc( filesize+1 );
2880 if( filesize>100000000 || filebuf==0 ){
2881 ErrorMsg(ps.filename,0,"Input file too large.");
2882 gp->errorcnt++;
2883 fclose(fp);
2884 return;
2886 if( fread(filebuf,1,filesize,fp)!=filesize ){
2887 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2888 filesize);
2889 free(filebuf);
2890 gp->errorcnt++;
2891 fclose(fp);
2892 return;
2894 fclose(fp);
2895 filebuf[filesize] = 0;
2897 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2898 preprocess_input(filebuf);
2900 /* Now scan the text of the input file */
2901 lineno = 1;
2902 for(cp=filebuf; (c= *cp)!=0; ){
2903 if( c=='\n' ) lineno++; /* Keep track of the line number */
2904 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
2905 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2906 cp+=2;
2907 while( (c= *cp)!=0 && c!='\n' ) cp++;
2908 continue;
2910 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2911 cp+=2;
2912 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2913 if( c=='\n' ) lineno++;
2914 cp++;
2916 if( c ) cp++;
2917 continue;
2919 ps.tokenstart = cp; /* Mark the beginning of the token */
2920 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2921 if( c=='\"' ){ /* String literals */
2922 cp++;
2923 while( (c= *cp)!=0 && c!='\"' ){
2924 if( c=='\n' ) lineno++;
2925 cp++;
2927 if( c==0 ){
2928 ErrorMsg(ps.filename,startline,
2929 "String starting on this line is not terminated before the end of the file.");
2930 ps.errorcnt++;
2931 nextcp = cp;
2932 }else{
2933 nextcp = cp+1;
2935 }else if( c=='{' ){ /* A block of C code */
2936 int level;
2937 cp++;
2938 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2939 if( c=='\n' ) lineno++;
2940 else if( c=='{' ) level++;
2941 else if( c=='}' ) level--;
2942 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2943 int prevc;
2944 cp = &cp[2];
2945 prevc = 0;
2946 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2947 if( c=='\n' ) lineno++;
2948 prevc = c;
2949 cp++;
2951 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2952 cp = &cp[2];
2953 while( (c= *cp)!=0 && c!='\n' ) cp++;
2954 if( c ) lineno++;
2955 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2956 int startchar, prevc;
2957 startchar = c;
2958 prevc = 0;
2959 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2960 if( c=='\n' ) lineno++;
2961 if( prevc=='\\' ) prevc = 0;
2962 else prevc = c;
2966 if( c==0 ){
2967 ErrorMsg(ps.filename,ps.tokenlineno,
2968 "C code starting on this line is not terminated before the end of the file.");
2969 ps.errorcnt++;
2970 nextcp = cp;
2971 }else{
2972 nextcp = cp+1;
2974 }else if( ISALNUM(c) ){ /* Identifiers */
2975 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2976 nextcp = cp;
2977 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2978 cp += 3;
2979 nextcp = cp;
2980 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
2981 cp += 2;
2982 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2983 nextcp = cp;
2984 }else{ /* All other (one character) operators */
2985 cp++;
2986 nextcp = cp;
2988 c = *cp;
2989 *cp = 0; /* Null terminate the token */
2990 parseonetoken(&ps); /* Parse the token */
2991 *cp = (char)c; /* Restore the buffer */
2992 cp = nextcp;
2994 free(filebuf); /* Release the buffer after parsing */
2995 gp->rule = ps.firstrule;
2996 gp->errorcnt = ps.errorcnt;
2998 /*************************** From the file "plink.c" *********************/
3000 ** Routines processing configuration follow-set propagation links
3001 ** in the LEMON parser generator.
3003 static struct plink *plink_freelist = 0;
3005 /* Allocate a new plink */
3006 struct plink *Plink_new(void){
3007 struct plink *newlink;
3009 if( plink_freelist==0 ){
3010 int i;
3011 int amt = 100;
3012 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
3013 if( plink_freelist==0 ){
3014 fprintf(stderr,
3015 "Unable to allocate memory for a new follow-set propagation link.\n");
3016 exit(1);
3018 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3019 plink_freelist[amt-1].next = 0;
3021 newlink = plink_freelist;
3022 plink_freelist = plink_freelist->next;
3023 return newlink;
3026 /* Add a plink to a plink list */
3027 void Plink_add(struct plink **plpp, struct config *cfp)
3029 struct plink *newlink;
3030 newlink = Plink_new();
3031 newlink->next = *plpp;
3032 *plpp = newlink;
3033 newlink->cfp = cfp;
3036 /* Transfer every plink on the list "from" to the list "to" */
3037 void Plink_copy(struct plink **to, struct plink *from)
3039 struct plink *nextpl;
3040 while( from ){
3041 nextpl = from->next;
3042 from->next = *to;
3043 *to = from;
3044 from = nextpl;
3048 /* Delete every plink on the list */
3049 void Plink_delete(struct plink *plp)
3051 struct plink *nextpl;
3053 while( plp ){
3054 nextpl = plp->next;
3055 plp->next = plink_freelist;
3056 plink_freelist = plp;
3057 plp = nextpl;
3060 /*********************** From the file "report.c" **************************/
3062 ** Procedures for generating reports and tables in the LEMON parser generator.
3065 /* Generate a filename with the given suffix. Space to hold the
3066 ** name comes from malloc() and must be freed by the calling
3067 ** function.
3069 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
3071 char *name;
3072 char *cp;
3074 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
3075 if( name==0 ){
3076 fprintf(stderr,"Can't allocate space for a filename.\n");
3077 exit(1);
3079 lemon_strcpy(name,lemp->filename);
3080 cp = strrchr(name,'.');
3081 if( cp ) *cp = 0;
3082 lemon_strcat(name,suffix);
3083 return name;
3086 /* Open a file with a name based on the name of the input file,
3087 ** but with a different (specified) suffix, and return a pointer
3088 ** to the stream */
3089 PRIVATE FILE *file_open(
3090 struct lemon *lemp,
3091 const char *suffix,
3092 const char *mode
3094 FILE *fp;
3096 if( lemp->outname ) free(lemp->outname);
3097 lemp->outname = file_makename(lemp, suffix);
3098 fp = fopen(lemp->outname,mode);
3099 if( fp==0 && *mode=='w' ){
3100 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3101 lemp->errorcnt++;
3102 return 0;
3104 return fp;
3107 /* Print the text of a rule
3109 void rule_print(FILE *out, struct rule *rp){
3110 int i, j;
3111 fprintf(out, "%s",rp->lhs->name);
3112 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3113 fprintf(out," ::=");
3114 for(i=0; i<rp->nrhs; i++){
3115 struct symbol *sp = rp->rhs[i];
3116 if( sp->type==MULTITERMINAL ){
3117 fprintf(out," %s", sp->subsym[0]->name);
3118 for(j=1; j<sp->nsubsym; j++){
3119 fprintf(out,"|%s", sp->subsym[j]->name);
3121 }else{
3122 fprintf(out," %s", sp->name);
3124 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3128 /* Duplicate the input file without comments and without actions
3129 ** on rules */
3130 void Reprint(struct lemon *lemp)
3132 struct rule *rp;
3133 struct symbol *sp;
3134 int i, j, maxlen, len, ncolumns, skip;
3135 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3136 maxlen = 10;
3137 for(i=0; i<lemp->nsymbol; i++){
3138 sp = lemp->symbols[i];
3139 len = lemonStrlen(sp->name);
3140 if( len>maxlen ) maxlen = len;
3142 ncolumns = 76/(maxlen+5);
3143 if( ncolumns<1 ) ncolumns = 1;
3144 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3145 for(i=0; i<skip; i++){
3146 printf("//");
3147 for(j=i; j<lemp->nsymbol; j+=skip){
3148 sp = lemp->symbols[j];
3149 assert( sp->index==j );
3150 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3152 printf("\n");
3154 for(rp=lemp->rule; rp; rp=rp->next){
3155 rule_print(stdout, rp);
3156 printf(".");
3157 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
3158 /* if( rp->code ) printf("\n %s",rp->code); */
3159 printf("\n");
3163 /* Print a single rule.
3165 void RulePrint(FILE *fp, struct rule *rp, int iCursor){
3166 struct symbol *sp;
3167 int i, j;
3168 fprintf(fp,"%s ::=",rp->lhs->name);
3169 for(i=0; i<=rp->nrhs; i++){
3170 if( i==iCursor ) fprintf(fp," *");
3171 if( i==rp->nrhs ) break;
3172 sp = rp->rhs[i];
3173 if( sp->type==MULTITERMINAL ){
3174 fprintf(fp," %s", sp->subsym[0]->name);
3175 for(j=1; j<sp->nsubsym; j++){
3176 fprintf(fp,"|%s",sp->subsym[j]->name);
3178 }else{
3179 fprintf(fp," %s", sp->name);
3184 /* Print the rule for a configuration.
3186 void ConfigPrint(FILE *fp, struct config *cfp){
3187 RulePrint(fp, cfp->rp, cfp->dot);
3190 /* #define TEST */
3191 #if 0
3192 /* Print a set */
3193 PRIVATE void SetPrint(out,set,lemp)
3194 FILE *out;
3195 char *set;
3196 struct lemon *lemp;
3198 int i;
3199 char *spacer;
3200 spacer = "";
3201 fprintf(out,"%12s[","");
3202 for(i=0; i<lemp->nterminal; i++){
3203 if( SetFind(set,i) ){
3204 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3205 spacer = " ";
3208 fprintf(out,"]\n");
3211 /* Print a plink chain */
3212 PRIVATE void PlinkPrint(out,plp,tag)
3213 FILE *out;
3214 struct plink *plp;
3215 char *tag;
3217 while( plp ){
3218 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
3219 ConfigPrint(out,plp->cfp);
3220 fprintf(out,"\n");
3221 plp = plp->next;
3224 #endif
3226 /* Print an action to the given file descriptor. Return FALSE if
3227 ** nothing was actually printed.
3229 int PrintAction(
3230 struct action *ap, /* The action to print */
3231 FILE *fp, /* Print the action here */
3232 int indent /* Indent by this amount */
3234 int result = 1;
3235 switch( ap->type ){
3236 case SHIFT: {
3237 struct state *stp = ap->x.stp;
3238 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
3239 break;
3241 case REDUCE: {
3242 struct rule *rp = ap->x.rp;
3243 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
3244 RulePrint(fp, rp, -1);
3245 break;
3247 case SHIFTREDUCE: {
3248 struct rule *rp = ap->x.rp;
3249 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
3250 RulePrint(fp, rp, -1);
3251 break;
3253 case ACCEPT:
3254 fprintf(fp,"%*s accept",indent,ap->sp->name);
3255 break;
3256 case ERROR:
3257 fprintf(fp,"%*s error",indent,ap->sp->name);
3258 break;
3259 case SRCONFLICT:
3260 case RRCONFLICT:
3261 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
3262 indent,ap->sp->name,ap->x.rp->iRule);
3263 break;
3264 case SSCONFLICT:
3265 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
3266 indent,ap->sp->name,ap->x.stp->statenum);
3267 break;
3268 case SH_RESOLVED:
3269 if( showPrecedenceConflict ){
3270 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
3271 indent,ap->sp->name,ap->x.stp->statenum);
3272 }else{
3273 result = 0;
3275 break;
3276 case RD_RESOLVED:
3277 if( showPrecedenceConflict ){
3278 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
3279 indent,ap->sp->name,ap->x.rp->iRule);
3280 }else{
3281 result = 0;
3283 break;
3284 case NOT_USED:
3285 result = 0;
3286 break;
3288 if( result && ap->spOpt ){
3289 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3291 return result;
3294 /* Generate the "*.out" log file */
3295 void ReportOutput(struct lemon *lemp)
3297 int i;
3298 struct state *stp;
3299 struct config *cfp;
3300 struct action *ap;
3301 struct rule *rp;
3302 FILE *fp;
3304 fp = file_open(lemp,".out","wb");
3305 if( fp==0 ) return;
3306 for(i=0; i<lemp->nxstate; i++){
3307 stp = lemp->sorted[i];
3308 fprintf(fp,"State %d:\n",stp->statenum);
3309 if( lemp->basisflag ) cfp=stp->bp;
3310 else cfp=stp->cfp;
3311 while( cfp ){
3312 char buf[20];
3313 if( cfp->dot==cfp->rp->nrhs ){
3314 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
3315 fprintf(fp," %5s ",buf);
3316 }else{
3317 fprintf(fp," ");
3319 ConfigPrint(fp,cfp);
3320 fprintf(fp,"\n");
3321 #if 0
3322 SetPrint(fp,cfp->fws,lemp);
3323 PlinkPrint(fp,cfp->fplp,"To ");
3324 PlinkPrint(fp,cfp->bplp,"From");
3325 #endif
3326 if( lemp->basisflag ) cfp=cfp->bp;
3327 else cfp=cfp->next;
3329 fprintf(fp,"\n");
3330 for(ap=stp->ap; ap; ap=ap->next){
3331 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3333 fprintf(fp,"\n");
3335 fprintf(fp, "----------------------------------------------------\n");
3336 fprintf(fp, "Symbols:\n");
3337 for(i=0; i<lemp->nsymbol; i++){
3338 int j;
3339 struct symbol *sp;
3341 sp = lemp->symbols[i];
3342 fprintf(fp, " %3d: %s", i, sp->name);
3343 if( sp->type==NONTERMINAL ){
3344 fprintf(fp, ":");
3345 if( sp->lambda ){
3346 fprintf(fp, " <lambda>");
3348 for(j=0; j<lemp->nterminal; j++){
3349 if( sp->firstset && SetFind(sp->firstset, j) ){
3350 fprintf(fp, " %s", lemp->symbols[j]->name);
3354 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
3355 fprintf(fp, "\n");
3357 fprintf(fp, "----------------------------------------------------\n");
3358 fprintf(fp, "Rules:\n");
3359 for(rp=lemp->rule; rp; rp=rp->next){
3360 fprintf(fp, "%4d: ", rp->iRule);
3361 rule_print(fp, rp);
3362 fprintf(fp,".");
3363 if( rp->precsym ){
3364 fprintf(fp," [%s precedence=%d]",
3365 rp->precsym->name, rp->precsym->prec);
3367 fprintf(fp,"\n");
3369 fclose(fp);
3370 return;
3373 /* Search for the file "name" which is in the same directory as
3374 ** the executable */
3375 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3377 const char *pathlist;
3378 char *pathbufptr;
3379 char *pathbuf;
3380 char *path,*cp;
3381 char c;
3383 #ifdef __WIN32__
3384 cp = strrchr(argv0,'\\');
3385 #else
3386 cp = strrchr(argv0,'/');
3387 #endif
3388 if( cp ){
3389 c = *cp;
3390 *cp = 0;
3391 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3392 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3393 *cp = c;
3394 }else{
3395 pathlist = getenv("PATH");
3396 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3397 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
3398 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3399 if( (pathbuf != 0) && (path!=0) ){
3400 pathbufptr = pathbuf;
3401 lemon_strcpy(pathbuf, pathlist);
3402 while( *pathbuf ){
3403 cp = strchr(pathbuf,':');
3404 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3405 c = *cp;
3406 *cp = 0;
3407 lemon_sprintf(path,"%s/%s",pathbuf,name);
3408 *cp = c;
3409 if( c==0 ) pathbuf[0] = 0;
3410 else pathbuf = &cp[1];
3411 if( access(path,modemask)==0 ) break;
3413 free(pathbufptr);
3416 return path;
3419 /* Given an action, compute the integer value for that action
3420 ** which is to be put in the action table of the generated machine.
3421 ** Return negative if no action should be generated.
3423 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3425 int act;
3426 switch( ap->type ){
3427 case SHIFT: act = ap->x.stp->statenum; break;
3428 case SHIFTREDUCE: {
3429 /* Since a SHIFT is inherent after a prior REDUCE, convert any
3430 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3431 ** REDUCE action: */
3432 if( ap->sp->index>=lemp->nterminal ){
3433 act = lemp->minReduce + ap->x.rp->iRule;
3434 }else{
3435 act = lemp->minShiftReduce + ap->x.rp->iRule;
3437 break;
3439 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3440 case ERROR: act = lemp->errAction; break;
3441 case ACCEPT: act = lemp->accAction; break;
3442 default: act = -1; break;
3444 return act;
3447 #define LINESIZE 1000
3448 /* The next cluster of routines are for reading the template file
3449 ** and writing the results to the generated parser */
3450 /* The first function transfers data from "in" to "out" until
3451 ** a line is seen which begins with "%%". The line number is
3452 ** tracked.
3454 ** if name!=0, then any word that begin with "Parse" is changed to
3455 ** begin with *name instead.
3457 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3459 int i, iStart;
3460 char line[LINESIZE];
3461 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3462 (*lineno)++;
3463 iStart = 0;
3464 if( name ){
3465 for(i=0; line[i]; i++){
3466 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3467 && (i==0 || !ISALPHA(line[i-1]))
3469 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3470 fprintf(out,"%s",name);
3471 i += 4;
3472 iStart = i+1;
3476 fprintf(out,"%s",&line[iStart]);
3480 /* The next function finds the template file and opens it, returning
3481 ** a pointer to the opened file. */
3482 PRIVATE FILE *tplt_open(struct lemon *lemp)
3484 static char templatename[] = "lempar.c";
3485 char buf[1000];
3486 FILE *in;
3487 char *tpltname;
3488 char *cp;
3489 char *to_free = NULL;
3491 /* first, see if user specified a template filename on the command line. */
3492 if (user_templatename != 0) {
3493 if( access(user_templatename,004)==-1 ){
3494 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3495 user_templatename);
3496 lemp->errorcnt++;
3497 return 0;
3499 in = fopen(user_templatename,"rb");
3500 if( in==0 ){
3501 fprintf(stderr,"Can't open the template file \"%s\".\n",
3502 user_templatename);
3503 lemp->errorcnt++;
3504 return 0;
3506 return in;
3509 cp = strrchr(lemp->filename,'.');
3510 if( cp ){
3511 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3512 }else{
3513 lemon_sprintf(buf,"%s.lt",lemp->filename);
3515 if( access(buf,004)==0 ){
3516 tpltname = buf;
3517 }else if( access(templatename,004)==0 ){
3518 tpltname = templatename;
3519 }else{
3520 tpltname = pathsearch(lemp->argv0,templatename,0);
3521 to_free = tpltname;
3523 if( tpltname==0 ){
3524 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3525 templatename);
3526 lemp->errorcnt++;
3527 return 0;
3529 in = fopen(tpltname,"rb");
3530 if (to_free) free(to_free);
3531 if( in==0 ){
3532 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3533 lemp->errorcnt++;
3534 return 0;
3536 return in;
3539 /* Print a #line directive line to the output file. */
3540 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3542 fprintf(out,"#line %d \"",lineno);
3543 while( *filename ){
3544 if( *filename == '\\' ) putc('\\',out);
3545 putc(*filename,out);
3546 filename++;
3548 fprintf(out,"\"\n");
3551 /* Print a string to the file and keep the linenumber up to date */
3552 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3554 if( str==0 ) return;
3555 while( *str ){
3556 putc(*str,out);
3557 if( *str=='\n' ) (*lineno)++;
3558 str++;
3560 if( str[-1]!='\n' ){
3561 putc('\n',out);
3562 (*lineno)++;
3564 if (!lemp->nolinenosflag) {
3565 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3567 return;
3571 ** The following routine emits code for the destructor for the
3572 ** symbol sp
3574 void emit_destructor_code(
3575 FILE *out,
3576 struct symbol *sp,
3577 struct lemon *lemp,
3578 int *lineno
3580 char *cp = 0;
3582 if( sp->type==TERMINAL ){
3583 cp = lemp->tokendest;
3584 if( cp==0 ) return;
3585 fprintf(out,"{\n"); (*lineno)++;
3586 }else if( sp->destructor ){
3587 cp = sp->destructor;
3588 fprintf(out,"{\n"); (*lineno)++;
3589 if( !lemp->nolinenosflag ){
3590 (*lineno)++;
3591 tplt_linedir(out,sp->destLineno,lemp->filename);
3593 }else if( lemp->vardest ){
3594 cp = lemp->vardest;
3595 if( cp==0 ) return;
3596 fprintf(out,"{\n"); (*lineno)++;
3597 }else{
3598 assert( 0 ); /* Cannot happen */
3600 for(; *cp; cp++){
3601 if( *cp=='$' && cp[1]=='$' ){
3602 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3603 cp++;
3604 continue;
3606 if( *cp=='\n' ) (*lineno)++;
3607 fputc(*cp,out);
3609 fprintf(out,"\n"); (*lineno)++;
3610 if (!lemp->nolinenosflag) {
3611 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3613 fprintf(out,"}\n"); (*lineno)++;
3614 return;
3618 ** Return TRUE (non-zero) if the given symbol has a destructor.
3620 int has_destructor(struct symbol *sp, struct lemon *lemp)
3622 int ret;
3623 if( sp->type==TERMINAL ){
3624 ret = lemp->tokendest!=0;
3625 }else{
3626 ret = lemp->vardest!=0 || sp->destructor!=0;
3628 return ret;
3632 ** Append text to a dynamically allocated string. If zText is 0 then
3633 ** reset the string to be empty again. Always return the complete text
3634 ** of the string (which is overwritten with each call).
3636 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3637 ** \000 terminator is stored. zText can contain up to two instances of
3638 ** %d. The values of p1 and p2 are written into the first and second
3639 ** %d.
3641 ** If n==-1, then the previous character is overwritten.
3643 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3644 static char *z = 0;
3645 static int alloced = 0;
3646 static int used = 0;
3647 int c;
3648 char zInt[40];
3649 if( zText==0 ){
3650 if( used==0 && z!=0 ) z[0] = 0;
3651 used = 0;
3652 return z;
3654 if( n<=0 ){
3655 if( n<0 ){
3656 used += n;
3657 assert( used>=0 );
3659 n = lemonStrlen(zText);
3661 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3662 alloced = n + sizeof(zInt)*2 + used + 200;
3663 z = (char *) realloc(z, alloced);
3665 if( z==0 ){
3666 fprintf(stderr,"Out of memory.\n");
3667 exit(1);
3669 while( n-- > 0 ){
3670 c = *(zText++);
3671 if( c=='%' && n>0 && zText[0]=='d' ){
3672 lemon_sprintf(zInt, "%d", p1);
3673 p1 = p2;
3674 lemon_strcpy(&z[used], zInt);
3675 used += lemonStrlen(&z[used]);
3676 zText++;
3677 n--;
3678 }else{
3679 z[used++] = (char)c;
3682 z[used] = 0;
3683 return z;
3687 ** Write and transform the rp->code string so that symbols are expanded.
3688 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3690 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3691 ** to be defined.
3693 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
3694 char *cp, *xp;
3695 int i;
3696 int rc = 0; /* True if yylhsminor is used */
3697 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
3698 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3699 char lhsused = 0; /* True if the LHS element has been used */
3700 char lhsdirect; /* True if LHS writes directly into stack */
3701 char used[MAXRHS]; /* True for each RHS element which is used */
3702 char zLhs[50]; /* Convert the LHS symbol into this string */
3703 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
3705 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3706 lhsused = 0;
3708 if( rp->code==0 ){
3709 rp->code = "\n";
3710 rp->line = rp->ruleline;
3711 rp->noCode = 1;
3712 }else{
3713 rp->noCode = 0;
3717 if( rp->nrhs==0 ){
3718 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3719 lhsdirect = 1;
3720 }else if( rp->rhsalias[0]==0 ){
3721 /* The left-most RHS symbol has no value. LHS direct is ok. But
3722 ** we have to call the distructor on the RHS symbol first. */
3723 lhsdirect = 1;
3724 if( has_destructor(rp->rhs[0],lemp) ){
3725 append_str(0,0,0,0);
3726 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3727 rp->rhs[0]->index,1-rp->nrhs);
3728 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3729 rp->noCode = 0;
3731 }else if( rp->lhsalias==0 ){
3732 /* There is no LHS value symbol. */
3733 lhsdirect = 1;
3734 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3735 /* The LHS symbol and the left-most RHS symbol are the same, so
3736 ** direct writing is allowed */
3737 lhsdirect = 1;
3738 lhsused = 1;
3739 used[0] = 1;
3740 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3741 ErrorMsg(lemp->filename,rp->ruleline,
3742 "%s(%s) and %s(%s) share the same label but have "
3743 "different datatypes.",
3744 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3745 lemp->errorcnt++;
3747 }else{
3748 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3749 rp->lhsalias, rp->rhsalias[0]);
3750 zSkip = strstr(rp->code, zOvwrt);
3751 if( zSkip!=0 ){
3752 /* The code contains a special comment that indicates that it is safe
3753 ** for the LHS label to overwrite left-most RHS label. */
3754 lhsdirect = 1;
3755 }else{
3756 lhsdirect = 0;
3759 if( lhsdirect ){
3760 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3761 }else{
3762 rc = 1;
3763 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3766 append_str(0,0,0,0);
3768 /* This const cast is wrong but harmless, if we're careful. */
3769 for(cp=(char *)rp->code; *cp; cp++){
3770 if( cp==zSkip ){
3771 append_str(zOvwrt,0,0,0);
3772 cp += lemonStrlen(zOvwrt)-1;
3773 dontUseRhs0 = 1;
3774 continue;
3776 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
3777 char saved;
3778 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
3779 saved = *xp;
3780 *xp = 0;
3781 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3782 append_str(zLhs,0,0,0);
3783 cp = xp;
3784 lhsused = 1;
3785 }else{
3786 for(i=0; i<rp->nrhs; i++){
3787 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3788 if( i==0 && dontUseRhs0 ){
3789 ErrorMsg(lemp->filename,rp->ruleline,
3790 "Label %s used after '%s'.",
3791 rp->rhsalias[0], zOvwrt);
3792 lemp->errorcnt++;
3793 }else if( cp!=rp->code && cp[-1]=='@' ){
3794 /* If the argument is of the form @X then substituted
3795 ** the token number of X, not the value of X */
3796 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3797 }else{
3798 struct symbol *sp = rp->rhs[i];
3799 int dtnum;
3800 if( sp->type==MULTITERMINAL ){
3801 dtnum = sp->subsym[0]->dtnum;
3802 }else{
3803 dtnum = sp->dtnum;
3805 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3807 cp = xp;
3808 used[i] = 1;
3809 break;
3813 *xp = saved;
3815 append_str(cp, 1, 0, 0);
3816 } /* End loop */
3818 /* Main code generation completed */
3819 cp = append_str(0,0,0,0);
3820 if( cp && cp[0] ) rp->code = Strsafe(cp);
3821 append_str(0,0,0,0);
3823 /* Check to make sure the LHS has been used */
3824 if( rp->lhsalias && !lhsused ){
3825 ErrorMsg(lemp->filename,rp->ruleline,
3826 "Label \"%s\" for \"%s(%s)\" is never used.",
3827 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3828 lemp->errorcnt++;
3831 /* Generate destructor code for RHS minor values which are not referenced.
3832 ** Generate error messages for unused labels and duplicate labels.
3834 for(i=0; i<rp->nrhs; i++){
3835 if( rp->rhsalias[i] ){
3836 if( i>0 ){
3837 int j;
3838 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3839 ErrorMsg(lemp->filename,rp->ruleline,
3840 "%s(%s) has the same label as the LHS but is not the left-most "
3841 "symbol on the RHS.",
3842 rp->rhs[i]->name, rp->rhsalias);
3843 lemp->errorcnt++;
3845 for(j=0; j<i; j++){
3846 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3847 ErrorMsg(lemp->filename,rp->ruleline,
3848 "Label %s used for multiple symbols on the RHS of a rule.",
3849 rp->rhsalias[i]);
3850 lemp->errorcnt++;
3851 break;
3855 if( !used[i] ){
3856 ErrorMsg(lemp->filename,rp->ruleline,
3857 "Label %s for \"%s(%s)\" is never used.",
3858 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3859 lemp->errorcnt++;
3861 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3862 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3863 rp->rhs[i]->index,i-rp->nrhs+1);
3867 /* If unable to write LHS values directly into the stack, write the
3868 ** saved LHS value now. */
3869 if( lhsdirect==0 ){
3870 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3871 append_str(zLhs, 0, 0, 0);
3872 append_str(";\n", 0, 0, 0);
3875 /* Suffix code generation complete */
3876 cp = append_str(0,0,0,0);
3877 if( cp && cp[0] ){
3878 rp->codeSuffix = Strsafe(cp);
3879 rp->noCode = 0;
3882 return rc;
3886 ** Generate code which executes when the rule "rp" is reduced. Write
3887 ** the code to "out". Make sure lineno stays up-to-date.
3889 PRIVATE void emit_code(
3890 FILE *out,
3891 struct rule *rp,
3892 struct lemon *lemp,
3893 int *lineno
3895 const char *cp;
3897 /* Setup code prior to the #line directive */
3898 if( rp->codePrefix && rp->codePrefix[0] ){
3899 fprintf(out, "{%s", rp->codePrefix);
3900 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3903 /* Generate code to do the reduce action */
3904 if( rp->code ){
3905 if( !lemp->nolinenosflag ){
3906 (*lineno)++;
3907 tplt_linedir(out,rp->line,lemp->filename);
3909 fprintf(out,"{%s",rp->code);
3910 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3911 fprintf(out,"}\n"); (*lineno)++;
3912 if( !lemp->nolinenosflag ){
3913 (*lineno)++;
3914 tplt_linedir(out,*lineno,lemp->outname);
3918 /* Generate breakdown code that occurs after the #line directive */
3919 if( rp->codeSuffix && rp->codeSuffix[0] ){
3920 fprintf(out, "%s", rp->codeSuffix);
3921 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3924 if( rp->codePrefix ){
3925 fprintf(out, "}\n"); (*lineno)++;
3928 return;
3932 ** Print the definition of the union used for the parser's data stack.
3933 ** This union contains fields for every possible data type for tokens
3934 ** and nonterminals. In the process of computing and printing this
3935 ** union, also set the ".dtnum" field of every terminal and nonterminal
3936 ** symbol.
3938 void print_stack_union(
3939 FILE *out, /* The output stream */
3940 struct lemon *lemp, /* The main info structure for this parser */
3941 int *plineno, /* Pointer to the line number */
3942 int mhflag /* True if generating makeheaders output */
3944 int lineno = *plineno; /* The line number of the output */
3945 char **types; /* A hash table of datatypes */
3946 int arraysize; /* Size of the "types" array */
3947 int maxdtlength; /* Maximum length of any ".datatype" field. */
3948 char *stddt; /* Standardized name for a datatype */
3949 int i,j; /* Loop counters */
3950 unsigned hash; /* For hashing the name of a type */
3951 const char *name; /* Name of the parser */
3953 /* Allocate and initialize types[] and allocate stddt[] */
3954 arraysize = lemp->nsymbol * 2;
3955 types = (char**)calloc( arraysize, sizeof(char*) );
3956 if( types==0 ){
3957 fprintf(stderr,"Out of memory.\n");
3958 exit(1);
3960 for(i=0; i<arraysize; i++) types[i] = 0;
3961 maxdtlength = 0;
3962 if( lemp->vartype ){
3963 maxdtlength = lemonStrlen(lemp->vartype);
3965 for(i=0; i<lemp->nsymbol; i++){
3966 int len;
3967 struct symbol *sp = lemp->symbols[i];
3968 if( sp->datatype==0 ) continue;
3969 len = lemonStrlen(sp->datatype);
3970 if( len>maxdtlength ) maxdtlength = len;
3972 stddt = (char*)malloc( maxdtlength*2 + 1 );
3973 if( stddt==0 ){
3974 fprintf(stderr,"Out of memory.\n");
3975 exit(1);
3978 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3979 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3980 ** used for terminal symbols. If there is no %default_type defined then
3981 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3982 ** a datatype using the %type directive.
3984 for(i=0; i<lemp->nsymbol; i++){
3985 struct symbol *sp = lemp->symbols[i];
3986 char *cp;
3987 if( sp==lemp->errsym ){
3988 sp->dtnum = arraysize+1;
3989 continue;
3991 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
3992 sp->dtnum = 0;
3993 continue;
3995 cp = sp->datatype;
3996 if( cp==0 ) cp = lemp->vartype;
3997 j = 0;
3998 while( ISSPACE(*cp) ) cp++;
3999 while( *cp ) stddt[j++] = *cp++;
4000 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
4001 stddt[j] = 0;
4002 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
4003 sp->dtnum = 0;
4004 continue;
4006 hash = 0;
4007 for(j=0; stddt[j]; j++){
4008 hash = hash*53 + stddt[j];
4010 hash = (hash & 0x7fffffff)%arraysize;
4011 while( types[hash] ){
4012 if( strcmp(types[hash],stddt)==0 ){
4013 sp->dtnum = hash + 1;
4014 break;
4016 hash++;
4017 if( hash>=(unsigned)arraysize ) hash = 0;
4019 if( types[hash]==0 ){
4020 sp->dtnum = hash + 1;
4021 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
4022 if( types[hash]==0 ){
4023 fprintf(stderr,"Out of memory.\n");
4024 exit(1);
4026 lemon_strcpy(types[hash],stddt);
4030 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4031 name = lemp->name ? lemp->name : "Parse";
4032 lineno = *plineno;
4033 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4034 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4035 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4036 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4037 fprintf(out,"typedef union {\n"); lineno++;
4038 fprintf(out," int yyinit;\n"); lineno++;
4039 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4040 for(i=0; i<arraysize; i++){
4041 if( types[i]==0 ) continue;
4042 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4043 free(types[i]);
4045 if( lemp->errsym->useCnt ){
4046 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4048 free(stddt);
4049 free(types);
4050 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4051 *plineno = lineno;
4055 ** Return the name of a C datatype able to represent values between
4056 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4057 ** for that type (1, 2, or 4) into *pnByte.
4059 static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4060 const char *zType = "int";
4061 int nByte = 4;
4062 if( lwr>=0 ){
4063 if( upr<=255 ){
4064 zType = "unsigned char";
4065 nByte = 1;
4066 }else if( upr<65535 ){
4067 zType = "unsigned short int";
4068 nByte = 2;
4069 }else{
4070 zType = "unsigned int";
4071 nByte = 4;
4073 }else if( lwr>=-127 && upr<=127 ){
4074 zType = "signed char";
4075 nByte = 1;
4076 }else if( lwr>=-32767 && upr<32767 ){
4077 zType = "short";
4078 nByte = 2;
4080 if( pnByte ) *pnByte = nByte;
4081 return zType;
4085 ** Each state contains a set of token transaction and a set of
4086 ** nonterminal transactions. Each of these sets makes an instance
4087 ** of the following structure. An array of these structures is used
4088 ** to order the creation of entries in the yy_action[] table.
4090 struct axset {
4091 struct state *stp; /* A pointer to a state */
4092 int isTkn; /* True to use tokens. False for non-terminals */
4093 int nAction; /* Number of actions */
4094 int iOrder; /* Original order of action sets */
4098 ** Compare to axset structures for sorting purposes
4100 static int axset_compare(const void *a, const void *b){
4101 struct axset *p1 = (struct axset*)a;
4102 struct axset *p2 = (struct axset*)b;
4103 int c;
4104 c = p2->nAction - p1->nAction;
4105 if( c==0 ){
4106 c = p1->iOrder - p2->iOrder;
4108 assert( c!=0 || p1==p2 );
4109 return c;
4113 ** Write text on "out" that describes the rule "rp".
4115 static void writeRuleText(FILE *out, struct rule *rp){
4116 int j;
4117 fprintf(out,"%s ::=", rp->lhs->name);
4118 for(j=0; j<rp->nrhs; j++){
4119 struct symbol *sp = rp->rhs[j];
4120 if( sp->type!=MULTITERMINAL ){
4121 fprintf(out," %s", sp->name);
4122 }else{
4123 int k;
4124 fprintf(out," %s", sp->subsym[0]->name);
4125 for(k=1; k<sp->nsubsym; k++){
4126 fprintf(out,"|%s",sp->subsym[k]->name);
4133 /* Generate C source code for the parser */
4134 void ReportTable(
4135 struct lemon *lemp,
4136 int mhflag /* Output in makeheaders format if true */
4138 FILE *out, *in;
4139 char line[LINESIZE];
4140 int lineno;
4141 struct state *stp;
4142 struct action *ap;
4143 struct rule *rp;
4144 struct acttab *pActtab;
4145 int i, j, n, sz;
4146 int szActionType; /* sizeof(YYACTIONTYPE) */
4147 int szCodeType; /* sizeof(YYCODETYPE) */
4148 const char *name;
4149 int mnTknOfst, mxTknOfst;
4150 int mnNtOfst, mxNtOfst;
4151 struct axset *ax;
4153 lemp->minShiftReduce = lemp->nstate;
4154 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4155 lemp->accAction = lemp->errAction + 1;
4156 lemp->noAction = lemp->accAction + 1;
4157 lemp->minReduce = lemp->noAction + 1;
4158 lemp->maxAction = lemp->minReduce + lemp->nrule;
4160 in = tplt_open(lemp);
4161 if( in==0 ) return;
4162 if( output_filename!=0 ){
4163 char *tmp = lemp->filename;
4164 char *ext = strrchr(output_filename, '.');
4165 if( ext==0 ) ext = ".c";
4166 lemp->filename = output_filename;
4167 out = file_open(lemp,ext,"wb");
4168 lemp->filename = tmp;
4169 }else{
4170 out = file_open(lemp,".c","wb");
4172 if( out==0 ){
4173 fclose(in);
4174 return;
4176 lineno = 1;
4177 tplt_xfer(lemp->name,in,out,&lineno);
4179 /* Generate the include code, if any */
4180 tplt_print(out,lemp,lemp->include,&lineno);
4181 if( mhflag ){
4182 char *incName = file_makename(lemp, ".h");
4183 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4184 free(incName);
4186 tplt_xfer(lemp->name,in,out,&lineno);
4188 /* Generate #defines for all tokens */
4189 if( mhflag ){
4190 const char *prefix;
4191 fprintf(out,"#if INTERFACE\n"); lineno++;
4192 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4193 else prefix = "";
4194 for(i=1; i<lemp->nterminal; i++){
4195 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4196 lineno++;
4198 fprintf(out,"#endif\n"); lineno++;
4200 tplt_xfer(lemp->name,in,out,&lineno);
4202 /* Generate the defines */
4203 fprintf(out,"#define YYCODETYPE %s\n",
4204 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
4205 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
4206 fprintf(out,"#define YYACTIONTYPE %s\n",
4207 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
4208 if( lemp->wildcard ){
4209 fprintf(out,"#define YYWILDCARD %d\n",
4210 lemp->wildcard->index); lineno++;
4212 print_stack_union(out,lemp,&lineno,mhflag);
4213 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
4214 if( lemp->stacksize ){
4215 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4216 }else{
4217 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4219 fprintf(out, "#endif\n"); lineno++;
4220 if( mhflag ){
4221 fprintf(out,"#if INTERFACE\n"); lineno++;
4223 name = lemp->name ? lemp->name : "Parse";
4224 if( lemp->arg && lemp->arg[0] ){
4225 i = lemonStrlen(lemp->arg);
4226 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4227 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
4228 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4229 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4230 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4231 name,lemp->arg,&lemp->arg[i]); lineno++;
4232 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4233 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
4234 }else{
4235 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4236 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4237 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4238 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
4240 if( mhflag ){
4241 fprintf(out,"#endif\n"); lineno++;
4243 if( lemp->errsym->useCnt ){
4244 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4245 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
4247 if( lemp->has_fallback ){
4248 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4251 /* Compute the action table, but do not output it yet. The action
4252 ** table must be computed before generating the YYNSTATE macro because
4253 ** we need to know how many states can be eliminated.
4255 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
4256 if( ax==0 ){
4257 fprintf(stderr,"malloc failed\n");
4258 exit(1);
4260 for(i=0; i<lemp->nxstate; i++){
4261 stp = lemp->sorted[i];
4262 ax[i*2].stp = stp;
4263 ax[i*2].isTkn = 1;
4264 ax[i*2].nAction = stp->nTknAct;
4265 ax[i*2+1].stp = stp;
4266 ax[i*2+1].isTkn = 0;
4267 ax[i*2+1].nAction = stp->nNtAct;
4269 mxTknOfst = mnTknOfst = 0;
4270 mxNtOfst = mnNtOfst = 0;
4271 /* In an effort to minimize the action table size, use the heuristic
4272 ** of placing the largest action sets first */
4273 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4274 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
4275 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
4276 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
4277 stp = ax[i].stp;
4278 if( ax[i].isTkn ){
4279 for(ap=stp->ap; ap; ap=ap->next){
4280 int action;
4281 if( ap->sp->index>=lemp->nterminal ) continue;
4282 action = compute_action(lemp, ap);
4283 if( action<0 ) continue;
4284 acttab_action(pActtab, ap->sp->index, action);
4286 stp->iTknOfst = acttab_insert(pActtab, 1);
4287 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4288 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4289 }else{
4290 for(ap=stp->ap; ap; ap=ap->next){
4291 int action;
4292 if( ap->sp->index<lemp->nterminal ) continue;
4293 if( ap->sp->index==lemp->nsymbol ) continue;
4294 action = compute_action(lemp, ap);
4295 if( action<0 ) continue;
4296 acttab_action(pActtab, ap->sp->index, action);
4298 stp->iNtOfst = acttab_insert(pActtab, 0);
4299 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4300 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
4302 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4303 { int jj, nn;
4304 for(jj=nn=0; jj<pActtab->nAction; jj++){
4305 if( pActtab->aAction[jj].action<0 ) nn++;
4307 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4308 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4309 ax[i].nAction, pActtab->nAction, nn);
4311 #endif
4313 free(ax);
4315 /* Mark rules that are actually used for reduce actions after all
4316 ** optimizations have been applied
4318 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4319 for(i=0; i<lemp->nxstate; i++){
4320 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4321 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
4322 ap->x.rp->doesReduce = 1;
4327 /* Finish rendering the constants now that the action table has
4328 ** been computed */
4329 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4330 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
4331 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
4332 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
4333 i = lemp->minShiftReduce;
4334 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4335 i = lemp->nstate + lemp->nrule;
4336 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4337 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4338 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4339 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4340 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4341 i = lemp->minReduce + lemp->nrule;
4342 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4343 tplt_xfer(lemp->name,in,out,&lineno);
4345 /* Now output the action table and its associates:
4347 ** yy_action[] A single table containing all actions.
4348 ** yy_lookahead[] A table containing the lookahead for each entry in
4349 ** yy_action. Used to detect hash collisions.
4350 ** yy_shift_ofst[] For each state, the offset into yy_action for
4351 ** shifting terminals.
4352 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4353 ** shifting non-terminals after a reduce.
4354 ** yy_default[] Default action for each state.
4357 /* Output the yy_action table */
4358 lemp->nactiontab = n = acttab_action_size(pActtab);
4359 lemp->tablesize += n*szActionType;
4360 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4361 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
4362 for(i=j=0; i<n; i++){
4363 int action = acttab_yyaction(pActtab, i);
4364 if( action<0 ) action = lemp->noAction;
4365 if( j==0 ) fprintf(out," /* %5d */ ", i);
4366 fprintf(out, " %4d,", action);
4367 if( j==9 || i==n-1 ){
4368 fprintf(out, "\n"); lineno++;
4369 j = 0;
4370 }else{
4371 j++;
4374 fprintf(out, "};\n"); lineno++;
4376 /* Output the yy_lookahead table */
4377 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
4378 lemp->tablesize += n*szCodeType;
4379 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
4380 for(i=j=0; i<n; i++){
4381 int la = acttab_yylookahead(pActtab, i);
4382 if( la<0 ) la = lemp->nsymbol;
4383 if( j==0 ) fprintf(out," /* %5d */ ", i);
4384 fprintf(out, " %4d,", la);
4385 if( j==9 || i==n-1 ){
4386 fprintf(out, "\n"); lineno++;
4387 j = 0;
4388 }else{
4389 j++;
4392 fprintf(out, "};\n"); lineno++;
4394 /* Output the yy_shift_ofst[] table */
4395 n = lemp->nxstate;
4396 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
4397 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4398 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4399 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
4400 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
4401 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4402 lineno++;
4403 lemp->tablesize += n*sz;
4404 for(i=j=0; i<n; i++){
4405 int ofst;
4406 stp = lemp->sorted[i];
4407 ofst = stp->iTknOfst;
4408 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
4409 if( j==0 ) fprintf(out," /* %5d */ ", i);
4410 fprintf(out, " %4d,", ofst);
4411 if( j==9 || i==n-1 ){
4412 fprintf(out, "\n"); lineno++;
4413 j = 0;
4414 }else{
4415 j++;
4418 fprintf(out, "};\n"); lineno++;
4420 /* Output the yy_reduce_ofst[] table */
4421 n = lemp->nxstate;
4422 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
4423 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4424 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4425 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
4426 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
4427 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4428 lemp->tablesize += n*sz;
4429 for(i=j=0; i<n; i++){
4430 int ofst;
4431 stp = lemp->sorted[i];
4432 ofst = stp->iNtOfst;
4433 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
4434 if( j==0 ) fprintf(out," /* %5d */ ", i);
4435 fprintf(out, " %4d,", ofst);
4436 if( j==9 || i==n-1 ){
4437 fprintf(out, "\n"); lineno++;
4438 j = 0;
4439 }else{
4440 j++;
4443 fprintf(out, "};\n"); lineno++;
4445 /* Output the default action table */
4446 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
4447 n = lemp->nxstate;
4448 lemp->tablesize += n*szActionType;
4449 for(i=j=0; i<n; i++){
4450 stp = lemp->sorted[i];
4451 if( j==0 ) fprintf(out," /* %5d */ ", i);
4452 if( stp->iDfltReduce<0 ){
4453 fprintf(out, " %4d,", lemp->errAction);
4454 }else{
4455 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4457 if( j==9 || i==n-1 ){
4458 fprintf(out, "\n"); lineno++;
4459 j = 0;
4460 }else{
4461 j++;
4464 fprintf(out, "};\n"); lineno++;
4465 tplt_xfer(lemp->name,in,out,&lineno);
4467 /* Generate the table of fallback tokens.
4469 if( lemp->has_fallback ){
4470 int mx = lemp->nterminal - 1;
4471 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
4472 lemp->tablesize += (mx+1)*szCodeType;
4473 for(i=0; i<=mx; i++){
4474 struct symbol *p = lemp->symbols[i];
4475 if( p->fallback==0 ){
4476 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4477 }else{
4478 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4479 p->name, p->fallback->name);
4481 lineno++;
4484 tplt_xfer(lemp->name, in, out, &lineno);
4486 /* Generate a table containing the symbolic name of every symbol
4488 for(i=0; i<lemp->nsymbol; i++){
4489 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
4490 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
4492 tplt_xfer(lemp->name,in,out,&lineno);
4494 /* Generate a table containing a text string that describes every
4495 ** rule in the rule set of the grammar. This information is used
4496 ** when tracing REDUCE actions.
4498 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4499 assert( rp->iRule==i );
4500 fprintf(out," /* %3d */ \"", i);
4501 writeRuleText(out, rp);
4502 fprintf(out,"\",\n"); lineno++;
4504 tplt_xfer(lemp->name,in,out,&lineno);
4506 /* Generate code which executes every time a symbol is popped from
4507 ** the stack while processing errors or while destroying the parser.
4508 ** (In other words, generate the %destructor actions)
4510 if( lemp->tokendest ){
4511 int once = 1;
4512 for(i=0; i<lemp->nsymbol; i++){
4513 struct symbol *sp = lemp->symbols[i];
4514 if( sp==0 || sp->type!=TERMINAL ) continue;
4515 if( once ){
4516 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4517 once = 0;
4519 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4521 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4522 if( i<lemp->nsymbol ){
4523 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4524 fprintf(out," break;\n"); lineno++;
4527 if( lemp->vardest ){
4528 struct symbol *dflt_sp = 0;
4529 int once = 1;
4530 for(i=0; i<lemp->nsymbol; i++){
4531 struct symbol *sp = lemp->symbols[i];
4532 if( sp==0 || sp->type==TERMINAL ||
4533 sp->index<=0 || sp->destructor!=0 ) continue;
4534 if( once ){
4535 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
4536 once = 0;
4538 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4539 dflt_sp = sp;
4541 if( dflt_sp!=0 ){
4542 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4544 fprintf(out," break;\n"); lineno++;
4546 for(i=0; i<lemp->nsymbol; i++){
4547 struct symbol *sp = lemp->symbols[i];
4548 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4549 if( sp->destLineno<0 ) continue; /* Already emitted */
4550 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4552 /* Combine duplicate destructors into a single case */
4553 for(j=i+1; j<lemp->nsymbol; j++){
4554 struct symbol *sp2 = lemp->symbols[j];
4555 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4556 && sp2->dtnum==sp->dtnum
4557 && strcmp(sp->destructor,sp2->destructor)==0 ){
4558 fprintf(out," case %d: /* %s */\n",
4559 sp2->index, sp2->name); lineno++;
4560 sp2->destLineno = -1; /* Avoid emitting this destructor again */
4564 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4565 fprintf(out," break;\n"); lineno++;
4567 tplt_xfer(lemp->name,in,out,&lineno);
4569 /* Generate code which executes whenever the parser stack overflows */
4570 tplt_print(out,lemp,lemp->overflow,&lineno);
4571 tplt_xfer(lemp->name,in,out,&lineno);
4573 /* Generate the table of rule information
4575 ** Note: This code depends on the fact that rules are numbered
4576 ** sequentially beginning with 0.
4578 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4579 fprintf(out," { %4d, %4d }, /* (%d) ",rp->lhs->index,-rp->nrhs,i);
4580 rule_print(out, rp);
4581 fprintf(out," */\n"); lineno++;
4583 tplt_xfer(lemp->name,in,out,&lineno);
4585 /* Generate code which execution during each REDUCE action */
4586 i = 0;
4587 for(rp=lemp->rule; rp; rp=rp->next){
4588 i += translate_code(lemp, rp);
4590 if( i ){
4591 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
4593 /* First output rules other than the default: rule */
4594 for(rp=lemp->rule; rp; rp=rp->next){
4595 struct rule *rp2; /* Other rules with the same action */
4596 if( rp->codeEmitted ) continue;
4597 if( rp->noCode ){
4598 /* No C code actions, so this will be part of the "default:" rule */
4599 continue;
4601 fprintf(out," case %d: /* ", rp->iRule);
4602 writeRuleText(out, rp);
4603 fprintf(out, " */\n"); lineno++;
4604 for(rp2=rp->next; rp2; rp2=rp2->next){
4605 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4606 && rp2->codeSuffix==rp->codeSuffix ){
4607 fprintf(out," case %d: /* ", rp2->iRule);
4608 writeRuleText(out, rp2);
4609 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
4610 rp2->codeEmitted = 1;
4613 emit_code(out,rp,lemp,&lineno);
4614 fprintf(out," break;\n"); lineno++;
4615 rp->codeEmitted = 1;
4617 /* Finally, output the default: rule. We choose as the default: all
4618 ** empty actions. */
4619 fprintf(out," default:\n"); lineno++;
4620 for(rp=lemp->rule; rp; rp=rp->next){
4621 if( rp->codeEmitted ) continue;
4622 assert( rp->noCode );
4623 fprintf(out," /* (%d) ", rp->iRule);
4624 writeRuleText(out, rp);
4625 if( rp->doesReduce ){
4626 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4627 }else{
4628 fprintf(out, " (OPTIMIZED OUT) */ Assert(yyruleno!=%d);\n",
4629 rp->iRule); lineno++;
4632 fprintf(out," break;\n"); lineno++;
4633 tplt_xfer(lemp->name,in,out,&lineno);
4635 /* Generate code which executes if a parse fails */
4636 tplt_print(out,lemp,lemp->failure,&lineno);
4637 tplt_xfer(lemp->name,in,out,&lineno);
4639 /* Generate code which executes when a syntax error occurs */
4640 tplt_print(out,lemp,lemp->error,&lineno);
4641 tplt_xfer(lemp->name,in,out,&lineno);
4643 /* Generate code which executes when the parser accepts its input */
4644 tplt_print(out,lemp,lemp->accept,&lineno);
4645 tplt_xfer(lemp->name,in,out,&lineno);
4647 /* Append any additional code the user desires */
4648 tplt_print(out,lemp,lemp->extracode,&lineno);
4650 fclose(in);
4651 fclose(out);
4652 return;
4655 /* Generate a header file for the parser */
4656 void ReportHeader(struct lemon *lemp)
4658 FILE *out, *in;
4659 const char *prefix;
4660 char line[LINESIZE];
4661 char pattern[LINESIZE];
4662 int i;
4664 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4665 else prefix = "";
4666 if( output_header_filename!=0 ){
4667 char *tmp = lemp->filename;
4668 char *ext = strrchr(output_header_filename, '.');
4669 if( ext==0 ) ext = ".h";
4670 lemp->filename = output_header_filename;
4671 in = file_open(lemp,ext,"rb");
4672 lemp->filename = tmp;
4673 }else{
4674 in = file_open(lemp,".h","rb");
4676 if( in ){
4677 int nextChar;
4678 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4679 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4680 prefix,lemp->symbols[i]->name,i);
4681 if( strcmp(line,pattern) ) break;
4683 nextChar = fgetc(in);
4684 fclose(in);
4685 if( i==lemp->nterminal && nextChar==EOF ){
4686 /* No change in the file. Don't rewrite it. */
4687 return;
4690 if( output_header_filename!=0 ){
4691 char *tmp = lemp->filename;
4692 char *ext = strrchr(output_header_filename, '.');
4693 if( ext==0 ) ext = ".h";
4694 lemp->filename = output_header_filename;
4695 out = file_open(lemp,ext,"wb");
4696 lemp->filename = tmp;
4697 }else{
4698 out = file_open(lemp,".h","wb");
4700 if( out ){
4701 for(i=1; i<lemp->nterminal; i++){
4702 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
4704 fclose(out);
4706 return;
4709 /* Reduce the size of the action tables, if possible, by making use
4710 ** of defaults.
4712 ** In this version, we take the most frequent REDUCE action and make
4713 ** it the default. Except, there is no default if the wildcard token
4714 ** is a possible look-ahead.
4716 void CompressTables(struct lemon *lemp)
4718 struct state *stp;
4719 struct action *ap, *ap2, *nextap;
4720 struct rule *rp, *rp2, *rbest;
4721 int nbest, n;
4722 int i;
4723 int usesWildcard;
4725 for(i=0; i<lemp->nstate; i++){
4726 stp = lemp->sorted[i];
4727 nbest = 0;
4728 rbest = 0;
4729 usesWildcard = 0;
4731 for(ap=stp->ap; ap; ap=ap->next){
4732 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4733 usesWildcard = 1;
4735 if( ap->type!=REDUCE ) continue;
4736 rp = ap->x.rp;
4737 if( rp->lhsStart ) continue;
4738 if( rp==rbest ) continue;
4739 n = 1;
4740 for(ap2=ap->next; ap2; ap2=ap2->next){
4741 if( ap2->type!=REDUCE ) continue;
4742 rp2 = ap2->x.rp;
4743 if( rp2==rbest ) continue;
4744 if( rp2==rp ) n++;
4746 if( n>nbest ){
4747 nbest = n;
4748 rbest = rp;
4752 /* Do not make a default if the number of rules to default
4753 ** is not at least 1 or if the wildcard token is a possible
4754 ** lookahead.
4756 if( nbest<1 || usesWildcard ) continue;
4759 /* Combine matching REDUCE actions into a single default */
4760 for(ap=stp->ap; ap; ap=ap->next){
4761 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4763 assert( ap );
4764 ap->sp = Symbol_new("{default}");
4765 for(ap=ap->next; ap; ap=ap->next){
4766 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
4768 stp->ap = Action_sort(stp->ap);
4770 for(ap=stp->ap; ap; ap=ap->next){
4771 if( ap->type==SHIFT ) break;
4772 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4774 if( ap==0 ){
4775 stp->autoReduce = 1;
4776 stp->pDfltReduce = rbest;
4780 /* Make a second pass over all states and actions. Convert
4781 ** every action that is a SHIFT to an autoReduce state into
4782 ** a SHIFTREDUCE action.
4784 for(i=0; i<lemp->nstate; i++){
4785 stp = lemp->sorted[i];
4786 for(ap=stp->ap; ap; ap=ap->next){
4787 struct state *pNextState;
4788 if( ap->type!=SHIFT ) continue;
4789 pNextState = ap->x.stp;
4790 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4791 ap->type = SHIFTREDUCE;
4792 ap->x.rp = pNextState->pDfltReduce;
4797 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4798 ** (meaning that the SHIFTREDUCE will land back in the state where it
4799 ** started) and if there is no C-code associated with the reduce action,
4800 ** then we can go ahead and convert the action to be the same as the
4801 ** action for the RHS of the rule.
4803 for(i=0; i<lemp->nstate; i++){
4804 stp = lemp->sorted[i];
4805 for(ap=stp->ap; ap; ap=nextap){
4806 nextap = ap->next;
4807 if( ap->type!=SHIFTREDUCE ) continue;
4808 rp = ap->x.rp;
4809 if( rp->noCode==0 ) continue;
4810 if( rp->nrhs!=1 ) continue;
4811 #if 1
4812 /* Only apply this optimization to non-terminals. It would be OK to
4813 ** apply it to terminal symbols too, but that makes the parser tables
4814 ** larger. */
4815 if( ap->sp->index<lemp->nterminal ) continue;
4816 #endif
4817 /* If we reach this point, it means the optimization can be applied */
4818 nextap = ap;
4819 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4820 assert( ap2!=0 );
4821 ap->spOpt = ap2->sp;
4822 ap->type = ap2->type;
4823 ap->x = ap2->x;
4830 ** Compare two states for sorting purposes. The smaller state is the
4831 ** one with the most non-terminal actions. If they have the same number
4832 ** of non-terminal actions, then the smaller is the one with the most
4833 ** token actions.
4835 static int stateResortCompare(const void *a, const void *b){
4836 const struct state *pA = *(const struct state**)a;
4837 const struct state *pB = *(const struct state**)b;
4838 int n;
4840 n = pB->nNtAct - pA->nNtAct;
4841 if( n==0 ){
4842 n = pB->nTknAct - pA->nTknAct;
4843 if( n==0 ){
4844 n = pB->statenum - pA->statenum;
4847 assert( n!=0 );
4848 return n;
4853 ** Renumber and resort states so that states with fewer choices
4854 ** occur at the end. Except, keep state 0 as the first state.
4856 void ResortStates(struct lemon *lemp)
4858 int i;
4859 struct state *stp;
4860 struct action *ap;
4862 for(i=0; i<lemp->nstate; i++){
4863 stp = lemp->sorted[i];
4864 stp->nTknAct = stp->nNtAct = 0;
4865 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
4866 stp->iTknOfst = NO_OFFSET;
4867 stp->iNtOfst = NO_OFFSET;
4868 for(ap=stp->ap; ap; ap=ap->next){
4869 int iAction = compute_action(lemp,ap);
4870 if( iAction>=0 ){
4871 if( ap->sp->index<lemp->nterminal ){
4872 stp->nTknAct++;
4873 }else if( ap->sp->index<lemp->nsymbol ){
4874 stp->nNtAct++;
4875 }else{
4876 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4877 stp->iDfltReduce = iAction;
4882 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4883 stateResortCompare);
4884 for(i=0; i<lemp->nstate; i++){
4885 lemp->sorted[i]->statenum = i;
4887 lemp->nxstate = lemp->nstate;
4888 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4889 lemp->nxstate--;
4894 /***************** From the file "set.c" ************************************/
4896 ** Set manipulation routines for the LEMON parser generator.
4899 static int size = 0;
4901 /* Set the set size */
4902 void SetSize(int n)
4904 size = n+1;
4907 /* Allocate a new set */
4908 char *SetNew(void){
4909 char *s;
4910 s = (char*)calloc( size, 1);
4911 if( s==0 ){
4912 extern void memory_error();
4913 memory_error();
4915 return s;
4918 /* Deallocate a set */
4919 void SetFree(char *s)
4921 free(s);
4924 /* Add a new element to the set. Return TRUE if the element was added
4925 ** and FALSE if it was already there. */
4926 int SetAdd(char *s, int e)
4928 int rv;
4929 assert( e>=0 && e<size );
4930 rv = s[e];
4931 s[e] = 1;
4932 return !rv;
4935 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4936 int SetUnion(char *s1, char *s2)
4938 int i, progress;
4939 progress = 0;
4940 for(i=0; i<size; i++){
4941 if( s2[i]==0 ) continue;
4942 if( s1[i]==0 ){
4943 progress = 1;
4944 s1[i] = 1;
4947 return progress;
4949 /********************** From the file "table.c" ****************************/
4951 ** All code in this file has been automatically generated
4952 ** from a specification in the file
4953 ** "table.q"
4954 ** by the associative array code building program "aagen".
4955 ** Do not edit this file! Instead, edit the specification
4956 ** file, then rerun aagen.
4959 ** Code for processing tables in the LEMON parser generator.
4962 PRIVATE unsigned strhash(const char *x)
4964 unsigned h = 0;
4965 while( *x ) h = h*13 + *(x++);
4966 return h;
4969 /* Works like strdup, sort of. Save a string in malloced memory, but
4970 ** keep strings in a table so that the same string is not in more
4971 ** than one place.
4973 const char *Strsafe(const char *y)
4975 const char *z;
4976 char *cpy;
4978 if( y==0 ) return 0;
4979 z = Strsafe_find(y);
4980 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4981 lemon_strcpy(cpy,y);
4982 z = cpy;
4983 Strsafe_insert(z);
4985 MemoryCheck(z);
4986 return z;
4989 /* There is one instance of the following structure for each
4990 ** associative array of type "x1".
4992 struct s_x1 {
4993 int size; /* The number of available slots. */
4994 /* Must be a power of 2 greater than or */
4995 /* equal to 1 */
4996 int count; /* Number of currently slots filled */
4997 struct s_x1node *tbl; /* The data stored here */
4998 struct s_x1node **ht; /* Hash table for lookups */
5001 /* There is one instance of this structure for every data element
5002 ** in an associative array of type "x1".
5004 typedef struct s_x1node {
5005 const char *data; /* The data */
5006 struct s_x1node *next; /* Next entry with the same hash */
5007 struct s_x1node **from; /* Previous link */
5008 } x1node;
5010 /* There is only one instance of the array, which is the following */
5011 static struct s_x1 *x1a;
5013 /* Allocate a new associative array */
5014 void Strsafe_init(void){
5015 if( x1a ) return;
5016 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5017 if( x1a ){
5018 x1a->size = 1024;
5019 x1a->count = 0;
5020 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
5021 if( x1a->tbl==0 ){
5022 memory_error();
5023 }else{
5024 int i;
5025 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5026 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5028 }else{
5029 memory_error();
5032 /* Insert a new record into the array. Return TRUE if successful.
5033 ** Prior data with the same key is NOT overwritten */
5034 int Strsafe_insert(const char *data)
5036 x1node *np;
5037 unsigned h;
5038 unsigned ph;
5040 if( x1a==0 ) return 0;
5041 ph = strhash(data);
5042 h = ph & (x1a->size-1);
5043 np = x1a->ht[h];
5044 while( np ){
5045 if( strcmp(np->data,data)==0 ){
5046 /* An existing entry with the same key is found. */
5047 /* Fail because overwrite is not allows. */
5048 return 0;
5050 np = np->next;
5052 if( x1a->count>=x1a->size ){
5053 /* Need to make the hash table bigger */
5054 int i,arrSize;
5055 struct s_x1 array;
5056 array.size = arrSize = x1a->size*2;
5057 array.count = x1a->count;
5058 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
5059 MemoryCheck(array.tbl);
5060 array.ht = (x1node**)&(array.tbl[arrSize]);
5061 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5062 for(i=0; i<x1a->count; i++){
5063 x1node *oldnp, *newnp;
5064 oldnp = &(x1a->tbl[i]);
5065 h = strhash(oldnp->data) & (arrSize-1);
5066 newnp = &(array.tbl[i]);
5067 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5068 newnp->next = array.ht[h];
5069 newnp->data = oldnp->data;
5070 newnp->from = &(array.ht[h]);
5071 array.ht[h] = newnp;
5073 free(x1a->tbl);
5074 *x1a = array;
5076 /* Insert the new data */
5077 h = ph & (x1a->size-1);
5078 np = &(x1a->tbl[x1a->count++]);
5079 np->data = data;
5080 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5081 np->next = x1a->ht[h];
5082 x1a->ht[h] = np;
5083 np->from = &(x1a->ht[h]);
5084 return 1;
5087 /* Return a pointer to data assigned to the given key. Return NULL
5088 ** if no such key. */
5089 const char *Strsafe_find(const char *key)
5091 unsigned h;
5092 x1node *np;
5094 if( x1a==0 ) return 0;
5095 h = strhash(key) & (x1a->size-1);
5096 np = x1a->ht[h];
5097 while( np ){
5098 if( strcmp(np->data,key)==0 ) break;
5099 np = np->next;
5101 return np ? np->data : 0;
5104 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5105 ** Create a new symbol if this is the first time "x" has been seen.
5107 struct symbol *Symbol_new(const char *x)
5109 struct symbol *sp;
5111 sp = Symbol_find(x);
5112 if( sp==0 ){
5113 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
5114 MemoryCheck(sp);
5115 sp->name = Strsafe(x);
5116 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
5117 sp->rule = 0;
5118 sp->fallback = 0;
5119 sp->prec = -1;
5120 sp->assoc = UNK;
5121 sp->firstset = 0;
5122 sp->lambda = LEMON_FALSE;
5123 sp->destructor = 0;
5124 sp->destLineno = 0;
5125 sp->datatype = 0;
5126 sp->useCnt = 0;
5127 Symbol_insert(sp,sp->name);
5129 sp->useCnt++;
5130 return sp;
5133 /* Compare two symbols for sorting purposes. Return negative,
5134 ** zero, or positive if a is less then, equal to, or greater
5135 ** than b.
5137 ** Symbols that begin with upper case letters (terminals or tokens)
5138 ** must sort before symbols that begin with lower case letters
5139 ** (non-terminals). And MULTITERMINAL symbols (created using the
5140 ** %token_class directive) must sort at the very end. Other than
5141 ** that, the order does not matter.
5143 ** We find experimentally that leaving the symbols in their original
5144 ** order (the order they appeared in the grammar file) gives the
5145 ** smallest parser tables in SQLite.
5147 int Symbolcmpp(const void *_a, const void *_b)
5149 const struct symbol *a = *(const struct symbol **) _a;
5150 const struct symbol *b = *(const struct symbol **) _b;
5151 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5152 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5153 return i1==i2 ? a->index - b->index : i1 - i2;
5156 /* There is one instance of the following structure for each
5157 ** associative array of type "x2".
5159 struct s_x2 {
5160 int size; /* The number of available slots. */
5161 /* Must be a power of 2 greater than or */
5162 /* equal to 1 */
5163 int count; /* Number of currently slots filled */
5164 struct s_x2node *tbl; /* The data stored here */
5165 struct s_x2node **ht; /* Hash table for lookups */
5168 /* There is one instance of this structure for every data element
5169 ** in an associative array of type "x2".
5171 typedef struct s_x2node {
5172 struct symbol *data; /* The data */
5173 const char *key; /* The key */
5174 struct s_x2node *next; /* Next entry with the same hash */
5175 struct s_x2node **from; /* Previous link */
5176 } x2node;
5178 /* There is only one instance of the array, which is the following */
5179 static struct s_x2 *x2a;
5181 /* Allocate a new associative array */
5182 void Symbol_init(void){
5183 if( x2a ) return;
5184 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5185 if( x2a ){
5186 x2a->size = 128;
5187 x2a->count = 0;
5188 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
5189 if( x2a->tbl==0 ){
5190 memory_error();
5191 }else{
5192 int i;
5193 x2a->ht = (x2node**)&(x2a->tbl[128]);
5194 for(i=0; i<128; i++) x2a->ht[i] = 0;
5196 }else{
5197 memory_error();
5200 /* Insert a new record into the array. Return TRUE if successful.
5201 ** Prior data with the same key is NOT overwritten */
5202 int Symbol_insert(struct symbol *data, const char *key)
5204 x2node *np;
5205 unsigned h;
5206 unsigned ph;
5208 if( x2a==0 ) return 0;
5209 ph = strhash(key);
5210 h = ph & (x2a->size-1);
5211 np = x2a->ht[h];
5212 while( np ){
5213 if( strcmp(np->key,key)==0 ){
5214 /* An existing entry with the same key is found. */
5215 /* Fail because overwrite is not allows. */
5216 return 0;
5218 np = np->next;
5220 if( x2a->count>=x2a->size ){
5221 /* Need to make the hash table bigger */
5222 int i,arrSize;
5223 struct s_x2 array;
5224 array.size = arrSize = x2a->size*2;
5225 array.count = x2a->count;
5226 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
5227 MemoryCheck(array.tbl);
5228 array.ht = (x2node**)&(array.tbl[arrSize]);
5229 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5230 for(i=0; i<x2a->count; i++){
5231 x2node *oldnp, *newnp;
5232 oldnp = &(x2a->tbl[i]);
5233 h = strhash(oldnp->key) & (arrSize-1);
5234 newnp = &(array.tbl[i]);
5235 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5236 newnp->next = array.ht[h];
5237 newnp->key = oldnp->key;
5238 newnp->data = oldnp->data;
5239 newnp->from = &(array.ht[h]);
5240 array.ht[h] = newnp;
5242 free(x2a->tbl);
5243 *x2a = array;
5245 /* Insert the new data */
5246 h = ph & (x2a->size-1);
5247 np = &(x2a->tbl[x2a->count++]);
5248 np->key = key;
5249 np->data = data;
5250 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5251 np->next = x2a->ht[h];
5252 x2a->ht[h] = np;
5253 np->from = &(x2a->ht[h]);
5254 return 1;
5257 /* Return a pointer to data assigned to the given key. Return NULL
5258 ** if no such key. */
5259 struct symbol *Symbol_find(const char *key)
5261 unsigned h;
5262 x2node *np;
5264 if( x2a==0 ) return 0;
5265 h = strhash(key) & (x2a->size-1);
5266 np = x2a->ht[h];
5267 while( np ){
5268 if( strcmp(np->key,key)==0 ) break;
5269 np = np->next;
5271 return np ? np->data : 0;
5274 /* Return the n-th data. Return NULL if n is out of range. */
5275 struct symbol *Symbol_Nth(int n)
5277 struct symbol *data;
5278 if( x2a && n>0 && n<=x2a->count ){
5279 data = x2a->tbl[n-1].data;
5280 }else{
5281 data = 0;
5283 return data;
5286 /* Return the size of the array */
5287 int Symbol_count()
5289 return x2a ? x2a->count : 0;
5292 /* Return an array of pointers to all data in the table.
5293 ** The array is obtained from malloc. Return NULL if memory allocation
5294 ** problems, or if the array is empty. */
5295 struct symbol **Symbol_arrayof()
5297 struct symbol **array;
5298 int i,arrSize;
5299 if( x2a==0 ) return 0;
5300 arrSize = x2a->count;
5301 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
5302 if( array ){
5303 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
5304 }else{
5305 memory_error();
5307 return array;
5310 /* Compare two configurations */
5311 int Configcmp(const char *_a,const char *_b)
5313 const struct config *a = (struct config *) _a;
5314 const struct config *b = (struct config *) _b;
5315 int x;
5316 x = a->rp->index - b->rp->index;
5317 if( x==0 ) x = a->dot - b->dot;
5318 return x;
5321 /* Compare two states */
5322 PRIVATE int statecmp(struct config *a, struct config *b)
5324 int rc;
5325 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5326 rc = a->rp->index - b->rp->index;
5327 if( rc==0 ) rc = a->dot - b->dot;
5329 if( rc==0 ){
5330 if( a ) rc = 1;
5331 if( b ) rc = -1;
5333 return rc;
5336 /* Hash a state */
5337 PRIVATE unsigned statehash(struct config *a)
5339 unsigned h=0;
5340 while( a ){
5341 h = h*571 + a->rp->index*37 + a->dot;
5342 a = a->bp;
5344 return h;
5347 /* Allocate a new state structure */
5348 struct state *State_new()
5350 struct state *newstate;
5351 newstate = (struct state *)calloc(1, sizeof(struct state) );
5352 MemoryCheck(newstate);
5353 return newstate;
5356 /* There is one instance of the following structure for each
5357 ** associative array of type "x3".
5359 struct s_x3 {
5360 int size; /* The number of available slots. */
5361 /* Must be a power of 2 greater than or */
5362 /* equal to 1 */
5363 int count; /* Number of currently slots filled */
5364 struct s_x3node *tbl; /* The data stored here */
5365 struct s_x3node **ht; /* Hash table for lookups */
5368 /* There is one instance of this structure for every data element
5369 ** in an associative array of type "x3".
5371 typedef struct s_x3node {
5372 struct state *data; /* The data */
5373 struct config *key; /* The key */
5374 struct s_x3node *next; /* Next entry with the same hash */
5375 struct s_x3node **from; /* Previous link */
5376 } x3node;
5378 /* There is only one instance of the array, which is the following */
5379 static struct s_x3 *x3a;
5381 /* Allocate a new associative array */
5382 void State_init(void){
5383 if( x3a ) return;
5384 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5385 if( x3a ){
5386 x3a->size = 128;
5387 x3a->count = 0;
5388 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
5389 if( x3a->tbl==0 ){
5390 memory_error();
5391 }else{
5392 int i;
5393 x3a->ht = (x3node**)&(x3a->tbl[128]);
5394 for(i=0; i<128; i++) x3a->ht[i] = 0;
5396 }else{
5397 memory_error();
5400 /* Insert a new record into the array. Return TRUE if successful.
5401 ** Prior data with the same key is NOT overwritten */
5402 int State_insert(struct state *data, struct config *key)
5404 x3node *np;
5405 unsigned h;
5406 unsigned ph;
5408 if( x3a==0 ) return 0;
5409 ph = statehash(key);
5410 h = ph & (x3a->size-1);
5411 np = x3a->ht[h];
5412 while( np ){
5413 if( statecmp(np->key,key)==0 ){
5414 /* An existing entry with the same key is found. */
5415 /* Fail because overwrite is not allows. */
5416 return 0;
5418 np = np->next;
5420 if( x3a->count>=x3a->size ){
5421 /* Need to make the hash table bigger */
5422 int i,arrSize;
5423 struct s_x3 array;
5424 array.size = arrSize = x3a->size*2;
5425 array.count = x3a->count;
5426 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
5427 MemoryCheck(array.tbl);
5428 array.ht = (x3node**)&(array.tbl[arrSize]);
5429 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5430 for(i=0; i<x3a->count; i++){
5431 x3node *oldnp, *newnp;
5432 oldnp = &(x3a->tbl[i]);
5433 h = statehash(oldnp->key) & (arrSize-1);
5434 newnp = &(array.tbl[i]);
5435 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5436 newnp->next = array.ht[h];
5437 newnp->key = oldnp->key;
5438 newnp->data = oldnp->data;
5439 newnp->from = &(array.ht[h]);
5440 array.ht[h] = newnp;
5442 free(x3a->tbl);
5443 *x3a = array;
5445 /* Insert the new data */
5446 h = ph & (x3a->size-1);
5447 np = &(x3a->tbl[x3a->count++]);
5448 np->key = key;
5449 np->data = data;
5450 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5451 np->next = x3a->ht[h];
5452 x3a->ht[h] = np;
5453 np->from = &(x3a->ht[h]);
5454 return 1;
5457 /* Return a pointer to data assigned to the given key. Return NULL
5458 ** if no such key. */
5459 struct state *State_find(struct config *key)
5461 unsigned h;
5462 x3node *np;
5464 if( x3a==0 ) return 0;
5465 h = statehash(key) & (x3a->size-1);
5466 np = x3a->ht[h];
5467 while( np ){
5468 if( statecmp(np->key,key)==0 ) break;
5469 np = np->next;
5471 return np ? np->data : 0;
5474 /* Return an array of pointers to all data in the table.
5475 ** The array is obtained from malloc. Return NULL if the array is empty. */
5476 struct state **State_arrayof(void)
5478 struct state **array;
5479 int i,arrSize;
5480 if( x3a==0 ) return 0;
5481 arrSize = x3a->count;
5482 array = (struct state **)calloc(arrSize, sizeof(struct state *));
5483 if( array ){
5484 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
5485 }else{
5486 memory_error();
5488 return array;
5491 /* Hash a configuration */
5492 PRIVATE unsigned confighash(struct config *a)
5494 unsigned h=0;
5495 h = h*571 + a->rp->index*37 + a->dot;
5496 return h;
5499 /* There is one instance of the following structure for each
5500 ** associative array of type "x4".
5502 struct s_x4 {
5503 int size; /* The number of available slots. */
5504 /* Must be a power of 2 greater than or */
5505 /* equal to 1 */
5506 int count; /* Number of currently slots filled */
5507 struct s_x4node *tbl; /* The data stored here */
5508 struct s_x4node **ht; /* Hash table for lookups */
5511 /* There is one instance of this structure for every data element
5512 ** in an associative array of type "x4".
5514 typedef struct s_x4node {
5515 struct config *data; /* The data */
5516 struct s_x4node *next; /* Next entry with the same hash */
5517 struct s_x4node **from; /* Previous link */
5518 } x4node;
5520 /* There is only one instance of the array, which is the following */
5521 static struct s_x4 *x4a;
5523 /* Allocate a new associative array */
5524 void Configtable_init(void){
5525 if( x4a ) return;
5526 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5527 if( x4a ){
5528 x4a->size = 64;
5529 x4a->count = 0;
5530 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
5531 if( x4a->tbl==0 ){
5532 memory_error();
5533 }else{
5534 int i;
5535 x4a->ht = (x4node**)&(x4a->tbl[64]);
5536 for(i=0; i<64; i++) x4a->ht[i] = 0;
5538 }else{
5539 memory_error();
5542 /* Insert a new record into the array. Return TRUE if successful.
5543 ** Prior data with the same key is NOT overwritten */
5544 int Configtable_insert(struct config *data)
5546 x4node *np;
5547 unsigned h;
5548 unsigned ph;
5550 if( x4a==0 ) return 0;
5551 ph = confighash(data);
5552 h = ph & (x4a->size-1);
5553 np = x4a->ht[h];
5554 while( np ){
5555 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
5556 /* An existing entry with the same key is found. */
5557 /* Fail because overwrite is not allows. */
5558 return 0;
5560 np = np->next;
5562 if( x4a->count>=x4a->size ){
5563 /* Need to make the hash table bigger */
5564 int i,arrSize;
5565 struct s_x4 array;
5566 array.size = arrSize = x4a->size*2;
5567 array.count = x4a->count;
5568 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
5569 MemoryCheck(array.tbl);
5570 array.ht = (x4node**)&(array.tbl[arrSize]);
5571 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5572 for(i=0; i<x4a->count; i++){
5573 x4node *oldnp, *newnp;
5574 oldnp = &(x4a->tbl[i]);
5575 h = confighash(oldnp->data) & (arrSize-1);
5576 newnp = &(array.tbl[i]);
5577 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5578 newnp->next = array.ht[h];
5579 newnp->data = oldnp->data;
5580 newnp->from = &(array.ht[h]);
5581 array.ht[h] = newnp;
5583 free(x4a->tbl);
5584 *x4a = array;
5586 /* Insert the new data */
5587 h = ph & (x4a->size-1);
5588 np = &(x4a->tbl[x4a->count++]);
5589 np->data = data;
5590 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5591 np->next = x4a->ht[h];
5592 x4a->ht[h] = np;
5593 np->from = &(x4a->ht[h]);
5594 return 1;
5597 /* Return a pointer to data assigned to the given key. Return NULL
5598 ** if no such key. */
5599 struct config *Configtable_find(struct config *key)
5601 int h;
5602 x4node *np;
5604 if( x4a==0 ) return 0;
5605 h = confighash(key) & (x4a->size-1);
5606 np = x4a->ht[h];
5607 while( np ){
5608 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
5609 np = np->next;
5611 return np ? np->data : 0;
5614 /* Remove all data from the table. Pass each data to the function "f"
5615 ** as it is removed. ("f" may be null to avoid this step.) */
5616 void Configtable_clear(int(*f)(struct config *))
5618 int i;
5619 if( x4a==0 || x4a->count==0 ) return;
5620 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5621 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5622 x4a->count = 0;
5623 return;